Skip to content

Instantly share code, notes, and snippets.

@pizzarob
Last active July 25, 2019 04:34
Show Gist options
  • Save pizzarob/f5a2e2d15c496e7a0ee6cba30275d344 to your computer and use it in GitHub Desktop.
Save pizzarob/f5a2e2d15c496e7a0ee6cba30275d344 to your computer and use it in GitHub Desktop.
// Update this with your crate ID
const CRATE_ID = '98';
// Initialize cargo using the development network. This will
// tell Cargo to use it's contracts on the Rinkeby network.
const cargo = new Cargo({
network: 'development',
});
const run = async () => {
// This will fetch Cargo contract information
// so we can begin interacting with those contracts when we are ready.
await cargo.init();
// In order to interact with cargo contracts we will need to call the enable method.
// This determines if the user has a provider available that will allow us to connect
// to the Ethereum blockcain.
const isEnabled = await cargo.enable();
// cargo.enable returns true or false, depending on whether or not we can interact with
// the Cargo smart contracts. We are passing that boolean value to the showContent function
// which will show content for each case. If isEnabled equals false then we can show UI
// that tells the user to install MetaMask, or another MetaMask type product.
showContent(isEnabled);
if (isEnabled) {
// Get all the vendors in your crate. The creator of the crate (you) is
// added as a default vendor.
const { data: vendors } = await cargo.api.getCrateVendors(CRATE_ID);
// Map through each vendor and get the token contracts they created.
const contractResponses = await Promise.all(
vendors.map(({ vendorId }) => cargo.api.getVendorTokenContracts(vendorId))
);
// Map the responses so we have an array of just the contract data.
const contracts = [];
// Each vendor response has an array of contracts so we spread that data into
// our contracts array do it is one dimensional.
contractResponses.forEach(({ data }) => {
contracts.push(...data);
});
// Pass our contract data to a function that will create some markup
// and add it to the page.
displayContractContent(contracts);
}
};
run();
// This function will loop through out contracts and create HTML
function displayContractContent(contracts) {
let template = '';
contracts.forEach(contract => {
const { name, symbol, tokenAddress } = contract;
template += `
<div class="contract-header">
<h2>${name} ${symbol}</h2>
<h3>${tokenAddress}</h3>
</div>
`;
});
document.querySelector('[data-id="token-rows"]').innerHTML = template;
}
function showContent(isEnabled) {
const el = document.querySelector(
`[data-id="provider-${isEnabled ? 'enabled' : 'required'}"]`
);
el.classList.remove('hide');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment