Mantle 백서

Mantle

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 37쪽 중 36쪽

hat the tokens on the bridged layer are backed up by real tokens on the layer of original mint. It is also necessary that the ERC-20 token contract on the layer of original mint *not* implement either of the interfaces, to make sure the bridge contracts don't get confused and think it is the bridged layer. **Warning:** The standard bridge does *not* support certain ERC-20 configurations: * [Fee on transfer tokens](https://github.com/d-xo/weird-erc20#fee-on-transfer) * [Tokens that modify balances without emitting a Transfer event](https://github.com/d-xo/weird-erc20#balance-modifications-outside-of-transfers-rebasingairdrops) For the purpose we import the `L2StandardERC20` from the `@mantleio/contracts` package. This standard token implementation is based on the OpenZeppelin ERC20 contract and implements the required `IL2StandardERC20` interface. You can import `@mantleio/contracts` to use the Mantle contracts within your own codebase. Install via `npm` or `yarn`: ```bash npm install @mantleio/contracts ``` Within your contracts: ```javascript import { L2StandardERC20 } from "@mantleio/contracts/standards/L2StandardERC20.sol"; ``` ## Deploying the custom token 1. Download the necessary packages. ```bash yarn ``` 2. Copy `.env.example` to `.env`. ```bash cp .env.example .env ``` 3. Edit `.env` to set the deployment parameters: * `PRIVATE_KEY`, the hex private key for an account that has enough ETH for the deployment. * `L1_RPC`, Ethereum endpoint RPC URL. * `L2_RPC`, Mantle endpoint RPC URL. * `L1_BRIDGE`, L1 standard bridge contract address. * `L2_BRIDGE`, L2 standard bridge contract address. * `L1_TOKEN_ADDRESS`, the address of the L1 ERC20 which you want to bridge. The default value, [`0xeE7Bf96bFd25931976F45a16C4483d336169Bc0F`](https://goerli.etherscan.io/address/0xee7bf96bfd25931976f45a16c4483d336169bc0f) is a test ERC-20 contract on Goerli that lets you call `faucet` to give yourself test tokens. 4. Open the hardhat console. ```bash yarn hardhat console --network mantle-network ``` 5. Deploy the contract. ```javascript l2CustomERC20Factory = await ethers.getContractFactory("L2CustomERC20") l2CustomERC20 = await l2CustomERC20Factory.deploy( "0x4200000000000000000000000000000000000010", process.env.L1_TOKEN_ADDRESS) ``` ## Transferring tokens 1. Get the token addresses. ```javascript l1Addr = process.env.L1_TOKEN_ADDRESS l2Addr = l2CustomERC20.address ``` ### Get setup for L1 (provider, wallet, tokens, etc) 1. Get the L1 wallet. ```javascript l1RpcProvider = new ethers.providers.JsonRpcProvider(process.env.L1_RPC) const privateKey = process.env.PRIVATE_KEY l1Wallet = new ethers.Wallet(privateKey, l1RpcProvider) ``` 2. Get the L1 contract. ```javascript l1Factory = await ethers.getContractFactory("MantleUselessToken") l1Contract = new ethers.Contract(process.env.L1_TOKEN_ADDRESS, l1Factory.interface, l1Wallet) ``` 3. Get tokens on L1 (and verify the balance) ```javascript tx = await l1Contract.faucet() rcpt = await tx.wait() await l1Contract.balanceOf(l1Wallet.address) ``` ### Transfer tokens Create and use [`CrossDomainMessenger`](https://sdk.mantle.xyz/classes/CrossChainMessenger.html) (the Mantle SDK object used to bridge assets). 1. Import the Mantle SDK. ```javascript const mantleSDK = require("@mantleio/sdk") ``` 2. Create the cross domain messenger. ```javascript l1ChainId = (await l1RpcProvider.getNetwork()).chainId l2ChainId = (await ethers.provider.getNetwork()).chainId l2Wallet = await ethers.provider.getSigner() crossChainMessenger = new mantleSDK.CrossChainMessenger({ l1ChainId: l1ChainId, l2ChainId: l2ChainId, l1SignerOrProvider: l1Wallet, l2SignerOrProvider: l2Wallet, }) ``` #### **Deposit (from Goerli to Mantle Testnet, or Ethereum to Mantle Mainnet)** 1. Give the L2 bridge an allowance to use the user's token. The L2 address is necessary to know which bridge is responsible and needs the allowance. ```javascript depositTx1 = await crossChainMessenger.approveERC20(l1Contract.address, l2Addr, 1e9) await depositTx1.wait() ``` 2. Check your balances on L1 and L2. ```javascript await l1Contract.balanceOf(l1Wallet.address) await l2CustomERC20.balanceOf(l1Wallet.address) ``` 3. Do the actual deposit ```javascript depositTx2 = await crossChainMessenger.depositERC20(l1Contract.address, l2Addr, 1e9) await depositTx2.wait() ``` 4. Wait for the deposit to be relayed. ```javascript await crossChainMessenger.waitForMessageStatus(depositTx2.hash, mantleSDK.MessageStatus.RELAYED) ``` 5. Check your balances on L1 and L2. ```javascript await l1Contract.balanceOf(l1Wallet.address) await l2CustomERC20.balanceOf(l1Wallet.address) ``` #### Withdrawal (from Mantle Mainnet to Ethereum, or Mantle Testnet to Goerli) 1. Initiate the withdrawal on L2 ```javascript withdrawalTx1 = await crossChainMessenger.withdrawERC20(l1Contract.address, l2Addr, 1e9) await withdrawalTx1.wait() ``` 2. Wait until the root state is published on L1, and then prove the withdrawal. This is likely to take within 30 minutes. ```javascript await crossChainMessenger.waitForMessageStatus(withdrawalTx1.hash, mantleSDK.MessageStatus.READY_TO_PROVE) withdrawalTx2 = await crossChainMessenger.proveMessage(withdrawalTx1.hash) await withdrawalTx2.wait() ``` 3. Wait the fraud challenge period (a short period on Goerli, currently 7 days(but may be adjusted in the future which can be checked [here](https://etherscan.io/address/0x89E9D387555AF0cDE22cb98833Bae40d640AD7fa#readContract#F1)) on the production network) and then finish the withdrawal. ```javascript await crossChainMessenger.waitForMessageStatus(withdrawalTx1.hash, mantleSDK.MessageStatus.READY_FOR_RELAY) withdrawalTx3 = await crossChainMessenger.finalizeMessage(withdrawalTx1.hash) await withdrawalTx3.wait() ``` 4. Check your balances on L1 and L2. The balance on L2 should be back to zero. ```javascript await l1Contract.balanceOf(l1Wallet.address) await l2CustomERC20.balanceOf(l1Wallet.address) ``` ## Use Factory Contract to Deploy L2StandardERC20 {% hint style="warning" %} The token contracts deployed using Factory contract are standard `IL2StandardERC20` contracts and can only take the name "L2StandardERC20". If you want to use a different name and methods, you can inherit the L2StandardERC20 contract and deploy is as a custom contract. {% endhint %} 1. Call the `createStandardL2Token` method of the `L2StandardTokenFactory` contract by passing the `l1Token`, `name`, `symbol`, and `decimal` parameters. The mainnet factory contract is deployed at: [`0x4200000000000000000000000000000000000012`](https://explorer.mantle.xyz/address/0x4200000000000000000000000000000000000012) <figure><img src="https://3701411312-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNHXgeqhgrznnRobzznxl%2Fuploads%2Foj6eBjNhvHqSWSBBCver%2Fimage.png?alt=media&amp;token=e22273ec-d35e-4a78-89a0-10199756da71" alt=""><figcaption></figcaption></figure> 2. The corresponding contract address will be generated upon a successful call. The creation transaction can be found under the internal transaction tab on the Explorer. Examples: * Creation transaction: <https://explorer.mantle.xyz/tx/0x5c50ed69505fc472c3ead137e5845973ae277f50a7d5d89341f2a2692ae8cc80> * Newly created contract: <https://explorer.mantle.xyz/address/0x7c6b91D9Be155A6Db01f749217d76fF02A7227F2> <figure><img src="https://3701411312-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNHXgeqhgrznnRobzznxl%2Fuploads%2FvxIVUYKWm4SlH3Seb6y2%2Fimage.png?alt=media&amp;token=72e9a3ec-c304-47d5-bbdf-4ab450b100da" alt=""><figcaption></figcaption></figure> {% hint style="warning" %} Internal transactions on mainnet can take upto \~12 minutes before they show up on the Explorer. {% endhint %} 3. The contract verification status, contract code, and the relevant parameters can also be found on the Explorer. Example: <https://explorer.mantle.xyz/address/0x7c6b91D9Be155A6Db01f749217d76fF02A7227F2/contracts#address-tabs> <figure><img src="https://3701411312-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNHXgeqhgrznnRobzznxl%2Fuploads%2F8wTCuBRYPcR2EwxDVMsP%2Fimage.png?alt=media&amp;token=1358cd1f-5b95-44ff-8d8c-7d276c284ce6" alt=""><figcaption></figcaption></figure> # Bridging $MNT using Mantle SDK Deposit and withdraw $MNT using the SDK {% hint style="danger" %} Mantle v2 Tectonic has been released, please move to the new [documentation](https://docs-v2.mantle.xyz/)! {% endhint %} This tutorial demonstrates how to use the Mantle SDK to deposit and withdraw $MNT tokens between Mantle and Ethereum. ## Set up local environment Make sure you have the following tools installed in your local environment. * [Git](https://git-scm.com/downloads) * [Node](https://nodejs.org/en/) * [Yarn](https://classic.yarnpkg.com/en/docs/install) Let's start by fetching the example JS scripts that we’ll work with and use to make SDK invocations from the Mantle Github. Clone the repository containing the sample scripts by executing the following command in your project directory. ```bash git clone https://github.com/mantlenetworkio/mantle-tutorial.git ``` Next, we can use `yarn` to download the SDK along with all the necessary dependencies, as shown below. All the dependencies are defined in the `yarn.lock` file, so we can just run `yarn` in the `./cross-dom-bridge-mnt` directory. We'll need a `.env` file from where we can add and modify wallet and network settings. The main directory contains two `.env` files, where `.env.local` specifies the configuration for a local environment, while `.env.testnet` specifies the configuration to connect to testnet. All the necessary contracts addresses are already included in the respective `.env` files, so you can specify your preferred L1 RPC endpoint and your wallet private key to start sending transactions. ```env # testnet ENV EXEC_ENV=testnet # rpc url L1_RPC= # L1 RPC Endpoint L2_RPC=https://rpc.testnet.mantle.xyz # chain id L1_CHAINID=5 L2_CHAINID=5001 # bridge address L1_BRIDGE=0xc92470D7Ffa21473611ab6c6e2FcFB8637c8f330 L2_BRIDGE=0x4200000000000000000000000000000000000010 # crossDomainMessenger address L1_CDM=0x7Bfe603647d5380ED3909F6f87580D0Af1B228B4 L2_CDM=0x4200000000000000000000000000000000000007 # token address L1_MNT=0xc1dC2d65A2243c22344E725677A3E3BEBD26E604 L2_MNT=0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000 L2_ETH=0xdEAddEaDdeadDEadDEADDEAddEADDEAddead1111 # local test key PRIV_KEY= # Wallet private key ``` Let's take a look at the main script. ## Analyzing and modifying the sample script The `index.js` script containing the code we need is located in the `./mantle-tutorial/cross-dom-bridge-eth` directory. By default, it is configured to run on a local test environment. You can run L1 and L2 instances on your system and start deploying contracts to test your applications. You can make a copy of the `index.js` file before we start modifying it if you want to try that out. > Check out the [tutorial here](https://github.com/mantlenetworkio/mantle-tutorial/tree/main/cross-dom-bridge-mnt) that demonstrates the same bridging functionality on a private network. ### Importing necessary libraries ```js require('dotenv').config() const ethers = require("ethers") const mantleSDK = require("@mantleio/sdk") const fs = require("fs") ``` This code does not need to be changed. We import three libraries, and the `.env` configuration file we created earlier. * `dotenv` : The `.env` file containing wallet and network configuration * `ethers` : The Ethers.js library comes handy with wallet and contract operations * `@mantlenetwork/sdk` : Mantle SDK instance * `fs`: File system module to read the contract ABI from a JSON file ### Generating contract bytecode from ABI ```js const L1TestERC20 = JSON.parse(fs.readFileSync("TestERC20.json")) ``` We don't need to modify this either. The contents of the JSON file containing the contract ABI are stored in `TestERC20.json` which we will be using later. ### Network configuration and wallet setup ```js const l1MntAddr = process.env.L1_MNT const l2MntAddr = process.env.L2_MNT const key = process.env.PRIV_KEY const l1RpcProvider = new ethers.providers.JsonRpcProvider(process.env.L1_RPC) const l2RpcProvider = new ethers.providers.JsonRpcProvider(process.env.L2_RPC) const l1Wallet = new ethers.Wallet(key, l1RpcProvider) const l2Wallet = new ethers.Wallet(key, l2RpcProvider) ``` We fetch the specified network and wallet configurations from the `.env` file, and create wallet objects by passing the private key and RPC addresses as parameters for L1 and L2. ### CrossChainMessenger object ```js //Global variables let crossChainMessenger let l1Mnt, l2Mnt let ourAddr const setup = async () => { ourAddr = l1Wallet.address // Assigning wallet address crossChainMessenger = new mantleSDK.CrossChainMessenger({ // CrossChainMessenger object instantiation l1ChainId: process.env.L1_CHAINID, // Assigning chain IDs from .env file l2ChainId: process.env.L2_CHAINID, l1SignerOrProvider: l1Wallet, // Wallets that will sign transactions l2SignerOrProvider: l2Wallet }) l1Mnt = new ethers.Contract(l1MntAddr, L1TestERC20.abi, l1Wallet) // Contract objects l2Mnt = new ethers.Contract(l2MntAddr, L1TestERC20.abi, l2Wallet) } ``` The `CrossChainMessenger` object calls the cross chain messenger contracts on L1 and L2 to transfer assets. Here we instantiate the object with chain IDs, wallet objects, and contract objects. ### Reporting balances ```js const reportBalances = async () => { const l1Balance = (await l1Mnt.balanceOf(ourAddr)).toString().slice(0, -18) const l2Balance = (await l2Mnt.balanceOf(ourAddr)).toString().slice(0, -18) console.log(`Token on L1:${l1Balance} Token on L2:${l2Balance}`) } ``` The `reportBalances` function fetches L1 and L2 wallet balances and prints them out. We'll use this method to keep track balance change after deposit and withdraw operations. ### Deposit function ```js const depositMNT = async () => { console.log("#################### Deposit MNT ####################") await reportBalances() // 1. Print balance before deposit const start = new Date() const allowanceResponse = await crossChainMessenger.approveERC20( // 2. Approve deposit amount l1MntAddr, l2MntAddr, depositToken) await allowanceResponse.wait() console.log(`Time so far ${(new Date() - start) / 1000} seconds`) const response = await crossChainMessenger.depositERC20( // 3. Send deposit transaction l1MntAddr, l2MntAddr, depositToken) console.log(`Deposit transaction hash (on L1): ${response.hash}`) // 4. Print L1 deposit transaction hash await response.wait() console.log("Waiting for status to change to RELAYED") console.log(`Time so far ${(new Date() - start) / 1000} seconds`) await crossChainMessenger.waitForMessageStatus(response.hash, mantleSDK.MessageStatus.RELAYED) await reportBalances() // 5. Print updated balance after deposit console.log(`depositERC20 took ${(new Date() - start) / 1000} seconds\n`) } ``` The `depositMNT` function deposits 1 $MNT token to L2 via the Mantle bridge. The deposit transaction is sent using the `depositERC20` method, which is picked up by an off-chain service and relayed to L2. The asynchronous function prints out the transaction hash and waits for the message to get relayed. Finally, we display the updated $MNT balance on L1 and L2. ### Withdraw function ```js const withdrawMNT = async () => { console.log("#################### Withdraw MNT ####################") const start = new Date() await reportBalances() // 1. Print balance before withdraw const response = await crossChainMessenger.withdrawERC20( // 2. Send withdraw transaction l1MntAddr, l2MntAddr, withdrawToken) console.log(`Transaction hash (on L2): ${response.hash}`) // 3. Print L2 withdraw transaction hash await response.wait() console.log("Waiting for status to change to IN_CHALLENGE_PERIOD") console.log(`Time so far ${(new Date() - start) / 1000} seconds`) await crossChainMessenger.waitForMessageStatus(response.hash, // 4. Function waits for transaction to enter challenge period mantleSDK.MessageStatus.IN_CHALLENGE_PERIOD) console.log("In the challenge period, waiting for status READY_FOR_RELAY") console.log(`Time so far ${(new Date() - start) / 1000} seconds`) await crossChainMessenger.waitForMessageStatus(response.hash, mantleSDK.MessageStatus.READY_FOR_RELAY) // 5. Check whether transaction is ready for relay console.log("Ready for relay, finalizing message now") console.log(`Time so far ${(new Date() - start) / 1000} seconds`) await crossChainMessenger.finalizeMessage(response) console.log("Waiting for status to change to RELAYED") console.log(`Time so far ${(new Date() - start) / 1000} seconds`) await crossChainMessenger.waitForMessageStatus(response, mantleSDK.MessageStatus.RELAYED) // 6. Wait for transaction to get relayed await reportBalances() // 7. Print updated balance after withdraw console.log(`withdrawERC20 took ${(new Date() - start) / 1000} seconds\n\n\n`) } ``` Similarly, the `withdrawMNT` function withdraws 1 $MNT token from L2 via the Mantle bridge. The function prints out the transaction hash. The transaction then goes into a challenge period. Once it is ready for relay, it is picked up by an off-chain service to be relayed to L1. Finally, we display the updated $MNT balance on L1 and L2. ### Invoking deposit and withdraw functions ```js const main = async () => { await setup() await depositMNT() await withdrawMNT() } main().then(() => process.exit(0)) .catch((error) => { console.error(error) process.exit(1) }) ``` We write a `main()` where we call the functions to perform configuration, deposit, and withdraw operations. ### Running the script Once the configuration is ready, you can run the script using the `yarn testnet` command. The script will automatically select the testnet configuration to perform both deposit and withdraw operations in the `index.js` script. If you want to run the script locally, you can run `yarn local`. ## Conclusion You can use this code to test out the token bridging mechanism via SDK on Mantle testnet and start integrating it to your applications. # Estimating Transaction Fees A tutorial showing how to accurately estimate the total transaction fees for a transaction on Mantle Network {% hint style="danger" %} Mantle v2 Tectonic has been released, please move to the new [documentation](https://docs-v2.mantle.xyz/)! {% endhint %} ## Description In this tutorial, we'll be looking at an example that shows how to use the Mantle SDK to estimate the total gas fees for a transaction on Mantle Network, which is a combination of the layer-2 (L2) execution fee, and the layer-1 (L1) rollup fee. In SDK version [`@mantleio/sdk @0.2.2`](https://www.npmjs.com/package/@mantleio/sdk/v/0.2.2) , we're introducing the parameters required to make accurate estimations of the L1 rollup fee that will be incurred for sending a transaction at any given time. The calculation to obtain L1 rollup fee is as follows: ``` L1RollupFee = L1GasPrice * Overhead * Scalar * Ratio ``` There are 4 interfaces available as part of the SDK, where: * `L1GasPrice * Ratio` can be fetched by calling the `getL1GasPrice` method. It invokes the `l1basefee()` function of the [`BVM_GasPriceOracle`](<https://explorer.mantle.xyz/address/0x420000000000000000000000000000000000000F >) contract. * `overhead`, `decimals`, and `scalar` values can be fetched from the [`BVM_GasPriceOracle`](<https://explorer.mantle.xyz/address/0x420000000000000000000000000000000000000F >) contract by calling the respective SDK methods with the same names. {% hint style="info" %} The `decimals` value in the contract is mainly used to control the precision of `scalar`, which helps ensure accurate L1 rollup fee calculation. {% endhint %} The L2 execution fee, on the other hand, is calculated as follows: ``` L2TxnFee = L2GasPrice * L2GasUsed ``` * L2 gas
프로젝트로 돌아가기