Let's see how we can interact with Metamask from the code playground. We can connect to Metamask, switch networks, add tokens to the Metamask asset list and send them to other accounts.
This post uses a live code editor. Check out this post to learn more about how it works.
Make sure that you have have Metamask installed in your browser.
Connect to Metamask
The following example shows how to connect Metamask to this browser page.
This function will only trigger an action if Metamask is not yet connect to the site. If you've already connected, nothing will happen.
This example shows how you can prompt a user to connect to a specific Celo network. This component renders two buttons, one to connect to Celo mainnet and one to connect to the Alfajores testnet. If you try to connect to a network that you are already connected to, nothing happens.
Try it out:
The following code example shows how you can add the cUSD token on the Alfajores testnet to Metamask. To add other tokens, just update the parameter options. You can read more about the Metamask API here.
Let's try to send some CELO on Alfajores. Make sure you are connected to the Alfajores testnet, you can double check by clicking the
Connect to Alfajores Testnet button above again.
Make sure you have some Alfajores CELO to send. If you need some, you can get some from the faucet here.
Click the button to send some CELO. Once you click submit, the transaction id will be logged in the browser console!
To send cUSD or interact with any other smart contract, you will have to encode the data and include it in the transaction data field. Libraries like web3.js and contractkit make this easier. We will go over using web3.js and contractkit in future posts.