This tutorial will act as a guide for a step-by-step process to understand and use Matic JS, which is the easiest way to interact with the Matic Network. This guide is directed towards developers starting their Ethereum journey. If you want to dive right in, feel free to skim through the article or choose to directly go to https://docs.matic.network/getting-started/.
Some ETH on Ropsten in your account
In order to make any transactions, you will also need some Ether in the test accounts that you will use while following the tutorial. In case you don’t have some ETH on Ropsten, you can use the faucet links given here — https://faucet.metamask.io/ or https://faucet.ropsten.be/.
Throughout this tutorial, we will be using the ERC20 token MTX on the Ropsten network as an example. This is a TEST token. In your DApp, you can replace it with any ERC20 token. To get some Test MTX tokens on Matic Network, you can access the Matic Faucet: https://wallet.matic.today/faucet
All you would need to do is follow simple steps on the link above and you will get some funds into your account:
Go to the link and enter your address
Copy the tweet content and tweet it
Now, paste the Tweet Id in the last field and click on Get Test Matic
Using Matic JS
We will be showcasing the flow for asset transfers on the Matic Network in this tutorial and how you can do the same using Matic.js:
User deposits tokens in Matic contract on mainchain
Once deposited tokens get confirmed on the main chain, the corresponding tokens will get reflected on the Matic chain.
The user can now transfer tokens to anyone they want instantly with negligible fees. Matic chain has faster blocks (approximately 1 second). That way, the transfer will be done almost instantly.
Once a user is ready, they can withdraw remaining tokens from the mainchain by establishing proof of remaining tokens on Root contract (contract deployed on Ropsten/Ethereum chain) within 7 days.
A user can also get a fast exit via 0x or Dharma (coming soon!)
The basic setup for the tutorial
To easily visualize the flow of funds on the Matic Network, it is instructive if you configure the Matic testnet on Metamask. Note that we are using Metamask here solely for visualization purposes. There is no requirement to use Metamask at all for using the Matic Network.
When you create multiple accounts at your end, your addresses will be different from those shown here.
In order to view the flow of funds easily on the Matic Network using Matic.js, you can configure Matic’s testnet URL on Metamask. Refer this link — https://docs.matic.network/newbies/conf-testnet-metamask/ to quickly set it up. Note that this is optional. You can query using web3 if you choose to.
Configuring Matic Test tokens on Metamask
The MTX token, taken as an example for this tutorial, can be configured in Metamask so as to easily visualize account balances. Again note this is optional. You can very easily query the token balances and other variables using web3
These Test tokens need to be added to all 3 test accounts in Metamask once each in both the Ropsten and Matic testnets:
Token name: MTX Where: Ropsten Network Contract address: 0x6b0b0e265321e788af11b6f1235012ae7b5a6808 ---------------------- Token name: MTX (Note: When adding the Matic Testnet token in Metamask, make sure you edit the ticker symbol from CHE to MTX) Where: Matic Testnet (Custom RPC: https://testnet2.matic.network) Contract address: 0xcc5de81d1af53dcb5d707b6b33a50f4ee46d983e
Note: You might need to install some dependencies such as [email protected].34 in case you run into any errors while running matic.js. To install this you can run the command $ npm [email protected]
Depositing Funds from Ropsten to Matic
Within the matic-js-test folder, create a new file and name it deposit-ERC20.js.
Let’s understand this a bit in detail.
token is the address of the MTX TEST ERC20 token contract taken as an example in this tutorial. You will replace it with the relevant ERC20 token address in your DApp.
const token = "config.ROPSTEN_TEST_TOKEN" // test token address
amount is the amount that is to be deposited. The amount is mentioned in wei . To those new to the field, 1 MTX token is equivalent to 10¹⁸ wei . In the code snippet, 0.01 MTX = 10¹⁶ wei.
const amount = "10000000000000000" // amount in wei (0.01 TEST)
from is your address. This will be the address from which funds will be debited. Note that this is my test account address - you will need to plug your own address in here.
const from = "0xdcd53258BA8A69C6a505300BE75447A772bFd3d6" // from address
matic.wallet is your private key. Never store your private key in code on production - this is added in the config.js file for illustration purposes. Typically a user's private key will be stored in a browser wallet such as Metamask or a mobile wallet such as the Matic wallet, Status or a hardware wallet.
matic.wallet = config.PRIVATE_KEY // prefix with `0x`
You will also need to create another file config.js. This will contain all configuration related to Matic.js.
For now, don’t worry about these values — just keep them as is.
You will need to add your private key here. The signing of transactions will require your private key. Again, it is NOT ADVISABLE to hard code your private key when on production. Later, you can build keeping in mind that the user will be handling their keys at their end with MetaMask, Matic Wallet or any other compatible user wallet.
Deposit is a 2 step process
The tokens need to be first approved to the Matic rootchain contract on Ethereum.
Once approved, the deposit function is to be invoked where the tokens get deposited to the Matic contract and are available for use in the Matic network.
For reference purposes, the screenshots below will provide context during the actual deposit.
We currently have 10 MTX tokens and 0.5 ETH at our address 0xdcd53258BA8A69C6a505300BE75447A772bFd3d6 on Ropsten Network,
while on Matic Network, we have 0 MTX tokens.
$ node deposit-ERC20.js
We will be depositing 1 MTX tokens to Matic Testnet.
Let’s run the Deposit function. To run use:
We have added console logging for both events, which when run successfully will display the Transaction Hash as well as a message "Deposit Tokens from Ropsten/Ethereum to Matic - Transaction Approved.". Once the deposit is complete, you will see the Transaction Hash and message "Tokens deposited from Ropsten/Ethereum to Matic." Since this is only for illustration purposes, the message can be customized to anything of your choice. By default, it will only display the Transaction Hash.
Let’s verify our account balances on Metamask.
Our Balance on Ropsten now shows 9 MTX which means our Deposit transaction of 1 MTX was successful.
Verifying our balance on Matic Testnet also shows that our balance is increased by 1 MTX.
Congratulations! You have successfully deposited funds from Ropsten to Matic.
In order to ensure you have more funds, deposit 1 MTX token to Matic by repeating the above process. Make sure you change the amount value in the above script.
Transferring funds from Matic
Once you have funds on Matic, you can use those funds to send to others instantly.
Create a new file — transfer-ERC20.js - in your code directory.
recipient is the receiver's address, to whom the funds are supposed to be sent.
const recipient = "0x05446221202a128a10978D4C9c4500C780455429" // to address
token is the Matic TEST token contract address on the Matic testnet. Note that this is different from the Ropsten MTX token contract address.. This is automatically picked up from the config.js file.
const token = config.MATIC_TEST_TOKEN // test token address
The config details are then mentioned appropriately. You need not to make any changes to it.
The transfer function is invoked here.
Sidenote — you can change the parent parameter to TRUE if you are using Matic.js to transfer funds on the main Ethereum network.
We have added console logging on both events, which when run successfully will display "Transfer done!" to assure that the transaction was completed successfully. These messages are completely customized for this tutorial, by default only the Transaction Hash will be displayed.
We will be making 2 different transfers worth 0.100 MTX and 0.010 MTX tokens respectively.
The screenshots below will provide context during the actual transfer.
We will be transferring 0.100 MTX from Account 1 to Account 2 on Matic Network.
Account 1- 0x74FE3F2b084062dEe9AE0662cA14ecf5C85b94a8. This account currently holds 9 MTX tokens.
$ node transfer-ERC20.js
Account 2- 0x05446221202a128a10978D4C9c4500C780455429. This account currently holds 0 MTX tokens.
Now we will run the transfer function. Run this on the terminal:
Once the code has run successfully, it will display a message of "Transfer done!"
Let’s verify our balances on Metamask.
Our balance on account address — 0xdcd53258BA8A69C6a505300BE75447A772bFd3d6 is now updated to 0.900 MTX tokens.
And to confirm that on our receiver’s account, our balance is now updated to 0.100 MTX tokens.
In this transaction, we will attempt to transfer 0.01 MTX from Account 1 to Account 3.
From — 0x74FE3F2b084062dEe9AE0662cA14ecf5C85b94a8
To — 0x552A00De3aa5953efe4caE8c2c8a04b48554B359. Account 3 currently has 0 MTX tokens.
We will again run $ node transfer-ERC20.js from the terminal. Once we get the 'Transfer done!' message, we will check our balances.
The balance on Account 1 now shows a balance of 0.890MTX,
whereas the balance on Account 3 shows us 0.010 MTX.
Withdraw funds from Matic
Funds that are available on Matic chain can be withdrawn back to the Ethereum Network.
In Matic, withdrawing is a 3 step process where:
Withdrawal of funds is initiated from Matic Network. A checkpoint interval of 5 mins is set, where all the blocks on the Matic block layer are validated since the last checkpoint.
Once the checkpoint is submitted to the mainchain Ethereum contract, an NFT Exit (ERC721) token is created of equivalent value. Users need to wait for a 7 day challenge period
Once the challenge period is complete, the withdrawn funds can be claimed back to your Ethereum account from the mainchain contract using a process-exit procedure.
For now, just go with the fact that the challenge period for withdrawals is an important part of the Plasma framework to ensure the security of your transactions. Later, once you get to know the system better, the reason for the 7-day withdrawal window will become clear to you.
Initiate WithdrawConfirm WithdrawProcess ExitNote: A checkpoint, which is a representation of all transactions happening on the Matic Network to the Ethereum chain every ~5 minutes, is submitted to the mainchain Ethereum contract.
Just for reference, there will be an active exit market, which will allow trading of exit tokens (ERC721), thereby leading to faster withdrawals — but that is an article for another day.
To keep the withdrawal process easier for now on the Matic Testnet, we have not enforced the 7-day withdrawal process. This means while going through this tutorial and developing apps on the testnet, for now, you will get the withdrawn funds immediately after you initiate the process-exit procedure.
Create 3 new files and name them initiate-withdraw-ERC20.js, confirm-withdraw-ERC20.js, and process-exit-ERCO20.js
Withdrawing funds from Matic to Ethereum
We will now initiate the Withdraw process.
We currently have 0.890 MTX tokens at our address on Matic - 0x74FE3F2b084062dEe9AE0662cA14ecf5C85b94a8
We will withdraw 0.010 MTX from the Matic Account.
To initiate the withdraw we will run $ node initiate-withdraw-ERC20.js.
Once this process is initiated, you will receive the transaction hash. The transaction hash will be used as input to run the next step i.e. confirm-withdraw process.
I’ll add the transaction hash to the code — 0x25af48b8699bf51140d74cd2d1e035c5d5ffdd0b1f86ea61ce2e2c6139b1c8d4. Note that in your case, this transaction hash will be different.
Once the initiate-withdraw process is complete, we will wait for ~5 minutes, before running the second script $ node confirm-withdraw.js.
To verify, we will also check the account balances on Metamask.
The balance on Account 1 on Matic Network now shows 0.880 MTX Tokens.
Now, in order to claim your funds after the challenge period is complete, you will need to run the process-exit-ERC20.js
So let’s run the $ process-exit-ERC20.js
Once this is complete, you will see the funds in your Ropsten account.
So that’s it, folks! You have withdrawn your funds successfully and have got to the end of this tutorial ?
Hope you have understood now that interacting with the Matic Network is quite easy. We will dive deeper and explore advanced interactions with Matic in later posts.
Similarly, as an exercise, you can Deposit, transfer and withdraw ERC721 and Ether using Matic.js following the same steps as above.
14th September - EY, a global professional services and technology firm, is collaborating with Polygon on building and implementing scaling and enterprise solutions for the Ethereum ecosystem. As part of this collaboration, EY and Polygon will work on Polygon Nightfall, a public, privacy-focused Rollup. In addition to this, EY will offer its other flagship blockchain […]
The Protocol team was recently established at Coinbase to work on scaling Ethereum through integration with L2 and other ETH scaling solutions. The Coinbase team plans to integrate Polygon PoS as their first scaling solution for Coinbase. The Coinbase Protocol team is an experienced group of engineers at Coinbase focused on contributing to scaling blockchains and […]
We are proud and excited to announce that Hermez, one of the most prominent zero-knowledge (ZK) cryptography-based scaling projects and teams, will be joining Polygon. Starting today, we will initiate the process of merging Hermez into the Polygon ecosystem, where it will be operating under the new name: Polygon Hermez. Polygon Hermez will become a part of […]
The Ethereum scaling solutions space has been heating up lately. Which is a good thing, because Ethereum (and its community) needs scaling as soon as possible. As you know, Polygon's mission is to develop various kinds of Ethereum scaling solutions, from sidechains to rollups (and more). But all these solutions come with trade-offs. There's no […]
Part 1: Polygon PoS engagement growth Polygon PoS set an all-time high for daily active users (DAUs) for the second consecutive week. Last week we saw an explosive week over week (w-o-w) growth of 16.64%. This week, Polygon PoS’ growth increased by 0.73%, bringing DAU to 177,300 active addresses per day. To contextualize this user […]