Mantle 백서

Mantle

원문

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

${(new Date() - start) / 1000} seconds`); await crossChainMessenger.waitForMessageStatus( response.hash, mantleSDK.MessageStatus.READY_TO_PROVE, ); ``` Wait until the state that includes the transaction gets past the challenge period, at which time we can finalize (also known as claim) the transaction. (Make sure your service and network are running well) ```javascript console.log(`Time so far ${(new Date() - start) / 1000} seconds`); await crossChainMessenger.proveMessage(response.hash); 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, ); ``` Finalizing the message also takes a bit of time. ```javascript console.log('Ready for relay, finalizing message now'); console.log(`Time so far ${(new Date() - start) / 1000} seconds`); await crossChainMessenger.finalizeMessage(response.hash); 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, ); ``` ### Invoke deposit and withdraw functions[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-mnt#invoke-deposit-and-withdraw-functions) <a href="#invoke-deposit-and-withdraw-functions" id="invoke-deposit-and-withdraw-functions"></a> We write a `main()` where we call the functions to perform configuration, deposit, and withdraw operations. ```javascript const main = async () => { await setup(); await depositMNT(); await withdrawMNT(); }; main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); ``` ## Conclusion[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-mnt#conclusion) <a href="#conclusion" id="conclusion"></a> You should now be able to write applications that use our SDK and bridge to transfer MNT between L1 and L2. # Bridging ETH with the Mantle SDK {% hint style="info" %} If you want to test the functionality of the Mantle SDK, we recommend using the testnet environment instead of the mainnet environment. The challenge period will be much shorter in the testnet (\~40 minutes) than in the mainnet (7 days). {% endhint %} This tutorial guides you on using the Mantle SDK to transfer ETH between layer 1 (L1) and layer 2 (L2). Check the complete code [here](https://github.com/mantlenetworkio/mantle-tutorial/blob/main/cross-dom-bridge-eth/index.js). ## Setup[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-eth#setup) <a href="#setup" id="setup"></a> 1. Ensure that your computer has the following installed: * [`git`](https://git-scm.com/downloads) * [`node`](https://nodejs.org/en/) * [`yarn`](https://classic.yarnpkg.com/lang/en/docs/install/#mac-stable) * [`docker`](https://www.docker.com/products/docker-desktop/) 2. Start L1 and L2 environments. Currently, we support the local environment or the testnet environment. If you want to deploy your own L1 and L2, please follow the instructions below. ```sh git clone https://github.com/mantlenetworkio/mantle-v2.git cd mantle/ops make up # check status make ps ``` **We highly recommend using the testnet environment, which means you can skip this step, you can apply your own L1 RPC** [**here**](https://www.alchemy.com/) **and replace the L1 RPC URL in the `.env` file.** 3. Clone this repository and navigate to it. ```sh git clone https://github.com/mantlenetworkio/mantle-tutorial.git cd mantle-tutorial/cross-dom-bridge-eth ``` 4. Install the necessary packages. ```sh yarn ``` ## Run the Sample Code[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-eth#run-the-sample-code) <a href="#run-the-sample-code" id="run-the-sample-code"></a> The sample code is in `index.js`, the whole execution flow will automatically start after running it. ### Node Environment[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-eth#node-environment) <a href="#node-environment" id="node-environment"></a> If you want to test by using your own nodes, you should configure the missing or changing environment variables in file `.env.local.tmp` then use `yarn local` to execute `index.js`. If you want to have a test in our testnet network you should do the same for `.env.testnet.tmp` and then use `yarn testnet` to execute `index.js`. ## How Does It Work?[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-eth#how-does-it-work) <a href="#how-does-it-work" id="how-does-it-work"></a> ### Import the Necessary Libraries[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-eth#import-the-necessary-libraries) <a href="#import-the-necessary-libraries" id="import-the-necessary-libraries"></a> ```javascript const ethers = require('ethers'); const mantleSDK = require('@mantleio/sdk'); ``` In this tutorial, we initialize the required libraries: * `ethers`: A JavaScript library for interacting with the Ethereum blockchain. It provides an easy-to-use interface for tasks like creating wallets, sending transactions, and interacting with smart contracts. * `mantleSDK`: The Mantleio SDK, which facilitates cross-chain transactions between Layer 1 (L1) and Layer 2 (L2) blockchains. It abstracts away complexities, making it easier to perform operations like depositing and withdrawing assets. ### Network Configuration and Wallet Setup[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-eth#network-configuration-and-wallet-setup) <a href="#network-configuration-and-wallet-setup" id="network-configuration-and-wallet-setup"></a> Next, the code defines some configuration parameters. We fetch the specified network and wallet configurations from the `.env` file. ```javascript const key = process.env.PRIV_KEY; const l2ETH = process.env.L2_ETH; ``` * `key`: The private key retrieved from the environment variables. * `l2ETH`: The address of the L2 ETH token. ```javascript // Global variable because we need them almost everywhere let crossChainMessenger; let addr; // Our address ``` * `crossChainMessenger`: A global variable initialized later in the `setup` function, representing the Mantle SDK's `CrossChainMessenger` object. * `addr`: A variable that will store the user's address. Then create wallet objects by passing the private key and RPC addresses as parameters for L1 and L2. ```javascript 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); ``` ### Setup CrossChainMessenger Object[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-eth#setup-crosschainmessenger-object) <a href="#setup-crosschainmessenger-object" id="setup-crosschainmessenger-object"></a> 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. ```javascript const setup = async () => { addr = l1Wallet.address crossChainMessenger = new mantleSDK.CrossChainMessenger({ l1ChainId: process.env.L1_CHAINID, l2ChainId: process.env.L2_CHAINID, l1SignerOrProvider: l1Wallet, l2SignerOrProvider: l2Wallet, bedrock: true, }) } ...... ``` ### Report the Balances[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-eth#report-the-balances) <a href="#report-the-balances" id="report-the-balances"></a> 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. ```javascript const reportBalances = async () => { const l1Balance = await crossChainMessenger.l1Signer.getBalance(); const ETH = new ethers.Contract(l2ETH, erc20ABI, l2Wallet); const l2Balance = await ETH.balanceOf( crossChainMessenger.l2Signer.getAddress(), ); console.log(`On L1:${l1Balance} On L2:${l2Balance} `); }; ``` ### Deposit[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-eth#deposit) <a href="#deposit" id="deposit"></a> The `depositETH` function deposits 0.01 ETH token to L2 via the Mantle bridge. The asynchronous function prints out the transaction hash and waits for the message to get relayed. Finally, we display the updated ETH balance on L1 and L2. To show that the deposit actually happened we show before and after balances. ```javascript console.log('Deposit ETH'); await reportBalances(); ``` `crossChainMessenger.depositETH()` creates and sends the deposit transaction on L1. ```javascript const start = new Date(); const response = await crossChainMessenger.depositETH(eth); ``` Of course, it takes time for the transaction to actually be processed on L1. ```javascript console.log(`Transaction hash (on L1): ${response.hash}`); await response.wait(); ``` After the transaction is processed on L1 it needs to be picked up by an off-chain service and relayed to L2. To show that the deposit actually happened we need to wait until the message is relayed. ```javascript 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, ); ``` Once the message is relayed the balance change on L2 is practically instantaneous. We can just report the balances and see that the L2 balance rose by 0.01 ETH. ```javascript await reportBalances(); console.log(`depositETH took ${(new Date() - start) / 1000} seconds\n\n`); ``` ### Withdraw[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-eth#withdraw) <a href="#withdraw" id="withdraw"></a> This function shows how to withdraw ETH from L2 to L1. To show that the withdrawal actually happened we show before and after balances. ```javascript console.log('#################### Withdraw ETH ####################'); await reportBalances(); ``` We need to make sure the allowance is approved. We can do that by sending an approval transaction on L1. ```javascript const approve = await crossChainMessenger.approveERC20( ethers.constants.AddressZero, l2ETH, doubleeth, {signer: l2Wallet, gasLimit: 300000}, ); console.log(`Approve transaction hash (on L2): ${approve.hash}`); ``` Then we withdraw the token from L2. ```javascript const response = await crossChainMessenger.withdrawERC20( ethers.constants.AddressZero, l2ETH, eth, {gasLimit: 300000}, ); console.log(`Transaction hash (on L2): ${response.hash}`); await response.wait(); ``` We need to wait until the message is ready to prove. ```javascript console.log('Waiting for status to be READY_TO_PROVE'); console.log(`Time so far ${(new Date() - start) / 1000} seconds`); await crossChainMessenger.waitForMessageStatus( response.hash, mantleSDK.MessageStatus.READY_TO_PROVE, ); ``` Wait until the state that includes the transaction gets past the challenge period, at which time we can finalize (also known as claim) the transaction. (Make sure your service and network are running well) ```javascript console.log(`Time so far ${(new Date() - start) / 1000} seconds`); await crossChainMessenger.proveMessage(response.hash); 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, 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, ); ``` Finalizing the message also takes a bit of time. ```javascript console.log('Ready for relay, finalizing message now'); console.log(`Time so far ${(new Date() - start) / 1000} seconds`); await crossChainMessenger.finalizeMessage(response.hash); 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, ); ``` ### Invoke deposit and withdraw functions <a href="#main" id="main"></a> We write a `main()` where we call the functions to perform configuration, deposit, and withdraw operations. ```javascript const main = async () => { await setup(); await depositETH(); await withdrawETH(); }; main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); ``` ## Conclusion[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-eth#conclusion) <a href="#conclusion" id="conclusion"></a> You should now be able to write applications using our SDK and bridge to transfer ETH between L1 and L2. # Bridging ERC-20 tokens with the Mantle SDK {% hint style="info" %} If you want to test the functionality of the Mantle SDK, we recommend using the testnet environment instead of the mainnet environment. The challenge period will be much shorter in the testnet (\~40 minutes) than in the mainnet (7 days). {% endhint %} This tutorial teaches you how to use the Mantle SDK to transfer ERC-20 tokens between layer 1 (L1) and layer 2 (L2). While you *could* use [the bridge contracts](https://github.com/mantlenetworkio/mantle-v2/blob/develop/packages/contracts/contracts/L1/messaging/L1StandardBridge.sol) directly. Check the complete code [here](https://github.com/mantlenetworkio/mantle-tutorial/blob/main/cross-dom-bridge-erc20/index.js). ## Setup[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-erc20#setup) <a href="#setup" id="setup"></a> 1. Ensure your computer has: * [`git`](https://git-scm.com/downloads) * [`node`](https://nodejs.org/en/) * [`yarn`](https://classic.yarnpkg.com/lang/en/docs/install/#mac-stable) * [`docker`](https://www.docker.com/products/docker-desktop/) 2. Start L1 and L2 environments. Currently, we support the local environment or the testnet environment. If you want to deploy your own L1 and L2, please follow the instructions below. ```sh git clone https://github.com/mantlenetworkio/mantle-v2.git cd mantle/ops make up # check status make ps ``` **We highly recommend using the testnet environment, which means you can skip this step, you can apply your own L1 RPC** [**here**](https://www.alchemy.com/) **and replace the L1 RPC URL in the `.env` file.** 3. Clone this repository and enter it. ```sh git clone https://github.com/mantlenetworkio/mantle-tutorial.git cd mantle-tutorial/cross-dom-bridge-erc20 ``` 4. Install the necessary packages. ```sh yarn ``` ## Run the sample code[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-erc20#run-the-sample-code) <a href="#run-the-sample-code" id="run-the-sample-code"></a> The sample code is in `index.js`, the whole execution flow will automatically start after running it. ### Node Environment[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-erc20#node-environment) <a href="#node-environment" id="node-environment"></a> If you want to test by using your own nodes, you should configure the missing or changing environment variables in file `.env.local.tmp` then use `yarn local` to execute `index.js`. If you want to have a test in our testnet network you should do the same for `.env.testnet.tmp` and then use `yarn testnet` to execute `index.js`. ## How does it work?[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-erc20#how-does-it-work) <a href="#how-does-it-work" id="how-does-it-work"></a> ### Import the Necessary Libraries[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-erc20#import-the-necessary-libraries) <a href="#import-the-necessary-libraries" id="import-the-necessary-libraries"></a> ```javascript const ethers = require('ethers'); const mantleSDK = require('@mantleio/sdk'); const fs = require('fs'); ``` In this tutorial, we initialize the required libraries: * `ethers`: A JavaScript library for interacting with the Ethereum blockchain. It provides an easy-to-use interface for tasks like creating wallets, sending transactions, and interacting with smart contracts. * `mantleSDK`: The Mantle SDK, which facilitates cross-chain transactions between Layer 1 (L1) and Layer 2 (L2) blockchains. It abstracts away complexities, making it easier to perform operations like depositing and withdrawing assets. * `fs`: The Node.js `fs` module for file system operations. It may be used later in the code for reading or writing files, although it's not explicitly used in the provided snippet. ### Network Configuration and Wallet Setup[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-erc20#network-configuration-and-wallet-setup) <a href="#network-configuration-and-wallet-setup" id="network-configuration-and-wallet-setup"></a> Next, the code defines some configuration parameters. We fetch the specified network and wallet configurations from the `.env` file. ```javascript const l1bridge = process.env.L1_BRIDGE; const l2bridge = process.env.L2_BRIDGE; const key = process.env.PRIV_KEY; ``` * `l1bridge` and `l2bridge`: Environment variables representing the addresses of the layer 1 (L1) and layer 2 (L2) bridges. * `key`: The private key retrieved from the environment variables. We need to deploy the ERC-20 token by ourselves, so we need to create a factory contract at first. ```javascript const L1TestERC20 = JSON.parse(fs.readFileSync('L1TestERC20.json')); const L2StandardERC20 = JSON.parse(fs.readFileSync('L2StandardERC20.json')); const factory__L1_ERC20 = new ethers.ContractFactory( L1TestERC20.abi, L1TestERC20.bytecode, ); const factory__L2_ERC20 = new ethers.ContractFactory( L2StandardERC20.abi, L2StandardERC20.bytecode, ); ``` The configuration parameters required for transfers. ```javascript // Global variable because we need them almost everywhere let crossChainMessenger; let l1ERC20, l2ERC20; let ourAddr; ``` Then create wallet objects by passing the private key and RPC addresses as parameters for L1 and L2. ```javascript 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); ``` ### Setup CrossChainMessenger Object[​](https://docs-v2.mantle.xyz/devs/dev-guides/how-to/bridge-erc20#setup-crosschainmessenger-object) <a href="#setup-crosschainmessenger-object" id="setup-crosschainmessenger-object"></a> 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. ```javascript ourAddr = l1Wallet.address; crossChainMessenger = new mantleSDK.CrossChainMessenger({ l1ChainId: process.env.L1_CHAINID, l2ChainId: process.env.L2_CHAINID, l1SignerOrProvider: l1Wallet, l2SignerOrProvider: l2Wallet, bedrock: true, }); ``` Deploy the ERC-20 token on L1. ```javascript console.log('#################### Deploy ERC20 ####################'); console.log('Deploying L1 ERC20...'); const L1_ERC20 = await factory__L1_ERC20 .connect(l1Wallet) .deploy('L1 TEST TOKEN', 'LTT'); await L1_ERC20.deployTransaction.wait(); console.log('L1 ERC20 Contract ExampleToken Address: ', L1_ERC20.address); ``` Mint the ERC-20 token on L1. ```javascript let amount = ethers.utils.parseEther('10'); await L1_ERC20.connect(l1Wallet).mint(amount); balance = ( await L1_ERC20.connect(l1Wallet).balanceOf(l1Wallet.address) ).toString(); console.log('mint to ', l1Wallet.address, balance, ' success'); ``` Approve the ERC-20 token on L1. ```javascript await L1_ERC20.connect(l1Wallet).approve(l1bridge, amount); let allowance = await
프로젝트로 돌아가기