Understanding of Matic Plasma Bridge - Everything you wanna know and you should know (Including Developer Guide)

Do repost and rate:

Matic PoS (Proof-of-Stake) token extension is presently live on the Matic mainnet for stores and withdrawals from Ethereum to Matic and the other way around. DApps would now be able to utilize the strong validator-run token extension to move ERC20, ERC721 and ERC1155 tokens from Ethereum to Matic and from Matic to Ethereum.

Stores from Ethereum to Matic take ~7-8 minutes to finish and withdrawals take ~30 minutes. This is a huge improvement from the past store and withdrawal instrument. Matic Network has actualized the PoS connect dependent on proposals from their engineer network, and this has been executed with strong Matic anchor token agreement expressiveness for sure.

In the event that you might want to see a specific token planned, it would be ideal if you don't hesitate to present a planning demand here:  https://docs.matic.network/docs/develop/ethereum-matic/submit-mapping-request  

Numerous extra highlights will be added to the PoS token extension in the coming days:

  • Planning of the most mainstream ERC20, ERC721 and ERC1155 tokens
  • UI interface to submit and follow token planning demands
  • Adding PoS token scaffold to https://wallet.matic.network
  • Adding PoS token extension backing to store and pull back UI gadgets
  • A more proficient withdrawal confirmation accommodation system to be added to https://wallet.matic.network and Matic.js

Different changes on the Plasma token scaffold and Matic.js in the coming days:

  • Quick leave uphold for withdrawals inside ~30 minutes
  • More productive pull back confirmation accommodation component to be included
  • Extra aide capacities

At Matic we pay attention to our locale criticism and ensure that we execute highlights which help designers to assemble versatile DApps in the most ideal way and make extraordinary client encounters. We anticipate more input from the network with respect to which new highlights or devices they might want to see on Matic so we can organize our element list in like manner.

Supercharge your DApp with Matic Network

On the off chance that you have a DApp on Ethereum or some other blockchain and might want to profit by Matic's rapid, low-charge foundation while getting backing to develop your client base, you can associate with our group on Discord here:

How Plasma Bridge works  Developer Guide Extracted from the official Documentation Pages!!

 

Plasma Bridge

A bridge is basically a set of contracts that help in moving assets from the root chain to the child chain. There are primarily two bridges to move assets between Ethereum and Matic. First one is the Plasma bridge and the second one is called the PoS Bridge or Proof of Stake bridgePlasma bridge provides an increased security guarantees due to the Plasma exit mechanism.

 

However, there are certain restrictions on the child token and there is a 7-day withdrawal period associated with all exits/withdraws from Matic to Ethereum on the Plasma bridge. The PoS Bridge is more flexible and features faster withdrawals.

This tutorial will act as a guide for step-by-step process to understand and use Plasma bridge using Matic JS, which is the easiest way to interact with the Plasma Bridge on Matic Network.

Assets flow in Plasma Bridge

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:

  1. User deposits crypto assets in Matic contract on mainchain
  2. Once deposited tokens get confirmed on the mainchain, 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.
  3. Once a user is ready, they can withdraw remaining tokens from the mainchain. Withdrawal of funds is initiated from the Plasma Sidechain. A checkpoint interval of 5 mins is set, where all the blocks on the Matic block layer are validated since the last checkpoint.
  4. Once the checkpoint is submitted to the mainchain Ethereum contract, an Exit NFT (ERC721) token is created of equivalent value.
  5. Users need to wait for a 7 day challenge period
  6. Once the challenge period is complete, the withdrawn funds can be claimed back to your Ethereum acccount from the mainchain contract using a process-exit procedure.
    • User can also get a fast exit via 0x or Dharma (coming soon!)

Prerequisites:

Gorli Faucet

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 Gorli, you can use the faucet links given here?—?https://goerli-faucet.slock.it/.

Matic Faucet

Throughout this tutorial, we will be using the ERC20 token TEST on the Gorli network as an example. This is a TEST token. In your DApp, you can replace it with any ERC20 token. To get some Test TEST tokens on Matic Network, you can access the Matic Faucet.

Note: To use your own tokens for deposits and withdrawals, you'll have to get the token 'mapped'. Which essentially means making the contracts on main chain and side chain 'aware' of your custom token. Read more about the Mapping process here, or you can submit a mapping request here.

Basic setup for the METAMASK Wallet (Optional)

  1. Create a wallet: If you are new to wallets, then Setup a Metamask Account.
  2. Configure the Matic testnet: To easily visualise 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.

  3. Create Multiple Accounts: Before starting with the tutorial, go ahead and have 3 Ethereum test accounts ready.
  4. Configure token on Matic: In order to view the flow of funds easily on the Matic Network using Matic.js, you can configure tokens on Metamask. The TEST token, taken as an example for this tutorial, can be configured in Metamask so as to easily visualise account balances. > Again note this is optional. You can very easily query the token balances and other variables using web3

ETH Deposit and Withdraw Guide

High Level Flow

Deposit ETH (1 step process)

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.

Transfer ETH

Once you have funds on Matic, you can use those funds to send to others instantly.

Withdraw ETH (3 step process)

  1. Withdrawal of funds is initiated from Matic Network. A checkpoint interval of 30 mins(For testnets wait for ~10 minutes) is set, where all the blocks on the Matic block layer are validated since the last checkpoint.
  2. Once the checkpoint is submitted to the mainchain ERC20 contract, an NFT Exit (ERC721) token is created of equivalent value. Users need to wait for a 7 day challenge period (For testnets wait for ~5 minutes for)
  3. Once the challenge period is complete, the withdrawn funds can be claimed back to your ERC20 acccount 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 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.

Setup Details

Configuring Matic SDK

Install Matic SDK (2.0.2)

npm install --save @maticnetwork/maticjs

util.js

Initiating Maticjs client

const bn = require("bn.js"); const HDWalletProvider = require("@truffle/hdwallet-provider");   const Network = require("@maticnetwork/meta/network"); const Matic = require("@maticnetwork/maticjs").default;   const SCALING_FACTOR = new bn(10).pow(new bn(18));   async function getMaticClient(_network = "testnet", _version = "mumbai") { const network =newNetwork(_network, _version); const{from}=getAccount(); const matic =newMatic({ network: _network, version: _version, parentProvider: new HDWalletProvider( process.env.PRIVATE_KEY, network.Main.RPC ), maticProvider: new HDWalletProvider( process.env.PRIVATE_KEY, network.Matic.RPC ), parentDefaultOptions: { from }, maticDefaultOptions: { from }, }); await matic.initialize(); return{ matic, network }; }   function getAccount() { if(!process.env.PRIVATE_KEY||!process.env.FROM){ thrownewError("Please set the PRIVATE_KEY/FROM env vars"); } return{ privateKey: process.env.PRIVATE_KEY,from: process.env.FROM}; }   module.exports = { SCALING_FACTOR, getMaticClient, getAccount, };

process.env

Create a new file in root directory name it process.env

PRIVATE_KEY = "" FROM = ""

deposit.js

deposit: Deposit can be done by calling depositEther on depositManagerContract contract.

Note that token needs to be mapped and approved for transfer beforehand.

depositEther method to make this call.

const utils = require('./utils')   async function execute() { const{ matic, network }=await utils.getMaticClient() const{from}= utils.getAccount()   const token = network.Main.Contracts.Tokens.MaticWeth const amount = matic.web3Client.web3.utils.toWei('1.567')   // deposit await matic.depositEther(token,from, amount)).then((res)=>{ console.log("deposit hash: ", res.transactionHash) }) } execute().then(_ => process.exit(0))

transfer.js

ETH on matic network is a WETH(ERC20 Token).

recipient is the receiver’s address, to whom the funds are supposed to be sent.

const utils = require("./utils");   async function execute() { const{ matic, network }=await utils.getMaticClient(); const{from}= utils.getAccount();   const recipient ="< >";   const amount = matic.web3Client.web3.utils.toWei("1.23");   await matic .transferEther(recipient, amount,{from, parent:false}) .then((res)=>{ console.log("Transfer hash: ", res.transactionHash); }); }   execute().then((_) => process.exit(0));

Withdraw

1. Burn

User can call withdraw function of getERC20TokenContract child token contract. This function should burn the tokens. Matic Plasma client exposes startWithdraw method to make this call.

const utils = require("./utils");   async function execute() { const{ matic, network }=await utils.getMaticClient(); const{from}= utils.getAccount();   const token = network.Matic.Contracts.Tokens.MaticWeth; const amount = matic.web3Client.web3.utils.toWei("5.678");   await matic.startWithdraw(token, amount,{from}).then((res)=>{ console.log("Burn hash: ", res.transactionHash); }); }   execute().then((_) => process.exit(0));

2. confirm-withdraw.js

User can call startExitWithBurntTokens function of erc20Predicate contract. This function should burn the tokens. Matic Plasma client exposes withdraw method to make this call.

//Wait for 5 mins till the checkpoint is submitted for burned transaction, then run the confirm withdraw

const utils = require("./utils");   async function execute() { const{ matic }=await utils.getMaticClient(); const{from}= utils.getAccount();   // Submit proof of burn on Main Chain const txHash ="<>"; await matic.withdraw(txHash,{from, gas:"7000000"}).then((res)=>{ console.log("Confirm withdraw hash: ", res.transactionHash); }); } // Withdraw process is completed, funds will be transfered to your account after challege period is over. execute().then((_) => process.exit(0));

3. Process Exit

Once the Challenge Period has been passed for the transaction present in checkpoint, user should call the processExits function of withdrawManager contract and submit the proof of burn. Upon submitting valid proof tokens are transferred to the user. Matic Plasma client exposes processExits method to make this call.

const utils = require("./utils");   async function execute() { const{ matic, network }=await utils.getMaticClient(); const{from}= utils.getAccount();   const token = network.Main.Contracts.Tokens.MaticWeth; await matic.processExits(token,{from, gas:7000000}).then((res)=>{ console.log("Exit hash: ", res.transactionHash); }); }   execute().then((_) => process.exit(0));

Note: 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.

ERC20 Deposit and Withdraw Guide

High Level Flow

Deposit ERC20 (2 step process)

  1. The tokens need to be first approved to the Matic rootchain contract on Parent Chain(Etheruem/Goerli).
  2. 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.

Transfer ERC20

Once you have funds on Matic, you can use those funds to send to others instantly.

Withdraw ERC20 (3 step process)

  1. Withdrawal of funds is initiated from Matic Network. A checkpoint interval of 30 mins(For testnets wait for ~10 minutes) is set, where all the blocks on the Matic block layer are validated since the last checkpoint.
  2. Once the checkpoint is submitted to the mainchain ERC20 contract, an NFT Exit (ERC721) token is created of equivalent value. Users need to wait for a 7 day challenge period (For testnets wait for ~5 minutes for)
  3. Once the challenge period is complete, the withdrawn funds can be claimed back to your ERC20 acccount 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 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.

Setup Details

Configuring Matic SDK

Install Matic SDK (2.0.2)

npm install --save @maticnetwork/maticjs

util.js

Initiating Maticjs client

const bn = require("bn.js"); const HDWalletProvider = require("@truffle/hdwallet-provider");   const Network = require("@maticnetwork/meta/network"); const Matic = require("@maticnetwork/maticjs").default;   const SCALING_FACTOR = new bn(10).pow(new bn(18));   async function getMaticClient(_network = "testnet", _version = "mumbai") { const network =newNetwork(_network, _version); const{from}=getAccount(); const matic =newMatic({ network: _network, version: _version, parentProvider: new HDWalletProvider( process.env.PRIVATE_KEY, network.Main.RPC ), maticProvider: new HDWalletProvider( process.env.PRIVATE_KEY, network.Matic.RPC ), parentDefaultOptions: { from }, maticDefaultOptions: { from }, }); await matic.initialize(); return{ matic, network }; }   function getAccount() { if(!process.env.PRIVATE_KEY||!process.env.FROM){ thrownewError("Please set the PRIVATE_KEY/FROM env vars"); } return{ privateKey: process.env.PRIVATE_KEY,from: process.env.FROM}; }   module.exports = { SCALING_FACTOR, getMaticClient, getAccount, };

process.env

Create a new file in root directory name it process.env

PRIVATE_KEY = "" FROM = ""

deposit.js

Approve: This is a normal ERC20 approval so that depositManagerContract can call transferFrom function. Matic Plasma client exposes approveERC20TokensForDeposit method to make this call.

deposit: Deposit can be done by calling depositERC20ForUser on depositManagerContract contract.

Note that token needs to be mapped and approved for transfer beforehand.

depositERC20ForUser method to make this call.

const utils = require('./utils')   async function execute() { const{ matic, network }=await utils.getMaticClient() const{from}= utils.getAccount()   const token = network.Main.Contracts.Tokens.TestToken const amount = matic.web3Client.web3.utils.toWei('1.567')   // approve await matic.approveERC20TokensForDeposit(token, amount).then((res)=>{ console.log("approve hash: ", res.transactionHash) })   // deposit await matic.depositERC20ForUser(token,from, amount)).then((res)=>{ console.log("deposit hash: ", res.transactionHash) }) } execute().then(_ => process.exit(0))

transfer.js

recipient is the receiver’s address, to whom the funds are supposed to be sent.

const utils = require("./utils");   async function execute() { const{ matic, network }=await utils.getMaticClient(); const{from}= utils.getAccount();   const recipient ="<>";   const childTokenAddress = network.Matic.Contracts.Tokens.TestToken; const amount = matic.web3Client.web3.utils.toWei("1.23");   await matic .transferERC20Tokens(childTokenAddress, recipient, amount,{ from, parent: false, }) .then((res)=>{ console.log("Transfer hash: ", res.transactionHash); }); }   execute().then((_) => process.exit(0));

Withdraw

1. Burn

User can call withdraw function of getERC20TokenContract child token contract. This function should burn the tokens. Matic Plasma client exposes startWithdraw method to make this call.

const utils = require("./utils");   async function execute() { const{ matic, network }=await utils.getMaticClient(); const{from}= utils.getAccount();   const token = network.Matic.Contracts.Tokens.TestToken; const amount = matic.web3Client.web3.utils.toWei("5.678");   await matic.startWithdraw(token, amount,{from}).then((res)=>{ console.log("Burn hash: ", res.transactionHash); }); }   execute().then((_) => process.exit(0));

2. confirm-withdraw.js

User can call startExitWithBurntTokens function of erc20Predicate contract. This function should burn the tokens. Matic Plasma client exposes withdraw method to make this call.

//Wait for ~10 mins for Mumbai testnet or ~30mins for Ethereum Mainnet till the checkpoint is submitted for burned transaction, then run the confirm withdraw const utils = require("./utils");   async function execute() { const{ matic }=await utils.getMaticClient(); const{from}= utils.getAccount();   // Submit proof of burn on Main Chain const txHash ="<>"; await matic.withdraw(txHash,{from, gas:"7000000"}).then((res)=>{ console.log("Confirm withdraw hash: ", res.transactionHash); }); } // Withdraw process is completed, funds will be transfered to your account after challege period is over. execute().then((_) => process.exit(0));

3. Process Exit

Once the Challenge Period has been passed for the transaction present in checkpoint, user should call the processExits function of withdrawManager contract and submit the proof of burn. Upon submitting valid proof tokens are transferred to the user. Matic Plasma client exposes processExits method to make this call.

const utils = require("./utils");   async function execute() { const{ matic, network }=await utils.getMaticClient(); const{from}= utils.getAccount();   const token = network.Main.Contracts.Tokens.TestToken; await matic.processExits(token,{from, gas:7000000}).then((res)=>{ console.log("Exit hash: ", res.transactionHash); }); }   execute().then((_) => process.exit(0));

Note: A checkpoint, which is a representation of all transactions happening on the Matic Network to the ERC20 chain every ~30 minutes, is submitted to the mainchain ERC20 contract.

Note: Once the checkpoint is submitted, user needs to wait for a challenge period of 7 days long.

 

API

  • new Matic()
  • matic.balanceOfERC20()
  • matic.balanceOfERC721()
  • matic.tokenOfOwnerByIndexERC721()
  • matic.depositEther()
  • matic.approveERC20TokensForDeposit()
  • matic.depositERC20ForUser()
  • matic.safeDepositERC721Tokens()
  • matic.transferERC20Tokens()
  • matic.transferERC721Tokens()
  • matic.startWithdraw()
  • matic.startWithdrawForNFT()
  • matic.withdraw()
  • matic.withdrawNFT()
  • matic.getTransferSignature()
  • matic.transferWithSignature()
  • matic.processExits()
WithdrawManager
  • matic.withdrawManager.startExitForMintableBurntToken()
  • matic.withdrawManager.startExitForMetadataMintableBurntToken()

new Matic(options)

Creates Matic SDK instance with give options. It returns a MaticSDK object.

import Matic from 'maticjs' const matic = new Matic(options)matic.initialize()

  • options is simple Javascript object which can have following fields:
    • maticProvider can be string or Web3.providers instance. This provider must connect to Matic chain. Value can be anyone of following:
      • 'https://rpc-mumbai.matic.today'
      • new Web3.providers.HttpProvider('http://localhost:8545')
      • WalletConnect Provider instance
    • parentProvider can be string or Web3.providers instance. This provider must connect to Ethereum chain (testnet or mainchain). Value can be anyone of following:
      • 'https://ropsten.infura.io'
      • new Web3.providers.HttpProvider('http://localhost:8545')
      • WalletConnect Provider instance
    • rootChain must be valid Ethereum contract address.
    • registry must be valid Ethereum contract address.
    • withdrawManager must be valid Ethereum contract address.
    • depositManager must be valid Ethereum contract address.

matic.balanceOfERC20(userAddress, token, options)

get balance of ERC20 token for address.

  • token must be valid token address
  • userAddress must be valid user address
  • options see more infomation here
    • parent must be boolean value. For balance on Main chain, use parent: true

This returns balance.

Example:

matic.balanceOfERC20('0xABc578455...','0x5E9c4ccB05...',{from:'0xABc578455...',}).then(balance=>{console.log('balance', balance)})

matic.balanceOfERC721(userAddress, token, options)

get balance of ERC721 token for address.

  • token must be valid token address
  • userAddress must be valid user address
  • options see more infomation here
    • parent must be boolean value. For balance on Main chain, use parent: true

This returns balance.

Example:

matic.balanceOfERC721('0xABc578455...','0x5E9c4ccB05...',{from:'0xABc578455...',}).then(balance=>{console.log('balance', balance)})

matic.tokenOfOwnerByIndexERC721(userAddress, token, index, options)

get ERC721 tokenId at index for token and for address.

  • token must be valid token address
  • userAddress must be valid user address
  • index index of tokenId

This returns matic tokenId.

Example:

matic.tokenOfOwnerByIndexERC721('0xfeb14b...','21',0,{from:'0xABc578455...',}).then(tokenID=>{console.log('Token ID', tokenID)})

matic.depositEthers(amount, options)

Deposit options.value

  • amount must be token amount in wei (string, not in Number)
  • options see more infomation here.
    • from must be valid account address(required)
    • encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: true

This returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).

Example:

matic.depositEthers(amount, {from:'0xABc578455...',})

matic.approveERC20TokensForDeposit(token, amount, options)

Approves given amount of token to rootChainContract.

  • token must be valid ERC20 token address
  • amount must be token amount in wei (string, not in Number)
  • options (optional) must be valid javascript object containing fromgasPricegasLimitnoncevalueonTransactionHashonReceipt or onError
    • from must be valid account address(required)
    • gasPrice same as Ethereum sendTransaction
    • gasLimit same as Ethereum sendTransaction
    • nonce same as Ethereum sendTransaction
    • value contains ETH value. Same as Ethereum sendTransaction. This returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).

Example:

matic.approveERC20TokensForDeposit('0x718Ca123...', '1000000000000000000', {from:'0xABc578455...',})

matic.depositERC20ForUser(token, user, amount, options)

Deposit given amount of token with user user.

  • token must be valid ERC20 token address
  • user must be value account address
  • amount must be token amount in wei (string, not in Number)
  • options see more infomation here
    • encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: true

This returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).

Example:

const user = or  matic.depositToken('0x718Ca123...', user, '1000000000000000000', {from:'0xABc578455...'})

matic.safeDepositERC721Tokens(token, tokenId, options)

Deposit given TokenID of token with user user.

  • token must be valid ERC20 token address
  • tokenId must be valid token ID
  • options see more infomation here

This returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).

Example:

matic.safeDepositERC721Tokens('0x718Ca123...', '70000000000', {from:'0xABc578455...',})

matic.transferERC20Tokens(token, user, amount, options)

Transfer given amount of token to user.

  • token must be valid ERC20 token address
  • user must be value account address
  • amount must be token amount in wei (string, not in Number)
  • options see more infomation here
    • parent must be boolean value. For token transfer on Main chain, use parent: true
    • encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: true

This returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).

Example:

const user = or  matic.transferERC20Tokens('0x718Ca123...', user, '1000000000000000000', {from:'0xABc578455...', // For token transfer on Main network// parent: true})

matic.transferERC721Tokens(token, user, tokenId, options)

Transfer given tokenId of token to user.

  • token must be valid ERC721 token address
  • user must be value account address
  • tokenId must be token amount in wei (string, not in Number)
  • options see more infomation here
    • parent must be boolean value. For token transfer on Main chain, use parent: true
    • encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: true

This returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).

Example:

const user = or  matic.transferERC721Tokens('0x718Ca123...', user, '100006500000000000000', {from:'0xABc578455...', // For token transfer on Main network// parent: true})

matic.startWithdraw(token, amount, options)

Start withdraw process with given amount for token.

  • token must be valid ERC20 token address
  • amount must be token amount in wei (string, not in Number)
  • options see more infomation here
    • encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: true

This returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).

Example:

matic.startWithdraw('0x718Ca123...', '1000000000000000000', {from:'0xABc578455...',})

matic.startWithdrawForNFT(token, tokenId, options)

Start withdraw process with given tokenId for token.

  • token must be valid ERC721 token address
  • tokenId must be token tokenId (string, not in Number)
  • options see more infomation here
    • encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: true

This returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).

Example:

matic.startWithdrawForNFT('0x718Ca123...', '1000000000000000000', {from:'0xABc578455...',})

matic.withdraw(txId, options)

Withdraw tokens on mainchain using txId from startWithdraw method after header has been submitted to mainchain.

  • txId must be valid tx hash
  • options see more infomation here

This returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).

Example:

matic.withdraw('0xabcd...789', {from:'0xABc578455...',})

matic.withdrawNFT(txId, options)

Withdraw tokens on mainchain using txId from startWithdraw method after header has been submitted to mainchain.

  • txId must be valid tx hash
  • options see more infomation here
    • encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: true

This returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).

Example:

matic.withdrawNFT('0xabcd...789', {from:'0xABc578455...',})

matic.getTransferSignature

Off-chain signature generation for transferWithSig function call

  • toSell object

    • token: address of token owned,
    • amount: amount/tokenId of the token to sell,
    • expiry: expiry (block number after which the signature should be invalid),
    • orderId: a random 32 byte hex string,
    • spender: the address approved to execute this transaction
  • toBuy object

    • token: address of token to buy
    • amount: amount/tokenId of token to buy
  • options see more infomation here

    • from: owner of the token (toSell)
    // sell orderlet toSell = {token: token2,amount: value2,expiry: expire,orderId: orderId,spender: spender,} // buy orderlet toBuy = {token: token1,amount: value1,} const sig = await matic.getTransferSignature(toSell, toBuy, {from: tokenOwner,})

matic.transferWithSignature

Executes transferWithSig on child token (erc20/721). Takes input as signature generated from matic.getTransferSignature

  • sig: signature generated with matic.getTransferSignature
  • toSell: object
    • token: address of token owned,
    • amount: amount/tokenId of the token to sell,
    • expiry: expiry (block number after which the signature should be invalid),
    • orderId: a random 32 byte hex string,
    • spender: the address approved to execute this transaction
  • toBuy: object
    • token: address of token to buy
    • amount: amount/tokenId of token to buy
  • orderFiller: address of user to transfer the tokens to
  • options see more infomation here
    • from: the approved spender in the toSell object by the token owner

transfers toSell.token from tokenOwner to orderFiller

// sell orderlet toSell = {token: token2,amount: value2,expiry: expire,orderId: orderId,spender: spender,} // buy orderlet toBuy = {token: token1,amount: value1,} const tx = await matic.transferWithSignature(sig, // signature with the intent to buy tokenstoSell, // sell ordertoBuy, // buy orderorderFiller, // order fulfiller{from: spender,// approved spender})

matic.processExits(rootTokenAddress, options)

Call processExits after completion of challenge period, after that withdrawn funds get transfered to your account on mainchain

  • rootTokenAddress RootToken address
  • options see more infomation here
    • encodeAbi must be boolean value. For Byte code of transaction, use encodeAbi: true

This returns Promise object, which will be fulfilled when transaction gets confirmed (when receipt is generated).

Example:

matic.processExits('0xabcd...789', {from:'0xABc578455...',})

WithdrawManager

matic.withdrawManager.startExitForMintableBurntToken(burnTxHash, predicate: address, options)

/*** Start an exit for a token that was minted and burnt on the side chain* Wrapper over contract call: MintableERC721Predicate.startExitForMintableBurntToken* @param burnTxHash Hash of the burn transaction on Matic* @param predicate address of MintableERC721Predicate*/

See MintableERC721Predicate.startExitForMintableBurntToken const burn = await this.maticClient.startWithdrawForNFT(childErc721.address, tokenId)await this.maticClient.withdrawManager.startExitForMintableBurntToken(burn.transactionHash, predicate.address)

matic.withdrawManager.startExitForMintableBurntToken(burnTxHash, predicate: address, options)

/*** Start an exit for a token with metadata (token uri) that was minted and burnt on the side chain* Wrapper over contract call: MintableERC721Predicate.startExitForMetadataMintableBurntToken* @param burnTxHash Hash of the burn transaction on Matic* @param predicate address of MintableERC721Predicate*/

See MintableERC721Predicate.startExitForMetadataMintableBurntToken const burn = await this.maticClient.startWithdrawForNFT(childErc721.address, tokenId)await this.maticClient.withdrawManager.startExitForMetadataMintableBurntToken(burn.transactionHash, predicate.address)

Support

Please write to [email protected] for integration support. If you have any queries, feedback or feature requests, feel free to reach out to us on telegram: t.me/maticnetwork  

Regulation and Society adoption

Ждем новостей

Нет новых страниц

Следующая новость