bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 37쪽 중 20쪽
eate Mantle Sepolia client
export const publicClientL2 = createPublicClient({
chain: mantleSepoliaTestnet,
transport: http(mantleSepoliaRpc),
}).extend(publicActionsL2());
// Create Mantle Sepolia wallet client
export const walletClientL2 = createWalletClient({
account,
chain: mantleSepoliaTestnet,
transport: http(mantleSepoliaRpc),
}).extend(walletActionsL2());
```
### Deposit ERC-20 (From L1 to L2)
The deposit operation moves ERC-20 tokens from L1 to L2. Here’s how to do it:
#### **Steps**
1. **Approve Token Transfer**
1. You need to set an allowance before depositing, which allows the L1 bridge contract to spend your ERC-20 tokens.
2. **Execute Deposit**
1. Call the `depositMNT` function to transfer tokens to L2.
3. **Wait for Confirmation**
1. Confirm the transaction on both L1 and L2.
#### Code Example
```typescript
import { getL2TransactionHashes } from "@mantleio/viem";
import { mantleSepoliaTestnet } from "@mantleio/viem/chains";
import { publicClientL1, publicClientL2, walletClientL1 } from "./config.ts";
import { erc20Abi, maxUint256, parseEther } from "viem";
console.log("Deposit Starts!!!!!!!");
// Step 1: Approve token transfer
const allowanceHash = await walletClientL1.writeContract({
// This is the token contract address for a ERC-20 in Sepolia network
address: "0x072d71b257ECa6B60b5333626F6a55ea1B0c451c",
abi: erc20Abi,
functionName: "approve",
args: [
mantleSepoliaTestnet.contracts.l1StandardBridge[11155111].address,
maxUint256,
],
});
console.log("The allowance L1 hash is:", allowanceHash);
const allowanceReceipt = await publicClientL1.waitForTransactionReceipt({
hash: allowanceHash,
});
console.log("The allowance L1 is processed.");
// Step 2: Execute the deposit transaction on the L1.
const depositHash = await walletClientL1.depositERC20({
request: {
amount: parseEther("1"),
},
targetChain: mantleSepoliaTestnet,
});
console.log("The deposit hash is:", depositHash);
// Step 3.1: Wait for the L1 transaction to be processed.
const depositReceipt = await publicClientL1.waitForTransactionReceipt({
hash: depositHash,
});
console.log("The deposit L1 Tx is processed.");
// Step 3.2: Get the L2 transaction hash from the L1 transaction receipt.
const [l2Hash] = getL2TransactionHashes(depositReceipt);
console.log("The deposit L2 Hash is:", l2Hash);
// Step 3.3: Wait for the L2 transaction to be processed.
const depositL2Receipt = await publicClientL2.waitForTransactionReceipt({
hash: l2Hash,
});
console.log("The deposit L2 Tx is processed.");
console.log("Deposit Finished");
```
### Withdraw MNT (From L2 to L1)
The withdraw operation transfers ERC-20 tokens from L2 back to L1. It involves multiple steps due to the bridge’s design.
#### **Steps**
1. **Approve Token Transfer**
1. You need to set an allowance before depositing, which allows the L1 bridge contract to spend your ERC-20 tokens.
2. **Initiate Withdrawal**
1. Start the withdrawal process on L2.
3. **Wait for Proof**
1. Wait until the withdrawal can be proven on L1.
4. **Prove Withdrawal**
1. Submit the withdrawal proof on L1.
5. **Wait for Finalization**
1. Wait until the withdrawal can be finalized.
2. We manually added a wait time here (1 minute) to prevent withdraw failures due to prove information not being updated by the rpc.
6. **Finalize Withdrawal**
1. Complete the process on L1.
#### Code Example
```typescript
import {
account,
publicClientL1,
publicClientL2,
walletClientL1,
walletClientL2,
} from "./config.ts";
import { mantleSepoliaTestnet } from "@mantleio/viem/chains";
import { erc20Abi, maxUint256, parseEther } from "viem";
console.log("Withdrawal Starts!!!!!");
// This is the contract address for ERC-20 token on Mantle Sepolia
const l2ETH = "0x9EF6f9160Ba00B6621e5CB3217BB8b54a92B2828";
// Step 1: Approve token transfer
const allowanceHash = await walletClientL2.writeContract({
address: l2ETH,
abi: erc20Abi,
functionName: "approve",
args: [mantleSepoliaTestnet.contracts.l2StandardBridge.address, maxUint256],
});
console.log("The allowance L1 hash is:", allowanceHash);
const allowanceReceipt = await publicClientL2.waitForTransactionReceipt({
hash: allowanceHash,
});
console.log("The allowance L1 is processed.");
// Step 2: Execute the initiate ETH withdrawal transaction on the L2.
const withdrawalHash = await walletClientL2.initiateERC20Withdrawal({
account,
request: {
amount: parseEther("0.1"),
},
});
console.log("The withdrawal L2 Tx hash is: ", withdrawalHash);
// Step 3.1: Wait for the initiate withdrawal transaction receipt.
const withdrawalReceipt = await publicClientL2.waitForTransactionReceipt({
hash: withdrawalHash,
});
console.log("The withdrawal L2 Tx is processed.");
// Step 3.2: Wait until the withdrawal is ready to prove.
const { output, withdrawal } = await publicClientL1.waitToProve({
receipt: withdrawalReceipt,
targetChain: walletClientL2.chain,
});
console.log("The withdrawal L2 Tx is waiting for proving");
// Step 3.3: Build parameters to prove the withdrawal on the L2.
const proveArgs = await publicClientL2.buildProveWithdrawal({
output,
withdrawal,
});
console.log("The withdrawal prove Tx paras are built.");
// Step 4: Prove the withdrawal on the L1.
const proveHash = await walletClientL1.proveWithdrawal(proveArgs);
console.log("The withdrawal prove tx hash is: ", proveHash);
// Step 5.1: Wait until the prove withdrawal is processed.
const proveReceipt = await publicClientL1.waitForTransactionReceipt({
hash: proveHash,
});
console.log("The withdrawal prove Tx is processed.");
// Step 5.2: Wait until the withdrawal is ready to finalize.
await publicClientL1.waitToFinalize({
targetChain: walletClientL2.chain,
withdrawalHash: withdrawal.withdrawalHash,
});
console.log("The withdrawal Tx is processed.");
// Step 5.3: Wait for rpc to update proving
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
console.log("Start waiting 1 minute...");
await sleep(1 * 60 * 1000); //
console.log("Continue with the subsequent code...");
// Step 6.1: Finalize the withdrawal.
const finalizeHash = await walletClientL1.finalizeWithdrawal({
targetChain: walletClientL2.chain,
withdrawal,
});
console.log("The withdrawal Tx hash is: ", finalizeHash);
// Step 6.2: Wait until the withdrawal is finalized.
const finalizeReceipt = await publicClientL1.waitForTransactionReceipt({
hash: finalizeHash,
});
console.log("The withdrawal Tx is finalized.");
```
### Summary
This guide provides the necessary steps and code to use Mantle Viem for depositing a ERC-20 token from L1 to L2 and withdrawing it back to L1 via the official bridge. Always test your implementation in a test environment first. For additional details, consult [here](https://viem.mantle.xyz/).
# How to Bridge Your Assets
# Bridging Your Standard ERC-20 Token Using the Standard Bridge
This tutorial walks through how to create a standard ERC-20 token on Mantle L2 that represents an existing ERC-20 token deployed on Ethereum (L1), and how to bridge tokens using the Mantle official bridge.By the end of this tutorial, you will:
* Deploy a Mantle-compatible L2 ERC-20 token via a factory contract
* Understand how the L2 token is linked to its L1 counterpart
* Bridge tokens from Ethereum to Mantle using the official bridge
This tutorial is intended for developers who already have an ERC-20 token deployed on Ethereum and want to create its canonical representation on Mantle.
{% hint style="info" %}
This tutorial focuses on **creating a standard bridged ERC-20 token on Mantle L2 using smart contracts** and bridging it via the Mantle official bridge.
If your goal is to **integrate token bridging into a dApp or application workflow**, rather than to create the L2 token itself, you should refer to the tutorial on [**bridging tokens using the Mantle Viem**](/network/for-developers/how-to-guides/how-to-use-mantle-viem).
{% endhint %}
### Prerequisites
Before starting this tutorial, make sure the following requirements are met:
* You already have a **standard ERC-20 token deployed on Ethereum (L1)**.
* Your token is **not** a fee-on-transfer token or a rebasing token.
* You do **not** require additional token logic such as upgradeability, blacklists/whitelists, or custom minting behavior. If you do, refer to the tutorial on **bridging custom ERC-20 tokens** instead.
* You have gas tokens on both L1/L2 networks. (For testnet, which are Ethereum Sepolia and Mantle Sepolia, check this to get testnet token)
* Your development environment is set up with:
* `cast` (Foundry)
* An RPC endpoint for both networks
* A private key funded with testnet gas
This tutorial assumes a **standard ERC-20 bridging flow** using the Mantle official bridge.
### Step 1: Prepare Environment Variables
Export your private key (used to sign transactions):
```bash
export TUTORIAL_PRIVATE_KEY=0x...
```
Make sure this account has MNT on Mantle.Set the Mantle RPC endpoint:
```bash
export TUTORIAL_RPC_URL=https://rpc.mantle.xyz
```
### Step 2: Specify the L1 ERC-20 Token Address
Set the address of your existing Ethereum ERC-20 token:
```bash
export TUTORIAL_L1_ERC20_ADDRESS=0xYourL1TokenAddress
```
This token will be treated as the canonical asset.
### Step 3: Deploy the L2 ERC-20 Token on Mantle
Mantle provides a factory contract that deploys standard L2 ERC-20 tokens compatible with the official bridge.Call the factory contract to create your L2 token:
```bash
cast send 0x4200000000000000000000000000000000000012 \
"createOptimismMintableERC20(address,string,string)" \
$TUTORIAL_L1_ERC20_ADDRESS \
"My Mantle Token" \
"mTOKEN" \
--private-key $TUTORIAL_PRIVATE_KEY \
--rpc-url $TUTORIAL_RPC_URL
```
This transaction deploys:
* A new ERC-20 contract on Mantle
* Links it permanently to the specified L1 token
* Grants mint/burn rights exclusively to the Mantle bridge
The resulting L2 token address will be returned in the transaction logs.
### Step 4: Add your token to the Mantle token list (Optional)
{% hint style="info" %}
If you don’t need your asset to be displayed in the Mantle Bridge UI, you don’t need to submit a PR for review. You can use [**Mantle Viem**](/network/for-developers/how-to-guides/how-to-use-mantle-viem) to quickly fulfill your asset bridging requirements.
{% endhint %}
Mantle maintains an official token list that is used by infrastructure such as the Mantle Bridge UI and other ecosystem tools.If you want your token to be discoverable and properly displayed across the Mantle ecosystem, you can submit it to the [Mantle token list](https://docs.mantle.xyz/network/for-developers/quick-access#token-list) following the review and inclusion guidelines.<br>
# Bridging Your Custom ERC-20 Token Using the Standard Bridge
### When Do You Need a Custom L2 Token?
The standard `OptimismMintableERC20` implementation is designed to cover the most common bridging use cases. Tokens created using the factory contract are:
* Fully compatible with the Mantle Standard Bridge
* Simple, minimal, and non-upgradeable
* Suitable for most canonical L2 representations of L1 tokens
However, this standard implementation intentionally limits extensibility.If your project requires **additional logic**, such as:
* Upgradeability
* Pausing or emergency controls
* Blacklists or allowlists
* Custom hooks on deposit or withdrawal
You **must** use a custom L2 token implementation.This tutorial explains how to build a **custom, upgradeable ERC-20 token** that remains compatible with the Mantle Standard Bridge, while allowing you to safely extend functionality over time.
{% hint style="info" %}
Custom logic must not modify bridge-critical behavior. 
Incorrect implementations can break bridge accounting or invalidate security assumptions.
{% endhint %}
### Prerequisites
Before starting this tutorial, make sure that:
1. You already have an ERC-20 token deployed on Ethereum (L1)
2. Your token is **not** a fee-on-transfer or rebasing token
3. You have gas tokens on both L1/L2 networks. (For testnet, which are Ethereum Sepolia and Mantle Sepolia, check this to get testnet token)
4. You are comfortable deploying contracts using Remix
If you do not need custom functionality, consider following the tutorial on **Bridging Your Standard ERC-20 Token Using the Standard Bridge** instead.
### Deploy an Upgradeable L2 Token with Remix
In this section, you will deploy a **custom, upgradeable L2 ERC-20 token** that is compatible with the Mantle Standard Bridge.
Unlike the standard `OptimismMintableERC20`, this approach allows you to introduce additional functionality such as upgradeability, access control, or custom transfer logic, while still preserving correct bridge behavior.
This tutorial uses [**Remix**](https://remix.ethereum.org) to simplify deployment. You may adapt the same pattern to frameworks such as Hardhat or Foundry if preferred.
{% hint style="info" %}
This tutorial demonstrates one possible approach to creating a custom, upgradeable ERC-20 token for use with the Standard Bridge.
It may **not be suitable for all use cases**. Contract design choices such as upgrade patterns, permission models, and security assumptions should be carefully reviewed before deploying to production.
Developers are encouraged to rely on battle-tested implementations and to review official resources, such as the [OpenZeppelin Contracts documentation](https://docs.openzeppelin.com/contracts/5.x)
{% endhint %}
1. **Open Remix**
Navigate to [Remix](https://remix.ethereum.org/) in your browser.
Make sure your wallet is connected to **Mantle Sepolia** and that Remix is using the **Injected Provider** environment.
2. **Create a new contract file**
Create a new Solidity file, for example:
```solidity
MyUpgradeableL2Token.sol
```
Below is a **minimal upgradeable ERC-20 example** that:
* Implements the `IOptimismMintableERC20` interface
* Uses OpenZeppelin’s upgradeable contracts
* Preserves the required `mint` / `burn` semantics for the Standard Bridge
* Can be safely upgraded via a proxy
```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { UUPSUpgradeable } from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import { ERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
/// @notice Interface required by the Mantle / OP Standard Bridge
interface IOptimismMintableERC20 {
function remoteToken() external view returns (address);
function bridge() external view returns (address);
function mint(address to, uint256 amount) external;
function burn(address from, uint256 amount) external;
}
/// @title Upgradeable L2 ERC-20 compatible with the Mantle Standard Bridge
/// @notice This contract demonstrates how to build an upgradeable token
/// without breaking bridge security assumptions.
contract UpgradeableL2ERC20 is
Initializable,
ERC20Upgradeable,
AccessControlUpgradeable,
UUPSUpgradeable,
IOptimismMintableERC20
{
/// -----------------------------------------------------------------------
/// Roles
/// -----------------------------------------------------------------------
bytes32 public constant BRIDGE_ROLE = keccak256("BRIDGE_ROLE");
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
/// -----------------------------------------------------------------------
/// Bridge-related storage (MUST remain stable across upgrades)
/// -----------------------------------------------------------------------
address private _bridge;
address private _remoteToken;
/// -----------------------------------------------------------------------
/// Initializer
/// -----------------------------------------------------------------------
/// @notice Initializes the token. Replaces constructor for upgradeable contracts.
/// @param bridge_ Address of the Mantle L2 Standard Bridge
/// @param remoteToken_ Address of the corresponding L1 ERC-20 token
/// @param name_ ERC-20 name
/// @param symbol_ ERC-20 symbol
/// @param upgrader Address that controls upgrades
function initialize(
address bridge_,
address remoteToken_,
string memory name_,
string memory symbol_,
address upgrader
) external initializer {
require(bridge_ != address(0), "Invalid bridge");
require(remoteToken_ != address(0), "Invalid remote token");
__ERC20_init(name_, symbol_);
__AccessControl_init();
__UUPSUpgradeable_init();
_bridge = bridge_;
_remoteToken = remoteToken_;
_grantRole(BRIDGE_ROLE, bridge_);
_grantRole(UPGRADER_ROLE, upgrader);
_setRoleAdmin(BRIDGE_ROLE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(UPGRADER_ROLE, DEFAULT_ADMIN_ROLE);
_grantRole(DEFAULT_ADMIN_ROLE, upgrader);
}
/// -----------------------------------------------------------------------
/// IOptimismMintableERC20
/// -----------------------------------------------------------------------
function bridge() external view override returns (address) {
return _bridge;
}
function remoteToken() external view override returns (address) {
return _remoteToken;
}
/// @notice Mint tokens on L2 (called by the Standard Bridge on deposit)
function mint(address to, uint256 amount) external override onlyRole(BRIDGE_ROLE) {
_mint(to, amount);
}
/// @notice Burn tokens on L2 (called by the Standard Bridge on withdrawal)
function burn(address from, uint256 amount) external override onlyRole(BRIDGE_ROLE) {
_burn(from, amount);
}
/// -----------------------------------------------------------------------
/// Upgrade Authorization
/// -----------------------------------------------------------------------
function _authorizeUpgrade(address newImplementation)
internal
override
onlyRole(UPGRADER_ROLE)
{}
}
```
3. **Deploy the proxy**
Using Remix:
1. Deploy the implementation contract
2. Deploy a **UUPS proxy** pointing to the implementation
3. Call `initialize` on the proxy with:
1. `_bridge`: Mantle L2 Standard Bridge address
2. `_remoteToken`: L1 ERC-20 token address
3. `_name`, `_symbol`: token metadata
{% hint style="warning" %}
Always interact with the **proxy address**, not the implementation address.
{% endhint %}
Once deployed, this proxy address represents your **L2 bridged token**.
4. **Bridge tokens**
After deployment, you can bridge tokens from L1 to L2 using the Mantle Standard Bridge or [Mantle Viem](/network/for-developers/how-to-guides/how-to-use-mantle-viem).
At this point, your upgradeable token behaves identically to a standard bridged token from the user’s perspective.
### Add your token to the Mantle Token List
Mantle maintains an official token list that is used by infrastructure such as the Mantle Bridge UI and other ecosystem tools.
If you want your token to be discoverable and properly displayed across the Mantle ecosystem, you can submit it to the [Mantle token list](https://github.com/mantlenetworkio/mantle-token-lists) following the review and inclusion guidelines.
---
[Next Page](https://docs.mantle.xyz/network/llms-full.txt/1)
# Troubleshooting
## General[](https://docs-v2.mantle.xyz/devs/dev-guides/troubleshooting#general) <a href="#general" id="general"></a>
* **Status code: 429 {"error": "API rate limit exceeded"}**
The official Mantle RPC employs rate limiting to ensure stability during traffic spikes. If your particular use case involves calling the Mantle API frequently, you might run into issues that arise due to rate limiting. In case this happens, please consider connecting to third-party RPCs instead. You can find the list of available RPC providers [here](/network/for-developers/resources-and-tooling/node-endpoints-and-providers).
* **RPC call Error: timeout**
While calling the methods of our rpc (e.g. debug trace / get logs) to sync data from bl프로젝트로 돌아가기