Initia 백서

Initia

원문

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

'0x1', 'coin', 'metadata', [], [ bcs.address().serialize(key.accAddress).toBase64(), bcs.string().serialize('MYCOIN').toBase64(), ], ) .then(console.log) // 0xcf921815f2b4827930ac01b3116ed3caad08ccd443f9df6eb22cd5344a548660 // Method 2: use sha3-256 console.log(coinMetadata(key.accAddress, 'MYCOIN')) // cf921815f2b4827930ac01b3116ed3caad08ccd443f9df6eb22cd5344a548660 } getCoinMetadata() function coinMetadata(creator: string, symbol: string): string { const OBJECT_FROM_SEED_ADDRESS_SCHEME = 0xfe const addrBytes = bcs.address().serialize(creator).toBytes() const seed = Buffer.from(symbol, 'ascii') const bytes = [...addrBytes, ...seed, OBJECT_FROM_SEED_ADDRESS_SCHEME] const hash = crypto.createHash('SHA3-256') const digest = hash.update(Buffer.from(bytes)).digest() return digest.toString('hex') } ``` </CodeGroup> ## Minting Coins <CodeGroup> ```bash CLI theme={null} initiad tx move execute 0x1 managed_coin mint_to \ --args '["address:0x...", "object:0x2d81ce0b6708fccc77a537d3d1abac8c9f1f674f4f76390e3e78a89a52d4aacb", "u64:100000000"]' \ --from [key-name] \ --gas auto --gas-adjustment 1.5 --gas-prices 0.015uinit \ --node [rpc-url]:[rpc-port] --chain-id [chain-id] ``` ```ts InitiaJS theme={null} import { bcs, RESTClient, MnemonicKey, MsgExecute, Wallet, } from '@initia/initia.js' import * as crypto from 'crypto' async function mintCoin() { const restClient = new RESTClient('https://rest.testnet.initia.xyz', { gasPrices: '0.015uinit', gasAdjustment: '1.5', }) const key = new MnemonicKey({ mnemonic: 'beauty sniff protect ...', }) const wallet = new Wallet(restClient, key) const msgs = [ new MsgExecute( key.accAddress, '0x1', 'managed_coin', 'mint_to', [], [ bcs.address().serialize(key.accAddress).toBase64(), bcs .object() .serialize(coinMetadata(key.accAddress, 'MYCOIN')) .toBase64(), bcs.u64().serialize(100000000).toBase64(), ], ), ] // sign tx const signedTx = await wallet.createAndSignTx({ msgs }) // send(broadcast) tx restClient.tx.broadcastSync(signedTx).then((res) => console.log(res)) // { // height: 0, // txhash: '593827F58F3E811686EC6FFDAD2E27E91DA707965F0FF33093DC071D47A46786', // raw_log: '[]' // } } mintCoin() function coinMetadata(creator: string, symbol: string): string { const OBJECT_FROM_SEED_ADDRESS_SCHEME = 0xfe const addrBytes = bcs.address().serialize(creator).toBytes() const seed = Buffer.from(symbol, 'ascii') const bytes = [...addrBytes, ...seed, OBJECT_FROM_SEED_ADDRESS_SCHEME] const hash = crypto.createHash('SHA3-256') const digest = hash.update(Buffer.from(bytes)).digest() return digest.toString('hex') } ``` </CodeGroup> After minting, you can check the balances to verify the minting process. # Move IBC Hooks Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/movevm/ibc-hooks The Move hook is an IBC middleware that allows ICS-20 token transfers to initiate contract calls. This allows cross-chain contract calls, that involve token movement. This is useful for a variety of use cases. One of primary importance is cross-chain swaps, which is an extremely powerful primitive. The mechanism enabling this is a `memo` field on every ICS20 and ICS721 transfer packet as of IBC v3.4.0. Move hooks is an IBC middleware that parses an ICS20 transfer, and if the memo field is of a particular form, executes a Move contract call. The following sections detail the memo format for Move contract calls, and the execution guarantees provided. # Move Contract Execution Format Before exploring the IBC metadata format, it is crucial to understand the hook data format. The Move `MsgExecute` is defined [here](https://github.com/initia-labs/initia/blob/main/x/move/types/tx.pb.go) and other types are defined [here](https://github.com/initia-labs/initia/blob/main/x/ibc-hooks/move-hooks/message.go) as the following type: ```go theme={null} // HookData defines a wrapper for Move execute message // and async callback. type HookData struct { // Message is a Move execute message which will be executed // at `OnRecvPacket` of receiver chain. Message movetypes.MsgExecute `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"` ModuleAddress string `json:"module_address"` ModuleName string `json:"module_name"` } type MsgExecute struct { // Sender is the actor that signed the messages Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty"` // ModuleAddress is the address of the module deployer ModuleAddress string `protobuf:"bytes,2,opt,name=module_address,json=moduleAddress,proto3" json:"module_address,omitempty"` // ModuleName is the name of module to execute ModuleName string `protobuf:"bytes,3,opt,name=module_name,json=moduleName,proto3" json:"module_name,omitempty"` // FunctionName is the name of a function to execute FunctionName string `protobuf:"bytes,4,opt,name=function_name,json=functionName,proto3" json:"function_name,omitempty"` // TypeArgs is the type arguments of a function to execute // ex) "0x1::BasicCoin::Initia", "bool", "u8", "u64" TypeArgs []string `protobuf:"bytes,5,rep,name=type_args,json=typeArgs,proto3" json:"type_args,omitempty"` // Args is the arguments of a function to execute // - number: little endian // - string: base64 bytes Args [][]byte `protobuf:"bytes,6,rep,name=args,proto3" json:"args,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 a Move module prefix. This is done by setting the sender to `Bech32(Hash(Hash("ibc-move-hook-intermediary") + channelID/sender))`, where the channelId is the channel id on the local chain. * `ModuleAddress`: This field should be directly obtained from the ICS-20 packet metadata * `ModuleName`: This field should be directly obtained from the ICS-20 packet metadata * `FunctionName`: This field should be directly obtained from the ICS-20 packet metadata * `TypeArgs`: This field should be directly obtained from the ICS-20 packet metadata * `Args`: This field should be directly obtained from the ICS-20 packet metadata. The constructed move message looks like: ```go theme={null} msg := MsgExecuteContract{ // Sender is the actor that signed the messages Sender: "init1-hash-of-channel-and-sender", // ModuleAddress is the address of the module deployer ModuleAddress: packet.data.memo["move"]["message"]["module_address"], // ModuleName is the name of module to execute ModuleName: packet.data.memo["move"]["message"]["module_name"], // FunctionName is the name of a function to execute FunctionName: packet.data.memo["move"]["message"]["function_name"], // TypeArgs is the type arguments of a function to execute // ex) "0x1::BasicCoin::Initia", "bool", "u8", "u64" TypeArgs: packet.data.memo["move"]["message"]["type_args"], // Args is the arguments of a function to execute // - number: little endian // - string: base64 bytes Args: packet.data.memo["move"]["message"]["args"] } ``` # ICS20 Packet Structure Given the details above, here is the implied ICS20 packet data structure. ICS20 is JSON native, so the memo format uses JSON. ```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": { "move": { // execute message on receive packet "message": { "module_address": "0x1", "module_name": "dex", "function_name": "swap", "type_args": ["0x1::native_uinit::Coin", "0x1::native_uusdc::Coin"], "args": ["base64 encoded bytes array"] }, // optional field to get async callback (ack and timeout) "async_callback": { "id": 1, "module_address": "0x1", "module_name": "dex" } } } } } ``` An ICS20 packet is formatted correctly for movehooks if the following all hold: * [x] `memo` is not blank * [x] `memo` is valid JSON * [x] `memo` has at least one key, with value `"move"` * [x] `memo["move"]["message"]` has exactly five entries, `"module_address"`, `"module_name"`, `"function_name"`, `"type_args"` and `"args"` * [x] `receiver` == "" || `receiver` == `"module_address::module_name::function_name"` An ICS20 packet is considered directed towards movehooks if all of the following hold: * [x] `memo` is not blank * [x] `memo` is valid JSON * [x] `memo` has at least one key, with name "move" If an ICS20 packet is not directed towards movehooks, movehooks doesn't do anything. If an ICS20 packet is directed towards movehooks, and is formatted incorrectly, then movehooks returns an error. # Execution Flow Pre Move hooks: * Ensure the incoming IBC packet is cryptographically valid * Ensure the incoming IBC packet is not timed out. In Move hooks, pre packet execution: * Ensure the packet is correctly formatted (as defined above) * Edit the receiver to be the hardcoded IBC module account In Move hooks, post packet execution: * Construct move message as defined before * Execute move message * if move 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, which wants to receive ack callback, has to implement two functions. * ibc\_ack * ibc\_timeout ```rust theme={null} public entry fun ibc_ack( account: &signer, callback_id: u64, success: bool, ) public entry fun ibc_timeout( account: &signer, callback_id: u64, ) ``` Also when a contract makes an IBC transfer request, it should provide async callback data through memo field. * `memo['move']['async_callback']['id']`: the async callback id is assigned from the contract. so later it will be passed as an argument of ibc\_ack and ibc\_timeout. * `memo['move']['async_callback']['module_address']`: The address of module which defines the callback function. * `memo['move']['async_callback']['module_name']`: The name of module which defines the callback function. # Tutorials This tutorial will guide you through the process of deploying a Move contract and calling it from another chain using IBC hooks. This example uses an IBC hook from chain to call a Move contract on Initia chain (L2 -> L1). ## Step 1. Deploy a Move Contract Write and deploy a simple token transfer contract to Initia. ```move theme={null} module deployer::example { use initia_std::coin; use initia_std::object::Object; use initia_std::fungible_asset::Metadata; public entry fun simple_transfer( account: &signer, receiver: address, metadata: Object<Metadata>, amount: u64 ){ let token = coin::withdraw(account, metadata, amount); coin::deposit(receiver, token); } } ``` ## Step 2. Update IBC Hook ACL for the Contract IBC hooks have the power to execute any function on the counterparty chain, which can easily be exploited for phishing. Therefore, you need to set the ACL for the contract to prevent unauthorized access. ```typescript theme={null} // for initia L1, you can update ACL by submitting a proposal const aclMsg = new MsgUpdateACL( 'init10d07y265gmmuvt4z0w9aw880jnsr700j55nka3', // authority 'init14qcr2mczuzlav8z2uqm3d0zdw04nuhf2jgndc3', // contract address true, // allow ) const msgs = [ new MsgSubmitProposal( [aclMsg], '100000000uinit', // deposit proposer.key.accAddress, // proposer 'uinit', // metadata 'awesome proposal', // title 'it is awesome', // summary false, // expedited ), ] const signedTx = await proposer.createAndSignTx({ msgs }) await proposer.rest.tx.broadcast(signedTx).then((res) => console.log(res)) ``` If you want to update MiniMove ACL, you need to use `MsgExecuteMessages` in OPchild module. ```typescript theme={null} const aclMsg = new MsgUpdateACL( 'init10d07y265gmmuvt4z0w9aw880jnsr700j55nka3', // authority 'init14qcr2mczuzlav8z2uqm3d0zdw04nuhf2jgndc3', // contract address true, // allow ) const msgs = [new MsgExecuteMessages(proposer.key.accAddress, [aclMsg])] const signedTx = await proposer.createAndSignTx({ msgs }) await proposer.rest.tx.broadcast(signedTx).then((res) => console.log(res)) ``` You can check the ACL list using the following command. ```bash theme={null} curl -X GET "https://rest.testnet.initia.xyz/initia/ibchooks/v1/acls" -H "accept: application/json" ``` Response: ```json theme={null} { "acls": [], "pagination": { "next_key": null, "total": "0" } } ``` ## 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 { bcs, Coin, Height, RESTClient, MnemonicKey, MsgTransfer, Wallet, } from '@initia/initia.js' function createHook(params: object) { const hook = { move: { message: params } } return JSON.stringify(hook) } async function main() { const l1RestClient = new RESTClient('https://rest.testnet.initia.xyz', { gasAdjustment: '1.75', gasPrices: '0.015uinit', }) const l2RestClient = new RESTClient( 'https://rest-move-1.anvil.asia-southeast.initia.xyz', { gasAdjustment: '1.75', gasPrices: '0.15l2/07b129ceb9c4b0bdef7db171ce1e22f90d34bc930058b23e21adf8cc938d8145', // set l2 gas price }, ) const sender = new Wallet( l2RestClient, new MnemonicKey({ mnemonic: 'power elder gather acoustic ...', }), ) const recipientAddress = 'init1wgl839zxdh5c89mvc4ps97wyx6ejjygxs4qmcx' const tokenPair = await l1RestClient.ophost.tokenPairByL1Denom(1458, 'uinit') // { l1_denom: 'uinit', l2_denom: 'l2/07b129ceb9c4b0bdef7db171ce1e22f90d34bc930058b23e21adf8cc938d8145' } const ibcTrace = 'transfer/' + 'channel-0/' + tokenPair.l2_denom // IBC denom trace = `port_id/channel_id/denom` const ibcDenomHash = await l1RestClient.ibcTransfer.denomHash(ibcTrace) // IBC denom = `ibc/${denom_hash}` const tokenMetadata = await l1RestClient.move.metadata('ibc/' + ibcDenomHash) const amount = 1000 const msgs = [ new MsgTransfer( 'transfer', 'channel-0', new Coin(tokenPair.l2_denom, 10), sender.key.accAddress, '0xA830356F02E0BFD61C4AE03716BC4D73EB3E5D2A::example::simple_transfer', // IBC hook receiver = `ModuleAddress::ModuleName::FunctionName` new Height(0, 0), ((new Date().valueOf() + 100000) * 1000000).toString(), createHook({ module_address: '0xA830356F02E0BFD61C4AE03716BC4D73EB3E5D2A', module_name: 'example', function_name: 'simple_transfer', type_args: [], args: [ bcs.address().serialize(recipientAddress).toBase64(), bcs.address().serialize(tokenMetadata).toBase64(), bcs.u64().serialize(amount).toBase64(), ], }), ), ] const signedTx = await sender.createAndSignTx({ msgs }) await l2RestClient.tx.broadcastSync(signedTx).then((res) => console.log(res)) } main() ``` # Multisig Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/movevm/multisig Multi Signature (multisig) allows multiple users to sign a transaction before it is broadcasted to the network. This ensures that no single user can execute a transaction unilaterally, adding an extra layer of security and trust. Multisig accounts are essential in environments where assets are managed collectively, such as corporate treasuries or joint accounts. In this tutorial, you will explore how to create and manage multisignature accounts, proposals, and execute them using the `InitiaJS` library. ## Create Multisig Accounts Creating a multisig account is the first step in setting up a multi-approval system. This account will require a predefined number of approvals (threshold) to execute transactions. ```move theme={null} public entry fun create_non_weighted_multisig_account( account: &signer, name: String, // name for make deterministic multisig address (account_addr + name) members: vector<address>, threshold: u64 ) ``` * `account`: The signer creating the multisig account. * `name`: A name to generate a unique multisig address. * `members`: A vector of addresses that will be members of the multisig account. * `threshold`: The minimum number of approvals required to execute a transaction. ```ts InitiaJS theme={null} const msgCreateNonWeightedMultisigAccount = new MsgExecute( multisigCreator.key.accAddress, '0x1', 'multisig_v2', 'create_non_weighted_multisig_account', [], [ bcs.string().serialize(multisigName), // name bcs .vector(bcs.address()) .serialize([ multisigCreator.key.accAddress, multisigMember1.key.accAddress, multisigMember2.key.accAddress, ]), // members bcs.u64().serialize(2), // threshold ].map((v) => v.toBase64()), ) ``` ## Create a Proposal Once the multisig account is established, members can create proposals for actions that require collective approval. A proposal outlines the intended transaction or changes that need to be approved by the members. ```move theme={null} public entry fun create_proposal( account: &signer, multisig_addr: address, module_address_list: vector<address>, module_name_list: vector<String>, function_name_list: vector<String>, type_args_list: vector<vector<String>>, args_list: vector<vector<vector<u8>>>, expiry_duration: Option<u64> ) ``` * `multisig_addr`: The address of the multisig account where the proposal is created. * `module_address_list`: module addresses to be executed in the proposal. * `module_name_list`: module names to be executed in the proposal. * `function_name_list`: function names to be executed in the proposal. * `type_args_list`: Type arguments required for the functions. * `args_list`: Arguments for the functions. * `expiry_duration`: Optional expiration duration for the proposal. In this example, two proposals are created. The first proposal sends tokens using the `0x1::cosmos::stargate` function, and the second proposal sends tokens using the `0x1::coin::transfer` function. ```ts InitiaJS theme={null} // Proposal 1. send token with `0x1::cosmos::stargate` function const recipient = 'init1nu7ujl76zac4pkdck8r2zve5zkjaus2xuz8thx' const msgMiultiSigProposal1 = new MsgSend( AccAddress.fromHex(multisigAddress), recipient, new Coins({ uinit: 1_000_000 }), ) // Proposal 2. send token with `0x1::coin::transfer` function const msgMiultiSigProposal2Args = [ bcs.address().serialize(recipient), // recipient bcs .object() .serialize( '0x8e4733bdabcf7d4afc3d14f0dd46c9bf52fb0fce9e4b996c939e195b8bc891d9', ), // coin metadata bcs.u64().serialize(1_000_000), // amount ] const msgCreateProposal = new MsgExecute( multisigCreator.key.accAddress, '0x1', 'multisig_v2', 'create_proposal', [], [ bcs.address().serialize(multisigAddress), // multisig address bcs.vector(bcs.address()).serialize(['0x1', '0x1']), // module addresses bcs.vector(bcs.string()).serialize(['cosmos', 'coin']), // module names bcs.vector(bcs.string()).serialize(['stargate', 'transfer']), // function names bcs.vector(bcs.vector(bcs.string())).serialize([[], []]), // function type args bcs.vector(bcs.vector(bcs.vector(bcs.u8()))).serialize([ [ [ ...bcs .vector(bcs.u8()) .serialize( Buffer.from(JSON.stringify(msgMiultiSigProposal1.toData())), ) .toBytes(), ], ], msgMiultiSigProposal2Args.map((v) => v.toBytes()), ]), // function args bcs.option(bcs.u64()).serialize(null), // expiry duratio
프로젝트로 돌아가기