Initia 백서

Initia

원문

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

opinit --help ``` # Running IBC Relayer Source: https://docs.initia.xyz/developers/developer-guides/tools/clis/weave-cli/rollup/relayer An IBC relayer is a software component that facilitates communication between two distinct blockchain networks that support the Inter-Blockchain Communication (IBC) protocol. Built-in oracle, Minitswap, and other cross-chain services require it to function with your rollup. Weave currently only supports Rapid relayer configuration generation. It will support running the rapid relayer directly in the future. For more detailed information about Rapid relayer, see the [Rapid relayer documentation](https://github.com/initia-labs/rapid-relayer). <Note> Weave only supports IBC relayer setup between Initia L1 and Interwoven Rollups. Setting up relayers between other arbitrary networks is not supported. </Note> ## Setting Up For this guide, you'll need Weave v0.3.0 or newer. You can check your Weave version by running `weave version`. If you need to upgrade, run `weave upgrade`. ```bash theme={null} weave relayer init ``` This command will guide you through 2 major parts of the relayer setup: * Setting up networks and channels to relay messages between * Setting up the account responsible for relaying messages For the former, Weave will present you with three options: 1. Configure channels between Initia L1 and a whitelisted Rollup (those available in [Initia Registry](https://github.com/initia-labs/initia-registry)) 2. Configure using artifacts from `weave rollup launch` (recommended for users who have just launched their rollup) 3. Configure manually As for the latter, Weave will ask whether you want to use the OPinit Challenger bot account for the relayer. This is recommended as it is exempted from gas fees on the rollup and able to stop other relayers from relaying when it detects a malicious message. <Warning> Relayer requires funds to relay messages between Initia L1 and your rollup (if it's not in the fee whitelist). If Weave detects that your account does not have enough funds, Weave will ask you to fund via Gas Station. </Warning> ## Running Relayer Currently, Weave generates the relayer configuration file but does not run the relayer directly. You'll need to manually set up and run the Rapid relayer using the generated configuration. <Note> Make sure you have Node.js and npm installed on your system if you wish to run the relayer in the same machine. </Note> <Steps> <Step title="Clone and Install Rapid relayer"> Clone the Rapid relayer repository and install its dependencies: ```bash theme={null} git clone https://github.com/initia-labs/rapid-relayer cd rapid-relayer npm install ``` </Step> <Step title="Copy Configuration File"> Move the generated configuration file to the Rapid relayer directory: ```bash theme={null} cp ~/.relayer/config.json ./config.json ``` </Step> <Step title="Start the Relayer"> Launch the relayer with the configuration: ```bash theme={null} npm start ``` </Step> </Steps> ## Help To see all the available commands: ```bash theme={null} weave relayer --help ``` # Single Asset Price Source: https://docs.initia.xyz/developers/developer-guides/tools/oracles/connect/fetching-prices-from-api/getting-single-asset-price GET /connect/oracle/v2/get_price?currency_pair={baseCurrency}/{quoteCurrency} <ParamField type="string"> The base currency of the asset to get the price for (e.g. `BTC`) </ParamField> <ParamField type="string"> The quote currency of the asset to get the price for (e.g. `USD`) </ParamField> This endpoint returns the latest price data for a given `baseCurrency` and `quoteCurrency` pair. Note that `baseCurrency` and `quoteCurrency` must be a pair supported and found in the [supported feeds](/developers/developer-guides/tools/oracles/connect/fetching-prices-from-api/getting-supported-feeds) endpoint, and combinations are not supported. For example, even if `BTC`/`USD` and `ETH`/`USD` are supported, `BTC`/`ETH` is not supported. # Supported Feeds Source: https://docs.initia.xyz/developers/developer-guides/tools/oracles/connect/fetching-prices-from-api/getting-supported-feeds GET /connect/oracle/v2/get_all_tickers This endpoint returns all of the asset/currency pairs that are currently supported by Connect on the given network. # Fetching Connect Prices from Smart Contract Source: https://docs.initia.xyz/developers/developer-guides/tools/oracles/connect/fetching-prices-from-contracts As mentioned earlier in this section, smart contracts can also fetch and use Connect price data directly. On Initia, the approach varies depending on which smart contract framework you use. <CardGroup> <Card title="EVM" icon="ethereum" href="/developers/developer-guides/vm-specific-tutorials/evm/connect-oracles"> Fetch prices from Solidity and other EVM-based smart contracts </Card> <Card title="MoveVM" icon="note-sticky" href="/developers/developer-guides/vm-specific-tutorials/movevm/connect-oracles"> Fetch prices from Move modules </Card> <Card title="WasmVM" icon="rust" href="/developers/developer-guides/vm-specific-tutorials/wasmvm/connect-oracles"> Fetch prices from CosmWasm contracts </Card> </CardGroup> # Introduction to Connect Source: https://docs.initia.xyz/developers/developer-guides/tools/oracles/connect/introduction Connect is an enshrined oracle service built by [Skip](https://skip.money), designed to deliver fast and up-to-date asset price data to the blockchain. The system achieves this by leveraging two new features introduced in Cosmos SDK version 0.50: [ABCI++](https://members.delphidigital.io/learn/abci) and [Vote Extensions](https://docs.cosmos.network/main/build/abci/vote-extensions). These features enable the chain's validators to submit arbitrary data, such as asset price information, into the block proposal process, which is then stored on-chain. This eliminates the possibility of price updates being censored or delayed due to chain congestion or other censorship attempts, ensuring the chain and its applications always have access to fresh and up-to-date price data. Once the data is on-chain, application developers can then query and make use of the data in various ways, such as querying the chain directly through the command line or a frontend, or through the smart contract level. In Initia's case, Connect prices can also be relayed from the Initia L1 to any rollup through the rollup's [OPinit Bot](/home/core-concepts/interwoven-stack/opinit-framework/components/introduction). This eliminates the need for rollup teams to spend resources and time finding and integrating their own oracle provider. For more information on Connect, please see their [documentation](https://docs.skip.build/connect/introduction). # Account Source: https://docs.initia.xyz/developers/developer-guides/tools/sdks/initia-js/accounts ## Creating an Account Before you can start building and transacting, you'll need to create an account. ```ts InitiaJS theme={null} import { MnemonicKey } from '@initia/initia.js' const key = new MnemonicKey() ``` <Warning> The mnemonic key is the only way to recover your account if you forget your password. </Warning> ## Importing an Account You can also import an account by providing a mnemonic phrase or a raw key. ```ts InitiaJS theme={null} import { MnemonicKey } from '@initia/initia.js' const keyByMnemonic = new MnemonicKey({ mnemonic: 'bird upset ... evil cigar', }) const keyByRawKey = new RawKey(keyByMnemonic.privateKey) console.log('keyByMnemonic:', keyByMnemonic.privateKey) console.log('keyByRawKey:', keyByRawKey.privateKey) ``` Output: ```bash theme={null} keyByMnemonic: <Buffer e5 71 db 8c 0c 44 d4 81 e1 ef 62 81 ec ab 5a 26 b4 35 db fb 6b ec b6 51 43 8e d8 c9 ef e0 40 c1> keyByRawKey: <Buffer e5 71 db 8c 0c 44 d4 81 e1 ef 62 81 ec ab 5a 26 b4 35 db fb 6b ec b6 51 43 8e d8 c9 ef e0 40 c1> ``` If you want to create an EVM account, you can use the following code: ```ts InitiaJS theme={null} const cosmosKeyByMnemonic = new MnemonicKey({ mnemonic: 'bird upset ... evil cigar', }) const evmKeyByMnemonic = new MnemonicKey({ mnemonic: 'bird upset ... evil cigar', coinType: 60, eth: true, }) console.log('cosmosKeyByMnemonic:', cosmosKeyByMnemonic.accAddress) console.log('evmKeyByMnemonic:', evmKeyByMnemonic.accAddress) ``` Output: ```bash theme={null} cosmosKeyByMnemonic: init1d7s3q7nmlzqz9v4tk6ntrvfmavu2vk656gr29j evmKeyByMnemonic: init1f7t8tqnltm2n0ghs3g9uyplkj3rf2mh9tcf4r9 ``` ## Retrieving Account Data You can retrieve account data from the key object. ```ts InitiaJS theme={null} import { MnemonicKey } from '@initia/initia.js' const key = new MnemonicKey({ mnemonic: 'across debate retreat border auction drum inflict demise jaguar fine dizzy absorb general include brush wet exclude host reward post angle shield mouse model', }) console.log('mnemonic:', key.mnemonic) console.log('private key:', key.privateKey) console.log('public key:', key.publicKey) console.log('account address:', key.accAddress) console.log('account validator address:', key.valAddress) ``` Output: ```bash theme={null} mnemonic: across debate retreat border auction drum inflict demise jaguar fine dizzy absorb general include brush wet exclude host reward post angle shield mouse model private key: <Buffer e5 71 db 8c 0c 44 d4 81 e1 ef 62 81 ec ab 5a 26 b4 35 db fb 6b ec b6 51 43 8e d8 c9 ef e0 40 c1> public key: Z { key: 'AmXrEF5FHNkRMehfDmBM3AwqZ4Y21r2H+hUMjS6++CSP' } account address: init17mq4sqemx2djc59tda76y20nwp4pfn4943x9ze account validator address: initvaloper17mq4sqemx2djc59tda76y20nwp4pfn49p5luvf ``` # Introduction Source: https://docs.initia.xyz/developers/developer-guides/tools/sdks/initia-js/introduction [InitiaJS](https://npmjs.org/@initia/initia.js) is a TypeScript library for interacting with the Initia L1 and rollups. The SDK allows developers to query data from the chains, sign and send transactions, and more. ## Getting Started To get started using InitiaJS, you simply need to install the SDK using npm or other package managers. ```bash theme={null} npm install @initia/initia.js ``` # Querying Data Source: https://docs.initia.xyz/developers/developer-guides/tools/sdks/initia-js/querying-data The InitiaJS SDK offers a powerful `RESTClient` that simplifies the process of querying data from both the Initia L1 and rollups. This client encapsulates various endpoints and methods into user-friendly helper functions, organized under sub-categories of the `rest` client based on their corresponding Cosmos SDK modules. In this tutorial, you'll explore several examples demonstrating how to leverage these helper functions to retrieve key data points efficiently using the SDK. For demonstration purposes, assume that all of these examples are implemented in a file named `src/query.ts`. ## Querying Account Balance To query the balance of an account, you can use the `balance` function from the `bank` module. This function takes in an address and returns the balance of the account. First, make the necessary imports and initialize the `RESTClient`. ```ts theme={null} import { RESTClient, Coin } from '@initia/initia.js' const restClient = new RESTClient('https://rest.testnet.initia.xyz', { chainId: 'initiation-2', gasPrices: '0.015uinit', // default gas prices gasAdjustment: '2.0', // default gas adjustment for fee estimation }) ``` <Note> Adjust gasPrices and gasAdjustment according to current [network](/resources/developer/initia-l1) conditions for optimal transaction processing. </Note> Next, create a function to query the balance of an account. This function will take in an address and return the balance of the account. Note that the response from the query is paginated, so you need to handle the pagination properly in the function. Specifically, responses that are paginated will return a `next_key` in the pagination object, which you can use to get the next page of results. Then keep looping through the results until you have all the pages, which you will know is the case when `next_key` is `null`. ```ts theme={null} async function queryBalance(address: string) { let allCoins: Coin[] = [] let nextKey: string | null = null do { const [coins, pagination] = await restClient.bank.balance(address, { 'pagination.key': nextKey || undefined, }) allCoins = [...allCoins, ...coins] nextKey = pagination.next_key || null } while (nextKey) console.log(`${address} has:`) allCoins.forEach((coin: Coin) => { console.log(`- ${coin.amount.toString()} ${coin.denom}`) }) } ``` You can then call the function with an address to query the balance of the account. ```ts theme={null} queryBalance('init1w4cqq6udjqtvl5xx0x6gjeyzgwtze8c05kysnu') ``` If successful, you should see an output similar to the following: ```sh theme={null} init1w4cqq6udjqtvl5xx0x6gjeyzgwtze8c05kysnu has: - 721662 uinit - 1000000 uinit ``` ## Complete Example ```ts src/query.ts theme={null} import { RESTClient, Coin } from '@initia/initia.js' const restClient = new RESTClient('https://rest.testnet.initia.xyz') async function queryBalance(address: string) { let allCoins: Coin[] = [] let nextKey: string | null = null do { const [coins, pagination] = await restClient.bank.balance(address, { 'pagination.key': nextKey || undefined, }) allCoins = [...allCoins, ...coins] nextKey = pagination.next_key || null } while (nextKey) console.log(`${address} has:`) allCoins.forEach((coin: Coin) => { console.log(`- ${coin.amount.toString()} ${coin.denom}`) }) } queryBalance('init1w4cqq6udjqtvl5xx0x6gjeyzgwtze8c05kysnu') ``` ## VM-Agnostic Queries VM-agnostic queries are queries that can be used across all VMs. * `balance()` : query the balance of an account ```typescript theme={null} const balances = await restClient.bank.balance( 'init14l3c2vxrdvu6y0sqykppey930s4kufsvt97aeu', ) ``` * `blockInfo()`: query the block information ```typescript theme={null} const blockInfo = await restClient.tendermint.blockInfo(10000) // If no height is given, the latest block is returned. ``` * `txInfo()`: query the transaction information ```typescript theme={null} const txInfo = await restClient.tx.txInfo( '6DFEE8E4BFC38341E8AADBD74A23588D8DE94FA38052CB5721DDA780A24F8B1D', ) ``` * `price()`: query the oracle price ```typescript theme={null} const currencyPair = new CurrencyPair('BTC', 'USD') const price = await restClient.oracle.price(currencyPair) ``` ## VM-Specific Queries ## MoveVM * `viewFunction()`: query the move contract view functions ```typescript theme={null} // `object.move` // // #[view] // public fun owner<T: key>(object: Object<T>): address acquires ObjectCore { // ... // } const res = await restClient.move.viewFunction( '0x1', // owner of the module 'object', // name of the module 'owner', // function name ['0x1::object::ObjectCore'], // type arguments [ bcs .object() .serialize( '0xc4f0b3c2300c99b0d7717ce43cd76821407a34c79587542919876a8c241a2f94', ) .toBase64(), ], // arguments ) ``` * `viewJSON()`: query the move contract view functions with JSON arguments ```typescript theme={null} const res = await restClient.move.viewJSON( '0x1', // owner of the module 'object', // name of the module 'owner', // function name ['0x1::object::ObjectCore'], // type arguments [`"0xc4f0b3c2300c99b0d7717ce43cd76821407a34c79587542919876a8c241a2f94"`], // arguments ) ``` * `resources()`: query the move contract resources ```typescript theme={null} const resources = await restClient.move.resources('0x1') const resource = await restClient.move.resource('0x1', '0x1::code::ModuleStore') ``` * `modules()`: query the move contract modules ```typescript theme={null} const modules = await restClient.move.module('0x1') const module = await restClient.move.module('0x1', 'object') ``` * `tableInfo()`: query the move contract table info ```typescript theme={null} const tableHandle = '0xc8c40eef193fc150fcb54264419bd3e39339c2ee8ba5834aed7826a9841cfb53' const entryKeyBytes = 'A0vD7ATVOvfCWo1T7H8Pz2MOt5k6rvsScYEGgXe0QDw=' const tableInfo = await restClient.move.tableInfo(tableHandle) const tableEntries = await restClient.move.tableEntries(tableHandle) const tableEntry = await restClient.move.tableEntry(tableHandle, entryKeyBytes) ``` ## WasmVM * `contractInfo()`: query the wasm contract info ```typescript theme={null} const contractInfo = await restClient.wasm.contractInfo( 'init14mv62l7x4ducykg0crfa9a22egf8yrltmxzy84zn0wqgmr496jqs5z7k0c', ) const contracts = await restClient.wasm.contractsByCode(1) ``` * `smartContractState()`: query the wasm smart contract state ```typescript theme={null} const contractState = await restClient.wasm.smartContractState( 'init1jue5rlc9dkurt3etr57duutqu7prchqrk2mes2227m52kkrual3qdrydg6', // contract address Buffer.from( JSON.stringify({ // query data get_stage_info: { stage: 1, }, }), ).toString('base64'), ) const allContractStates = await restClient.wasm.allContractState( 'init14mv62l7x4ducykg0crfa9a22egf8yrltmxzy84zn0wqgmr496jqs5z7k0c', ) ``` ## EVM * `call()`: query the evm contract ```typescript theme={null} const contractInfo = JSON.parse( fs .readFileSync( '../solidity/evm-example/artifacts/contracts/example.sol/example.json', // path of build response ) .toString(), ) const contract = new ethers.Contract(contractAddress, contractInfo.abi) const res = await restClient.evm.call( 'init1jvxywa6dmdxumr9nhdez838af06f9v42w0rd26', // sender '0x16e999092BF37913a3eff185949997b6f7bd698c', // contract_addr contract.interface .encodeFunctionData( 'getPoints', [2, 0, 10], // hex encoded execution input bytes ) .slice(2), false, // whether to return the trace ) ``` # Quickstart Source: https://docs.initia.xyz/developers/developer-guides/tools/sdks/initia-js/quickstart The following examples in this section assume that you implement the guides on each page as separate functions and files under a single project directory. To set up your project, follow the steps below. <Steps> <Step title="Create Directory"> First, create a directory to store your project files. ```bash theme={null} mkdir initia-js-quickstart && cd initia-js-quickstart ``` </Step> <Step title="Initialize Project"> Next, initialize your project. ```bash theme={null} npm init && npm add -D typescript @types/node ts-node && npx tsc --init && mkdir src && echo 'async function example() { console.log("Running example!")}; example()' > src/quickstart.ts ``` </Step> <Step title="Install InitiaJS"> Install InitiaJS. ```bash theme={null} npm add @initia/initia.js ``` </Step> <Step title="Test Installation"> Once you have installed InitiaJS, test your installation. Replace the contents of `src/quickstart.ts` with the following code. ```ts theme={null} import { RESTClient, Coin } from '@initia/initia.js'; const restClient = new RESTClient('https://rest.testnet.initia.xyz'); (async () => { const chainId = await restClient.tendermint.chainId(); console.log(chainId); })(); ``` Then, run the script. ```bash theme={null} npx ts-node src/quickstart.ts ``` If you get `initiation-2` as the output, your installation was successful! </Step> </Steps> # Messages Source: https://docs.initia.xyz/developers/developer-guides/tools/sdks/initia-js/transactions/messages Message is a data structure that represents an action to be executed on the blockchain. It is a part of the transaction, which is a collection of messages that are executed atomically. This guide will show you how to create a message object for different types of actions. ## VM-Agnostic Messages VM-agnostic messages are messages that can be used across all VMs. * `MsgSend()`: send coins to other address ```typescript theme={null} const msg = new MsgSend( 'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // sender address 'init18sj3x80fdjc6gzfvwl7lf8sxcvuvqjpvcmp6np', // recipient address '1000uinit', // send amount ) ``` * `MsgDelegate()`: dele
프로젝트로 돌아가기