bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 38쪽 중 11쪽
sing the `createERC20` method of the
ERC20Factory contract.
Implement the `createERC20` function:
```js theme={null}
// Send the transaction.
async function createERC20() {
try {
// Call createERC20 function on the factory contract to create a new ERC20 token.
const hash = await client.writeContract({
address: erc20FactoryAddress,
abi: erc20FactoryAbi,
functionName: 'createERC20',
args: ['Test', 'TST', 18],
})
console.log('Transaction sent. Hash:', hash)
// Wait briefly for the transaction to be processed.
await new Promise((resolve) => setTimeout(resolve, 500))
// Get the transaction receipt and parse the logs for the ERC20Created event.
const receipt = await publicClient.getTransactionReceipt({ hash })
const erc20CreatedLog = receipt.logs.find(
// Check if the log is from the factory address.
(log) => log.address.toLowerCase() === erc20FactoryAddress.toLowerCase(),
)
// Check whether the ERC20Created event exists in the logs, then decode the created ERC20 address.
if (erc20CreatedLog) {
const decodedLog = decodeEventLog({
abi: erc20FactoryAbi,
data: erc20CreatedLog.data,
topics: erc20CreatedLog.topics,
})
console.log('New ERC20 address:', decodedLog.args.erc20)
// Try reading data from the new ERC20 contract.
const erc20 = await getContract({
address: decodedLog.args.erc20,
abi: erc20Abi,
client: {
public: publicClient,
wallet: client,
},
})
console.log('ERC20 name:', await erc20.read.name())
console.log('ERC20 symbol:', await erc20.read.symbol())
console.log('ERC20 decimals:', await erc20.read.decimals())
} else {
console.log('ERC20Created event not found in logs')
}
} catch (error) {
console.error('Error sending transaction:', error)
}
}
createERC20()
```
### Full Script Reference
Here is the entire script for reference:
```js theme={null}
const {
createPublicClient,
createWalletClient,
decodeEventLog,
getContract,
http,
} = require('viem')
const { privateKeyToAccount } = require('viem/accounts')
const erc20Abi = require('../abis/erc20Abi.json')
const erc20FactoryAbi = require('../abis/erc20FactoryAbi.json')
const miniEVM = require('./chain')
require('dotenv').config()
const rawPrivateKey = process.env.PRIVATE_KEY
if (!rawPrivateKey) {
throw new Error('PRIVATE_KEY environment variable is not set.')
}
const privateKey = rawPrivateKey.startsWith('0x')
? rawPrivateKey
: `0x${rawPrivateKey}`
const erc20FactoryAddress = process.env.ERC20_FACTORY_ADDRESS
if (!erc20FactoryAddress) {
throw new Error('ERC20_FACTORY_ADDRESS environment variable is not set.')
}
// Create an account from the private key.
const account = privateKeyToAccount(privateKey)
// Create a wallet client.
const client = createWalletClient({
account,
chain: miniEVM,
transport: http(),
})
// Create a public client.
const publicClient = createPublicClient({
chain: miniEVM,
transport: http(),
})
// Send the transaction.
async function createERC20() {
try {
// Call createERC20 function on the factory contract to create a new ERC20 token.
const hash = await client.writeContract({
address: erc20FactoryAddress,
abi: erc20FactoryAbi,
functionName: 'createERC20',
args: ['Test', 'TST', 18],
})
console.log('Transaction sent. Hash:', hash)
// Wait briefly for the transaction to be processed.
await new Promise((resolve) => setTimeout(resolve, 500))
// Get the transaction receipt and parse the logs for the ERC20Created event.
const receipt = await publicClient.getTransactionReceipt({ hash })
const erc20CreatedLog = receipt.logs.find(
// Check if the log is from the factory address.
(log) => log.address.toLowerCase() === erc20FactoryAddress.toLowerCase(),
)
// Check whether the ERC20Created event exists in the logs, then decode the created ERC20 address.
if (erc20CreatedLog) {
const decodedLog = decodeEventLog({
abi: erc20FactoryAbi,
data: erc20CreatedLog.data,
topics: erc20CreatedLog.topics,
})
console.log('New ERC20 address:', decodedLog.args.erc20)
// Try reading data from the new ERC20 contract.
const erc20 = await getContract({
address: decodedLog.args.erc20,
abi: erc20Abi,
client: {
public: publicClient,
wallet: client,
},
})
console.log('ERC20 name:', await erc20.read.name())
console.log('ERC20 symbol:', await erc20.read.symbol())
console.log('ERC20 decimals:', await erc20.read.decimals())
} else {
console.log('ERC20Created event not found in logs')
}
} catch (error) {
console.error('Error sending transaction:', error)
}
}
createERC20()
```
### Running the Script
Run the script to create a new ERC20 token:
```sh theme={null}
node src/index.js
```
A successful run outputs something like this:
```sh theme={null}
Transaction sent. Hash: 0x58b0b9326e9c877c0b966db112b3df8db710f986ba309345601ac222ddcb4c77
New ERC20 address: 0x9F363EB9649879b1C4993f9Ea9821d48346c3e04
ERC20 name: Test
ERC20 symbol: TST
ERC20 decimals: 18
```
You have now successfully created a new ERC20 token on the MiniEVM!
# EVM IBC Hooks
Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/evm/ibc-hooks
EVM hooks, implemented as IBC middleware, play a critical role in facilitating
cross-chain contract calls that involve token transfers. This capability is
particularly crucial for cross-chain swaps, providing a robust mechanism for
decentralized trading across different blockchain networks. The key to this
functionality is the `memo` field in the ICS20 and ICS721 transfer packets, as
introduced in
[IBC v3.4.0](https://medium.com/the-interchain-foundation/moving-beyond-simple-token-transfers-d42b2b1dc29b).
# EVM Contract Execution Format
Before diving into the IBC metadata format, take a look at the hook data format
and the fields that need to be set. The EVM `MsgCall` is defined
[here](https://github.com/initia-labs/minievm/blob/main/x/evm/types/tx.pb.go)
and other types are defined
[here](https://github.com/initia-labs/minievm/blob/main/app/ibc-hooks/message.go).
```go theme={null}
// HookData defines a wrapper for evm execute message
// and async callback.
type HookData struct {
// Message is an evm execute message which will be executed
// at `OnRecvPacket` of receiver chain.
Message evmtypes.MsgCall `json:"message"`
// AsyncCallback is a callback message which will be executed
// at `OnTimeoutPacket` and `OnAcknowledgementPacket` of
// sender chain.
AsyncCallback *AsyncCallback `json:"async_callback,omitempty"`
}
// AsyncCallback is data wrapper which is required
// when we implement async callback.
type AsyncCallback struct {
// callback id should be issued from the executor contract
Id uint64 `json:"id"`
ContractAddr string `json:"contract_addr"`
}
// MsgCall is a message to call an Ethereum contract.
type MsgCall struct {
// Sender is the actor that signed the messages
Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"`
// ContractAddr is the contract address to be executed.
// It can be cosmos address or hex encoded address.
ContractAddr string `protobuf:"bytes,2,opt,name=contract_addr,json=contractAddr,proto3" json:"contract_addr,omitempty"`
// Hex encoded execution input bytes.
Input string `protobuf:"bytes,3,opt,name=input,proto3" json:"input,omitempty"`
}
```
Here is where each of these fields comes from:
* `Sender`: The sender of an IBC packet cannot be trusted, as the counter-party
chain has full ability to lie about it. This sender must not be confused for a
particular user or module address on Initia. So the sender is replaced with an
account to represent the sender prefixed by the channel and an evm module
prefix. This is done by setting the sender to
`Bech32(Hash(Hash("ibc-evm-hook-intermediary") + channelID/sender))`, where
the channelId is the channel id on the local chain.
* `ContractAddr`: This field should be directly obtained from the ICS-20 packet
metadata
* `Input`: This field should be directly obtained from the ICS-20 packet
metadata.
The constructed EVM call message looks like:
```go theme={null}
msg := MsgCall{
// Sender is the actor that signed the messages
Sender: "init1-hash-of-channel-and-sender",
// ContractAddr is the contract address to be executed.
// It can be cosmos address or hex encoded address.
ContractAddr: packet.data.memo["evm"]["message"]["contract_addr"],
// Hex encoded execution input bytes.
Input: packet.data.memo["evm"]["message"]["input"],
}
```
# ICS20 packet structure
Given the details above, here is the implied ICS20 packet data structure. ICS20
is JSON native, so we use JSON for the memo format.
```json theme={null}
{
//... other ibc fields that we don't care about
"data": {
"denom": "denom on counterparty chain (e.g. uatom)", // will be transformed to the local denom (ibc/...)
"amount": "1000",
"sender": "addr on counterparty chain", // will be transformed
"receiver": "ModuleAddr::ModuleName::FunctionName",
"memo": {
"evm": {
// execute message on receive packet
"message": {
"contract_addr": "0x1",
"input": "hex encoded byte string"
},
// optional field to get async callback (ack and timeout)
"async_callback": {
"id": 1,
"contract_addr": "0x1"
}
}
}
}
}
```
An ICS20 packet is formatted correctly for evmhooks iff the following all hold:
* [x] `memo` is not blank
* [x] `memo` is valid JSON
* [x] `memo` has at least one key, with value `"evm"`
* [x] `memo["evm"]["message"]` has exactly two entries, `"contract_addr"` and
`"input"`
* [x] `receiver` == "" || `receiver` ==
`"module_address::module_name::function_name"`
An ICS20 packet is considered directed towards evmhooks iff all of the following
hold:
* `memo` is not blank
* `memo` is valid JSON
* `memo` has at least one key, with name `"evm"`
If an ICS20 packet is not directed towards evmhooks, evmhooks doesn't do
anything. If an ICS20 packet is directed towards evmhooks, and is formatted
incorrectly, then evmhooks returns an error.
# Execution flow
Pre evm hooks:
* Ensure the incoming IBC packet is cryptographically valid
* Ensure the incoming IBC packet is not timed out.
In evm hooks, pre packet execution:
* Ensure the packet is correctly formatted (as defined above)
* Edit the receiver to be the hardcoded IBC module account
In evm hooks, post packet execution:
* Construct evm message as defined before
* Execute evm message
* if evm message has error, return ErrAck
* otherwise continue through middleware
# Async Callback
A contract that sends an IBC transfer, may need to listen for the ACK from that
packet. To allow contracts to listen on the ack of specific packets, the
framework provides Ack callbacks. The contract that wants to receive ack
callbacks must implement two functions.
* ibc\_ack
* ibc\_timeout
```go theme={null}
interface IIBCAsyncCallback {
function ibc_ack(uint64 callback_id, bool success) external;
function ibc_timeout(uint64 callback_id) external;
}
```
Also when a contract makes an IBC transfer request, it should provide async
callback data through memo field.
* `memo['evm']['async_callback']['id']`: the async callback id is assigned from
the contract. so later it will be passed as argument of `ibc_ack` and
`ibc_timeout`.
* `memo['evm']['async_callback']['contract_addr']`: The address of module which
defines the callback function.
# Tutorials
This tutorial will guide you through the process of deploying an EVM contract
and calling it from another chain using IBC hooks. This example uses an IBC hook
from Initia chain to call an EVM contract on MiniEVM chain.
## Step 1. Deploy a Contract on MiniEVM Chain
Write and deploy a simple
[counter contract](https://github.com/initia-labs/minievm/blob/main/x/evm/contracts/counter/Counter.sol)
to Initia.
```solidity theme={null}
contract Counter is IIBCAsyncCallback {
uint256 public count;
event increased(uint256 oldCount, uint256 newCount);
constructor() payable {}
function increase() external payable {
count++;
emit increased(count - 1, count);
}
function ibc_ack(uint64 callback_id, bool success) external {
if (success) {
count += callback_id;
} else {
count++;
}
}
function ibc_timeout(uint64 callback_id) external {
count += callback_id;
}
function query_cosmos(
string memory path,
string memory req
) external returns (string memory result) {
return COSMOS_CONTRACT.query_cosmos(path, req);
}
}
```
## Step 2. Update IBC Hook ACL for the Contract
IBC hooks have the power to execute any functions on the counterparty chain and
this can be used for phishing easily. So, you need to set the ACL for the
contract to prevent unauthorized access. To update MiniEVM ACL, use
`MsgExecuteMessages` in OPchild module.
```typescript theme={null}
const config = {
authority: 'init10d07y265gmmuvt4z0w9aw880jnsr700j55nka3',
contractAddress:
'init1436kxs0w2es6xlqpp9rd35e3d0cjnw4sv8j3a7483sgks29jqwgs9nxzw8',
}
const aclMsg = new MsgUpdateACL(config.authority, config.contractAddress, true)
const msgs = [new MsgExecuteMessages(proposer.key.accAddress, [aclMsg])]
const signedTx = await proposer.createAndSignTx({ msgs })
try {
const result = await proposer.rest.tx.broadcast(signedTx)
console.log('Transaction successful:', result)
} catch (error) {
console.error('Transaction failed:', error)
throw error
}
```
```bash theme={null}
curl -X GET "https://rest-evm-1.anvil.asia-southeast.initia.xyz/initia/ibchooks/v1/acls" -H "accept: application/json"
```
Response:
```json theme={null}
{
"acls": [
{
"address": "init10lfct45epqj8gdh5nh32rtlkgwxhts7qd9z5v5",
"allowed": true
}
],
"pagination": {
"next_key": null,
"total": "1"
}
}
```
## Step 3. Execute IBC Hooks Message
After the contract is deployed and the ACL is set, you can execute the IBC hooks
message to call the contract.
```typescript theme={null}
import {
Coin,
Height,
RESTClient,
MnemonicKey,
MsgTransfer,
Wallet,
} from '@initia/initia.js'
import { ethers } from 'ethers'
import * as fs from 'fs'
function createHook(params: object) {
const hook = { evm: { message: params } }
return JSON.stringify(hook)
}
async function main() {
const restClient = new RESTClient('https://rest.testnet.initia.xyz', {
gasAdjustment: '1.75',
gasPrices: '0.015uinit',
})
const sender = new Wallet(
restClient,
new MnemonicKey({
mnemonic: '<your-mnemonic-here>',
}),
)
const amount = '1000'
const contractInfo = JSON.parse(
fs.readFileSync('./bin/Counter.json').toString(),
)
const abi = contractInfo.abi
const contractAddress = '0x4cb5cE12e3bB85348791A3cDd4dc3A5b7836270e'
const contract = new ethers.Contract(contractAddress, abi)
const methodName = 'increase'
const args: any[] = []
const encodedData = contract.interface.encodeFunctionData(methodName, args)
const msgs = [
new MsgTransfer(
'transfer',
'channel-10',
new Coin('uinit', amount),
sender.key.accAddress,
contractAddress,
new Height(0, 0),
((new Date().valueOf() + 100000) * 1000000).toString(),
createHook({
contract_addr: contractAddress,
input: encodedData,
}),
),
]
const signedTx = await sender.createAndSignTx({ msgs })
await restClient.tx.broadcastSync(signedTx).then((res) => console.log(res))
}
main()
```
# Update Fee with ERC20 Token
Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/evm/update-fee-token
## Prerequisites
* [NodeJS](https://nodejs.org)
## Update Fee Token with ERC20 Token
You may want to use an ERC20 token as the Fee Token instead of the tokens issued
by the Cosmos Bank module.
To achieve this, you can update the chain parameter of the EVM module to set the
Fee Token as an ERC20 token.
Use validator (admin) account to update the chain parameter.
<Warning>
The deployed ERC20 token must inherit the `InitiaERC20` contract.
</Warning>
```ts theme={null}
import {
EvmParams,
RESTClient,
MnemonicKey,
MsgUpdateEvmParams,
Wallet,
MsgExecuteMessages,
} from '@initia/initia.js'
/**
* main() demonstrates how to update EVM-related chain parameters (such as fee denom, allowed publishers, etc.).
* Note: This requires the mnemonic for the chain’s operator(a.k.a validator), which you must obtain from the chain administrator.
*/
async function main() {
/**
* 1) Instantiate a RESTClient using the chain’s RPC endpoint.
* - The first argument is the base URL or RPC endpoint of your chain.
* - The second argument is an object providing client options like gas prices.
*
* For example:
* "https://maze-rpc-sequencer-fd70c395-4cfc-4624-ab8a-8e025af6a140.ane1-prod-nocsm.newmetric.xyz/"
* is a special endpoint in this context (provided by NewMetric).
*/
const client = new RESTClient(
'https://maze-rpc-sequencer-fd70c395-4cfc-4624-ab8a-8e025af6a140.ane1-prod-nocsm.newmetric.xyz/',
{
/**
* gasPrices: '0GAS'
* - This can be set to '0GAS' if the chain you’re using allows 0 gas prices or free transactions
* for certain operations (testnet or specific config).
* - In production or other networks, you usually set this to something like "0.025<feeDenom>" or
* whatever fee denom and minimum gas price the network expects.
*/
gasPrices: '0GAS',
},
)
/**
* 2) Create a Wallet instance using the client and a MnemonicKey.
* - The MnemonicKey is derived from the chain operator's mnemonic (private key).
* - This wallet has permission to execute the EVM parameter update because it’s
* presumably the authorized validator or has the necessary roles on the chain.
*/
const wallet = new Wallet(
client,
new MnemonicKey({
/**
* Replace with the actual mnemonic of the chain operator or the account with
* the authority to update EVM params.
* Make sure you keep this mnemonic secret.
*/
mnemonic: '', // enter validator mnemonic
}),
)
/**
* 3) Construct the MsgUpdateEvmParams message.
* - This message tells the chain which parameters to update in the EVM module.
* - The first argument is the "opchild module address" or "authority address" (in bech32 format).
* This is the authority that is allowed to update the EVM params on chain.
* This is obtained from `/cosmos/auth/v1beta1/module_accounts/opchild` endpoint.
*
* - Then we instantiate a new EvmParams object:
* @param extra_eip (array): Optional EIPs to enable
* @param allowed_publisher (array): Entities allowed to publish certain EVM data
* @param allow_custom_erc20 (boolean): Toggle for custom ERC20 tokens
* @param allowed_custom_erc20s (array): A list of allowed custom ERC20 addresses
* (could be 0x or bech32, depending on chain config)
* @param fee_denom (string): The fee denomination on-chain (e.g. 'umin').
* It typically should match the chain’s native fee token.
*/
const msgs = [
new MsgUpdateEvmParams(
'init1gz9n8jnu9fgqw7vem9ud67gqjk5q4m2w0aejne', // Authority/Opchild module address
new EvmParams(
[], // extra_eip - e.g. ["EIP1559"] if needed
[], // allowed_publisher - e.g. ['0x123...'] if you want certain publishers
/**
* allow_custom_erc20 (boolean)
* - Determines whether custom ERC20 tokens are allowed beyond the default token factory.
*
* - If true and allowed_custom_erc20s = []:
* => All custom ERC20 tokens are allowed.
*
* - If true and allowed_custom_erc20s = [addr1, addr2]:
* => Only the tokens specified in the list [addr1, addr2] are allowed.
*
* - If false and allowed_custom_erc20s = []:
* => Only tokens created by the chain's token factory are allowed; no arbitrary custom tokens.
*/
true,
/**
* allowed_custom_erc20s (string[])
* - A list of custom ERC20 addresses (0x or bech32, depending on your chain) that are permitted.
* - This array must be considered in conjunction with allow_custom_erc20 (above).
* - If allow_custom_erc20 = true but this is empty => all custom ERC20 tokens are allowed.
* - If allow_custom_erc20 = true and you specify addresses => only those addresses are allowed.
*/
[],
/**
* fee_denom (string)
* - Must be the chain's fee token; often in the format `evm/<erc20Address>`
* on an EVM-compatible chain.
* - Example: "evm/9D9c32921575Fd98e67E27C0189ED4b750Cb17C5"
*/
'evm/9D9c32921575Fd98e67E27C0189ED4프로젝트로 돌아가기