Initia 백서

Initia

원문

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

will generate output similar to this: <Tabs> <Tab title="CLI Output"> ```bash theme={null} - address: init1ejr270mhdw260hk4ggp4kwmxd20authfag282m name: example pubkey: '{"@type":"/cosmos.crypto.secp256k1.PubKey","key":"AzBfkuS1ojSqNfqztk34Pn86n7D5MbhKobmsUIN372QG"}' type: local **Important** write this mnemonic phrase in a safe place. It is the only way to recover your account if you ever forget your password. [mnemonic from environment variable] ``` </Tab> <Tab title="InitiaJS Output"> **For new account generation:** ```bash theme={null} mnemonic: sunset major dog cat window spider victory ocean crystal repair guard volcano front husband duck prepare pioneer today shift patrol desert friend power master private key: <Buffer a3 f4 c2 9e 7b 5f d8 91 3c 2a 8b 47 9e c1 d5 6b 8f 92 3a 7c 4e 1b 9f 8c 73 2d 9a b5 6e 1f 4c> public key: Z { key: 'A2Bf8uK9RMehfDmBM3AwqZ4Y21r2H+hUMjS6++CSP' } account address: init1d7s3q7nmlzqz9v4tk6ntrvfmavu2vk656gr29j ``` **For importing existing account:** ```bash theme={null} account address: init17mq4sqemx2djc59tda76y20nwp4pfn4943x9ze ``` </Tab> </Tabs> <Warning> **Secure Your Mnemonic Phrase** Your mnemonic phrase is the only way to recover your account. Store it securely and never share it publicly. Consider using a password manager or writing it down and storing it in a safe place. </Warning> </Step> <Step title="Fund Your Development Account"> To deploy and test Move modules, your account needs tokens to pay for transaction fees. ### Testnet Funding For testnet development, use the official Initia faucet to get free tokens: <Card title="Initia Testnet Faucet" icon="droplet" href="https://v1.app.testnet.initia.xyz/faucet"> Get free testnet tokens for development and testing purposes. </Card> ### Funding Process 1. Visit the [Initia faucet](https://v1.app.testnet.initia.xyz/faucet) 2. Enter your account address (from the previous step) 3. Request tokens for your target network 4. Wait for the transaction to be processed <Info> Faucet tokens are only for testnet use and have no monetary value. They're designed specifically for development and testing purposes. </Info> ### Verify Your Balance After funding, verify your account has received tokens: <CodeGroup> <CodeBlock> initiad query bank balances \[your-address] </CodeBlock> <CodeBlock> minitiad query bank balances \[your-address] </CodeBlock> </CodeGroup> </Step> </Steps> ## Next Steps With your development environment set up, you're ready to start building with Move! The next section will guide you through creating, compiling, deploying, and interacting with your first Move module. <CardGroup> <Card title="Network Configuration" icon="network-wired"> Learn how to configure your CLI for different networks and environments. </Card> <Card title="Move Module Basics" icon="cubes"> Understand the fundamentals of Move module structure and development. </Card> </CardGroup> # Using Connect Oracle Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/wasmvm/connect-oracles To query prices from Connect oracle on WasmVM, you need to utilize the queries provided by the [wasm-connect-query](https://github.com/initia-labs/wasm-connect-query) contract. Specifically, the contract provides 3 queries: 1. `GetAllCurrencyPairs`: Returns all of the currently supported asset pairs 2. `GetPrice`: Returns the price of a single asset pair 3. `GetPrices`: Returns the price of multiple asset pairs ## Integrating the Queries Into Your Contract To make the queries from your own contracts, you can copy the `packages` folder found in the wasm-connect-query contract repository into your own project. This folder contains the necessary files and definitions to make the queries from your own contracts. See [here](https://github.com/initia-labs/examples/tree/main/wasmvm/examples) for an example contract that integrated the queries. The way that you use each query and the response structure returned from each is then outlined below. ### GetAllCurrencyPairs This query takes no arguments and returns the list of all of the currently supported asset pairs. **Example Usage (Simplified)** ```rust theme={null} #[derive(Clone, Debug, PartialEq, Deserialize, Serialize, JsonSchema)] pub struct GetAllCurrencyPairsResponse { pub currency_pairs: Vec<CurrencyPairResponse>, } #[derive(Clone, Debug, PartialEq, Deserialize, Serialize, JsonSchema)] #[allow(non_snake_case)] pub struct CurrencyPairResponse { pub Base: String, pub Quote: String, } pub fn example_get_all_currency_pairs(deps: Deps) -> StdResult<GetAllCurrencyPairsResponse> { let state = STATE.load(deps.storage)?; let connect_addr = state.connect; deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart { contract_addr: connect_addr.to_string(), msg: to_json_binary(&connect_wasm::oracle::QueryMsg::GetAllCurrencyPairs {})?, })) } ``` The response is of type `GetAllCurrencyPairsResponse` and is in the following form: **Example Response** ```json theme={null} { "data": { "currency_pairs": [ { "Base": "AAVE", "Quote": "USD" }, { "Base": "ADA", "Quote": "USD" } ] } } ``` ## GetPrice This query takes two arguments: `base` and `quote`, which represent the base and quote asset symbol strings of the asset pair you want to query. Note that the `base` and `quote` pair must be supported by Connect and be included in the `GetAllCurrencyPairsResponse`. For example, "BTC" and "USD" is a valid pair, but "BTC" and "AAVE" is not. **Example Usage (Simplified)** ```rust theme={null} #[derive(Clone, Debug, PartialEq, Deserialize, Serialize, JsonSchema)] pub struct QuotePrice { pub price: Uint256, pub block_timestamp: Timestamp, pub block_height: u64, } #[derive(Clone, Debug, PartialEq, Deserialize, Serialize, JsonSchema)] pub struct GetPriceResponse { pub price: QuotePrice, pub nonce: u64, pub decimals: u64, pub id: u64, } pub fn example_get_price(deps: Deps) -> StdResult<GetPriceResponse> { let state = STATE.load(deps.storage)?; let connect_addr = state.connect; let base_asset = "BTC"; let quote_asset = "USD"; deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart { contract_addr: connect_addr.to_string(), msg: to_json_binary(&connect_wasm::oracle::QueryMsg::GetPrice { base: base_asset.to_string(), quote: quote_asset.to_string(), })?, })) } ``` **Example Response** ```json theme={null} { "data": { "price": { "price": "5719601000", "block_timestamp": "1720511108184124288", "block_height": 2924966 }, "nonce": 1195438, "decimals": 5, "id": 2 } } ``` ## GetPrices This query takes a list of asset pair IDs and returns the prices of the asset pairs. Unlike for `GetPrice`, the pair IDs are not an object symbol, but instead a single string in the format `{base}/{quote}`. For example, `BTC/USD` or `ETH/USD`. **Example Usage (Simplified)** ```rust theme={null} #[derive(Clone, Debug, PartialEq, Deserialize, Serialize, JsonSchema)] pub struct QuotePrice { pub price: Uint256, pub block_timestamp: Timestamp, pub block_height: u64, } #[derive(Clone, Debug, PartialEq, Deserialize, Serialize, JsonSchema)] pub struct GetPriceResponse { pub price: QuotePrice, pub nonce: u64, pub decimals: u64, pub id: u64, } #[derive(Clone, Debug, PartialEq, Deserialize, Serialize, JsonSchema)] pub struct GetPricesResponse { pub prices: Vec<GetPriceResponse>, } pub fn example_get_prices(deps: Deps) -> StdResult<GetPricesResponse> { let state = STATE.load(deps.storage)?; let connect_addr = state.connect; let pair_ids = vec!["BTC/USD".to_string(), "ETH/USD".to_string()]; deps.querier.query(&QueryRequest::Wasm(WasmQuery::Smart { contract_addr: connect_addr.to_string(), msg: to_json_binary(&connect_wasm::oracle::QueryMsg::GetPrices { pair_ids })?, })) } ``` **Example Response** ```json theme={null} { "data": { "prices": [ { "price": { "price": "5720974000", "block_timestamp": "1720511618058897916", "block_height": 2925527 }, "nonce": 1195719, "decimals": 5, "id": 2 }, { "price": { "price": "3065580000", "block_timestamp": "1720511618058897916", "block_height": 2925527 }, "nonce": 1195719, "decimals": 6, "id": 59 } ] } } ``` # WasmVM IBC Hooks Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/wasmvm/ibc-hooks The Wasm hook is an IBC middleware that allows ICS20 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 or ICS721 transfer packet as of [IBC v3.4.0](https://medium.com/the-interchain-foundation/moving-beyond-simple-token-transfers-d42b2b1dc29b). Wasm hooks is an IBC middleware that parses an ICS20 transfer, and if the memo field is of a particular form, executes a wasm contract call. This section details the memo format for wasm contract calls, and the execution guarantees provided. # Cosmwasm Contract Execution Format Before diving into the IBC metadata format, here is the CosmWasm execute message format, showing the fields that need to be set. The CosmWasm `MsgExecuteContract` is defined [here](https://github.com/CosmWasm/wasmd/blob/4fe2fbc8f322efdaf187e2e5c99ce32fd1df06f0/x/wasm/types/tx.pb.go#L340-L349) as the following type: ```go theme={null} // HookData defines a wrapper for wasm execute message // and async callback. type HookData struct { // Message is a wasm execute message which will be executed // at `OnRecvPacket` of receiver chain. Message *wasmtypes.MsgExecuteContract `json:"message,omitempty"` // AsyncCallback is a contract address AsyncCallback string `json:"async_callback,omitempty"` } type MsgExecuteContract struct { // Sender is the actor that committed the message in the sender chain Sender string // Contract is the address of the smart contract Contract string // Msg json encoded message to be passed to the contract Msg RawContractMessage // Funds coins that are transferred to the contract on execution Funds sdk.Coins } ``` Here is where each of these fields comes from: * `Sender`: The sender of an IBC packet cannot be trusted, as the counterparty 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 wasm module prefix. This is done by setting the sender to Bech32(Hash("ibc-wasm-hook-intermediary" || channelID || sender)), where the channelId is the channel id on the local chain. * `Contract`: This field should be directly obtained from the ICS-20 packet metadata * `Msg`: This field should be directly obtained from the ICS-20 packet metadata. * `Funds`: This field is set to the amount of funds being sent over in the ICS 20 packet. One detail is that the denom in the packet is the counterparty chain's representation of the denom, so it must be translated to Initia's representation. <Note> Due to a [bug](https://x.com/SCVSecurity/status/1682329758020022272) in the packet forward middleware, the sender from chains that use PFM cannot be trusted. Until that is fixed, chains should not trust the sender on contracts executed via IBC hooks. </Note> ```go theme={null} msg := MsgExecuteContract{ // Sender is the actor that signed the messages Sender: "init1-hash-of-channel-and-sender", // Contract is the address of the smart contract Contract: packet.data.memo["wasm"]["contract"], // Msg json encoded message to be passed to the contract Msg: packet.data.memo["wasm"]["msg"], // Funds coins that are transferred to the contract on execution Funds: sdk.NewCoin{Denom: ibc.ConvertSenderDenomToLocalDenom(packet.data.Denom), Amount: packet.data.Amount} } ``` # 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": "contract addr or blank", "memo": { "wasm": { "contract": "init1contractAddr", "msg": { "raw_message_fields": "raw_message_data" }, "funds": [{ "denom": "ibc/denom", "amount": "100" }] } } } } ``` An ICS20 packet is formatted correctly for wasmhooks iff the following all hold: * [x] `memo` is not blank * [x] `memo` is valid JSON * [x] `memo` has at least one key, with value `"wasm"` * [x] `memo["wasm"]["message"]` has exactly three entries, `"contract"`, `"msg"` and `"funds"` * [x] `memo["wasm"]["message"]["msg"]` is a valid JSON object * [x] `receiver` == "" || `receiver` == `memo["wasm"]["contract"]` An ICS20 packet is considered directed towards wasmhooks iff all of the following hold: * [x] `memo` is not blank * [x] `memo` is valid JSON * [x] `memo` has at least one key, with name `"wasm"` If an ICS20 packet is not directed towards wasmhooks, wasmhooks doesn't do anything. If an ICS20 packet is directed towards wasmhooks, and is formatted incorrectly, then wasmhooks returns an error. # Execution flow Pre Wasm hooks: * Ensure the incoming IBC packet is cryptographically valid * Ensure the incoming IBC packet is not timed out. In Wasm hooks, pre packet execution: * Ensure the packet is correctly formatted (as defined above) * Edit the receiver to be the hardcoded IBC module account In Wasm hooks, post packet execution: * Construct wasm message as defined before * Execute wasm message * if wasm message has error, return ErrAck * otherwise continue through middleware # Ack callbacks 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. ## Design The sender of an IBC transfer packet may specify a callback for when the ack of that packet is received in the memo field of the transfer packet. Crucially, only the IBC packet sender can set the callback. ## Use Case The crosschain swaps implementation sends an IBC transfer. If the transfer were to fail, the sender needs to be able to retrieve their funds (which would otherwise be stuck in the contract). To do this, users can retrieve the funds after the timeout has passed, but without the ack information, there is no guarantee that the send hasn't failed (i.e.: returned an error ack notifying that the receiving chain didn't accept it) # Implementation ## Callback Information in Memo For the callback to be processed, the transfer packet's memo should contain the following in its JSON: ```json theme={null} { "wasm": { "async_callback": "init1contractAddr" } } ``` When an ack is received, it will notify the specified contract via a sudo message. ## Interface for Receiving the Acks and Timeouts The contract that awaits the callback should implement the following interface for a sudo message: ```rust theme={null} #[cw_serde] pub enum IBCLifecycleComplete { #[serde(rename = "ibc_ack")] IBCAck { /// The source channel (miniwasm side) of the IBC packet channel: String, /// The sequence number that the packet was sent with sequence: u64, /// String encoded version of the ack as seen by OnAcknowledgementPacket(..) ack: String, /// Whether an ack is a success or failure according to the transfer spec success: bool, }, #[serde(rename = "ibc_timeout")] IBCTimeout { /// The source channel (miniwasm side) of the IBC packet channel: String, /// The sequence number that the packet was sent with sequence: u64, }, } /// Message type for `sudo` entry_point #[cw_serde] pub enum SudoMsg { #[serde(rename = "ibc_lifecycle_complete")] IBCLifecycleComplete(IBCLifecycleComplete), } ``` # Tutorials This tutorial will guide you through the process of deploying a Wasm contract and calling it from another chain using IBC hooks. This example uses an IBC hook from Initia chain to call a Wasm contract on MiniWasm chain. ## Step 1. Deploy a Wasm Contract ```rust theme={null} // ... #[entry_point] pub fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> StdResult<Response> { match msg { ExecuteMsg::SimpleTransfer { amount, denom, receiver } => simple_transfer(deps, env, info, amount, denom, receiver), } } pub fn simple_transfer( _deps: DepsMut, _env: Env, _info: MessageInfo, amount: u128, denom: String, receiver: String, ) -> StdResult<Response> { let mut messages: Vec<CosmosMsg> = vec![]; messages.push(CosmosMsg::Bank(BankMsg::Send { to_address: receiver, amount: coins(amount, denom) })); Ok(Response::new().add_messages(messages)) } // ... ``` ## 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 MiniWasm ACL, use `MsgExecuteMessages` in OPchild module. ```typescript theme={null} const aclMsg = new MsgUpdateACL( 'init10d07y265gmmuvt4z0w9aw880jnsr700j55nka3', // authority 'init1436kxs0w2es6xlqpp9rd35e3d0cjnw4sv8j3a7483sgks29jqwgs9nxzw8', // 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)) ``` ```bash theme={null} curl -X GET "https://rest-wasm-1.anvil.asia-southeast.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 { Coin, Height, RESTClient, MnemonicKey, MsgTransfer, sha256, Wallet, } from '@initia/initia.js' function createHook(params: object) { const hook = { wasm: { message: params } } return JSON.stringify(hook) } function ibcDenom(channelId: string, denom: string) { const fullTrace = `transfer/${channelId}/${denom}` const shaSum = sha256(Buffer.from(fullTrace)) const hash = Buffer.from(shaSum).toString('hex').toUpperCase() return `ibc/${hash}` } async function main() { const l1RestClient = new RESTClient('https://rest.testnet.initia.xyz', { gasAdjustment: '1.75', gasPrices: '0.015uinit', // set l1 gas price }) const sender = new Wallet( l1RestClient, new MnemonicKey({ mnemonic: 'power elder gather acoustic ...', }), ) const recipientAddress = 'init1wgl839zxdh5c89mvc4ps97wyx6ejjygxs4qmcx' const tokenPair = await l1RestClient.ophost.tokenPairByL1Denom(1457, 'uinit') // { l1_denom: 'uinit', l2_denom: 'l2/8b3e1fc559b327a35335e3f26ff657eaee5ff8486ccd3c1bc59007a93cf23156' } const denom = ibcDenom('channel-0', tokenPair.l1_denom) // use IBC channel on MiniWasm side const amount = '1000' const msgs = [ new MsgTransfer( 'transfer', 'channel-2', new Coin(tokenPair.l1_denom, amount), sender.key.accAddress, 'init1436kxs0w2es6xlqpp9rd35e3d0cjnw4sv8j3a7483sgks29jqwgs9nxzw8', // IBC hook receiver = `ModuleAddress::ModuleName::FunctionName` new Height(0, 0), ((new Date().valueOf() + 100000) * 1000000).toString(), createHook({ contract: 'init1436kxs0w2es6xlqpp9rd35e3d0cjnw4sv8j3a7483sgks29jqwgs9nxzw8', msg: { simple_transfer: { amount: Number(amount), denom: denom, receiver: recipientAddress, }, }, funds: [{ denom: denom, amount: amount }], }), ), ] const signedTx = await sender.createAndSignTx({ msgs }) await l1RestClient.tx.broadcastSync(signedTx).then((res) => console.log(res
프로젝트로 돌아가기