Mantle 백서

Mantle

원문

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

o: > cast run --debug $TX\_HASH Taking this deposit transaction as an example: ```Bash cast run 0x16a3d14f54fc36097184b2b774b0d30e35e03e033805eb3180a0ee8d4c5427ef --debug ``` <figure><img src="https://3701411312-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNHXgeqhgrznnRobzznxl%2Fuploads%2FaXl1YadXuH4s9RxG1LHA%2Fimage.png?alt=media&amp;token=3702debe-a7b3-4c55-9bae-40e098063ad8" alt=""><figcaption></figcaption></figure> Learn more about the debugger interface here: <https://book.getfoundry.sh/forge/debugger> **cast block / cast tx** [`cast block`](https://book.getfoundry.sh/reference/cast/cast-block) can be used to fetch block information from the chain. Running `cast block` returns block info for the latest block. <figure><img src="https://3701411312-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNHXgeqhgrznnRobzznxl%2Fuploads%2FECK6o7u2E4hTR3pKWpoA%2Fimage.png?alt=media&amp;token=a746926c-53c4-4c26-bcd2-74770d16e433" alt=""><figcaption></figcaption></figure> [`cast tx`](https://book.getfoundry.sh/reference/cast/cast-tx) can be used to fetch transaction information from the chain using the transaction hash. The command structure is as follows: > cast tx $TX\_HASH **cast rpc** [`cast rpc`](https://book.getfoundry.sh/reference/cast/cast-rpc) can be used to send a raw JSON-RPC request to a node.Since Mantle Network supports Ethereum's JSON-RPC interface, you can use the following command to call `eth_getBlockByNumber` and fetch information for the latest block: > cast rpc --rpc-url <https://rpc.mantle.xyz/> eth\_getBlockByNumber "latest" "false" #### cast storage & cast index [`cast storage`](https://book.getfoundry.sh/reference/cast/cast-storage) can be used to fetch the raw value of a contract's storage slot. cast-index can compute the storage slot location for an entry in a mapping.The cast index calculates the storage location based on the KEY\_TYPE, KEY, and SLOT\_NUMBER.For example, to fetch the value of slot 0 for a contract: > cast storage $contract\_address 0 We'll take the balance of account 0x1858d52cf57c07A018171D7a1E68DC081F17144f about $WMNT as an example, which can be obtained in two ways: * **Conventional function call method** This has already been implemented in the aforementioned cast call. * **Reading contract slot storage method** First, based on the WMNT source code, it's determined that the balanceOf state variable is located at the 0th slot with KEY\_TYPE being 'address'. ```Solidity contract WMANTLE is ERC20 { constructor() ERC20("Wrapped Mantle", "WMNT") {} event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); ... contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; ... ``` ```Bash # For KEY 0x1858d52cf57c07A018171D7a1E68DC081F17144f and slot 0, the corresponding storage location. cast index address 0x1858d52cf57c07A018171D7a1E68DC081F17144f 0 //0x2edcadc9f197c279f92ccdbf8b108a59937d545e881935fccd2cb58923bc739b # Retrieve the raw data from the corresponding storage location, converting from address to integer, address=>int cast storage $WMNT 0x2edcadc9f197c279f92ccdbf8b108a59937d545e881935fccd2cb58923bc739b 0x00000000000000000000000000000000000000000006cfd1854e3ec57a5d636d ``` **cast abi-decode / cast abi-encode** [`cast abi-decode`](https://book.getfoundry.sh/reference/cast/cast-abi-decode) can be used to decode any ABI-encoded data. For example, to decode the output data for a `balanceOf` call: > cast abi-decode "balanceOf(address)(uint256)" \0x000000000000000000000000000000000000000000000000000000000000000a [`cast abi-encode`](https://book.getfoundry.sh/reference/cast/cast-abi-encode) can be used to ABI encode any given function arguments, excluding the selector. For example, to ABI-encode the arguments for a function call: > cast abi-encode "someFunc(address,uint256)" 0x... 1 ### forge #### 5.1 Initialize the project.**-forge init** > forge init \<dir\_name>forge init —template \<template\_path> \<dir\_name> <figure><img src="https://3701411312-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNHXgeqhgrznnRobzznxl%2Fuploads%2FJ6RF80ymA2iD2zDelleV%2Fimage.png?alt=media&amp;token=066aae18-3062-441d-baa5-1ac2be39f940" alt=""><figcaption></figcaption></figure> View the current directory structure. ```Plaintext (base) ➜ tree -L 2 . └── hello_foundry ├── foundry.toml ├── lib ├── script ├── src └── test ``` #### 5.2 **forge build** The corresponding compile command is ```Plaintext cd hello_foundry forge build forge build -w ``` Typically, two panes are opened in tmux. The first pane is used to view real-time coding status, monitoring in real-time with the `-w` option. In the second pane, code is written. After each code modification, once saved, the first pane will display in real-time whether the compilation has passed. #### 5.3 Automated testin&#x67;**-forge test** ```Plaintext # You can print logs using the -v level, -vv level, and -vvv level. forge test -v /-vv / -vvv # Use -w for watch mode. forge test -v /-vv / -vvv -w ``` For more detailed procedures on testing, please refer to. <https://book.getfoundry.sh/reference/forge/forge-test> #### Forge debug Forge ships with an interactive debugger. > forge debug --debug $FILE --sig $FUNC In the newly initialized project, we can enter the following command to enable the interactive debugger. ```Bash forge debug --debug Counter --sig "setNumber(uint256)" 5 ``` If you want to debug on the forked mainnet, you can enter the following command. ```Bash forge debug --debug Counter --sig "setNumber(uint256)" 5 -f http://127.0.0.1:8545 ``` or ```Bash forge debug --debug Counter --sig "setNumber(uint256)" 5 --fork-url https://rpc.mantle.xyz ``` **breakpoint** Places a breakpoint to jump to in the debugger view\.Calling `vm.breakpoint('<char>, true)` is equivalent to `vm.breakpoint('<char>)`, but calling `vm.breakpoint('<char, false)` will erase the breakpoint at `'<char`.If the char is overwritten, only the last one that was visited in the execution steps is considered. #### Example ```Solidity function testBreakpoint() public { vm.breakpoint("a"); } ``` Opening up the debugger in a test environment and pressing `'a` will then place the debugger step at the place where the breakpoint cheatcode was called. ![](https://3701411312-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNHXgeqhgrznnRobzznxl%2Fuploads%2Fs5GjaTOxnHdA61nbJkMM%2Fimage.png?alt=media\&token=e657e6f2-7e3a-460f-aa0d-52788aaa4895)<br> By integrating Anvil and Cast, you can fork and test by interacting with contracts on the live network. # Migrating $BIT to $MNT on Goerli With the v0.4.0 update on June 9, 2023, we have created a new $MNT token contract on Goerli, since $MNT will serve as the native token of the Mantle ecosystem moving forward. The $BIT contract remains unchanged. Here’s a list of contract addresses on Goerli that we’ll interact with in this guide: <table><thead><tr><th width="247" align="center">Contract</th><th>Address</th></tr></thead><tbody><tr><td align="center">MantleTokenMigrator</td><td><a href="https://goerli.etherscan.io/address/0x144D9B7F34a4e3133C6F347886fBe2700c4cb268">0x144D9B7F34a4e3133C6F347886fBe2700c4cb268</a></td></tr><tr><td align="center">$MNT Token</td><td><a href="https://goerli.etherscan.io/address/0xc1dC2d65A2243c22344E725677A3E3BEBD26E604">0xc1dC2d65A2243c22344E725677A3E3BEBD26E604</a></td></tr><tr><td align="center">$BIT Token</td><td><a href="https://goerli.etherscan.io/token/0x5a94dc6cc85fda49d8e9a8b85dde8629025c42be">0x5a94dc6cc85fda49d8e9a8b85dde8629025c42be</a></td></tr></tbody></table> In this short guide, we’ll go over how to migrate your test $BIT to $MNT on Goerli. This is to enable access to $MNT for developers and teams with existing dApps on Goerli testnet that utilize $BIT. {% hint style="info" %} We recommend users without developer experience to wait for the official migration tool to go live and use that to migrate tokens instead! {% endhint %} ## Step 1: Install Foundry and Cast The first step would be to install Foundry, since we’re going to be using a command line tool, which is part of the foundry developer toolkit, called `cast` to initiate $BIT approval transactions. 1. Follow this link to install Foundry: <https://book.getfoundry.sh/getting-started/installation> 2. To confirm `cast` is correctly installed, run this command: ```bash cast --version ``` If cast was installed correctly, it will print out the current version, like this: ```bash cast 0.2.0 (6cd6618 2022-08-11T00:05:44.416299Z) ``` ## Step 2: Get an API Key Once we've installed Foundry, we need to obtain an API key for a Goerli RPC node provider. For this guide, we'll use Infura. 1. Click this link and login to the Infura dashboard: <https://app.infura.io/login> 2. Create an API Key by clicking the “Create new API Key” button, then select “Web3 API” from the Network dropdown menu. <figure><img src="https://lh3.googleusercontent.com/XamXVurDlaoPj8zsh8f-0Zr2zrNk8D4Ay0L4FhcVjNtWFGE5ZQJDdtT2GZJdlZS_ZqZLn79e1cRFzquzRvbU_hxGHCAtzqJXe2rfD2-FmWwGyqNmr0PhHBCjGDqCaBEQf-0d1FcgTKW4Tk8SO2ctqc8" alt="" width="375"><figcaption></figcaption></figure> 3. After entering the name of your key, move to the “Endpoints” tab where you’ll see your API Key! <figure><img src="https://lh4.googleusercontent.com/nC5d8mUDUlCq5XUpBsn0x-TrQdBIyXeJcK69Qssx0QXlfVQvsAYr69GWCASP_U1YBI9lQzCZpcZ2WgYXhyYPWDmiaG_eodTm4cT4oajvKI3CgkftJ4xqwUTzmWlvKnqoYSaFllpo32_LEvRnVls3YxU" alt="" width="563"><figcaption></figcaption></figure> Copy and save it somewhere! You'll need it for the next step. ## Step 3: Approve $BIT Spending for Migration Contract Now, use the following command to send a transaction to approve $BIT spending for the migration contract. You'll need to replace the arguments with your wallet address containing the $BIT tokens, private key, the amount of $BIT you want to approve, and your API key. {% hint style="info" %} Note that the amount of $BIT needs to be specified in ***wei***, which means 1 $BIT will need to be specified as 10^18, or 1 followed by 18 zeroes. You can use [this tool](https://eth-converter.com/) for an accurate conversion.&#x20; {% endhint %} The amount you pass here is important because this is the maximum amount of $BIT the migration contract will be able to migrate.&#x20; {% hint style="info" %} Make sure your wallet has sufficient $gETH to send this transaction {% endhint %} {% code overflow="wrap" %} ```bash cast send --from "your address" --private-key "your private key" 0x5a94dc6cc85fda49d8e9a8b85dde8629025c42be "approve(address,uint256)" 0x144D9B7F34a4e3133C6F347886fBe2700c4cb268 “amount” --rpc-url https://goerli.infura.io/v3/"your api key" ``` {% endcode %} Upon running the command, you'll see a response like the following: <figure><img src="https://lh6.googleusercontent.com/6MnQtj-iY3y-_hW2O6xxt40NPkEFl9_HjjmjlpQHRXupH_OHJAoDzs2sSLZttmM6Pic-T1mvFRlbYs5RMUjb91RQoFirSJQx3o5wvsnT8a5_daWgDMiIyisYbhzNrJvK4xix6p5xLaW-ZPmV4JeJVJ4" alt=""><figcaption></figcaption></figure> ## Step 4: Migrate $BIT to $MNT We can call the migration contract from Etherscan. 1. Follow the link below to navigate to the migration contract on Etherscan. {% embed url="<https://goerli.etherscan.io/address/0x144D9B7F34a4e3133C6F347886fBe2700c4cb268#writeContract>" %} 2. Connect your wallet to the webpage. 3. You can now use the `migrateAllBIT` function is you've approved all the available $BIT in your wallet. To specify an amount, use the `migrateBIT` function and enter the amount in ***wei**.* This means 1 $BIT will be denoted as 10^18, or 1 followed by 18 zeroes. You can use [this tool](https://eth-converter.com/) for an accurate conversion. Use the "+" button to select and enter an initial value automatically. 4. Click on the write button to send the transaction. Once the transaction is sent out successfully, you'll see the $MNT balance update in your wallet. {% hint style="info" %} If you don't see the balance updates, make sure you're connected to Goerli and have imported the $MNT token to your wallet. If you haven't, you can do so using the $MNT token contract address:\ `0xc1dC2d65A2243c22344E725677A3E3BEBD26E604` {% endhint %} # Viewing Transactions between Layers Look up transactions passed between Mantle and Ethereum {% hint style="danger" %} Mantle v2 Tectonic has been released, please move to the new [documentation](https://docs-v2.mantle.xyz/)! {% endhint %} In this tutorial, we'll be going over how to use the [Mantle SDK](https://sdk.mantle.xyz/) to view transactions passed between Mantle network (L2) and Ethereum (L1). This function is particularly useful for dApps that make contract calls between L2 and L1. ## Set up local environment {% hint style="info" %} Before moving ahead, please make sure you have [Node.js](https://nodejs.org/en/), [Yarn](https://classic.yarnpkg.com/lang/en/), and [Git](https://git-scm.com/) installed and configured in your environment. We'll need to use them to download and run our example script. {% endhint %} Let's download the JS script that we'll be using to make SDK calls. The easiest way is to download the files from the Mantle GitHub repo using a Git command like so: ```bash git clone https://github.com/mantlenetworkio/mantle.git ``` We need to configure the wallet that we're going to be using to send transactions. In the main directory, you'll see a `.env.testnet` file. You can specify your wallet private key in the `PRIV_KEY` field, and an `L1_RPC` URL for [Goerli network](https://chainlist.org/chain/5).&#x20; Now, navigate to the `./sdk-view-tx` directory and run the `yarn` command to download the necessary dependencies to your local environment, such as the ethers.js library, the SDK modules, and more. They can all be found in the `node_modules` directory once you successfully run `Yarn`. Let's go over the files in the `./sdk-view-tx` directory and see what purpose each of them serves. * `index.js`: the main JS script that sends requests to node RPCs on L1 and L2 to query on-chain data * `package.json`: specifies dependencies and commands for script automation * `yarn.lock`: specifies dependencies ## Script Logic We can now start looking at the code in `index.js`.&#x20; ```javascript #! /usr/local/bin/node const ethers = require("ethers") const mantleSDK = require("@mantleio/sdk") // Global variable because we need them almost everywhere let crossChainMessenger const setup = async () => { crossChainMessenger = new mantleSDK.CrossChainMessenger({ l1ChainId: process.env.L1_CHAINID, l2ChainId: process.env.L2_CHAINID, l1SignerOrProvider: l1Wallet, l2SignerOrProvider: l2Wallet }) } ``` We first create a `crossChainMessenger` object that we'll use to fetch and view transaction information. This operation is limited to fetching public on-chain data using `view` functions, so we don't need signers to send these requests. However, we do need chain ID values to direct requests to the correct node RPC. ```javascript // Only the part of the ABI we need to get the symbol const ERC20ABI = [ { "constant": true, "inputs": [], "name": "symbol", "outputs": [ { "name": "", "type": "string" } ], "payable": false, "stateMutability": "view", "type": "function" } ] const getSymbol = async l1Addr => { if (l1Addr == '0x0000000000000000000000000000000000000000') return "ETH" if (l1Addr == '0xc1dC2d65A2243c22344E725677A3E3BEBD26E604') return "MNT" ``` If the `l1Addr` field contains all zeroes, this implies the transferred token was $ETH. We also check the `l1Addr` for $MNT token's contract address. {% code overflow="wrap" lineNumbers="true" %} ```javascript const l1Contract = new ethers.Contract(l1Addr, ERC20ABI, crossChainMessenger.l1SignerOrProvider) return await l1Contract.symbol() } ``` {% endcode %} Otherwise, we fetch the token symbol from the contract. The same query logic can be used for both L1 and L2 contracts. {% code overflow="wrap" lineNumbers="true" %} ```javascript // Describe a cross domain transaction, either deposit or withdrawal const describeTx = async tx => { console.log(`tx:${tx.transactionHash}`) // Assume all tokens have decimals = 18 console.log(`\tAmount: ${tx.amount / 1e18} ${await getSymbol(tx.l1Token)}`) console.log(`\tRelayed: ${await crossChainMessenger.getMessageStatus(tx.transactionHash) == mantleSDK.MessageStatus.RELAYED}`) } ``` {% endcode %} The response of `crossDomainMessenger.getMessageStatus()`is a `MessageStatus` enumerated value. What we're checking for is whether the deposit/withdrawal transaction is completed or still in progress. {% code overflow="wrap" lineNumbers="true" %} ```javascript const main = async () => { await setup() const deposits = await crossChainMessenger.getDepositsByAddress(l1Wallet.address) console.log(`Deposits by address ${addr}`) for (var i=0; i<deposits.length; i++) await describeTx(deposits[i]) const withdrawals = await crossChainMessenger.getWithdrawalsByAddress(l1Wallet.address) console.log(`\n\n\nWithdrawals by address ${addr}`) for (var i=0; i<withdrawals.length; i++) await describeTx(withdrawals[i]) } ``` {% endcode %} The `crossChainMessenger.getDepositsByAddress()` function call returns records of all deposit transactions made by an address, and `crossChainMessenger.getWithdrawalsByAddress()` returns records of all withdrawal transactions sent by an address. Finally, we print the deposit and withdraw records to the console. ## Running the Script With L1 and L2 RPC endpoints and the wallet private key configured, you can go ahead and run the `index.js` script by simply running the `yarn testnet` command. If you have a local L2 or L1 instance running in your environment, you can switch up the respective RPC URLs in the `.env.local` configuration file in the main directory and use the `yarn local` command to run the script locally. ## Results The output would look something like: ``` Deposits by address 0x23618e81E3f5cdF7f54C3d65f7FBc0aBf5B21E8f tx:0x3979f14c8e890aec790fa3743c2d7ae736b48aebfc9dc990e84b77cfaf744525 Amount: 1 L1EPT Relayed: true Withdrawals by address 0x23618e81E3f5cdF7f54C3d65f7FBc0aBf5B21E8f tx:0xe650064362f163a394d3123e20029ed1b03846a6ae62e4cc8e962482c9cd4814 Amount: 1 L1EPT Relayed: false ``` ## Conclusion At this point, you should be able to look up deposits and withdrawals performed by any specific address. There are some additional tracing functions in [`CrossChainMessenger`](https://github.com/mantlenetworkio/mantle/blob/4e2e3fe64fc0ba62a473235ec617b4ac2fefd89c/packages/sdk/src/cross-chain-messenger.ts#L58), but they are very similar in terms of operation. # Bridging Custom ERC20 Tokens Using Standard Bridge {% hint style="danger" %} Mantle v2 Tectonic has been released, please move to the new [documentation](https://docs-v2.mantle.xyz/)! {% endhint %} For an L1/L2 token pair to work on the Standard Bridge, there has to be a layer of original mint (where the minting and burning of tokens is controlled by the business logic), and a bridged layer where the Standard Bridge controls minting and burning. The most common configuration is to have L1 as the layer of original mint, and L2 as the bridged layer, this allows for ERC-20 contracts that were written with no knowledge of Mantle Mainnet to be bridged. The contract on the bridged layer has to implement the legacy [`IL2StandardERC20`](https://github.com/mantlenetworkio/mantle-erc20-bridge/blob/main/contracts/ERC20/IL2StandardERC20.sol) interface (only if the bridged layer is L2). For this to be done securely, the *only* entity that is allowed to mint and burn tokens on the bridged layer has to be the Standard Bridge, to ensure t
프로젝트로 돌아가기