# Agent Skills Source: https://docs.initia.xyz/ai/agent-skills Agent skills for building with Initia The [Initia Appchain Dev skill](https://github.com/initia-labs/agent-skills) is a skill that teaches AI coding agents how to build on Initia. Once installed, your agent can help with: * **Chain deployment** using the Weave CLI * **Smart contract development** across all supported VMs * **Frontend integration** including using InterwovenKit ## Installation ### Using skills.sh ```bash theme={null} npx skills add initia-labs/agent-skills ``` ### Manual Installation ```bash theme={null} git clone https://github.com/initia-labs/agent-skills cd agent-skills ./install.sh ``` For a project-local install: ```bash theme={null} ./install.sh --project ``` For a custom destination: ```bash theme={null} ./install.sh --path /custom/path/initia-appchain-dev ``` ### Verify Installation ```bash theme={null} npx skills add . --list ``` You should see one skill named `initia-appchain-dev`. ## What the Skill Covers The skill provides reference material organized by layer: | Layer | Coverage | | ---------------------------- | -------------------------------------------------------------------------- | | **Contracts** | Move, Wasm, and EVM contract scaffolding, building, deploying, and testing | | **Frontend (InterwovenKit)** | Provider setup, wallet connection, transactions, auto-sign, bridge | | **Frontend (EVM JSON-RPC)** | wagmi + viem setup for pure EVM apps | | **Appchain Operations** | Weave CLI commands, rollup config schema, runtime discovery | | **Troubleshooting** | Common errors and recovery steps across all layers | ## skill.md The Initia docs also provide a `skill.md` file at [docs.initia.xyz/skill.md](https://docs.initia.xyz/skill.md). This is a lightweight skill file that teaches AI agents how to work with the documentation site itself. To add it: ```bash theme={null} npx skills add docs.initia.xyz/skill.md ``` ## Example Prompts Once the skill is installed, try prompts like: * "Scaffold an EVM contract on Initia and add an oracle read function." * "Set up InterwovenKit providers in my Next.js app and implement wallet connect." * "Create a `weave` launch config for a testnet EVM rollup." * "My rollup is not producing blocks. Help me debug it step by step." * "Convert this `0x...` address to Initia bech32 and add it to genesis accounts." ## Reference Material Included The skill bundles references that your agent reads on demand: * **Common tasks** — funding, address conversion, token precision * **Contracts** — Move / Wasm / EVM development guides * **Frontend (InterwovenKit)** — provider setup, hooks, transactions * **Frontend (EVM JSON-RPC)** — wagmi + viem integration * **End-to-end recipes** — full workflows from contract to frontend * **Runtime discovery** — auto-detecting chain ID, VM, endpoints * **Weave CLI commands** — complete CLI reference * **Rollup config schema** — launch configuration format * **Troubleshooting** — error diagnosis and recovery ## Contributing The skill repository is open source. 1. Fork the [initia-labs/agent-skills](https://github.com/initia-labs/agent-skills) repository 2. Edit the relevant reference files in the `skill/references/` directory 3. Run the quality checks to validate your changes: ```bash theme={null} ./scripts/ci-check.sh ``` 4. Submit a pull request with a description of what you changed and why # Docs MCP Source: https://docs.initia.xyz/ai/docs-mcp Connect your AI coding agent to Initia docs via the Model Context Protocol. The Initia documentation provides a [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server that allows AI coding agents to search the docs directly from your IDE. ## What Is MCP The Model Context Protocol is an open standard that lets AI applications connect to external data sources. The Initia Docs MCP server exposes a search tool that your agent can use to find relevant documentation based on natural language queries. ## Setup Add the following to your Cursor MCP configuration (`.cursor/mcp.json`): ```json theme={null} { "mcpServers": { "initia-docs": { "url": "https://docs.initia.xyz/mcp" } } } ``` Add the MCP server using the Claude Code CLI: ```bash theme={null} claude mcp add initia-docs https://docs.initia.xyz/mcp ``` Or add it to your `.mcp.json` configuration: ```json theme={null} { "mcpServers": { "initia-docs": { "type": "http", "url": "https://docs.initia.xyz/mcp" } } } ``` Add the following to your Windsurf MCP configuration: ```json theme={null} { "mcpServers": { "initia-docs": { "serverUrl": "https://docs.initia.xyz/mcp" } } } ``` Add the following to your VS Code settings (`.vscode/mcp.json`): ```json theme={null} { "servers": { "initia-docs": { "type": "http", "url": "https://docs.initia.xyz/mcp" } } } ``` For any tool that supports MCP, use the following endpoint: ``` https://docs.initia.xyz/mcp ``` Consult your tool's documentation for how to add an MCP server. The Initia Docs MCP server uses the standard HTTP-based MCP transport. ## Mintlify Native MCP The Initia docs are built with [Mintlify](https://mintlify.com), which provides native MCP support. You can access the MCP server directly from any documentation page using the built-in contextual options. Look for the **MCP**, **Cursor**, or **VS Code** buttons on any page to connect your AI tools. ## How It Works Once configured, your agent can: 1. **Search** the docs using your natural language query 2. **Retrieve** relevant documentation content 3. **Use** that context to generate accurate responses and code ## Example Usage With the MCP server connected, try asking your agent: * "How do I deploy a rollup on Initia?" * "What hooks does InterwovenKit provide?" * "Show me how to create an ERC20 on MiniEVM." * "What is the Router API and how do I compute a route?" ## Inline Documentation Access Initia documentation pages also include buttons to quickly use page content with AI tools: * **Copy as Markdown** — copy the page content for pasting into an LLM * **Open in ChatGPT** — open the page content directly in ChatGPT * **Open in Claude** — open the page content directly in Claude # llms.txt Source: https://docs.initia.xyz/ai/llms-txt Use llms.txt to give LLMs structured context about the Initia documentation. The Initia docs provide `llms.txt` and `llms-full.txt` files following the [llms.txt standard](https://llmstxt.org) for making documentation accessible to language models. ## llms.txt A lightweight index of every page in the Initia documentation, containing the title and URL of each page. ``` https://docs.initia.xyz/llms.txt ``` Use `llms.txt` to give an LLM an overview of available documentation without loading the full content. This is useful for: * Letting an LLM understand the scope of Initia documentation * Letting an LLM decide which pages to fetch based on a question * Adding lightweight context without consuming a large context window ## llms-full.txt The complete text of every documentation page in a single file. ``` https://docs.initia.xyz/llms-full.txt ``` Use `llms-full.txt` when you need comprehensive coverage and your LLM has a large enough context window. This is useful for: * Deep research across multiple documentation topics * Answering complex questions that span several areas of Initia * Pre-loading an AI coding agent with complete documentation `llms-full.txt` contains the full text of every documentation page. Check the file size before loading to ensure it fits within your LLM's context window. ## Using with AI Tools ### Paste into an LLM Chat Copy the contents of `llms.txt` or `llms-full.txt` and paste it into your conversation with an LLM to provide documentation context. ### Load in Your IDE Many AI-powered IDEs allow you to add documentation context: Add `llms.txt` as a documentation source in **Cursor Settings > Features > Docs** using the URL: ``` https://docs.initia.xyz/llms.txt ``` Paste the URL or content of `llms.txt` directly into your conversation as context. ``` https://docs.initia.xyz/llms.txt ``` Point your tool to the `llms.txt` URL. Consult your tool's documentation for how to add external documentation sources. ``` https://docs.initia.xyz/llms.txt ``` # Overview Source: https://docs.initia.xyz/ai/overview Tools and resources to help AI agents and LLMs build with Initia. Initia provides tools to help AI coding agents and LLMs work with the Interwoven Stack. These give your tools the context they need to generate accurate code for contracts, frontends, and rollup operations. ## Available Tools A skill that teaches AI agents how to build on Initia end-to-end. A structured index of all Initia documentation pages for LLM context. A Model Context Protocol server for searching Initia docs from your IDE. ## When to Use Each Tool | Tool | Best for | Setup | | ---------------- | -------------------------------------------------------- | ----------------------------------------- | | **Agent Skills** | Building full-stack apps (contracts, frontends, rollups) | `npx skills add initia-labs/agent-skills` | | **llms.txt** | Giving an LLM broad context about all docs | Paste the URL into your LLM context | | **Docs MCP** | Targeted search of docs from your IDE | Add the MCP server endpoint to your IDE | ## Getting Started If you are building a full app, start with **Agent Skills**. For quick reference lookups, use the **Docs MCP**. To give an LLM broad context in a single prompt, use **llms.txt**. Follow the setup instructions on the respective tool page. Use natural language prompts to scaffold contracts, build frontends, and manage rollup operations. # Get Assets Source: https://docs.initia.xyz/api-reference/assets-&-chains/get-assets /api-reference/router-api/openapi.yaml get /v2/fungible/assets Returns a map of supported fungible assets across all chains. You can optionally filter by specific chain IDs. # Get Balances Source: https://docs.initia.xyz/api-reference/assets-&-chains/get-balances /api-reference/router-api/openapi.yaml post /v2/info/balances Returns token balances and USD values for given addresses across multiple chains. # Get Chains Source: https://docs.initia.xyz/api-reference/assets-&-chains/get-chains /api-reference/router-api/openapi.yaml get /v2/info/chains Returns the list of all supported chains available for cross-chain transfers. You can optionally filter by specific chain IDs. # Get average block time Source: https://docs.initia.xyz/api-reference/blocks/get-average-block-time /api-reference/rollup-indexer/openapi.yaml get /indexer/block/v1/avg_blocktime Returns the average block time in seconds, computed over the most recent blocks. # Get block by height Source: https://docs.initia.xyz/api-reference/blocks/get-block-by-height /api-reference/rollup-indexer/openapi.yaml get /indexer/block/v1/blocks/{height} Returns a specific block by its height. # Get blocks Source: https://docs.initia.xyz/api-reference/blocks/get-blocks /api-reference/rollup-indexer/openapi.yaml get /indexer/block/v1/blocks Returns a paginated list of blocks. # Get EVM internal transactions Source: https://docs.initia.xyz/api-reference/evm-internal-transactions/get-evm-internal-transactions /api-reference/rollup-indexer/openapi.yaml get /indexer/tx/v1/evm-internal-txs Returns a paginated list of EVM internal transactions. Only available on EVM chains with internal transaction indexing enabled. # Get EVM internal transactions by account Source: https://docs.initia.xyz/api-reference/evm-internal-transactions/get-evm-internal-transactions-by-account /api-reference/rollup-indexer/openapi.yaml get /indexer/tx/v1/evm-internal-txs/by_account/{account} Returns EVM internal transactions associated with a specific account. Only available on EVM chains. # Get EVM internal transactions by hash Source: https://docs.initia.xyz/api-reference/evm-internal-transactions/get-evm-internal-transactions-by-hash /api-reference/rollup-indexer/openapi.yaml get /indexer/tx/v1/evm-internal-txs/{tx_hash} Returns EVM internal transactions for a specific transaction hash. Only available on EVM chains. # Get EVM internal transactions by height Source: https://docs.initia.xyz/api-reference/evm-internal-transactions/get-evm-internal-transactions-by-height /api-reference/rollup-indexer/openapi.yaml get /indexer/tx/v1/evm-internal-txs/by_height/{height} Returns EVM internal transactions at a specific block height. Only available on EVM chains. # Get EVM transaction by hash Source: https://docs.initia.xyz/api-reference/evm-transactions/get-evm-transaction-by-hash /api-reference/rollup-indexer/openapi.yaml get /indexer/tx/v1/evm-txs/{tx_hash} Returns a specific EVM transaction by its hash. Only available on EVM chains. # Get EVM transactions Source: https://docs.initia.xyz/api-reference/evm-transactions/get-evm-transactions /api-reference/rollup-indexer/openapi.yaml get /indexer/tx/v1/evm-txs Returns a paginated list of EVM transactions. Only available on EVM chains. # Get EVM transactions by account Source: https://docs.initia.xyz/api-reference/evm-transactions/get-evm-transactions-by-account /api-reference/rollup-indexer/openapi.yaml get /indexer/tx/v1/evm-txs/by_account/{account} Returns EVM transactions associated with a specific account. Only available on EVM chains. # Get EVM transactions by height Source: https://docs.initia.xyz/api-reference/evm-transactions/get-evm-transactions-by-height /api-reference/rollup-indexer/openapi.yaml get /indexer/tx/v1/evm-txs/by_height/{height} Returns EVM transactions at a specific block height. Only available on EVM chains. # Overview Source: https://docs.initia.xyz/api-reference/introduction Reference and interactive playgrounds for all Initia APIs. Cross-chain transfer routing for bridging tokens and NFTs across Initia Stack chains and external networks. Query indexed chain data including blocks, transactions, NFTs, and token holders across Initia Stack chains. # NFT Transfer Source: https://docs.initia.xyz/api-reference/nft/nft-transfer /api-reference/router-api/openapi.yaml post /nft Computes routes and generates transaction messages for cross-chain NFT transfers within the Initia ecosystem. Supports: - Same-chain transfers (EVM, Move, and Wasm chains) - Single-hop IBC (L2 to L1 or L1 to L2 via ICS-721) - Multi-hop (L2 to L1 to L2, two IBC hops) # Get NFT collection details Source: https://docs.initia.xyz/api-reference/nfts/get-nft-collection-details /api-reference/rollup-indexer/openapi.yaml get /indexer/nft/v1/collections/{collection_addr} Returns the details of a specific NFT collection by its address. # Get NFT collections Source: https://docs.initia.xyz/api-reference/nfts/get-nft-collections /api-reference/rollup-indexer/openapi.yaml get /indexer/nft/v1/collections Returns a paginated list of all NFT collections. # Get NFT collections by account Source: https://docs.initia.xyz/api-reference/nfts/get-nft-collections-by-account /api-reference/rollup-indexer/openapi.yaml get /indexer/nft/v1/collections/by_account/{account} Returns NFT collections that contain tokens owned by the specified account. # Get NFT collections by name Source: https://docs.initia.xyz/api-reference/nfts/get-nft-collections-by-name /api-reference/rollup-indexer/openapi.yaml get /indexer/nft/v1/collections/by_name/{name} Returns NFT collections matching the specified name. # Get NFT tokens by account Source: https://docs.initia.xyz/api-reference/nfts/get-nft-tokens-by-account /api-reference/rollup-indexer/openapi.yaml get /indexer/nft/v1/tokens/by_account/{account} Returns NFT tokens owned by the specified account. You can optionally filter by collection address and token ID. # Get NFT tokens by collection Source: https://docs.initia.xyz/api-reference/nfts/get-nft-tokens-by-collection /api-reference/rollup-indexer/openapi.yaml get /indexer/nft/v1/tokens/by_collection/{collection_addr} Returns all NFT tokens within a specific collection. You can optionally filter by token ID. # Get NFT transactions Source: https://docs.initia.xyz/api-reference/nfts/get-nft-transactions /api-reference/rollup-indexer/openapi.yaml get /indexer/nft/v1/txs/{collection_addr}/{token_id} Returns transactions related to a specific NFT identified by its collection address and token ID. # Get token holders Source: https://docs.initia.xyz/api-reference/rich-list/get-token-holders /api-reference/rollup-indexer/openapi.yaml get /indexer/richlist/v1/{denom} Returns a ranked list of token holders for a specific denomination, ordered by amount. # Introduction Source: https://docs.initia.xyz/api-reference/rollup-indexer/introduction Overview of the Indexer API for querying indexed chain data. All Initia Stack chains come with a built-in indexer that automatically indexes and stores all relevant data on the chain. This data is exposed through a REST API that you can use to query historical and current data, including blocks, transactions, NFTs, and token holders. ## Base URLs Each chain has its own indexer endpoint. Select the appropriate base URL for the chain you want to query. The URLs below are **testnet endpoints** for demonstration and testing purposes. In production, each chain will have its own unique indexer URL. | Chain | Base URL (testnet) | | ------ | -------------------------------------------------------------- | | evm-1 | `https://rollytics-api-evm-1.anvil.asia-southeast.initia.xyz` | | move-1 | `https://rollytics-api-move-1.anvil.asia-southeast.initia.xyz` | | wasm-1 | `https://rollytics-api-wasm-1.anvil.asia-southeast.initia.xyz` | ## Features * **Block queries** — List blocks, look up blocks by height, and get average block time * **Transaction queries** — List transactions, look up by account, block height, or transaction hash, with optional message type filtering * **EVM transaction queries** — Query EVM-specific transactions and internal transactions (available on EVM chains only) * **NFT queries** — Retrieve collections and tokens by account, name, or collection address, and look up NFT transaction history * **Rich list** — Get ranked token holder lists for any denomination ## Pagination All list endpoints support cursor-based and offset-based pagination through query parameters: | Parameter | Type | Description | | ------------------------ | ------- | -------------------------------------------------- | | `pagination.key` | string | Cursor key for the next page. | | `pagination.offset` | integer | Number of records to skip. | | `pagination.limit` | integer | Maximum records to return (default: 100). | | `pagination.count_total` | boolean | Include total count in response (default: `true`). | | `pagination.reverse` | boolean | Descending order when `true` (default: `true`). | ## EVM-Only Endpoints Endpoints under the **EVM Transactions** and **EVM Internal Transactions** groups are only available on EVM chains (e.g., evm-1). These return a `404` on non-EVM chains. # Introduction Source: https://docs.initia.xyz/api-reference/router-api/introduction Overview of the Initia Router API for cross-chain asset transfers. The Router API supports cross-chain transfers from Initia Stack-based chains to external networks, automatically determining the optimal route across supported networks, chains, and DEXes. ## Base URL The Router API is available at the following base URL: * Mainnet: `https://router-api.initia.xyz` * Testnet: `https://router-api.initiation-2.initia.xyz` ## Features * **Asset Queries** — Query supported fungible assets and chains across Initia and external networks * **Balance Queries** — Fetch token balances and USD values across multiple chains * **Route Computation** — Find optimal transfer paths between any supported source and destination * **Transaction Generation** — Get signable transaction messages for computed routes * **Transaction Tracking** — Monitor cross-chain transfer progress * **NFT Transfers** — Bridge NFTs across Initia L1 and L2 chains via ICS-721 * **RPC Proxy** — Forward a limited set of JSON-RPC requests to supported Cosmos chains # Usage Source: https://docs.initia.xyz/api-reference/router-api/usage How to bridge tokens and track transfers using the Router API. The Router API handles route computation and transaction generation, but does not broadcast transactions. The application is responsible for signing and submitting the transaction to the chain. This page walks through the full flow. ## Flow Overview ```mermaid theme={null} sequenceDiagram participant App participant Router API participant Chain RPC App->>Router API: 1. Compute Route Router API-->>App: Route + operations App->>Router API: 2. Generate Transaction Router API-->>App: Signable tx messages App->>Chain RPC: 3. Sign & broadcast Chain RPC-->>App: tx_hash App->>Router API: 4. Track Transaction (tx_hash) Router API-->>App: Registered loop Until terminal state App->>Router API: 5. Get Transaction Status Router API-->>App: Status + transfer sequence end ``` ## Bridging Tokens Bridging tokens between chains is a two-step process using the Routing endpoints. Call **Compute Route** (`POST /v2/fungible/route`) with the source and destination assets and the amount to transfer. The API evaluates available pathways (IBC, LayerZero, Optimistic bridges, etc.) and returns the optimal route, including the expected output amount and an `operations` array for each hop. ```bash theme={null} curl -X POST https://router-api.initia.xyz/v2/fungible/route \ -H "Content-Type: application/json" \ -d '{ "amount_in": "1000000", "source_asset_chain_id": "interwoven-1", "source_asset_denom": "uinit", "dest_asset_chain_id": "8453", "dest_asset_denom": "0x..." }' ``` Pass the route details to **Generate Transaction** (`POST /v2/fungible/msgs`) along with the relevant addresses and slippage tolerance. The API returns signable transaction messages for the source chain. If the route response included `required_op_hook: true`, first call **Get OP Hook** (`POST /op-hook`) with the source and destination addresses and assets to obtain the hook payload. Then sign the hook and include it in the `signed_op_hook` field of the Generate Transaction request. ```bash theme={null} curl -X POST https://router-api.initia.xyz/v2/fungible/msgs \ -H "Content-Type: application/json" \ -d '{ "amount_in": "1000000", "amount_out": "999000", "source_asset_chain_id": "interwoven-1", "source_asset_denom": "uinit", "dest_asset_chain_id": "8453", "dest_asset_denom": "0x...", "address_list": ["init1abc...", "0xdef..."], "operations": [], "slippage_tolerance_percent": "1" }' ``` Sign the returned transaction messages with a wallet or SDK, then broadcast to the source chain's RPC endpoint. This step happens outside the Router API. ## Tracking Transfers Because the transaction is signed and broadcast outside the Router API's scope, the API has no knowledge of the transaction until the application explicitly provides the transaction hash. The transaction must be registered before its cross-chain progress can be monitored. After broadcasting, call **Track Transaction** (`POST /v2/tx/track`) once with the transaction hash and the chain ID where it was submitted. This registers the transaction so the tracking service can watch for relay events and bridge confirmations. ```bash theme={null} curl -X POST https://router-api.initia.xyz/v2/tx/track \ -H "Content-Type: application/json" \ -d '{ "tx_hash": "ABCDEF1234567890...", "chain_id": "interwoven-1" }' ``` Call **Get Transaction Status** (`GET /v2/tx/status`) repeatedly to check the transfer progress. The response includes the overall status and the state of each hop in the transfer sequence. ```bash theme={null} curl "https://router-api.initia.xyz/v2/tx/status?tx_hash=ABCDEF1234567890...&chain_id=interwoven-1" ``` Keep polling until the status reaches a terminal state such as `STATE_COMPLETED` or `STATE_FAILED`. ## Endpoint Reference | Step | Endpoint | Purpose | | ---- | ------------------------- | ------------------------------------------ | | 1 | `POST /v2/fungible/route` | Find the optimal route | | 1b | `POST /op-hook` | Get OP hook data (when `required_op_hook`) | | 2 | `POST /v2/fungible/msgs` | Get signable transaction messages | | 3 | *(wallet/SDK)* | Sign and broadcast to the chain | | 4 | `POST /v2/tx/track` | Register the tx hash for tracking | | 5 | `GET /v2/tx/status` | Poll until transfer completes | # Compute Route Source: https://docs.initia.xyz/api-reference/routing/compute-route /api-reference/router-api/openapi.yaml post /v2/fungible/route This is the first step when bridging tokens between chains. Call this endpoint with your source and destination assets to find the optimal transfer route. The response includes the expected output amount, USD value estimates, and an ordered list of operations. After receiving a route, pass the full response (including `operations`) to the Generate Transaction endpoint (`POST /v2/fungible/msgs`) to get signable transaction messages you can broadcast. If the route involves an IBC transfer between the Initia L1 chain and an external Cosmos chain, the endpoint also checks that the transfer fits within the current IBC rate-limit capacity. When the requested amount exceeds the remaining send or receive capacity, the request is rejected with a `400` error whose message reports the remaining capacity in human-readable units. # Generate Transaction Source: https://docs.initia.xyz/api-reference/routing/generate-transaction /api-reference/router-api/openapi.yaml post /v2/fungible/msgs This is the second step when bridging tokens. After computing a route with Compute Route (`POST /v2/fungible/route`), pass the route details and your addresses to this endpoint. It returns signable transaction messages that you can broadcast to the source chain. The typical flow is: **Compute Route** → **Generate Transaction** → sign and broadcast → **Track Transaction**. # Get OP hook Source: https://docs.initia.xyz/api-reference/routing/get-op-hook /api-reference/router-api/openapi.yaml post /op-hook Generates OP hook data required for certain cross-chain routes that involve Optimistic bridge withdrawals with ERC-20 token conversion. When the Compute Route response includes `required_op_hook: true`, you must call this endpoint to obtain the hook payload before generating transaction messages. Pass the returned hook data to the Generate Transaction endpoint (`POST /v2/fungible/msgs`) in the `signed_op_hook` field after signing it. # Cosmos RPC Proxy Source: https://docs.initia.xyz/api-reference/rpc/cosmos-rpc-proxy /api-reference/router-api/openapi.yaml post /api/rpc/{chainId} JSON-RPC 2.0 proxy to the Cosmos RPC of a supported Cosmos chain. The request and response follow the standard [JSON-RPC 2.0 specification](https://www.jsonrpc.org/specification). Only a limited set of RPC methods is supported: - `status` — fetch the node status. `params` must be `{}`. - `abci_query` — query application state. `params` must include `data` (string), `path` (string), and `prove` (boolean). Allowed `path` values: - `/cosmos.auth.v1beta1.Query/Account` - `/cosmos.bank.v1beta1.Query/AllBalances` - `/cosmos.tx.v1beta1.Service/Simulate` - `broadcast_tx_sync` — broadcast a signed transaction. `params` must contain a single `tx` field (string). - `tx_search` — search for transactions. `params` must include `page` (string, only `"1"` is allowed) and `query` (string, must match `tx.hash='<64-hex>'`). Any other method or unsupported parameter shape returns a `400` error. # Get Transaction Status Source: https://docs.initia.xyz/api-reference/tracking-transactions/get-transaction-status /api-reference/router-api/openapi.yaml get /v2/tx/status Polls the current status of a transaction that was previously registered with Track Transaction (`POST /v2/tx/track`). Returns the overall status and the state of each hop in the transfer sequence. Call this endpoint repeatedly until the status reaches a terminal state (e.g. `STATE_COMPLETED` or `STATE_FAILED`). This is useful for showing transfer progress in your UI. # Track Transaction Source: https://docs.initia.xyz/api-reference/tracking-transactions/track-transaction /api-reference/router-api/openapi.yaml post /v2/tx/track Registers a transaction for cross-chain tracking. Call this once with the transaction hash and chain ID immediately after broadcasting. This is required before you can poll the transaction status. After calling this endpoint, use Get Transaction Status (`GET /v2/tx/status`) to poll for progress updates. # Get transaction by hash Source: https://docs.initia.xyz/api-reference/transactions/get-transaction-by-hash /api-reference/rollup-indexer/openapi.yaml get /indexer/tx/v1/txs/{tx_hash} Returns a specific transaction by its hash. # Get transactions Source: https://docs.initia.xyz/api-reference/transactions/get-transactions /api-reference/rollup-indexer/openapi.yaml get /indexer/tx/v1/txs Returns a paginated list of transactions. You can optionally filter by message type. # Get transactions by account Source: https://docs.initia.xyz/api-reference/transactions/get-transactions-by-account /api-reference/rollup-indexer/openapi.yaml get /indexer/tx/v1/txs/by_account/{account} Returns transactions associated with a specific account address. # Get transactions by height Source: https://docs.initia.xyz/api-reference/transactions/get-transactions-by-height /api-reference/rollup-indexer/openapi.yaml get /indexer/tx/v1/txs/by_height/{height} Returns all transactions at a given block height. # Exchange Integration Source: https://docs.initia.xyz/developers/developer-guides/guides/exchange-integration This guide provides instructions for exchanges on how to integrate with Initia, from running a node to handling transactions and monitoring network activities. ## Network Details You can find the details of Initia's network, including the chain endpoints, nodes, and peer information, below. * [Initia L1 Networks](/resources/developer/initia-l1) ## Running a Node For more information on running a node, please refer to * [Running an Initia Node](/nodes-and-rollups/running-nodes/running-l1-nodes/l1-nodes-initiad) ## Creating and Managing Accounts * [Creating an Account](/developers/developer-guides/tools/sdks/initia-js/accounts) ## Sending Transactions ### Transferring Tokens * [Sending Transactions](/developers/developer-guides/tools/sdks/initia-js/transactions/sending-transactions) ### Signing Transactions Offline In cases where network security is crucial, signing transactions offline ensures safe transaction handling. * [Signing Transactions](/developers/developer-guides/tools/sdks/initia-js/transactions/signing-transactions) ### Handle Transaction Errors Learn how to handle transaction errors to ensure that your transactions are executed properly. * [Handling Errors](/developers/developer-guides/tools/sdks/initia-js/transactions/handling-errors) ## Monitoring Transactions Initia provides various tools to monitor transaction activities, including event indexing and querying network data. To keep track of transactions and blockchain events, you can use a simple indexer example: * [Simple Indexer](https://github.com/initia-labs/simple-indexer) For additional data like account balances and block details, you can use InitiaJS: * [Querying Data](/developers/developer-guides/tools/sdks/initia-js/querying-data) Additionally, you can manually monitor transactions with the following tools: * [InitiaScan](https://scan.testnet.initia.xyz/initiation-2) * [REST Swagger](https://rest.testnet.initia.xyz/swagger/#/Service/GetTx) # Interacting with InitiaDEX Source: https://docs.initia.xyz/developers/developer-guides/integrating-initia-apps/initiadex ## Creating New Pools InitiaDEX allows anyone to create a liquidity pool. ```move theme={null} public entry fun create_pair_script( creator: &signer, name: String, symbol: String, swap_fee_rate: Decimal128, coin_a_weight: Decimal128, coin_b_weight: Decimal128, coin_a_metadata: Object, coin_b_metadata: Object, coin_a_amount: u64, coin_b_amount: u64, ) ``` | Parameter | Description | | --------------------------------------- | ------------------------------------------------------- | | `name` | Name of the trading pair and the corresponding LP Token | | `symbol` | Symbol for the LP Token | | `swap_fee_rate` | Fee rate applied to swaps | | `coin_a_weight` and `coin_b_weight` | Balancer weights for the respective coins | | `coin_a_metadata` and `coin_b_metadata` | Metadata for each coin in the pair | | `coin_a_amount` and `coin_b_amount` | Initial amounts for each coin | *For more information on metadata, please refer to [obtaining metadata](/developers/developer-guides/vm-specific-tutorials/movevm/creating-move-coin#obtaining-metadata).* ```bash CLI theme={null} initiad tx move execute 0x1 dex create_pair_script \ --args '["string:name", "string:symbol", "bigdecimal:0.001", "bigdecimal:0.8", "bigdecimal:0.2", "object:0x...", "object:0x...", "u64:100", "u64:100"]' \ --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'; async function main() { 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', 'dex', 'create_pair_script', [], [ bcs.string().serialize('name'), // name bcs.string().serialize('symbol'), // symbol bcs.bigdecimal().serialize('0.003'), // swap fee bcs.bigdecimal().serialize('0.2'), // coin a weight bcs.bigdecimal().serialize('0.8'), // coin b weight bcs.object().serialize('0x...'), // coin a bcs.object().serialize('0x...'), // coin b bcs.u64().serialize(7500000000000), // coin a amount bcs.u64().serialize(3000000000000), // coin b amount ].map(v => v.toBase64()) ), ]; // sign tx const signedTx = await wallet.createAndSignTx({ msgs }); // send(broadcast) tx restClient.tx.broadcastSync(signedTx).then(res => console.log(res)); // { // height: 0, // txhash: '0F2B255EE75FBA407267BB57A6FF3E3349522DA6DBB31C0356DB588CC3933F37', // raw_log: '[]' // } } main(); ``` ## How to Provide Liquidity ### Provide Liquidity `provide_liquidity` enables you to provide liquidity of both `coin_a` and `coin_b` in the specific pair. To maximize the LP tokens received and minimize slippage, provide liquidity in proportion with the current ratio. The Move module interface is as follows: ```move theme={null} public entry fun provide_liquidity_script( account: &signer, pair: Object, coin_a_amount_in: u64, coin_b_amount_in: u64, min_liquidity: Option ) ``` * `pair`: The metadata or object address of pair. * `coin_a_amount_in` and `coin_b_amount_in`: Amount of token provided for `coin_a` and `coin_b`. * `min_liquidity`: Minimum amount of liquidity token to receive. In case that the actual value is smaller than `min_liquidity`, the transaction will fail. ```bash CLI theme={null} initiad tx move execute 0x1 dex provide_liquidity_script \ --args '["object:0x...", "u64:100", "u64:100", "option:100"]' \ --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'; async function main() { 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', 'dex', 'provide_liquidity_script', [], [ bcs.object().serialize('0x...'), // pair object bcs.u64().serialize(7500000000000), // coin a amount bcs.u64().serialize(3000000000000), // coin b amount bcs.option(bcs.u64()).serialize(100000000), // min liquidity amount ].map(v => v.toBase64()) ), ]; // sign tx const signedTx = await wallet.createAndSignTx({ msgs }); // send(broadcast) tx restClient.tx.broadcastSync(signedTx).then(res => console.log(res)); // { // height: 0, // txhash: '0F2B255EE75FBA407267BB57A6FF3E3349522DA6DBB31C0356DB588CC3933F37', // raw_log: '[]' // } } main(); ``` ### Single Asset Provide Liquidity Instead of providing both tokens in a pair, you can provide liquidity using only one token. Internally, half of the token is swapped to the other token in the pair to provide liquidity, which may result in fees and slippage. The Move function interface is as follows: ```move theme={null} public entry fun single_asset_provide_liquidity_script( account: &signer, pair: Object, provide_coin: Object, amount_in: u64, min_liquidity: Option ) ``` * `pair`: The metadata or object address of pair. * `provide_coin`: The metadata of the provided coin. * `amount_in`: The amount of provided coin. * `min_liquidity`: Minimum amount of liquidity token to receive. In case that the actual value is smaller than `min_liquidity`, the transaction will fail. ```bash CLI theme={null} initiad tx move execute 0x1 dex single_asset_provide_liquidity_script \ --args '["object:0x...", "object:0x..", "u64:100", "option:100"]' \ --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'; async function main() { 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', 'dex', 'single_asset_provide_liquidity_script', [], [ bcs.object().serialize('0x...'), // pair object bcs.object().serialize('0x...'), // provide asset metadata bcs.u64().serialize(3000000000000), // provide amount bcs.option(bcs.u64()).serialize(100000000), // min liquidity amount ].map(v => v.toBase64()) ), ]; // sign tx const signedTx = await wallet.createAndSignTx({ msgs }); // send(broadcast) tx restClient.tx.broadcastSync(signedTx).then(res => console.log(res)); // { // height: 0, // txhash: '0F2B255EE75FBA407267BB57A6FF3E3349522DA6DBB31C0356DB588CC3933F37', // raw_log: '[]' // } } main(); ``` ## How to Withdraw Liquidity ### Withdraw Liquidity `withdraw_liquidity` allows you to provide liquidity tokens and receive `coin_a` and `coin_b`. The Move module interface is as follows: ```move theme={null} public entry fun withdraw_liquidity_script( account: &signer, pair: Object, liquidity: u64, min_coin_a_amount: Option, min_coin_b_amount: Option, ) ``` * `pair`: The metadata or object address of pair. * `liquidity`: Amount of liquidity token. * `min_coin_a_amount` and `min_coin_b_amount` : Minimum amount of `coin_a` or `coin_b` to receive. In case that the actual value is smaller than `min_coin_a_amount` or `min_coin_b_amount`, the transaction will fail. ```bash CLI theme={null} initiad tx move execute 0x1 dex withdraw_liquidity_script \ --args '["object:0x...", "u64:100", "option:100", "option:100"]' \ --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'; async function main() { 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', 'dex', 'withdraw_liquidity_script', [], [ bcs.object().serialize('0x...'), // pair object bcs.u64().serialize(100000000), // liquidity bcs.option(bcs.u64()).serialize(100000000), // min coin a amount bcs.option(bcs.u64()).serialize(100000000), // min coin b amount ].map(v => v.toBase64()) ), ]; // sign tx const signedTx = await wallet.createAndSignTx({ msgs }); // send(broadcast) tx restClient.tx.broadcastSync(signedTx).then(res => console.log(res)); // { // height: 0, // txhash: '0F2B255EE75FBA407267BB57A6FF3E3349522DA6DBB31C0356DB588CC3933F37', // raw_log: '[]' // } } main(); ``` ## How to Swap Pair ### Swap Simulation `swap_simulation` is a view function to estimate the return value of said swap. ```move theme={null} #[view] /// Return swap simulation result public fun get_swap_simulation( pair: Object, offer_metadata: Object, offer_amount: u64, ): u64 // return amount ``` * `pair`: The metadata or object address of pair. * `offer_metadata`: Metadata of offered coin. * `offer_amount`: Amount of offered coin. ```bash curl theme={null} curl -X POST "https://rest.testnet.initia.xyz/initia/move/v1/accounts/0x1/modules/dex/view_functions/get_swap_simulation" \ -H "accept: application/json" \ -H "Content-Type: application/json" \ -d "{ \"args\": [ \"[BCS_ENCODED_OBJECT, BCS_ENCODED_OBJECT, BCS_ENCODED_OFFER_AMOUNT]\" ]}" #{ # "data": "\"100\"", # "events": [], # "gas_used": "5699" #} ``` ```bash CLI theme={null} initiad query move view 0x1 dex get_swap_simulation \ --args '["object:0x...", "object:0x...", "u64:123"]' \ --node [rpc-url]:[rpc-port] # data: '"123"' # events: [] # gas_used: "5699" ``` ```ts InitiaJS theme={null} import { RESTClient, bcs } from '@initia/initia.js'; const restClient = new RESTClient('https://rest.testnet.initia.xyz', { gasPrices: '0.015uinit', gasAdjustment: '1.5', }); restClient.move .view( '0x1', 'dex', 'get_swap_simulation', [], [ bcs.object().serialize('0x...').toBase64(), bcs.object().serialize('0x...').toBase64(), bcs.u64().serialize(100).toBase64(), ] ) .then(console.log); // { data: '"100"', events: [], gas_used: '21371' } ``` ### Swap The Move module interface for swap function is as follows: ```move theme={null} public entry fun swap_script( account: &signer, pair: Object, offer_coin: Object, offer_coin_amount: u64, min_return: Option, ) ``` * `pair`: The metadata or object address of pair. * `offer_coin`: Metadata of offered coin. * `offer_coin_amount`: Amount of offered coin. * `min_return`: Minimum return amount of coin. In case that the actual value is smaller than `min_return`, the transaction will fail. ```bash CLI theme={null} initiad tx move execute 0x1 dex swap_script \ --args '["object:0x...", "object:0x...", "u64:100", "option:100"]' \ --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'; async function main() { 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', 'dex', 'swap_script', [], [ bcs.object().serialize('0x...'), // pair object bcs.object().serialize('0x...'), // offer asset metadata bcs.u64().serialize(100000000), // offer amount bcs.option(bcs.u64()).serialize(100000000), // min return amount ].map(v => v.toBase64()) ), ]; // sign tx const signedTx = await wallet.createAndSignTx({ msgs }); // send(broadcast) tx restClient.tx.broadcastSync(signedTx).then(res => console.log(res)); // { // height: 0, // txhash: '0F2B255EE75FBA407267BB57A6FF3E3349522DA6DBB31C0356DB588CC3933F37', // raw_log: '[]' // } } main(); ``` ## How to Delegate LP Tokens ### Whitelist a Pair To delegate your LP tokens to a validator, you need to whitelist the LP token first. You can use [MsgWhitelist](https://github.com/initia-labs/initia/blob/30d4e297f127c450626ebc06e99be0f263463cc8/proto/initia/move/v1/tx.proto#L299-L313) to whitelist the LP token. ```json proposal.json theme={null} { "messages": [ { "@type": "/initia.move.v1.MsgWhitelist", "authority": "init10d07y265gmmuvt4z0w9aw880jnsr700j55nka3", "metadata_lp": "init1law8gy5hj9mvtelssjnvg0amudfyn0y42kv4v04q4yl30pevmm2qhvvk8v", "reward_weight": "1000000000000000000" } ], "deposit": "100000000uinit", "metadata": "uinit", "summary": "it is awesome", "title": "awesome proposal" } ``` ```bash theme={null} initiad tx gov submit-proposal proposal.json \ --from [key-name] \ --gas auto --gas-adjustment 1.5 --gas-prices 0.015uinit \ --node [rpc-url]:[rpc-port] --chain-id [chain-id] ``` ```ts theme={null} async function getLastProposalId(restClient: RESTClient): Promise { const [proposals, pagination] = await restClient.gov.proposals() if (proposals.length === 0) return 0 return proposals[proposals.length - 1].id } async function whitelistLP(lpMetadata: string) { const msgWhiteList = new MsgWhitelist( 'init10d07y265gmmuvt4z0w9aw880jnsr700j55nka3', // authority AccAddress.fromHex(lpMetadata), // metadata '1000000000000000000' // weight for reward (10^18) ) const proposal = new MsgSubmitProposal( [msgWhiteList], '100000000uinit', // deposit user.key.accAddress, // proposer 'uinit', // metadata 'awesome proposal', // title 'it is awesome', // summary false // expedited ) const proposalId = (await getLastProposalId(user.rest)) + 1 // if there's only one validator, it will exceed the quorum (cause we set as user = validator) const vote = new MsgVote(proposalId, user.key.accAddress, VoteOption.VOTE_OPTION_YES, '') const signedTx = await user.createAndSignTx({ msgs: [proposal, vote]}) await user.rest.tx.broadcast(signedTx).catch(console.log) } ``` ### Delegate LP Tokens After whitelisting the LP token, you can delegate your LP tokens to a validator. You can use `MsgDelegate` to delegate LP tokens. ```bash CLI theme={null} # initiad tx mstaking delegate [validator-addr] [amount] initiad tx mstaking delegate initvaloper1.... 100move/ff5c7412979 \ --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} async function delegateLP( lpMetadata: string, amount: number ) { // we can get lp denom from lp metadata by adding 'move/' prefix // if lp metadata is ff5c7412979... // then lp denom is move/ff5c7412979... const msg = new MsgDelegate( user.key.accAddress, // delegator validator.key.valAddress, // validator `${amount}move/${lpMetadata}` // lp token ) const signedTx = await user.createAndSignTx({ msgs: [msg] }) await user.rest.tx.broadcast(signedTx).catch(console.log) } ``` ## Example Code The following example demonstrates the above functions in a single script using InitiaJS. The script includes the following steps: 1. Create a pair 2. Provide liquidity 3. Whitelist LP 4. Delegate LP tokens to the validator 5. Withdraw rewards from the validator To run the script, you need to install the following packages: ```bash theme={null} npm install @initia/initia.js @initia/initia.proto @noble/hashes @cosmjs/encoding bluebird ``` Also, we assume: * Local Initia node is running on `http://localhost:1317`. * The user and validator share the same mnemonic for simplicity. ```ts create-and-provide-liquidity.ts theme={null} // NOTE: In this example, we use the same mnemonic for both user and validator. // The reason is that we want to simplify the example. // This will make it easier to whitelist during the proposal. // It takes a bit of time to whitelist, so you can skip this step 3 and do it manually. // Some possible errors: // location=0000000000000000000000000000000000000000000000000000000000000001::object, code=524289 -> The object (pair) is already created, skip step 1 // location=0000000000000000000000000000000000000000000000000000000000000001::object, code=393218 -> The object (pair) is not created yet, retry step 1 import { AccAddress, bcs, RESTClient, MnemonicKey, MsgDelegate, MsgExecute, MsgSubmitProposal, MsgVote, MsgWhitelist, MsgWithdrawDelegatorReward, Wallet, } from '@initia/initia.js' import { ProposalStatus, VoteOption, } from '@initia/initia.proto/cosmos/gov/v1/gov' import { delay } from 'bluebird' import { sha3_256 } from '@noble/hashes/sha3' import { concatBytes, toBytes } from '@noble/hashes/utils' import { toHex } from '@cosmjs/encoding' import { MsgUndelegate } from 'vm/move/msgs/staking' const user = new Wallet( new RESTClient('http://localhost:1317', { gasPrices: '0.015uinit', gasAdjustment: '1.75', }), new MnemonicKey({ // TODO: put your mnemonic here mnemonic: 'mimic exist actress ...', }), ) const validator = new Wallet( new RESTClient('http://localhost:1317', { gasPrices: '0.015uinit', gasAdjustment: '1.75', }), new MnemonicKey({ // TODO: put your mnemonic here mnemonic: 'mimic exist actress ...', }), ) function coinMetadata(creator: string, symbol: string) { const OBJECT_FROM_SEED_ADDRESS_SCHEME = 0xfe const addrBytes = bcs.address().serialize(creator).toBytes() const seed = toBytes(symbol) const bytes = new Uint8Array([ ...concatBytes(addrBytes, seed), OBJECT_FROM_SEED_ADDRESS_SCHEME, ]) const sum = sha3_256.create().update(bytes).digest() return toHex(sum) } async function getLastProposalId( restClient: RESTClient, ): Promise { const [proposals, pagination] = await restClient.gov.proposals() if (proposals.length === 0) return 0 return proposals[proposals.length - 1].id } async function getProposalStatus( restClient: RESTClient, proposalId: number, ): Promise { const proposal = await restClient.gov.proposal(proposalId) return proposal ? proposal.status : null } async function checkProposalPassed( restClient: RESTClient, proposalId: number, ): Promise { for (;;) { console.log( `checking proposal ${proposalId} status... in ${restClient.URL}/cosmos/gov/v1/proposals/${proposalId}`, ) const status = await getProposalStatus(restClient, proposalId) if (status === ProposalStatus.PROPOSAL_STATUS_PASSED) return if (status === ProposalStatus.PROPOSAL_STATUS_REJECTED) throw new Error(`proposal ${proposalId} rejected`) if (status === ProposalStatus.PROPOSAL_STATUS_FAILED) throw new Error(`proposal ${proposalId} failed`) await delay(5_000) } } async function provideLiquidity( lp_metadata: string, coin_a_amount: number, coin_b_amount: number, min_liquidity: number | null, ) { const msg = new MsgExecute( user.key.accAddress, '0x1', 'dex', 'provide_liquidity_script', [], [ bcs.string().serialize(lp_metadata).toBase64(), bcs.u64().serialize(coin_a_amount).toBase64(), bcs.u64().serialize(coin_b_amount).toBase64(), bcs.option(bcs.u64()).serialize(min_liquidity).toBase64(), ], ) const signedTx = await user.createAndSignTx({ msgs: [msg] }) await user.rest.tx.broadcast(signedTx).catch(console.log) } async function createPairScript( sender: Wallet, name: string, symbol: string, swap_fee_rate: number, coin_a_weight: number, coin_b_weight: number, coin_a_metadata: string, coin_b_metadata: string, coin_a_amount: number, coin_b_amount: number, ) { const msg = new MsgExecute( sender.key.accAddress, '0x1', 'dex', 'create_pair_script', [], [ bcs.string().serialize(name).toBase64(), bcs.string().serialize(symbol).toBase64(), bcs.bigdecimal().serialize(swap_fee_rate).toBase64(), bcs.bigdecimal().serialize(coin_a_weight).toBase64(), bcs.bigdecimal().serialize(coin_b_weight).toBase64(), bcs.object().serialize(coin_a_metadata).toBase64(), bcs.object().serialize(coin_b_metadata).toBase64(), bcs.u64().serialize(coin_a_amount).toBase64(), bcs.u64().serialize(coin_b_amount).toBase64(), ], ) const signedTx = await sender.createAndSignTx({ msgs: [msg] }) await sender.rest.tx.broadcast(signedTx).catch(console.log) } async function whitelistLP(lpMetadata: string) { const msgWhiteList = new MsgWhitelist( 'init10d07y265gmmuvt4z0w9aw880jnsr700j55nka3', // authority AccAddress.fromHex(lpMetadata), // metadata '1000000000000000000', // weight for reward (10^18) ) const proposal = new MsgSubmitProposal( [msgWhiteList], '100000000uinit', // deposit user.key.accAddress, // proposer 'uinit', // metadata 'awesome proposal', // title 'it is awesome', // summary false, // expedited ) const proposalId = (await getLastProposalId(user.rest)) + 1 // if there's only one validator, it will exceed the quorum (cause we set as // user = validator) const vote = new MsgVote( proposalId, user.key.accAddress, VoteOption.VOTE_OPTION_YES, '', ) const signedTx = await user.createAndSignTx({ msgs: [proposal, vote] }) await user.rest.tx.broadcast(signedTx).catch(console.log) await checkProposalPassed(user.rest, proposalId) } async function delegateLP(lpMetadata: string, amount: number) { // we can get lp denom from lp metadata by adding 'move/' prefix // if lp metadata is ff5c7412979... // then lp denom is move/ff5c7412979... const msg = new MsgDelegate( user.key.accAddress, // delegator validator.key.valAddress, // validator `${amount}move/${lpMetadata}`, // lp token ) const signedTx = await user.createAndSignTx({ msgs: [msg] }) await user.rest.tx.broadcast(signedTx).catch(console.log) } async function withdrawRewards() { const msg = new MsgWithdrawDelegatorReward( user.key.accAddress, validator.key.valAddress, ) const signedTx = await user.createAndSignTx({ msgs: [msg] }) await user.rest.tx.broadcast(signedTx).catch(console.log) } // NOTE: if you uncomment step 2, there will be an error // because it takes a bit of time to create a pair async function main() { console.log('user:', user.key.accAddress) console.log('validator:', validator.key.valAddress) // step 1: create pair script await createPairScript( user, 'init-usdc', 'init-usdc', 0.003, 0.5, 0.5, coinMetadata('0x1', 'uinit'), coinMetadata('0x1', 'uusdc'), 100_000_000, 100_000_000, ) const lpMetadata = coinMetadata(user.key.accAddress, 'init-usdc') // // ff5c7412979176c5e7f084a6... console.log('step 1 done, lp metadata:', lpMetadata) // step 2 (optional): provide liquidity // you will get LP tokens when you create a pair, so you can skip this step // await provideLiquidity( // lpMetadata, // 100_000_000, // 100_000_000, // 100_000 // ) // console.log('step 2 provide liquidity done') // step 3: whitelist LP // this step could take a while (check your 'expedited_voting_period' time in // genesis.json) await whitelistLP(lpMetadata) console.log('step 3 whitelist done') // step 4: delegate LP tokens to the validator await delegateLP(lpMetadata, 100_000) console.log('step 4 delegate done') // step 5: withdraw rewards // await withdrawRewards() // console.log('step 5 withdraw done') } if (require.main === module) { main() } ``` # Introduction Source: https://docs.initia.xyz/developers/developer-guides/integrating-initia-apps/registry/introduction To support an asset or rollup across all Initia apps — App, Bridge, Scan, and Wallet — you must register it in the [Initia Registry](https://github.com/initia-labs/initia-registry). Currently, registration is done via a GitHub pull request to the registry repository. The file and directory that need to be updated in the PR vary depending on the type of information being added. ## Adding Profiles To display your application's information — including logo, name, description, and more — on Initia's [ecosystem page](https://initia.xyz/ecosystem), register it in the [Initia Registry](https://github.com/initia-labs/initia-registry). In the registration PR, create a new file in the `profiles` directory with the structure that follows [this schema](https://github.com/initia-labs/initia-registry/blob/main/profile.schema.json). The JSON file name should be the name of the application. This step can be completed at any time before your rollup is live and public. ## Adding Rollups Once your rollup is live, you also then need to register it in the registry for it to be supported on the Bridge, Scan, and Wallet pages. For this, navigate to the corresponding network directory in the registry repository and create a new folder. The folder name should be the same as the profile JSON file name you created in the previous step. You then need to create two files in the folder: 1. [chain.json](https://github.com/initia-labs/initia-registry/blob/main/chain.schema.json) - Contains key information about the rollup including the chain ID, name, API endpoints, and more. 2. [assetlist.json](https://github.com/initia-labs/initia-registry/blob/main/assetlist.schema.json) - A file containing all of the major assets on the rollup such as symbol, logo, and decimal precision. You can create a PR to add both a profile and rollup at the same time, but the profile file is required for the rollup to be fully supported. ## Adding Assets When creating new assets, teams and developers should also register the asset information in the registry. This will allow the assets to be displayed in the user's balances, selectable on bridge and swap pages, and more. To do so, modify the corresponding rollup's and Initia L1's `assetlist.json` file in the registry repository with the new asset information. # Querying Initia Usernames Source: https://docs.initia.xyz/developers/developer-guides/integrating-initia-apps/usernames ## Module Addresses | Network | Address | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Testnet (initiation-2) | [0x42cd8467b1c86e59bf319e5664a09b6b5840bb3fac64f5ce690b5041c530565a](https://scan.testnet.initia.xyz/initiation-2/modules/0x42cd8467b1c86e59bf319e5664a09b6b5840bb3fac64f5ce690b5041c530565a/usernames) | ## Tutorials ### Getting Address from Usernames To retrieve an address from a username, we use the `get_address_from_name` function. The function interface is as follows: ```move theme={null} #[view] public fun get_address_from_name(name: String): Option
``` ```js InitiaJS theme={null} const { RESTClient, bcs } = require('@initia/initia.js') const moduleAddress = '0x...' const name = 'initia' const restClient = new RESTClient('https://rest.testnet.initia.xyz', { gasPrices: '0.015uinit', gasAdjustment: '1.5', }) restClient.move .view( moduleAddress, 'usernames', 'get_address_from_name', [], [bcs.string().serialize(name).toBase64()], ) .then(console.log) // Response: // { // data: '"0x.."', // events: [], // gas_used: '5699' // } ``` ### Getting Usernames from Address To retrieve a username from an address, we use the `get_name_from_address` function. ```move theme={null} #[view] public fun get_name_from_address(addr: address): Option ``` ```js InitiaJS theme={null} const { RESTClient, bcs } = require('@initia/initia.js') const moduleAddress = '0x...' const address = 'init1...' const restClient = new RESTClient('https://rest.testnet.initia.xyz', { gasPrices: '0.015uinit', gasAdjustment: '1.5', }) restClient.move .view( moduleAddress, 'usernames', 'get_name_from_address', [], [bcs.address().serialize(address).toBase64()], ) .then(console.log) // Response: // { // data: '"abc..."', // events: [], // gas_used: '5699' // } ``` # Integrating VIP Source: https://docs.initia.xyz/developers/developer-guides/integrating-initia-apps/vip/integrate-vip This guide explains how a rollup can prepare for and integrate Initia's [VIP](/home/core-concepts/vip). ## Prerequisites * [Weave CLI](/developers/developer-guides/tools/clis/weave-cli/rollup/introduction) * [Minitiad CLI](/developers/developer-guides/tools/clis/minitiad-cli/introduction) First, launch your rollup. For local deployments, you can use the [Weave CLI](/developers/developer-guides/tools/clis/weave-cli/rollup/introduction) to launch a rollup. Once your rollup is running, fetch the rollup's version by running the following command: ```bash theme={null} export RPC_URL={YOUR_ROLLUP_RPC_URL} curl -X POST $RPC_URL/abci_info ``` The output will be in the format below. The `version` field is the rollup's version. ```json highlight={7} theme={null} { "jsonrpc": "2.0", "id": -1, "result": { "response": { "data": "minitia", "version": "v1.0.2", "last_block_height": "10458738", "last_block_app_hash": "lS/hN6BDFU45Z0Oee04MZm15TS49yx+//SQJsXSSfms=" } } } ``` Next, install the `minitiad` CLI that matches the rollup's version. export MINIEVM\_VERSION=1.1.7 # Replace with your rollup's version git clone [https://github.com/initia-labs/minievm.git](https://github.com/initia-labs/minievm.git) cd minievm git checkout \$MINIEVM\_VERSION make install export MINIMOVE\_VERSION=1.0.6 git clone [https://github.com/initia-labs/minimove.git](https://github.com/initia-labs/minimove.git) cd minimove git checkout \$MINIMOVE\_VERSION # Replace with your rollup's version make install export MINIWASM\_VERSION=1.0.6 # Replace with your rollup's version git clone [https://github.com/initia-labs/miniwasm.git](https://github.com/initia-labs/miniwasm.git) cd miniwasm git checkout \$MINIWASM\_VERSION make install Next, create a VIP operator account and a VIP contract deployer account to deploy the VIP scoring contract. * The VIP operator account will receive the VIP operator rewards * The VIP contract deployer account will handle the deployment of the VIP scoring contract. If you have an existing account for these roles, use the `--recover` option to recover it with a BIP39 mnemonic phrase. If you do not have a mnemonic phrase, create a new account without this option. ```bash theme={null} export OPERATOR_KEY_NAME=operator export DEPLOYER_KEY_NAME=deployer minitiad keys add $OPERATOR_KEY_NAME --recover # > Enter your bip39 mnemonic # glare boil shallow hurt distance grant rose pledge begin main stage affair alpha garlic tornado enemy enable swallow unusual foster maid pelican also bus minitiad keys add $DEPLOYER_KEY_NAME --recover # > Enter your bip39 mnemonic # room fruit chalk buyer budget wisdom theme sound north square regular truck deal anxiety wrestle toy flight release actress critic saddle garment just found ``` Alternatively, if you want to use a Ledger hardware wallet, you can use the `--ledger` option to create an account that uses Ledger for signing transactions. ```bash theme={null} minitiad keys add $OPERATOR_KEY_NAME --ledger ``` In this step, you will deploy the VIP scoring contract that tracks addresses and scores. To do so, follow the steps based on your rollup's VM. The VIP scoring contract must specify the stage at which the rollup participates in VIP when deployed. To retrieve the current VIP stage, select the example for your network and run the curl request or the TypeScript example. Both query the VIP module store on L1 and return the current stage information. ```bash curl theme={null} curl https://rest.initia.xyz/initia/move/v1/accounts/0x3a886b32a802582f2e446e74d4a24d1d7ed01adf46d2a8f65c5723887e708789/resources/by_struct_tag?struct_tag=0x3a886b32a802582f2e446e74d4a24d1d7ed01adf46d2a8f65c5723887e708789%3A%3Avip%3A%3AModuleStore ``` ```ts initia.js theme={null} import { RESTClient } from '@initia/initia.js' const L1_VIP_CONTRACT = '0x3a886b32a802582f2e446e74d4a24d1d7ed01adf46d2a8f65c5723887e708789' const L1_REST_URL = 'https://rest.initia.xyz' async function getCurrentStage(): Promise { const rest = new RESTClient(L1_REST_URL) return rest.move.resource(L1_VIP_CONTRACT, `${L1_VIP_CONTRACT}::vip::ModuleStore`).then((res) => res.data.stage) } ``` ```bash curl theme={null} curl https://rest.testnet.initia.xyz/initia/move/v1/accounts/0xe55cc823efb411bed5eed25aca5277229a54c62ab3769005f86cc44bc0c0e5ab/resources/by_struct_tag?struct_tag=0xe55cc823efb411bed5eed25aca5277229a54c62ab3769005f86cc44bc0c0e5ab%3A%3Avip%3A%3AModuleStore ``` ```ts initia.js theme={null} import { RESTClient } from '@initia/initia.js' const L1_VIP_CONTRACT = '0xe55cc823efb411bed5eed25aca5277229a54c62ab3769005f86cc44bc0c0e5ab' const L1_REST_URL = 'https://rest.testnet.initia.xyz' async function getCurrentStage(): Promise { const rest = new RESTClient(L1_REST_URL) return rest.move.resource(L1_VIP_CONTRACT, `${L1_VIP_CONTRACT}::vip::ModuleStore`).then((res) => res.data.stage) } ``` Clone the [`vip-score-evm`](https://github.com/initia-labs/vip-score-evm) repository. ```bash theme={null} git clone https://github.com/initia-labs/vip-score-evm.git ``` Compile the `VIPScore.sol` contract. If you do not have [Foundry](https://github.com/foundry-rs/foundry) installed, follow the [Foundry installation instructions](https://getfoundry.sh). ```bash theme={null} forge build ``` Deploy the contract. Before running the script, set these environment variables: * `JSON_RPC_URL`: your rollup's RPC endpoint * `PRIVATE_KEY`: the VIP contract deployer key * `INIT_STAGE`: the starting VIP stage number To get `INIT_STAGE`, you can check the current VIP stage by using the curl request or the TypeScript example provided in the previous note. ```bash theme={null} export JSON_RPC_URL=https://jsonrpc-evm-1.anvil.asia-southeast.initia.xyz # Replace with your rollup's JSON_RPC endpoint export PRIVATE_KEY=0xabcd1234... # Replace with your deployer's private key export INIT_STAGE=1 # Replace with the starting stage number for scoring. forge script script/VipScore.s.sol:DeployVipScore --rpc-url $JSON_RPC_URL --broadcast # ... # ✅ [Success] Hash: 0xd55beed5a745b203b56dc68c9e9141fcfd433c4c47587ce50655a99f5c449abc # Contract Address: 0x1F00dfc319F1B74462B2Ef301c3978ee71f0d0E2 # Block: 238 # Paid: 0.000000000000525763 ETH (525763 gas * 0.000000001 gwei) # ✅ Sequence #1 on 1982194020580198 | Total Paid: 0.000000000000525763 ETH (525763 gas * avg 0.000000001 gwei) # ... ``` Clone the [`vip-score-move`](https://github.com/initia-labs/vip-score-move) repository. ```bash theme={null} git clone https://github.com/initia-labs/vip-score-move.git ``` Set the `vip_score.move` deployer address in the `Move.toml` file. You will use this address to deploy and interact with the contract. ```toml theme={null} [addresses] vip_score = "0x1234..." # Replace with your deployer address ``` Compile the Move package. ```bash theme={null} cd vip-score-move minitiad move build ``` Deploy the contract. Make sure to set the `GAS_PRICES`, `RPC_NODE_URL`, and `CHAIN_ID` environment variables before running the command. ```bash theme={null} export GAS_PRICES=0.015l2/07b129ceb9c4b0bdef7db171ce1e22f90d34bc930058b23e21adf8cc938d8145 # Replace with your rollup gas prices export RPC_NODE_URL=https://rpc-move-1.anvil.asia-southeast.initia.xyz # Replace with your rollup's RPC endpoint export CHAIN_ID=move-1 # Replace with your rollup's chain ID minitiad move deploy \ --from $DEPLOYER_KEY_NAME \ --gas auto \ --gas-prices $GAS_PRICES \ --node $RPC_NODE_URL \ --chain-id $CHAIN_ID ``` Clone the [`vip-score-wasm`](https://github.com/initia-labs/vip-score-wasm) repository. ```bash theme={null} git clone https://github.com/initia-labs/vip-score-wasm.git ``` Compile the Wasm package. If you don't have [Rust](https://www.rust-lang.org/), follow the [Rust and Cargo installation instructions](https://doc.rust-lang.org/cargo/getting-started/installation.html). ```bash theme={null} cd vip-score-wasm cargo build --release --target wasm32-unknown-unknown ``` Upload the contract. Make sure to set the `GAS_PRICES`, `RPC_NODE_URL`, and `CHAIN_ID` environment variables before running the command. ```bash theme={null} export GAS_PRICES=0.015l2/8b3e1fc559b327a35335e3f26ff657eaee5ff8486ccd3c1bc59007a93cf23156 # Replace with your rollup gas prices export RPC_NODE_URL=https://rpc-wasm-1.anvil.asia-southeast.initia.xyz # Replace with your rollup's RPC endpoint export CHAIN_ID=wasm-1 # Replace with your rollup's chain ID minitiad tx wasm store ./target/wasm32-unknown-unknown/release/vip_score.wasm \ --from $DEPLOYER_KEY_NAME \ --gas auto \ --gas-prices $GAS_PRICES \ --node $RPC_NODE_URL \ --chain-id $CHAIN_ID ``` To instantiate the contract, you need to fetch the code ID from the transaction output. You'll need [`jq`](https://jqlang.org/download/) to parse the JSON output. ```bash theme={null} TX_HASH=4CDCE81C5D0FFBCB92683E64198B4DA9F449707BB4F87FCFD8E3F02EBCE042CF RESP=$(minitiad q tx $TX_HASH -o json --node $RPC_NODE_URL) echo "$RESP" | jq -r '.events[]| select(.type=="store_code").attributes[]| select(.key=="code_id").value' ``` The output is the code ID of the uploaded contract, which you will use to instantiate it. To get `INIT_STAGE`, check the current VIP stage using the curl request or TypeScript example from the previous note. ```bash theme={null} export ADDRESS=$(minitiad keys show $KEY_NAME -a) export CODE_ID=100 # Replace with the actual code ID from the previous step export INIT_STAGE=1 # Set the initial stage number export LABEL="vip_score" # Set the label for the contract export INIT_MSG='{"allow_list":["'"$ADDRESS"'"],"init_stage":'"$INIT_STAGE"'}' minitiad tx wasm instantiate "$CODE_ID" "$INIT_MSG" \ --admin $ADDRESS \ --from $KEY_NAME \ --label $LABEL \ --gas auto \ --gas-prices $GAS_PRICES \ --node $RPC_NODE_URL \ --chain-id $CHAIN_ID ``` Save the deployed contract address. You will need it for the VIP whitelist proposal. Clone the Initia Registry repository. ```bash theme={null} git clone https://github.com/initia-labs/initia-registry.git ``` Then, add your rollup information to the registry repo before submitting a pull request. For detailed instructions, see the [Initia Registry page](/developers/developer-guides/integrating-initia-apps/registry/introduction). Draft a forum post with the whitelist template. Include your operator address, scoring policy, and VIP score contract address. See the [Whitelisting Rollup for VIP](/developers/developer-guides/integrating-initia-apps/vip/whitelist-rollup-for-vip) guide for the full procedure. This proposal is required only for mainnet rollups. For testnet deployments, contact the Initia team directly. Each VIP stage follows the same sequence of steps. Use the methods below to update scores and finalize each stage. | Action | Method | Description | | -------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------- | | Update scores | `updateScores(stage, addrs[], amounts[])` | Update the scores for a list of addresses in the specified stage | | Finalize stage | `finalizeStage(uint64 stage)` | Finalize the given stage, preventing further changes and prepares the contract for the next stage | This code snippet shows how to use the [viem](https://viem.sh/) library to interact with the VIP scoring contract: ```ts vip-score-evm-tutorial.ts theme={null} import { createPublicClient, createWalletClient, http, parseAbi, encodeFunctionData, Hash, defineChain } from 'viem'; import { privateKeyToAccount } from 'viem/accounts'; import { RESTClient } from '@initia/initia.js'; /* -------------------------------------------------------- * * Environment variables * * -------------------------------------------------------- */ const JSON_RPC_URL = process.env.JSON_RPC_URL || 'https://jsonrpc-evm-1.anvil.asia-southeast.initia.xyz'; // Your rollup's JSON RPC endpoint const PRIVATE_KEY = process.env.PRIVATE_KEY || '0xabcd1234...'; // Your contract deployer's private key. Do not hardcode it in production const SCORE_CONTRACT = process.env.SCORE_CONTRACT || '0x12345...'; // The deployed VIP scoring contract address const EVM_CHAIN_ID = process.env.EVM_CHAIN_ID || '1982194020580198'; // Your rollup's chain ID const TARGET_STAGE = process.env.TARGET_STAGE || '1'; // The stage number you want to update scores for /* -------------------------------------------------------- * * Update addresses and scores (Mock Implementation) * * Replace these with actual addresses and scores * * -------------------------------------------------------- */ // ADDRESSES and SCORES should be arrays of the same length. const ADDRESSES = [ '0x1111111111111111111111111111111111111111', '0x2222222222222222222222222222222222222222', ] as `0x${string}`[]; const SCORES = [100n, 250n]; const chain = defineChain({ id: parseInt(EVM_CHAIN_ID), name: 'MiniEVM', nativeCurrency: { decimals: 18, name: 'Gas Token', symbol: 'GAS', }, rpcUrls: { default: { http: [JSON_RPC_URL], }, }, }) const publicClient = createPublicClient({ chain, transport: http(JSON_RPC_URL) }); const account = privateKeyToAccount(PRIVATE_KEY as `0x${string}`); const walletClient = createWalletClient({ chain, transport: http(JSON_RPC_URL), account }); const vipAbi = parseAbi([ 'function updateScores(uint64 stage, address[] addrs, uint64[] amounts)', 'function finalizeStage(uint64 stage)', ]); async function send(txData: Hash) { const receipt = await publicClient.waitForTransactionReceipt({ hash: txData }); if (receipt.status !== 'success') throw new Error(`Tx failed: ${txData}`); return receipt; } async function run() { const stage = TARGET_STAGE; // or await getCurrentStage(); /* update scores ---------------------------------- */ const tx1 = await walletClient.sendTransaction({ to: SCORE_CONTRACT as `0x${string}`, data: encodeFunctionData({ abi: vipAbi, functionName: 'updateScores', args: [BigInt(stage), ADDRESSES, SCORES], }), }); await send(tx1); console.log('Scores updated successfully.'); /* finalize stage --------------------------------- */ const tx2 = await walletClient.sendTransaction({ to: SCORE_CONTRACT as `0x${string}`, data: encodeFunctionData({ abi: vipAbi, functionName: 'finalizeStage', args: [BigInt(stage)] }), }); await send(tx2); console.log('Stage finalized successfully.'); } run().catch(console.error); ``` To get the EVM chain ID, call the `eth_chainId` JSON-RPC method. For example, using `curl`: ```bash theme={null} curl -X POST https://jsonrpc-evm-1.anvil.asia-southeast.initia.xyz/ \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' ``` | Action | Method | Description | | -------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Add deployer | `add_deployer_script(signer, stage)` | Add the deployer to the VIP scoring contract for the specified stage. This ensures that the deployer has the necessary permissions to interact with the contract. | | Set init stage | `set_init_stage(signer, stage)` | Set the initial stage for the VIP process | | Update scores | `update_score_script(signer, stage, addrs[], amounts[])` | Update the scores for a list of addresses in the specified stage | | Finalize stage | `finalize_script(signer, stage)` | Finalize the given stage, preventing further changes and prepares the contract for the next stage | ```ts vip-score-move-tutorial.ts theme={null} import { bcs, isTxError, MnemonicKey, Msg, MsgExecute, RESTClient, Wallet } from '@initia/initia.js' /* -------------------------------------------------------- * * Environment variables * * -------------------------------------------------------- */ const REST_URL = process.env.REST_URL || 'https://rest-move-1.anvil.asia-southeast.initia.xyz'; // Your rollup's REST endpoint const MNEMONIC_KEY = process.env.MNEMONIC_KEY || 'castle lung ...'; // Your contract deployer's mnemonic key. Do not hardcode it in production const SCORE_CONTRACT = process.env.SCORE_CONTRACT || '0x12345...'; // The deployed VIP scoring contract address const TARGET_STAGE = process.env.TARGET_STAGE || '1'; // The stage number you want to update scores for /* -------------------------------------------------------- * * Update addresses and scores (Mock Implementation) * * Replace these with actual addresses and scores * * -------------------------------------------------------- */ // ADDRESSES and SCORES should be arrays of the same length. const ADDRESSES = [ '0x1111111111111111111111111111111111111111', '0x2222222222222222222222222222222222222222' ] as `0x${string}`[] const SCORES = [100n, 250n] const restClient = new RESTClient(REST_URL) const wallet = new Wallet( restClient, new MnemonicKey({ mnemonic: MNEMONIC_KEY }) ) async function send(msgs: Msg[]) { const tx = await wallet.createAndSignTx({ msgs }) const broadcastRes = await wallet.rest.tx.broadcast(tx) if (isTxError(broadcastRes)) { throw new Error(`Error while sending tx: ${broadcastRes.code} ${broadcastRes.raw_log}`) } } async function run() { const stage = TARGET_STAGE // or await getCurrentStage(); /* add deployer ------------------------------ */ const msgs0 = [ new MsgExecute( wallet.key.accAddress, SCORE_CONTRACT, 'vip_score', 'add_deployer_script', [], [ bcs.address().serialize(wallet.key.accAddress).toBase64() ] ) ] await send(msgs0) console.log('Deployer added successfully.') /* set initial stage ---------------------------- */ const msgs1 = [ new MsgExecute( wallet.key.accAddress, SCORE_CONTRACT, 'vip_score', 'set_init_stage', [], [ bcs.u64().serialize(TARGET_STAGE).toBase64() ] ) ] await send(msgs1) console.log('Initial stage set successfully.') /* update scores --------------------------------- */ const msgs2 = [ new MsgExecute( wallet.key.accAddress, SCORE_CONTRACT, 'vip_score', 'update_score_script', [], [ bcs.u64().serialize(stage).toBase64(), bcs.vector(bcs.address()).serialize(ADDRESSES).toBase64(), bcs.vector(bcs.u64()).serialize(SCORES).toBase64() ] ) ] await send(msgs2) console.log('Scores updated successfully.') /* finalize stage --------------------------------- */ const msgs3 = [ new MsgExecute( wallet.key.accAddress, SCORE_CONTRACT, 'vip_score', 'finalize_script', [], [ bcs.u64().serialize(stage).toBase64() ] ) ] await send(msgs3) console.log('Stage finalized successfully.') } run().catch(console.error) ``` | Action | Method | Description | | -------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------- | | Update scores | `update_scores(signer, stage, addrs[], amounts[])` | Update the scores for a list of addresses in the specified stage | | Finalize stage | `finalize_stage(stage)` | Finalize the given stage, preventing further changes and prepares the contract for the next stage | ```ts vip-score-wasm-tutorial.ts theme={null} import { Coins, isTxError, MnemonicKey, Msg, MsgExecuteContract, RESTClient, Wallet } from '@initia/initia.js' /* -------------------------------------------------------- * * Environment variables * * -------------------------------------------------------- */ const RPC_URL = process.env.REST_URL || 'https://rest-wasm-1.anvil.asia-southeast.initia.xyz'; // Your rollup's REST endpoint const MNEMONIC_KEY = process.env.MNEMONIC_KEY || 'castle ping ...'; // Your contract deployer's mnemonic key. Do not hardcode it in production const SCORE_CONTRACT = process.env.SCORE_CONTRACT || 'init1ga1g...'; // The deployed VIP scoring contract address const TARGET_STAGE = process.env.TARGET_STAGE || '1'; // The stage number you want to update scores for /* -------------------------------------------------------- * * Update addresses and scores (Mock Implementation) * * Replace these with actual addresses and scores * * -------------------------------------------------------- */ // ADDRESSES and SCORES should be arrays of the same length. const ADDRESSES = [ 'init1lf0swvvhy3vqautdemmvunfmp0grfrjgzznx9s', 'init1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqpqr5e3d' ] const SCORES = [100, 250] const restClient = new RESTClient(RPC_URL) const wallet = new Wallet( restClient, new MnemonicKey({ mnemonic: MNEMONIC_KEY }) ) async function send(msgs: Msg[]) { const tx = await wallet.createAndSignTx({ msgs }) const broadcastRes = await wallet.rest.tx.broadcast(tx) if (isTxError(broadcastRes)) { throw new Error(`Error while sending tx: ${broadcastRes.code} ${broadcastRes.raw_log}`) } } async function run() { const stage = Number(TARGET_STAGE) // or await getCurrentStage(); /* update scores ----------------------------- */ const msgs1 = [ new MsgExecuteContract( wallet.key.accAddress, SCORE_CONTRACT, Buffer.from( JSON.stringify({ update_scores: { stage, scores: [ ...ADDRESSES.map((addr, i) => ([addr, SCORES[i]])) ] } }) ).toString('base64'), new Coins() ) ] await send(msgs1) console.log('Scores updated successfully.') /* finalize stage --------------------------------- */ const msgs2 = [ new MsgExecuteContract( wallet.key.accAddress, SCORE_CONTRACT, Buffer.from( JSON.stringify({ finalize_stage: { stage, }, }) ).toString('base64'), new Coins() ) ] await send(msgs2) console.log('Stage finalized successfully.') } run().catch(console.error) ``` # Managing Operator Settings Source: https://docs.initia.xyz/developers/developer-guides/integrating-initia-apps/vip/manage-operator-settings ## Prerequisites * [Initiad CLI](/developers/developer-guides/tools/clis/initiad-cli) ## Updating Operator Address The operator is the account you specify during VIP whitelisting that will receive your rollup's operator commission rewards. To learn more about the VIP operator rewards, see [this section](/home/core-concepts/vip/architecture#distribution-to-rollup-operators). To replace the operator address, call `update_operator` on the VIP contract and pass two arguments in order: the rollup bridge ID and the new operator address. The bridge ID uniquely identifies your rollup bridge and can be retrieved from `${REST_URL}/opinit/opchild/v1/bridge_info`. export BRIDGE\_ID=29 # Replace with your rollup bridge ID. You can get it from `${REST_URL}/opinit/opchild/v1/bridge_info` export NEW\_OPERATOR\_ADDRESS=init14zmga05vl324ddaw7wqwdqt9pcvjeeyae3jn2k # Replace with the new operator address export OPERATOR\_KEY\_NAME=operator # Replace with your operator key. Check `initiad keys list` for the list of your keys export VIP\_CONTRACT='init182yxkv4gqfvz7tjyde6dfgjdr4ldqxklgmf23aju2u3cslnss7ys6dy6w8' export RPC\_URL='[https://rpc.initia.xyz](https://rpc.initia.xyz)' export CHAIN\_ID='interwoven-1' initiad tx move execute-json $VIP_CONTRACT vip update_operator \ --args '["'$'", "'${NEW_OPERATOR_ADDRESS}'"]' \ --from $OPERATOR\_KEY\_NAME \ \--node $RPC_URL \ --chain-id $CHAIN\_ID \ \--gas-prices 0.015uinit \ \--gas auto export BRIDGE\_ID=29 # Replace with your rollup bridge ID. You can get it from `${REST_URL}/opinit/opchild/v1/bridge_info` export NEW\_OPERATOR\_ADDRESS=init14zmga05vl324ddaw7wqwdqt9pcvjeeyae3jn2k # Replace with the new operator address export OPERATOR\_KEY\_NAME=operator # Replace with your operator key. Check `initiad keys list` for the list of your keys export VIP\_CONTRACT='init1u4wvsgl0ksgma40w6fdv55nhy2d9f332kdmfqp0cdnzyhsxquk4swhuwfz' export RPC\_URL='[https://rpc.testnet.initia.xyz](https://rpc.testnet.initia.xyz)' export CHAIN\_ID='initiation-2' initiad tx move execute-json $VIP_CONTRACT vip update_operator \ --args '["'$'", "'${NEW_OPERATOR_ADDRESS}'"]' \ --from $OPERATOR\_KEY\_NAME \ \--node $RPC_URL \ --chain-id $CHAIN\_ID \ \--gas-prices 0.015uinit \ \--gas auto ## Updating Operator Commission Operator commissions can be adjusted based on the `operator_commission_max_rate` and `operator_commission_max_change_rate` settings established during VIP whitelisting. Note that the commission value can be modified only once per stage, and any updated rate will take effect starting from the next stage. To update the operator commission, call `update_operator_commission` on the VIP contract. This function takes three arguments: 1. the rollup bridge ID 2. the version number 3. the new commission rate Use version value `1` when the rollup is listed for the first time. If the rollup is delisted and later relisted, set the version to the previous value plus 1. export BRIDGE\_ID=29 # Replace with your actual bridge ID. You can get it from `${REST_URL}/opinit/opchild/v1/bridge_info` export VERSION=1 # Use 1 unless your rollup has been delisted before export NEW\_COMMISSION\_RATE=0.05 # Replace with the new commission rate (e.g., 0.05 for 5%) export OPERATOR\_KEY\_NAME=operator # Replace with your operator key name. Check `initiad keys list` for the list of your keys export VIP\_CONTRACT='init182yxkv4gqfvz7tjyde6dfgjdr4ldqxklgmf23aju2u3cslnss7ys6dy6w8' export RPC\_URL='[https://rpc.initia.xyz](https://rpc.initia.xyz)' export CHAIN\_ID='interwoven-1' initiad tx move execute-json $VIP_CONTRACT vip update_operator_commission \ --args '["'$'", "'${VERSION}'", "'$'"]' \ \--from $OPERATOR_KEY_NAME \ --node $RPC\_URL \ \--chain-id \$CHAIN\_ID \ \--gas-prices 0.015uinit \ \--gas auto export BRIDGE\_ID=29 # Replace with your actual bridge ID. You can get it from `${REST_URL}/opinit/opchild/v1/bridge_info` export VERSION=1 # Use 1 unless your rollup has been delisted before export NEW\_COMMISSION\_RATE=0.05 # Replace with the new commission rate (e.g., 0.05 for 5%) export OPERATOR\_KEY\_NAME=operator # Replace with your operator key name. Check `initiad keys list` for the list of your keys export VIP\_CONTRACT='init1u4wvsgl0ksgma40w6fdv55nhy2d9f332kdmfqp0cdnzyhsxquk4swhuwfz' export RPC\_URL='[https://rpc.testnet.initia.xyz](https://rpc.testnet.initia.xyz)' export CHAIN\_ID='initiation-2' initiad tx move execute-json $VIP_CONTRACT vip update_operator_commission \ --args '["'$'", "'${VERSION}'", "'$'"]' \ \--from $OPERATOR_KEY_NAME \ --node $RPC\_URL \ \--chain-id \$CHAIN\_ID \ \--gas-prices 0.015uinit \ \--gas auto # Updating VIP Scoring Criteria Source: https://docs.initia.xyz/developers/developer-guides/integrating-initia-apps/vip/update-vip-scoring-criteria This guide explains how to update the VIP scoring criteria for a rollup. Use the provided [proposal template](https://forum.initia.xyz/t/epoch-x-rollup-vip-update/263) to submit a forum proposal on the [Initia Forum](https://forum.initia.xyz) outlining the new scoring criteria and the changes. Submit this proposal at least one week before the VIP scoring criteria update date so the community can review and discuss it. In your original VIP whitelist proposal forum post, add a comment that links to the new draft so community members can follow the discussion. Inform the Initia team about your new criteria and share the link to the corresponding forum post so the VIP Committee can review it. The VIP committee will verify that your new criteria follow the [scoring policy](/home/core-concepts/vip/scoring#scoring-criteria) and are logically sound. If the new scoring criteria meet the requirements, the VIP committee will approve them and notify you. After the VIP committee approves the new scoring criteria, announce the changes at least one week before it is implemented to your community. Examples include posting on Discord, X (Twitter), and your other communication channels. The announcement must clearly explain every change, giving the exact date and time when the new criteria take effect. It should also link to the forum post and list any actions users must take so they have enough time to prepare. # Whitelisting Rollup for VIP Source: https://docs.initia.xyz/developers/developer-guides/integrating-initia-apps/vip/whitelist-rollup-for-vip You must whitelist your rollup before it can participate in the Vested Interest Program (VIP). The following steps are for whitelisting a rollup for VIP on Mainnet. For testnet rollups, please contact the Initia team. This section also assumes you have already added your rollup to the [Initia Registry](/developers/developer-guides/integrating-initia-apps/registry/introduction). If not, please follow the guide in the [previous section](/developers/developer-guides/integrating-initia-apps/vip/integrate-vip). Deploy the appropriate VIP scoring contract for your rollup’s VM. * EVM: [https://github.com/initia-labs/vip-score-evm](https://github.com/initia-labs/vip-score-evm) * Wasm: [https://github.com/initia-labs/vip-score-wasm](https://github.com/initia-labs/vip-score-wasm) * Move: [https://github.com/initia-labs/vip-score-move](https://github.com/initia-labs/vip-score-move) Before your rollup can be whitelisted, you must create a proposal in the [Initia Forum](https://forum.initia.xyz). See the [template](https://forum.initia.xyz/t/whitelist-new-rollup-on-vip/146) for the necessary information. After creating the forum proposal, you finally need to submit a governance proposal on the Initia L1. The script below shows how to do so. ```ts vip-l1-gov-proposal.ts expandable theme={null} import { MnemonicKey, RESTClient, Wallet, bcs, MsgSubmitProposal, MsgGovExecute } from '@initia/initia.js' const MNEMONIC_KEY = process.env.MNEMONIC_KEY || 'castle lung ...' // Your wallet's mnemonic key const REST_URL = process.env.REST_URL || 'https://rest.initia.xyz' // Initia L1 REST endpoint // Core parameters const VIP_CONTRACT_ADDRESS = process.env.VIP_CONTRACT || 'init182yxkv4gqfvz7tjyde6dfgjdr4ldqxklgmf23aju2u3cslnss7ys6dy6w8' // Rollup's VIP contract address const OPERATOR_ADDRESS = process.env.OPERATOR_ADDRESS || '0x68b8295438b3d50f81679db88260a596b8ab1f4be1caa94af87c6b853baf7b20' // Rollup's VIP operator address const BRIDGE_ID = process.env.BRIDGE_ID || '16' // Bridge ID const BRIDGE_ADDRESS = process.env.BRIDGE_ADDRESS || 'init1y3avrs2r9q3ggj5xs2q5zg4mmpqvr2necwl6s6fhfergtyp93ueq5270ht' // Bridge address const L2_SCORE_CONTRACT_ADDRESS = process.env.L2_SCORE_CONTRACT_ADDRESS || '0x668dc438bd71f365d1e9ae39ac92f35d5ccde03d' // L2 score contract address // Operator commission settings const OPERATOR_COMMISSION_MAX_RATE = process.env.OPERATOR_COMMISSION_MAX_RATE || '0.2' // Operator commission max rate, e.g., 0.2 for 20% const OPERATOR_COMMISSION_MAX_CHANGE_RATE = process.env.OPERATOR_COMMISSION_MAX_CHANGE_RATE || '0.2' // Operator commission max change rate, e.g., 0.2 for 20% const OPERATOR_COMMISSION_RATE = process.env.OPERATOR_COMMISSION_RATE || '0.2' // Operator commission rate, e.g., 0.2 for 20% // Proposal parameters const PROPOSAL_METADATA = process.env.PROPOSAL_METADATA || 'https://forum.initia.xyz' // VIP proposal forum URL const PROPOSAL_TITLE = process.env.PROPOSAL_TITLE || 'Whitelist Rollup on VIP' // VIP proposal title const PROPOSAL_SUMMARY = process.env.PROPOSAL_SUMMARY || 'This proposal is to whitelist Rollup on Initia VIP program.' // VIP proposal summary const ROLLUP_VM_TYPE = process.env.ROLLUP_VM_TYPE || 0 // Rollup VM type, 0 for MoveVM, 1 for WasmVM, 2 for EVM async function main() { const key = new MnemonicKey({ mnemonic: MNEMONIC_KEY }) const rest = new RESTClient(REST_URL, { gasPrices: `0.015uinit` }) const wallet = new Wallet(rest, key) const msg = new MsgSubmitProposal( [ new MsgGovExecute( 'init10d07y265gmmuvt4z0w9aw880jnsr700j55nka3', VIP_CONTRACT_ADDRESS, VIP_CONTRACT_ADDRESS, 'vip', 'register', [], [ bcs.address().serialize(OPERATOR_ADDRESS).toBase64(), bcs.u64().serialize(BRIDGE_ID).toBase64(), bcs.address().serialize(BRIDGE_ADDRESS).toBase64(), bcs.string().serialize(L2_SCORE_CONTRACT_ADDRESS).toBase64(), bcs.bigdecimal().serialize(OPERATOR_COMMISSION_MAX_RATE).toBase64(), bcs.bigdecimal().serialize(OPERATOR_COMMISSION_MAX_CHANGE_RATE).toBase64(), bcs.bigdecimal().serialize(OPERATOR_COMMISSION_RATE).toBase64(), bcs.u64().serialize(ROLLUP_VM_TYPE).toBase64() ] ) ], '100000000uinit', wallet.key.accAddress, PROPOSAL_METADATA, PROPOSAL_TITLE, PROPOSAL_SUMMARY, false ) const tx = await wallet.createAndSignTx({ msgs: [msg] }) const result = await rest.tx.broadcast(tx) console.log('Transaction result:', result) } main().catch(console.error) ``` After you submit the proposal, it enters a 7-day voting period. If the proposal passes, VIP whitelists and activates your rollup. # Account Source: https://docs.initia.xyz/developers/developer-guides/tools/clis/initiad-cli/accounts ## Creating an Account Before you can start building and transacting, you'll need to create an account. ```bash theme={null} export ACCOUNT_NAME=test-account initiad keys add $ACCOUNT_NAME # - address: init17exjfvgtpn5ne4pgmuatjg52mvvtj08773tgfx # name: test-account # pubkey: '{"@type":"/cosmos.crypto.secp256k1.PubKey","key":"Ap+WnRzOsJGgfgsrgc4APi/EiTzl3t52ruiKGev7X9LW"}' # 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. # glass easy miracle sign tent anchor position cluster shift calm march elite menu must nose inform antique reason meadow relief layer term crush gesture ``` The mnemonic key is the only way to recover your account if you forget your password. If you want to create an EVM account, you can use the following command: ```bash theme={null} export ETH_KEY_TYPE=eth_secp256k1 export ETH_COIN_TYPE=60 initiad keys add $ACCOUNT_NAME --key-type $ETH_KEY_TYPE --coin-type $ETH_COIN_TYPE ``` Even with the same mnemonic phrase, the derived addresses differ because the method of generating the public key varies, leading to each account being treated separately. ## Importing an Account You can import an account by providing a mnemonic phrase. ```bash theme={null} initiad keys add $ACCOUNT_NAME --recover > Enter your bip39 mnemonic glass easy miracle sign tent anchor position cluster shift calm march elite menu must nose inform antique reason meadow relief layer term crush gesture # - address: init1x7jl4cx6pq4urdppmnhwtyzfdtn5w7ssw4hjfm # name: test-account # pubkey: '{"@type":"/cosmos.crypto.secp256k1.PubKey","key":"Am9tmvRft+pcol+h/unlMB9gRbKAZF/7Y8K3iWOtr9Dw"}' # type: local ``` To export the account's private key, run: ```bash theme={null} initiad keys export $ACCOUNT_NAME > key.json >Enter passphrase to encrypt the exported key: # key.json # -----BEGIN TENDERMINT PRIVATE KEY----- # kdf: argon2 # salt: BE84B59652876BFBEEB0E01CA2AA753C # type: secp256k1 # edch8EcPYgSQrWHdJlmRMZGmh7gqOLYvAHsynbovXonq2reSeP+eEgtvwNYEnrQu # 2MZwMIs= # =ObmR # -----END TENDERMINT PRIVATE KEY----- ``` The exported private key is encrypted with a passphrase. So, you can only import it using `initiad` CLI. It is not possible to import it directly on Wallet Apps. To import the account using the exported private key, run: ```bash theme={null} export NEW_ACCOUNT_NAME=test-account2 initiad keys import $NEW_ACCOUNT_NAME key.json ``` ## Retrieving Account Data You can retrieve account data stored in the keyring. ```bash theme={null} initiad keys list # - address: init1x7jl4cx6pq4urdppmnhwtyzfdtn5w7ssw4hjfm # name: test-account # pubkey: '{"@type":"/cosmos.crypto.secp256k1.PubKey","key":"Am9tmvRft+pcol+h/unlMB9gRbKAZF/7Y8K3iWOtr9Dw"}' # type: local ``` ## Validator Address If you run a validator node, you can get the validator address by running: ```bash theme={null} initiad comet show-address # initvalcons1kknrtmntc39v3z4hgv84hddeclyfsxdgzdtn3q ``` To get validator consensus public key, run: ```bash theme={null} initiad comet show-validator # {"@type":"/cosmos.crypto.ed25519.PubKey","key":"lusuUL6CKywnZDPul5COzCFKLPLDGEMbLEIZIZlDp44="} ``` # Introduction Source: https://docs.initia.xyz/developers/developer-guides/tools/clis/initiad-cli/introduction Learn how to install and get started with the initiad command-line interface for interacting with Initia L1 The [initiad CLI](https://github.com/initia-labs/initia) is a command-line interface for interacting with the Initia L1. This tool provides comprehensive functionality for developers and users to manage accounts, query blockchain data, submit transactions, and perform other operations. ## Overview With initiad, you can: * **Account Management**: Create, import, and manage blockchain accounts * **Transaction Operations**: Send transactions, delegate tokens, and interact with smart contracts * **Data Queries**: Query blockchain state, account balances, and transaction history * **Validator Operations**: Create validators, delegate stakes, and manage governance proposals * **Network Interaction**: Connect to different networks (mainnet, testnet, local) initiad is built using the Cosmos SDK and provides a familiar interface for users of other Cosmos-based chains. ## Prerequisites Before installing initiad, ensure you have the following requirements: * **Go**: Version 1.21 or higher * **Git**: For cloning the repository * **Make**: For building the binary You can verify your Go installation by running `go version` in your terminal. ## Installation First, clone the initiad repository from GitHub: ```bash theme={null} git clone https://github.com/initia-labs/initia.git cd initia ``` Fetch the current network version and checkout the corresponding tag. Select the network that matches your intended use case: # Get the current mainnet version and checkout export VERSION=$(curl -s https://rest.initia.xyz/cosmos/base/tendermint/v1beta1/node_info | jq -r '.application_version.version' | grep -oE 'v[0-9]+\.[0-9]+\.[0-9]+') echo "Checking out version: $VERSION" git checkout \$VERSION # Get the current testnet version and checkout export VERSION=$(curl -s https://rest.testnet.initia.xyz/cosmos/base/tendermint/v1beta1/node_info | jq -r '.application_version.version' | grep -oE 'v[0-9]+\.[0-9]+\.[0-9]+') echo "Checking out version: $VERSION" git checkout \$VERSION # Manually set a specific version and checkout export VERSION=v0.5.7 echo "Checking out version: $VERSION" git checkout $VERSION Always use a specific version tag rather than the main branch for production environments to ensure stability. Mainnet and testnet may run different versions, so select the appropriate network endpoint. Compile and install the initiad binary: ```bash theme={null} make install ``` This will build the binary and install it to your `$GOPATH/bin` directory. ## Verification After installation, verify that initiad is correctly installed and accessible: ### Check CLI Version ```bash theme={null} initiad version # Output: v0.5.7 ``` ### Verify Installation Path ```bash theme={null} which initiad # Output: /Users/username/go/bin/initiad (or your $GOPATH/bin path) ``` ### Check Available Commands ```bash theme={null} initiad --help ``` ## Network Configuration By default, initiad connects to the Initia mainnet. You can configure it to connect to different networks: initiad config chain-id initia-1 initiad config node [https://rpc.initia.xyz:443](https://rpc.initia.xyz:443) initiad config chain-id initiation-1 initiad config node [https://rpc.testnet.initia.xyz:443](https://rpc.testnet.initia.xyz:443) initiad config chain-id local-initia initiad config node tcp\://localhost:26657 ## Next Steps Now that you have initiad installed and configured, you can: Set up accounts for sending transactions and managing assets Learn how to query balances, transactions, and network information Execute transactions, transfers, and smart contract interactions # Querying Data Source: https://docs.initia.xyz/developers/developer-guides/tools/clis/initiad-cli/querying-data The initiad CLI offers a range of commands for querying data from Initia L1. This guide walks you through using these commands to retrieve blockchain data. `initiad query` command enables you to query data from the blockchain. Each module provides a client-facing query interface. The general syntax for querying data is: ```bash theme={null} initiad query [module-name] [query-name] [args] [flags] ``` ## Querying Account Balance After receiving tokens to your address, you can view your account's balance like: ```bash theme={null} export ADDRESS=init1x7jl4cx6pq4urdppmnhwtyzfdtn5w7ssw4hjfm export NODE_URL=https://rpc.testnet.initia.xyz initiad query bank balances $ADDRESS --node $NODE_URL # - amount: "100000000" # denom: uinit ``` ## Querying Blocks You can query a single block by its height or hash using the following command: ```bash theme={null} export BLOCK_HEIGHT=1000 export BLOCK_HASH=04B7658B40508B290B04C61A0021EB5E9354F1E8C70DF5D6AE2A9B1F0B8D32A3 initiad query block --type=height $BLOCK_HEIGHT --node $NODE_URL initiad query block --type=hash $BLOCK_HASH --node $NODE_URL ``` ## Querying Transactions You can query a single transaction by its hash using the following command: ```bash theme={null} export TX_HASH=6DFEE8E4BFC38341E8AADBD74A23588D8DE94FA38052CB5721DDA780A24F8B1D initiad query tx $TX_HASH --node $NODE_URL # code: 0 # codespace: "" # data: 12240A222F696E697469612E6D6F76652E76312E4D736745786563757465526573706F6E7365 # events: # - attributes: # - index: true # key: sender # value: 0x1,0x512536dfca0b50144483dab26790912ad85b17fe # ... ``` ## Querying Params You can query the module parameters using the following command: ```bash theme={null} initiad query mstaking params --node $NODE_URL # bond_denoms: # - uinit # - move/dbf06c48af3984ec6d9ae8a9aa7dbb0bb1e784aa9b8c4a5681af660cf8558d7d # - move/a2b0d3c8e53e379ede31f3a361ff02716d50ec53c6b65b8c48a81d5b06548200 # - move/b134ae6786f10ef74294e627d2519b63b7c742a6735f98682929fea9a84744d2 # historical_entries: 10000 # max_entries: 7 # max_validators: 100 # min_commission_rate: "0.000000000000000000" # min_voting_power: "1000000" # unbonding_time: 1814400s initiad query move params --node $NODE_URL # allowed_publishers: [] # base_denom: uinit # base_min_gas_price: "0.015000000000000000" # contract_shared_revenue_ratio: "0.000000000000000000" # script_enabled: true ``` ## Querying Oracle If a node has the oracle module enabled, you can query the currency pairs and price using the following commands: ```bash theme={null} initiad query oracle currency-pairs --node $NODE_URL # currency_pairs: # - Base: AAVE # Quote: USD # - Base: ADA # Quote: USD # - Base: AEVO # Quote: USD initiad query oracle price AAVE USD --node $NODE_URL # decimals: "8" # id: "19" # nonce: "1233969" # price: # block_height: "1237222" # block_timestamp: "2024-10-30T05:36:59.810774835Z" # price: "15143771245" ``` # Transactions Source: https://docs.initia.xyz/developers/developer-guides/tools/clis/initiad-cli/transactions `initiad tx` command enables you to modify the chain state by submitting a transaction. Each module provides a client-facing transaction interface. The general syntax for submitting a transaction is: ```bash theme={null} initiad tx [module-name] [action-name] [args] [flags] ``` ## Send Tokens To send tokens from one account to another, you can use the following command: ```bash theme={null} export NODE_URL=https://rpc.testnet.initia.xyz export ACCOUNT_NAME=test-account export RECIPIENT_ADDRESS=init1x7jl4cx6pq4urdppmnhwtyzfdtn5w7ssw4hjfm export CHAIN_ID=initiation-2 initiad tx bank send $ACCOUNT_NAME $RECIPIENT_ADDRESS 1000uinit \ --node $NODE_URL \ --from $ACCOUNT_NAME \ --chain-id $CHAIN_ID \ --gas auto \ --gas-adjustment 1.4 ``` ## Deploy Move Module First, clone the initia-tutorials repository, which contains the read\_write module we'll be using. ```bash theme={null} git clone git@github.com:initia-labs/initia-tutorials.git ``` Before building the module, you need to update the module owner's address to your own address in the `Move.toml` configuration file located in `./initia-tutorials/move/read_write`. Use the following command to parse your Initia address into bytes format, which is your HEX address. ```bash theme={null} initiad keys parse init138ntr4czqvrfzz8vvfsmdz0a36u8h6g5ct5cna # bytes: 89E6B1D70203069108EC6261B689FD8EB87BE914 # human: init ``` Now, modify the `Move.toml` file to include your HEX address: ```toml theme={null} [package] name = "read_write" version = "0.0.0" [dependencies] InitiaStdlib = { git = "https://github.com/initia-labs/movevm.git", subdir = "precompile/modules/initia_stdlib", rev = "main" } [addresses] std = "0x1" your_address = "0x89E6B1D70203069108EC6261B689FD8EB87BE914" ``` Build the module using either CLI: ```bash theme={null} initiad move build --path ./initia-tutorials/move/read_write ``` Then, publish the module to the Initia blockchain: ```bash theme={null} initiad move deploy \ --path ./initia-tutorials/move/read_write \ --upgrade-policy COMPATIBLE \ --from $ACCOUNT_NAME \ --gas auto --gas-adjustment 1.5 \ --gas-prices 0.015uinit \ --node $NODE_URL \ --chain-id $CHAIN_ID ``` **About the upgrade policy:** | Policy | Description | | -------------- | --------------------------------------------------------------------------------------------------------------------- | | **COMPATIBLE** | Performs a compatibility check during upgrades, ensuring no public function changes or resource layout modifications. | | **IMMUTABLE** | Marks the modules as immutable, preventing any future upgrades. | To interact with the module, you can use the following command: ```bash theme={null} export MODULE_ADDRESS=0x89E6B1D70203069108EC6261B689FD8EB87BE914 initiad query move view $MODULE_ADDRESS read_write read \ --node $NODE_URL # data: '"initial content"' # events: [] # gas_used: "1166" initiad tx move execute $MODULE_ADDRESS read_write write \ --args '["string:new_string"]' \ --from $ACCOUNT_NAME \ --gas auto --gas-adjustment 1.5 --gas-prices 0.015uinit \ --node $NODE_URL --chain-id $CHAIN_ID initiad query move view $MODULE_ADDRESS read_write read \ --node $NODE_URL # data: '"new_string"' # events: [] # gas_used: "1150" ``` # Introduction Source: https://docs.initia.xyz/developers/developer-guides/tools/clis/minitiad-cli/introduction Learn how to install and get started with the minitiad command-line interface for interacting with Initia rollups The minitiad CLI is a command-line interface for interacting with appchains built on the Interwoven Stack. This tool provides comprehensive functionality for developers and users to manage accounts, query blockchain data, submit transactions, and perform various other operations. ## Overview With minitiad, you can: * **Account Management**: Create, import, and manage blockchain accounts * **Transaction Operations**: Send transactions, delegate tokens, and interact with smart contracts * **Data Queries**: Query blockchain state, account balances, and transaction history * **Validator Operations**: Create validators, delegate stakes, and manage governance proposals * **Multi-Chain Support**: Connect to different Initia rollup chains using configurable endpoints * **VM-Specific Builds**: Different implementations for Move, Wasm, and EVM rollup chains minitiad is built using the Cosmos SDK and provides a familiar interface for users of other Cosmos-based chains, specifically optimized for Initia rollups. ## VM Types and Repositories Different Initia rollup chains use different Virtual Machines (VMs), and each requires a specific minitiad implementation: * **Move**: [minimove](https://github.com/initia-labs/minimove) - For rollups running Move smart contracts * **Wasm**: [miniwasm](https://github.com/initia-labs/miniwasm) - For rollups running WebAssembly smart contracts * **EVM**: [minievm](https://github.com/initia-labs/minievm) - For rollups running Ethereum Virtual Machine smart contracts Check your rollup chain's documentation to determine which VM type it uses before installation. ## Prerequisites Before installing minitiad, ensure you have the following requirements: * **Go**: Version 1.21 or higher * **Git**: For cloning the repository * **Make**: For building the binary You can verify your Go installation by running `go version` in your terminal. ## Installation First, clone the appropriate repository based on your rollup's VM type: git clone [https://github.com/initia-labs/minimove.git](https://github.com/initia-labs/minimove.git) cd minimove git clone [https://github.com/initia-labs/miniwasm.git](https://github.com/initia-labs/miniwasm.git) cd miniwasm git clone [https://github.com/initia-labs/minievm.git](https://github.com/initia-labs/minievm.git) cd minievm Make sure to select the correct repository that matches your target rollup chain's VM type. Fetch the current network version and checkout the corresponding tag. Set your rollup chain endpoints first: # Set your rollup chain endpoints (replace with your specific chain) export CHAIN\_REST\_ENDPOINT="[https://rest.your-rollup-chain.com](https://rest.your-rollup-chain.com)" export CHAIN\_RPC\_ENDPOINT="[https://rpc.your-rollup-chain.com](https://rpc.your-rollup-chain.com)" # Get the current rollup version and checkout export VERSION=$(curl -s $CHAIN\_REST\_ENDPOINT/cosmos/base/tendermint/v1beta1/node\_info | jq -r '.application\_version.version' | grep -oE 'v\[0-9]+.\[0-9]+.\[0-9]+') echo "Checking out version: $VERSION" git checkout $VERSION # Manually set a specific version and checkout export VERSION=v0.5.7 echo "Checking out version: $VERSION" git checkout $VERSION Always use a specific version tag rather than the main branch for production environments to ensure stability. Different rollup chains may run different versions. Always fetch the version from your target rollup chain. Compile and install the minitiad binary: ```bash theme={null} make install ``` This will build the binary and install it to your `$GOPATH/bin` directory. ## Verification After installation, verify that minitiad is correctly installed and accessible: The CLI binary is always named `minitiad` regardless of which VM-specific repository you cloned. ### Check CLI Version ```bash theme={null} minitiad version # Output: v0.5.7 ``` ### Verify Installation Path ```bash theme={null} which minitiad # Output: /Users/username/go/bin/minitiad (or your $GOPATH/bin path) ``` ### Check Available Commands ```bash theme={null} minitiad --help ``` ## Network Configuration Configure the CLI to connect to your specific rollup chain by setting the appropriate endpoints: ### Setting Chain Endpoints ```bash theme={null} # Set your rollup chain endpoints export CHAIN_REST_ENDPOINT="https://rest.your-rollup-chain.com" export CHAIN_RPC_ENDPOINT="https://rpc.your-rollup-chain.com" export CHAIN_ID="your-chain-id" # Configure minitiad minitiad config chain-id $CHAIN_ID minitiad config node $CHAIN_RPC_ENDPOINT ``` Make sure to use the correct endpoints for your specific rollup chain. Each Initia rollup has its own unique endpoints and chain ID. ## Next Steps Now that you have minitiad installed and configured, you can start building and deploying applications on Initia rollup chains. The specific workflow will depend on your rollup's VM type (Move, Wasm, or EVM). Additional minitiad CLI documentation pages are currently being developed and will be available soon. # Gas Station Source: https://docs.initia.xyz/developers/developer-guides/tools/clis/weave-cli/gas-station The Gas Station is a dedicated account used by Weave to fund critical infrastructure components of the Interwoven stack. It distributes funds to essential services like [OPinit Bots](/home/core-concepts/interwoven-stack/opinit-framework/introduction) (including Bridge Executor, Output Submitter, Batch Submitter, and Challenger) and the [IBC relayer](https://tutorials.cosmos.network/academy/2-cosmos-concepts/13-relayer-intro.html) to ensure smooth operation of the network. This is essential for seamless operation with Weave as it eliminates the need for manual fund distribution. While Weave requires your consent for all fund transfers, using a separate account prevents any potential misuse of an existing account. Creating a new dedicated account for Gas Station use rather than using an existing account is strongly recommended. ## Setting Up the Gas Station ```bash theme={null} weave gas-station setup ``` You can either import an existing mnemonic or have Weave generate a new one. Once setup is complete, you'll see two addresses in `init` and `celestia` format. While the Gas Station addresses for Celestia and the Initia ecosystem will be different, both are derived from the same mnemonic that you entered. Then fund the account with at least 10 INIT tokens to support the necessary components. If you're planning to use Celestia as your Data Availability Layer, you'll also need to fund the account with `TIA` tokens. For testnet operations: - Get testnet `INIT` tokens from the [Initia faucet](https://faucet.testnet.initia.xyz/) - Get testnet `TIA` tokens from the [Celestia faucet](https://docs.celestia.org/how-to-guides/mocha-testnet#mocha-testnet-faucet) ## Viewing Gas Station Information ```bash theme={null} weave gas-station show ``` This command displays the addresses and current balances of the Gas Station account in both `init` and `celestia` bech32 formats. # Bootstrapping Initia Node Source: https://docs.initia.xyz/developers/developer-guides/tools/clis/weave-cli/initia-node Setting up a node for a Cosmos SDK chain has traditionally been a complex process requiring multiple steps: * Locating the correct repository and version of the node binary compatible with your target network * Either cloning and building the source code or downloading a pre-built binary from the release page * Configuring the node with appropriate `config.toml` and `app.toml` files, which involves: * Setting correct values for `seeds`, `persistent_peers`, and `pruning` * Navigating through numerous other parameters that rarely need modification * Finding and implementing the correct genesis file to sync with the network * Setting up cosmovisor for automatic updates or manually maintaining the node binary Weave streamlines this entire process into a simple command. ## Initialize Your Node ```bash theme={null} weave initia init ``` This command guides you through the node setup process, taking you from an empty directory to a fully synced node ready for operation. Once complete, you can run the node using `weave initia start`. **Available Flags** The directory to store the node's data and configuration files. ## Running Your Node ```bash theme={null} weave initia start ``` **Available Flags** Whether to run the node in the background. `bash weave initia stop ` `bash weave initia restart ` ```bash theme={null} weave initia log ``` **Available Flags** The number of lines to display from the end of the logs. ## Help To see all the available commands: ```bash theme={null} weave initia --help ``` # Installation & Setup Source: https://docs.initia.xyz/developers/developer-guides/tools/clis/weave-cli/installation ## Prerequisites * Operating System: **Linux, MacOS** * Go **v1.24** or higher (when building from source) * NPM & Node **v20** or higher (if you wish to run relayer in the same machine) * Docker and Docker Compose * For macOS: Install Docker Desktop from [https://www.docker.com/products/docker-desktop/](https://www.docker.com/products/docker-desktop/) * For Linux: Install Docker Engine and Docker Compose from [https://docs.docker.com/engine/install/](https://docs.docker.com/engine/install/) * Verify: `docker --version` and `docker compose version` * LZ4 compression tool * For macOS: `brew install lz4` * For Ubuntu/Debian: `apt-get install lz4` ## Installation ```bash theme={null} brew install initia-labs/tap/weave ``` **AMD64** ```bash theme={null} VERSION=$(curl -s https://api.github.com/repos/initia-labs/weave/releases/latest | grep '"tag_name":' | cut -d'"' -f4 | cut -c 2-) wget https://github.com/initia-labs/weave/releases/download/v$VERSION/weave-$VERSION-linux-amd64.tar.gz tar -xvf weave-$VERSION-linux-amd64.tar.gz ``` **ARM64** ```bash theme={null} VERSION=$(curl -s https://api.github.com/repos/initia-labs/weave/releases/latest | grep '"tag_name":' | cut -d'"' -f4 | cut -c 2-) wget https://github.com/initia-labs/weave/releases/download/v$VERSION/weave-$VERSION-linux-arm64.tar.gz tar -xvf weave-$VERSION-linux-arm64.tar.gz ``` ```bash theme={null} git clone https://github.com/initia-labs/weave.git cd weave VERSION=$(curl -s https://api.github.com/repos/initia-labs/weave/releases/latest | grep '"tag_name":' | cut -d'"' -f4 | cut -c 2-) git checkout tags/v$VERSION make install ``` ```bash theme={null} weave version ``` This should return the version of the Weave binary you have installed. To get started with Weave, run ```bash theme={null} weave init ``` It will ask you to set up the [Gas Station](/developers/developer-guides/tools/clis/weave-cli/gas-station) account and ask which infrastructure you want to set up. After that, Weave will guide you through the setup process step-by-step. Read the [Gas Station](/developers/developer-guides/tools/clis/weave-cli/gas-station) section to understand the purpose and usage of the Gas Station before proceeding. By default, Weave collects non-identifiable usage data to help improve the product. If you prefer not to share this data, you can opt out by running the following command: ```bash theme={null} weave analytics disable ``` ### Next Steps Set up your Initia node and start syncing with the chain. Configure and launch your own rollup. Set up and run the IBC relayer. This is necessary for the built-in oracle to work. Set up the OPinit bots to complete the optimistic rollup setup. or run ```bash theme={null} weave --help ``` to learn more about all the commands available. # Introduction Source: https://docs.initia.xyz/developers/developer-guides/tools/clis/weave-cli/introduction Weave is a CLI tool designed to make working with Initia and its Interwoven Rollups easier. Instead of dealing with multiple tools and extensive documentation, developers can use a single command-line interface for the entire development and deployment workflow. Its primary purpose is to solve several key challenges: 1. **Infrastructure Management:** Weave can handle all critical infrastructure components within the Interwoven Rollup ecosystem: * Initia node setup and management (including state sync and chain upgrade management) * Rollup deployment and configuration * OPinit bots setup for the Optimistic bridge * IBC Relayer setup between Initia L1 and your Rollup 2. **Built for both local development and production deployments:** Weave provides * Interactive guided setup for step-by-step configuration and * Configuration file support for automated deployments 3. **Developer Experience:** Not only does it consolidate multiple complex operations into a single CLI tool, but it also changes how you interact with the tool to set up your configuration. ## How Experience with Weave Is Different Here are some of the key features that make it stand out: 1. **Tooltip support in each step:** You can toggle tooltips on and off in each step by pressing `Ctrl + T` to get more information about the current step. This gives you the right amount of information at the right time, reducing time spent searching for what you need. 2. **Ability to go back to the previous step (for most steps):** Weave allows you to go back to the previous step in the setup process by pressing `Ctrl + Z`. This is particularly useful when you make a mistake in the setup process and need to correct it. Please note that this is not available for all steps. 3. **Simple service management:** Weave provides a simple command to start, stop, restart a service just like how you would do it with `systemctl` or `launchctl`. It also provides a `log` command to view the logs of the service. In essence, every infra-service you set up can be managed with the following commands: ```bash theme={null} weave start, stop, restart, log ``` Get started with Weave now by following this [installation guide](/developers/developer-guides/tools/clis/weave-cli/installation). # Introduction Source: https://docs.initia.xyz/developers/developer-guides/tools/clis/weave-cli/rollup/introduction Previously, for your rollup to be fully operational, you needed to follow a series of extensive steps (multiple binaries, multiple configuration files, etc.) described [here](/nodes-and-rollups/deploying-rollups). Weave CLI simplifies all these steps into a set of easy-to-follow commands, getting your rollup fully operational in no time. **For a complete rollup deployment from scratch, follow these steps in order**. If you only need to set up specific components, you can navigate directly to the relevant sections. 1. [Launch your rollup and run sequencer/operator node(s)](/developers/developer-guides/tools/clis/weave-cli/rollup/launch) 2. [Running IBC Relayer](/developers/developer-guides/tools/clis/weave-cli/rollup/relayer) (necessary for the built-in oracle and IBC support) 3. [Running OPinit Bots](/developers/developer-guides/tools/clis/weave-cli/rollup/opinit-bots) (executor and challenger) # Launching Your Rollup Source: https://docs.initia.xyz/developers/developer-guides/tools/clis/weave-cli/rollup/launch Weave simplifies [this lengthy complex rollup deployment process](/nodes-and-rollups/deploying-rollups) into a single command. Weave will send some funds from Gas Station to the OPinit Bot accounts during this process. Please make sure that your Gas Station account has enough funds to cover the total amount of funds to be sent (this amount will be shown to you before sending the funds). Haven't set up the Gas Station yet? Please [Check out this guide](/developers/developer-guides/tools/clis/weave-cli/gas-station) first. ```bash theme={null} weave rollup launch ``` Once the process completes, your rollup node will be running and ready to process queries and transactions. The command also provides an [InitiaScan](https://scan.testnet.initia.xyz/) magic link that automatically adds your local rollup to the explorer, allowing you to instantly view your rollup's transactions and state. This command only sets up the bot addresses but does not start the OPinit Bots (executor and challenger). To complete the setup, proceed to the [OPinit Bots setup](/developers/developer-guides/tools/clis/weave-cli/rollup/opinit-bots) section to configure and run the OPinit Bots. To launch from the config file without going through the interactive setup process, use the `--with-config` and `--vm` flags. ```bash theme={null} weave rollup launch --with-config --vm ``` **Available Flags** The directory to store the rollup node data and configuration files. Path to the rollup config file. Use this flag to launch from a config file without going through the interactive setup process. The VM to use for the rollup node. The available options are `move`, `wasm`, and `evm`. **This is required when `--with-config` flag is provided.** Force the launch of the rollup node even if the config file already exists. **This only works when `--with-config` flag is provided.** ## Running Your Rollup Node `bash weave rollup start ` Note that `launch` command already starts the rollup node for you. This command is only needed if you have stopped the node and want to start it again. **Available Flags** Whether to run the rollup node in the background. `bash weave rollup stop ` `bash weave rollup restart ` `bash weave rollup log ` **Available Flags** The number of lines to display from the end of the logs. ## Help To see all the available commands: ```bash theme={null} weave rollup --help ``` # Next Steps Source: https://docs.initia.xyz/developers/developer-guides/tools/clis/weave-cli/rollup/next-steps ## Building on Your Rollup Once your rollup node is launched and both the OPinit bots and IBC Relayer are configured, you can start integrating it with Initia tools. The resources below will help you get started: * **VM-specific tutorials**: Learn how to deploy contracts and interact with your rollup on each VM. * [EVM tutorials](/developers/developer-guides/vm-specific-tutorials/evm) * [MoveVM tutorials](/developers/developer-guides/vm-specific-tutorials/movevm) * [WasmVM tutorials](/developers/developer-guides/vm-specific-tutorials/wasmvm) * **[Oracle](/developers/developer-guides/tools/oracles/connect/fetching-prices-from-api/getting-single-asset-price)**: Integrate oracles to fetch off-chain token price data and use it in your rollup applications. * **[Indexer](/developers/developer-guides/tools/indexers/transactions-by-account)**: Use the Initia Indexer to query and retrieve data from your rollup. * **[SDKs](/developers/developer-guides/tools/sdks)**: Explore the Initia SDKs for building applications on your rollup. ## Going Live If you are launching a rollup for testing purposes, you can skip this section. When your rollup is ready for production and you want it to be publicly visible in the Initia ecosystem, contact the Initia team first via [Discord](https://discord.gg/initia) by raising a ticket. We will walk you through the registry and bridge integration steps described below. To make your rollup node visible to the Initia ecosystem, register it in the [Initia Registry](https://github.com/initia-labs/initia-registry) and the [Skip Go Registry](https://github.com/initia-labs/skip-go-registry). To list your rollup node on **InitiaScan** and the **Initia Wallet widget**, follow these steps: * **[Register Initia Registry](/nodes-and-rollups/deploying-rollups/initia-registry)** For bridge integration, register your rollup in Initia Registry first, then open a PR that adds your node information to **skip-go-registry** repository. * **[Skip Go Registry Repository](https://github.com/skip-mev/skip-go-registry)** # Running OPinit Bots Source: https://docs.initia.xyz/developers/developer-guides/tools/clis/weave-cli/rollup/opinit-bots Weave provides a streamlined way to configure and run [OPinit Bots](/home/core-concepts/interwoven-stack/opinit-framework/introduction) (executor and challenger) for your rollup. ## Setting Up ```bash theme={null} weave opinit init ``` This command will guide you through selecting the bot type (executor or challenger), configuring bot keys if needed, and setting up the bot's configuration. You can also specify the bot type directly: ```bash theme={null} weave opinit init executor ``` To set up Executor from the [config file](https://github.com/initia-labs/opinit-bots/blob/main/executor/README.md) without going through the interactive setup process, use the `--with-config` flag together with either `--generate-key-file` or `--key-file` flags. For example, to let Weave generate Executor's keys for you, use the following command: ```bash theme={null} weave opinit init executor --with-config --generate-key-file ``` To provide your own keys, use the following command: ```bash theme={null} weave opinit init executor --with-config --key-file ``` **Available Flags** The directory to store OPinit bots data and configuration files Path to the rollup directory that contains the rollup's artifacts. This is useful when you are setting up OPinit bots for a rollup that you have just launched, as it can use the artifacts from the rollup to set up the bots. Path to the rollup [config file](https://github.com/initia-labs/opinit-bots/blob/main/executor/README.md). Use this flag to set up Executor from a config file without going through the interactive setup process. Whether to generate Executor's keys during the setup process. Can only be used when `--with-config` flag is provided. Conflicts with `--key-file` flag. Path to the Executor's keys file. Can only be used when `--with-config` flag is provided. Conflicts with `--generate-key-file` flag. ```bash theme={null} weave opinit init challenger ``` To set up Challenger from the [config file](https://github.com/initia-labs/opinit-bots/blob/main/challenger/README.md) without going through the interactive setup process, use the `--with-config` flag together with either `--generate-key-file` or `--key-file` flags. For example, to let Weave generate Challenger's keys for you, use the following command: ```bash theme={null} weave opinit init challenger --with-config --generate-key-file ``` To provide your own OPinit bot keys, use the following command: ```bash theme={null} weave opinit init challenger --with-config --key-file ``` **Available Flags** The directory to store OPinit bots data and configuration files Path to the rollup directory that contains the rollup's artifacts. This is useful when you are setting up OPinit bots for a rollup that you have just launched, as it can use the artifacts from the rollup to set up the bots. Path to the rollup [config file](https://github.com/initia-labs/opinit-bots/blob/main/challenger/README.md). Use this flag to set up Challenger from a config file without going through the interactive setup process. Whether to generate Challenger's keys during the setup process. Can only be used when `--with-config` flag is provided. Conflicts with `--key-file` flag. Path to the Challenger's keys file. Can only be used when `--with-config` flag is provided. Conflicts with `--generate-key-file` flag. ## Managing Keys To modify bot keys, use the following command to either generate new keys or restore existing ones: ```bash theme={null} weave opinit setup-keys ``` **Available Flags** The directory to store OPinit bots data and configuration files Path to the rollup directory that contains the rollup's artifacts. This is useful when you are setting up OPinit bots for a rollup that you have just launched, as it can use the artifacts from the rollup to set up the bots. For the Executor bot to work, set up the Bridge Executor, Output Submitter, and Batch Submitter keys. For the Challenger bot to work, set up the Challenger key. For rollups with built-in oracle enabled, set up the Oracle Executor key. ## Resetting OPinit Bots Reset Executor's database. This will clear all the data stored in the Executor's database (the configuration files are not affected). ```bash theme={null} weave opinit reset executor ``` Reset Challenger's database. This will clear all the data stored in the Challenger's database (the configuration files are not affected). ```bash theme={null} weave opinit reset challenger ``` ## Running OPinit Bots `bash weave opinit start executor ` **Available Flags** Whether to run the Executor in the background. `bash weave opinit stop executor ` `bash weave opinit restart executor ` `bash weave opinit log executor ` **Available Flags** The number of lines to display from the end of the Executor's logs. `bash weave opinit start challenger ` **Available Flags** Whether to run the node in the background. `bash weave opinit stop challenger ` `bash weave opinit restart challenger ` `bash weave opinit log challenger ` **Available Flags** The number of lines to display from the end of the logs. ## Help To see all the available commands: ```bash theme={null} weave 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). Weave only supports IBC relayer setup between Initia L1 and Interwoven Rollups. Setting up relayers between other arbitrary networks is not supported. ## 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. 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. ## 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. Make sure you have Node.js and npm installed on your system if you wish to run the relayer in the same machine. 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 ``` Move the generated configuration file to the Rapid relayer directory: ```bash theme={null} cp ~/.relayer/config.json ./config.json ``` Launch the relayer with the configuration: ```bash theme={null} npm start ``` ## 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} The base currency of the asset to get the price for (e.g. `BTC`) The quote currency of the asset to get the price for (e.g. `USD`) 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. Fetch prices from Solidity and other EVM-based smart contracts Fetch prices from Move modules Fetch prices from CosmWasm contracts # 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() ``` The mnemonic key is the only way to recover your account if you forget your password. ## 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: keyByRawKey: ``` 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: 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 }) ``` Adjust gasPrices and gasAdjustment according to current [network](/resources/developer/initia-l1) conditions for optimal transaction processing. 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(object: Object): 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. First, create a directory to store your project files. ```bash theme={null} mkdir initia-js-quickstart && cd initia-js-quickstart ``` 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 ``` Install InitiaJS. ```bash theme={null} npm add @initia/initia.js ``` 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! # 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()`: delegate governance coin to validators (staking) ```typescript theme={null} const msg = new MsgDelegate( 'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // delegator address 'initvaloper14qekdkj2nmmwea4ufg9n002a3pud23y8l3ep5z', // validator's operator address '100000uinit', // delegate amount ) ``` ## VM-Specific Messages #### MoveVM * `MsgExecute()`: execute move contract entry functions ```typescript theme={null} const msg = new MsgExecute( 'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // sender address '0x1', // module owner address 'dex', // module name 'swap_script', // function name [], // type arguments [ bcs.address().serialize('0x2').toBase64(), // arguments, BCS-encoded bcs.address().serialize('0x3').toBase64(), // arguments, BCS-encoded bcs.u64().serialize(10000).toBase64(), // arguments, BCS-encoded ], ) ``` #### WasmVM * `MsgStoreCode()`: store wasm contract code ```typescript theme={null} const wasmByteCode = fs .readFileSync('./wasm-modules/miniwasm/example.wasm') // path of wasm file .toString('base64') const msg = new MsgStoreCode( 'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // sender address wasmByteCode, // raw or gzip compressed wasm bytecode undefined, // instantiate permission (optional) ) ``` * `MsgInstantiateContract()`: instantiate wasm contract ```typescript theme={null} const instantiateMsg = Buffer.from( JSON.stringify({ init_list: ['init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu'], }), ).toString('base64') const msg = new MsgInstantiateContract( 'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // sender address 'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // admin address 9, // code id 'example', // label instantiateMsg, // instantiate msg new Coins(), // init funds ) ``` * `MsgExecuteContract()`: execute wasm contract functions ```typescript theme={null} const jsonEncodedMsg = Buffer.from( JSON.stringify({ prepare_point: { stage: 1, }, }), ).toString('base64') const msg = new MsgExecuteContract( 'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // sender address 'init1jue5rlc9dkurt3etr57duutqu7prchqrk2mes2227m52kkrual3qdrydg6', // contract address jsonEncodedMsg, // json encoded input msg new Coins(), // coins transferred to the contract on execution ) ``` #### EVM * `MsgCreate()`: create EVM contract code ```typescript theme={null} const contractInfo = JSON.parse( fs .readFileSync( '../solidity/evm-example/artifacts/contracts/example.sol/example.json', // path of build response ) .toString(), ) const msg = new MsgCreate( 'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // sender address contractInfo.bytecode.slice(2), // hex encoded raw contract bytes code ) ``` * `MsgCall()`: execute EVM contract functions ```typescript theme={null} const contractAddress = '0x1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu' 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 msg = new MsgCall( 'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // sender address contractAddress, // contract address contract.interface.encodeFunctionData('preparePoint', [2]).slice(2), // hex encoded execution input bytes ) ``` # Sending Transactions Source: https://docs.initia.xyz/developers/developer-guides/tools/sdks/initia-js/transactions/sending-transactions Sending transactions using InitiaJS is straightforward. First, import the necessary classes and functions. ```ts theme={null} import { Wallet, RESTClient, MnemonicKey, MsgSend, Tx, WaitTxBroadcastResult, } from '@initia/initia.js' ``` Next, set up your environment variables. You will need the following: * `MNEMONIC`: The mnemonic of the account that will be sending the transaction. * `REST_URL`: The URL of the Initia REST. * `GAS_PRICES`: The gas prices for the transaction. * `SENDER_ADDRESS`: The address of the account that will be sending the transaction. * `RECIPIENT_ADDRESS`: The address of the account that will be receiving the transaction. * `AMOUNT`: The amount of tokens to send. ```ts theme={null} if (!process.env.MNEMONIC) { throw new Error('MNEMONIC environment variable is required') } const mnemonic = process.env.MNEMONIC const restUrl = process.env.REST_URL || 'https://rest.testnet.initia.xyz' const gasPrices = process.env.GAS_PRICES || '0.015uinit' // Will be INIT for mainnet const senderAddress = process.env.SENDER_ADDRESS || 'init1w4cqq6udjqtvl5xx0x6gjeyzgwtze8c05kysnu' const recipientAddress = process.env.RECIPIENT_ADDRESS || 'init1w4cqq6udjqtvl5xx0x6gjeyzgwtze8c05kysnu' const amount = process.env.AMOUNT || '1000uinit' ``` You can then use these variables to ultimately create the `wallet` client, as well as the `sendMsg` object. Since for this example you're making a token transfer, we'll use the `MsgSend` object. But the SDK provides many other message types for different actions related to staking, governance, and more. ```ts theme={null} const key: MnemonicKey = new MnemonicKey({ mnemonic }) // Create a key from the mnemonic const restClient: RESTClient = new RESTClient(restUrl, { gasPrices }) const wallet: Wallet = new Wallet(restClient, key) const sendMsg: MsgSend = new MsgSend(senderAddress, recipientAddress, amount) ``` Next, create the function to send the transaction. * First, create the transaction by calling `wallet.createAndSignTx`. This function takes in the raw message object, signs it using the `wallet`, and returns a signed transaction object. * Then, broadcast the transaction by calling `restClient.tx.broadcast`. This function takes in the signed transaction object and broadcasts it to the network. ```ts theme={null} async function sendTransaction(): Promise { try { const signedTx: Tx = await wallet.createAndSignTx({ msgs: [sendMsg], memo: 'memo', }) const result: WaitTxBroadcastResult = await restClient.tx.broadcast(signedTx) console.log('Transaction successful') console.log('Transaction hash:', result.txhash) return result } catch (error: unknown) { if (error instanceof Error) { console.error('Transaction failed:', error.message) } else { console.error('Transaction failed with an unknown error') } throw error } } ``` Finally, call the function to send the transaction. ```ts theme={null} sendTransaction() .then(() => process.exit(0)) .catch(() => process.exit(1)) ``` If you then run the script using `npx ts-node src/sending-transactions.ts`, you should see an output similar to the following: ``` Transaction successful Transaction hash: 4F0B810D15FA7D6A2B9EC2B98B263B0A20E791A8DABCB549620445941B25C699 ``` ### Full Example ```ts src/sending-transactions.ts theme={null} import { Wallet, RESTClient, MnemonicKey, MsgSend, Tx, WaitTxBroadcastResult, } from '@initia/initia.js' const mnemonic = process.env.MNEMONIC const restUrl = process.env.REST_URL || 'https://rest.testnet.initia.xyz' const gasPrices = process.env.GAS_PRICES || '0.015uinit' // Will be INIT for mainnet const senderAddress = process.env.SENDER_ADDRESS || 'init1w4cqq6udjqtvl5xx0x6gjeyzgwtze8c05kysnu' const recipientAddress = process.env.RECIPIENT_ADDRESS || 'init1w4cqq6udjqtvl5xx0x6gjeyzgwtze8c05kysnu' const amount = process.env.AMOUNT || '1000uinit' const key: MnemonicKey = new MnemonicKey({ mnemonic }) const restClient: RESTClient = new RESTClient(restUrl, { gasPrices }) const wallet: Wallet = new Wallet(restClient, key) const sendMsg: MsgSend = new MsgSend(senderAddress, recipientAddress, amount) async function sendTransaction(): Promise { try { const signedTx: Tx = await wallet.createAndSignTx({ msgs: [sendMsg], memo: 'memo', }) const result: WaitTxBroadcastResult = await restClient.tx.broadcast(signedTx) console.log('Transaction successful') console.log('Transaction hash:', result.txhash) return result } catch (error: unknown) { if (error instanceof Error) { console.error('Transaction failed:', error.message) } else { console.error('Transaction failed with an unknown error') } throw error } } sendTransaction() .then(() => process.exit(0)) .catch(() => process.exit(1)) ``` # Signing Transactions Source: https://docs.initia.xyz/developers/developer-guides/tools/sdks/initia-js/transactions/signing-transactions Sometimes, you may want to sign a transaction without broadcasting it. This is useful in situations where you want to sign a transaction and then broadcast it later. To showcase this, you will write a script that will sign a transaction, compute the transaction hash from the signed transaction, and compare the transaction hash to what you receive from broadcasting the transaction. First, import the necessary classes and functions. * `Coins`: A class that represents a list of [Cosmos SDK coins](https://github.com/cosmos/cosmos-sdk/blob/main/types/coin.go). * `Fee`: A class that's used to define the fee for a transaction. * `RESTClient`: A class that represents a REST client. * `MnemonicKey`: A class that's used to create a key from a mnemonic. * `MsgSend`: A class that represents a message to send. * `Wallet`: A class that represents a wallet. ```ts theme={null} import { Coins, Fee, RESTClient, MnemonicKey, MsgSend, Wallet, } from '@initia/initia.js' import crypto from 'crypto' ``` Next, set up your environment variables. You will need the following: * `mnemonic`: The mnemonic of the account that will be signing the transaction. * `chainId`: The chain ID of the network you are working on. * `restUrl`: The URL of the Initia REST. * `gasPrices`: The gas prices for the transaction. ```ts theme={null} const mnemonic = process.env.MNEMONIC const chainId = process.env.CHAIN_ID || 'initiation-2' const restUrl = process.env.REST_URL || 'https://rest.testnet.initia.xyz' const gasPrices = process.env.GAS_PRICES || '0.015uinit' // Will be INIT for mainnet ``` You will also need to create a helper function to convert the signed transaction data into a transaction hash hex string. ```ts theme={null} export function getTxHash(tx: Uint8Array): string { const s256Buffer = crypto .createHash(`sha256`) .update(Buffer.from(tx)) .digest() const txbytes = new Uint8Array(s256Buffer) return Buffer.from(txbytes.slice(0, 32)).toString(`hex`).toUpperCase() } ``` Finally, create the main function to sign the transaction and compare the transaction hash. Let's call this function `offlineSigningTest`. To start, create two `RESTClient` instances. One that is connected to the network, and one that is offline. You will use the offline REST client to sign the transaction, and the online REST client to broadcast the transaction to later compare. ```ts theme={null} const offlineRestClient = new RESTClient(``, { chainId: chainId, gasPrices: gasPrices, }) // rest client that is connected const onlineRestClient = new RESTClient(restUrl, { chainId: chainId, gasPrices: gasPrices, }) ``` Next, generate the wallet client, as well as define the message, gas limit, and fee for the transaction. You need to define the latter two because you will be signing the transaction completely offline without interacting with the network or any nodes. ```ts theme={null} // set up key const key = new MnemonicKey({ mnemonic: mnemonic, }) const account = await onlineRestClient.auth.accountInfo(key.accAddress) // you have to know account number and current sequence const wallet = new Wallet(offlineRestClient, key) // msg to send const msg = new MsgSend(key.accAddress, key.accAddress, '100uinit') // use fixed fee to not estimate gas const gasLimit = 500000 const feeAmount = new Coins(offlineRestClient.config.gasPrices) .toArray()[0] .mul(gasLimit) const fee = new Fee(gasLimit, new Coins([feeAmount])) ``` Once you have all of that, create the transaction by calling `wallet.createAndSignTx`. This function takes * `msgs`: The message to send. * `accountNumber`: The account number of the account that will be signing the transaction. * `sequence`: The sequence number of the account that will be signing the transaction. * `fee`: The fee for the transaction. and returns a signed transaction object. Then convert the signed transaction object to a byte array and compute the transaction hash using the helper function created earlier. ```ts theme={null} const signedTx = await wallet.createAndSignTx({ msgs: [msg], accountNumber: account.getAccountNumber(), sequence: account.getSequenceNumber(), fee, }) const signedTxBytes = signedTx.toBytes() const txHash = getTxHash(signedTxBytes) ``` Finally, if you want to broadcast the transaction to the network later, you can do so by using the `onlineRestClient` client. If you then retrieve the transaction hash from the online REST client and compare it to the transaction hash you computed earlier, you should see that they match. ```ts theme={null} const broadcastRes = await onlineRestClient.tx.broadcastSync(signedTx) // true console.log(txHash === broadcastRes.txhash) ``` ### Full Example ```ts src/signing-transaction.ts theme={null} import { Coins, Fee, RESTClient, MnemonicKey, MsgSend, Wallet, } from '@initia/initia.js' import crypto from 'crypto' const mnemonic = process.env.MNEMONIC const chainId = process.env.CHAIN_ID || 'initiation-2' const restUrl = process.env.REST_URL || 'https://rest.testnet.initia.xyz' const gasPrices = process.env.GAS_PRICES || '0.015uinit' // Will be INIT for mainnet export function getTxHash(tx: Uint8Array): string { const s256Buffer = crypto .createHash(`sha256`) .update(Buffer.from(tx)) .digest() const txbytes = new Uint8Array(s256Buffer) return Buffer.from(txbytes.slice(0, 32)).toString(`hex`).toUpperCase() } async function offlineSigningTest() { // rest client that is not connected const offlineRestClient = new RESTClient(``, { chainId: chainId, gasPrices: gasPrices, }) // rest client that is connected const onlineRestClient = new RESTClient(restUrl, { chainId: chainId, gasPrices: gasPrices, }) // set up key const key = new MnemonicKey({ mnemonic: mnemonic, }) const account = await onlineRestClient.auth.accountInfo(key.accAddress) // you have to know account number and current sequence const wallet = new Wallet(offlineRestClient, key) // msg to send const msg = new MsgSend(key.accAddress, key.accAddress, '100uinit') // use fixed fee to not estimate gas const gasLimit = 500000 const feeAmount = new Coins(offlineRestClient.config.gasPrices) .toArray()[0] .mul(gasLimit) const fee = new Fee(gasLimit, new Coins([feeAmount])) const signedTx = await wallet.createAndSignTx({ msgs: [msg], accountNumber: account.getAccountNumber(), sequence: account.getSequenceNumber(), fee, }) const signedTxBytes = signedTx.toBytes() const txHash = getTxHash(signedTxBytes) const broadcastRes = await onlineRestClient.tx.broadcastSync(signedTx) // true console.log(txHash === broadcastRes.txhash) } offlineSigningTest() ``` # Address Format Conversion Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/evm/address-conversion [Tutorial GitHub Repository](https://github.com/initia-labs/examples/tree/main/evm/address-conversion) This tutorial demonstrates how to convert between an EVM hex address and a Cosmos bech32 address. ## Prerequisites * [NodeJS](https://nodejs.org) ## Project Setup First, create a new directory for your project. ```sh theme={null} mkdir address-conversion cd address-conversion ``` Next, initialize the project and install the `bech32-converting` package. ```sh theme={null} npm init npm install bech32-converting ``` Then create a new file called `index.js` in the `src` directory where you will write your code. You can use any package that allows you to encode and decode bech32-prefixed addresses. However, the specific steps for using those packages may vary. ## Development For this tutorial, assume that you have an EVM address `0x0901aeeD1d5144987DaE3D95AB219ff75e9bA636` that you want to convert to a Cosmos address, and then convert it back to an EVM address. First, import the `bech32-converting` package and initialize the variable for the chain's Bech32 prefix. ```js src/index.js theme={null} const converter = require('bech32-converting') let bech32Address = 'init1pyq6amga29zfsldw8k26kgvl7a0fhf3kftflmr' ``` ### EVM Address to Cosmos Address To convert an EVM address to a Cosmos address, use the `bech32-converting` package's `toHex` function. ```js src/index.js theme={null} const hexAddress = converter('init').toHex(bech32Address) console.log(hexAddress) // 0x0901aeeD1d5144987DaE3D95AB219ff75e9bA636 ``` ### Cosmos Address to EVM Address To convert a Cosmos address to an EVM address, use the `bech32-converting` package's `fromHex` function. ```js src/index.js theme={null} bech32Address = converter('init').toBech32(hexAddress) console.log(bech32Address) // init1pyq6amga29zfsldw8k26kgvl7a0fhf3kftflmr ``` The full code for the script is then as follows: ```js src/index.js theme={null} const converter = require('bech32-converting') let bech32Address = 'init1pyq6amga29zfsldw8k26kgvl7a0fhf3kftflmr' const hexAddress = converter('init').toHex(bech32Address) console.log(hexAddress) // 0x0901aeeD1d5144987DaE3D95AB219ff75e9bA636 bech32Address = converter('init').toBech32(hexAddress) console.log(bech32Address) // init1pyq6amga29zfsldw8k26kgvl7a0fhf3kftflmr ``` If you run this script, you should see the following output: ```sh theme={null} 0x0901aeeD1d5144987DaE3D95AB219ff75e9bA636 init1pyq6amga29zfsldw8k26kgvl7a0fhf3kftflmr ``` # Using Connect Oracle Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/evm/connect-oracles Compiling contracts that use [ConnectOracle.sol](https://github.com/initia-labs/minievm/blob/main/x/evm/contracts/connect_oracle/ConnectOracle.sol) requires the [viaIR](https://soliditylang.org/blog/2024/07/12/a-closer-look-at-via-ir) feature. For Foundry/Forge, this can be done by using the `--via-ir` flag. The relevant methods for other tools may vary. ### Foundry For this tutorial, you will be using the [Foundry](https://github.com/foundry-rs/foundry) toolkit to develop, compile, and deploy your contracts. If you do not have Foundry installed, follow the [Foundry installation instructions](https://getfoundry.sh/). ## Setup Create a new project directory and initialize it with `forge init`: ```sh theme={null} mkdir connect-oracle cd connect-oracle forge init ``` ## Implementing the Contract Before writing the contract, first rename the template contract to `Oracle.sol`. ```sh theme={null} mv src/Counter.sol src/Oracle.sol ``` Then update the contract from the template to be your oracle contract. Declare the `IConnectOracle` interface, which will be used to interact with the ConnectOracle contract. ```solidity src/Oracle.sol theme={null} // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; interface IConnectOracle { struct Price { uint256 price; uint256 timestamp; uint64 height; uint64 nonce; uint64 decimal; uint64 id; } function get_price(string memory pair_id) external view returns (Price memory); function get_prices(string[] memory pair_ids) external view returns (Price[] memory); } contract Oracle { IConnectOracle public connect; ``` Next, define the constructor for the contract. This will be used to initialize the contract with the ConnectOracle contract address. The ConnectOracle contract is on MiniEVM precompiles. You can get its address by querying `${REST_URL}/minievm/evm/v1/connect_oracle` where `${REST_URL}` refers to the REST endpoint URL of the rollup. ```sh theme={null} curl https://rest-evm-1.anvil.asia-southeast.initia.xyz/minievm/evm/v1/connect_oracle ``` The output will look like this: ```json theme={null} { "address": "0x031ECb63480983FD216D17BB6e1d393f3816b72F" } ``` ```solidity src/Oracle.sol theme={null} constructor(address oracleAddress) { connect = IConnectOracle(oracleAddress); } ``` Once the constructor is implemented, move on to defining the different functions that the contract will have. * `oracle_get_price`: This function will return the price of a single asset pair * `oracle_get_prices`: This function will return the price of multiple asset pairs ```solidity src/Oracle.sol theme={null} function oracle_get_price() external view returns (uint256 price, uint256 timestamp) { IConnectOracle.Price memory p = connect.get_price("BTC/USD"); return (p.price, p.timestamp); } function oracle_get_prices() external view returns (uint256[] memory prices) { string[] memory pair_ids = new string[](2); pair_ids[0] = "BTC/USD"; pair_ids[1] = "ETH/USD"; IConnectOracle.Price[] memory result = connect.get_prices(pair_ids); prices = new uint256[](result.length); for (uint256 i = 0; i < result.length; i++) { prices[i] = result[i].price; } } ``` The complete contract will then look like this: ```solidity src/Oracle.sol theme={null} // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; interface IConnectOracle { struct Price { uint256 price; uint256 timestamp; uint64 height; uint64 nonce; uint64 decimal; uint64 id; } function get_price(string memory pair_id) external view returns (Price memory); function get_prices(string[] memory pair_ids) external view returns (Price[] memory); } contract Oracle { IConnectOracle public connect; constructor(address oracleAddress) { connect = IConnectOracle(oracleAddress); } function oracle_get_price() external view returns (uint256 price, uint256 timestamp) { IConnectOracle.Price memory p = connect.get_price("BTC/USD"); return (p.price, p.timestamp); } function oracle_get_prices() external view returns (uint256[] memory prices) { string[] memory pair_ids = new string[](2); pair_ids[0] = "BTC/USD"; pair_ids[1] = "ETH/USD"; IConnectOracle.Price[] memory result = connect.get_prices(pair_ids); prices = new uint256[](result.length); for (uint256 i = 0; i < result.length; i++) { prices[i] = result[i].price; } return prices; } } ``` Running `forge compile` will fail unless you provide a test file that matches the `Oracle.sol` contract. Foundry expects a test file like `Oracle.t.sol` to exist and import the contract under test. To resolve this, rename the existing test file `Counter.t.sol` to `Oracle.t.sol`. ```sh theme={null} mv test/Counter.t.sol test/Oracle.t.sol ``` Also replace the file contents with placeholder content. ```solidity test/Oracle.t.sol theme={null} // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.24; import {Test, console} from "forge-std/Test.sol"; contract OracleTest is Test { } ``` Now running `forge compile` should work without any errors. ```sh theme={null} forge compile # [Expected Output]: # [⠢] Compiling... # [⠰] Compiling 27 files with 0.8.21 # [⠃] Solc 0.8.21 finished in 6.25s # Compiler run successful! ``` ## Deploying the Contract Now that the contract is compiled and ready, you can deploy it to the MiniEVM. To accomplish this, use Foundry's `forge script` command. First, create a script file to handle the deployment. Create a new file named `Oracle.s.sol` in the `script` directory. ```solidity script/Oracle.s.sol theme={null} // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.24; import {Script, console} from "forge-std/Script.sol"; import {Oracle} from "../src/Oracle.sol"; contract OracleScript is Script { Oracle public oracle; function setUp() public {} function run() public { address oracleAddress = 0x031ECb63480983FD216D17BB6e1d393f3816b72F; vm.startBroadcast(); oracle = new Oracle(oracleAddress); vm.stopBroadcast(); } } ``` Set your environment variables and run the deployment. Be sure to replace `PRIVATE_KEY` with the deployer's private key, and `JSON_RPC_URL` with your rollup's JSON-RPC endpoint. ```sh theme={null} export PRIVATE_KEY=0x... export JSON_RPC_URL=https://jsonrpc-evm-1.anvil.asia-southeast.initia.xyz forge script script/Oracle.s.sol:OracleScript \ --rpc-url $JSON_RPC_URL \ --private-key $PRIVATE_KEY \ --broadcast \ --via-ir \ --with-gas-price 0 \ --skip-simulation ``` Output should look like this: ```sh theme={null} [⠊] Compiling... [⠊] Compiling 18 files with Solc 0.8.28 [⠒] Solc 0.8.28 finished in 918.49ms Compiler run successful! Script ran successfully. SKIPPING ON-CHAIN SIMULATION. ##### 4303131403034904 ✅ [Success] Hash: 0x8d9c488d7599fd867e45eee3b3a6ede24fec8f6459433051c341ef1937026bcf Contract Address: 0x505500221090Cd06400125B4f41A266B89Ffd62e Block: 10493369 Gas Used: 290728 ✅ Sequence #1 on 4303131403034904 | Total Paid: 0. ETH (290728 gas * avg 0 gwei) ``` To query the `oracle_get_price()` function, use Foundry’s cast call command. ```sh theme={null} cast call 0x505500221090Cd06400125B4f41A266B89Ffd62e "oracle_get_price()" --rpc-url $JSON_RPC_URL ``` Output should look like this: ```sh theme={null} 0x00000000000000000000000000000000000000000000000000000002c3cd0d430000000000000000000000000000000000000000000000001856610b4b695788 ``` The output is an ABI-encoded hexadecimal result containing the price and timestamp. The first 32 bytes represent the price, and the next 32 bytes represent the timestamp. | Field | ABI-Encoded Value | Decoded Value | | --------- | ------------------ | ------------------- | | Price | 0x2c3cd0d43 | 11874929987 | | Timestamp | 0x1856610b4b695788 | 1753695806045116296 | # Token Denom Conversion Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/evm/cosmos-coin-to-erc20 [Tutorial GitHub Repository](https://github.com/initia-labs/examples/tree/main/evm/cosmos-coin-to-erc20) This tutorial demonstrates how to convert between a hex-based ERC20 token address and a Cosmos coin denom. ## Prerequisites * [NodeJS](https://nodejs.org) ## Project Setup First, create a new directory for your project. ```sh theme={null} mkdir cosmos-coin-to-erc20 cd cosmos-coin-to-erc20 ``` Next, initialize the project and create an `index.js` file in a `src` directory. ```sh theme={null} npm init touch src/index.js ``` ## Development For this tutorial, assume that you have an ERC20 token address `0x5E5f1a92eECA58053E8364630b66763aa6265Ab0` that you want to convert to a Cosmos coin denom, and then convert it back to an ERC20 token address. First, initialize the variable for the chain's REST endpoint and the ERC20 token address. ```js src/index.js theme={null} const restUrl = `https://rest-evm-1.anvil.asia-southeast.initia.xyz` const erc20Address = '0x5E5f1a92eECA58053E8364630b66763aa6265Ab0' ``` ### ERC20 to Cosmos Denom To actually do the conversion, use the REST's `/minievm/evm/v1/denoms/{contractAddress}` endpoint. ```js src/index.js theme={null} // previous code async function erc20ToCoinDenom(contractAddress) { const response = await fetch( `${restUrl}/minievm/evm/v1/denoms/${contractAddress}`, ) const data = await response.json() return data } ``` If the address is a valid ERC20 token address, the response just returns the token's Cosmos coin denom. ```sh theme={null} evm/5E5f1a92eECA58053E8364630b66763aa6265Ab0 ``` ### Cosmos Denom to ERC20 Address To convert a Cosmos coin denom back to an ERC20 token address, use the REST's `/minievm/evm/v1/contracts/by_denom?denom={denom}` endpoint. ```js src/index.js theme={null} // previous code async function coinDenomToErc20(denom) { const response = await fetch( `${restUrl}/minievm/evm/v1/contracts/by_denom?denom=${denom}`, ) const data = await response.json() return data } ``` If the denom is a valid Cosmos coin denom, the response just returns the token's ERC20 token address. ```sh theme={null} 0x5E5f1a92eECA58053E8364630b66763aa6265Ab0 ``` The full code for the script, including the section to actually call the function is as follows: ```js src/index.js theme={null} const restUrl = `https://rest-evm-1.anvil.asia-southeast.initia.xyz` const erc20Address = '0x5E5f1a92eECA58053E8364630b66763aa6265Ab0' async function erc20ToCoinDenom(contractAddress) { const response = await fetch( `${restUrl}/minievm/evm/v1/denoms/${contractAddress}`, ) const data = await response.json() return data } async function coinDenomToErc20(denom) { const response = await fetch( `${restUrl}/minievm/evm/v1/contracts/by_denom?denom=${denom}`, ) const data = await response.json() return data } ;(async () => { const coinDenomResponse = await erc20ToCoinDenom(erc20Address) console.log(coinDenomResponse.denom) const erc20Response = await coinDenomToErc20(coinDenomResponse.denom) console.log(erc20Response.address) })() ``` If you run this script, you should see the following output: ```sh theme={null} evm/5E5f1a92eECA58053E8364630b66763aa6265Ab0 0x5E5f1a92eECA58053E8364630b66763aa6265Ab0 ``` # Creating Custom ERC20s Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/evm/creating-erc20s/creating-custom-erc20s [Tutorial GitHub Repository](https://github.com/initia-labs/examples/tree/main/evm/initia-custom-erc20) ## Prerequisites ### Foundry For this tutorial, you will be using the [Foundry](https://github.com/foundry-rs/foundry) toolkit to develop, compile, and deploy your contracts. If you do not have Foundry installed, follow the [Foundry installation instructions](https://getfoundry.sh/). ## Setup First, create a new directory for your project. ```sh theme={null} mkdir initia-erc20 cd initia-erc20 ``` Next, initialize a new Foundry project inside that directory. ```sh theme={null} forge init ``` Once the project is initialized, you can proceed to installing the required dependencies needed for this tutorial. In this case, you only need Initia's [EVM contracts](https://github.com/initia-labs/initia-evm-contracts). ```sh theme={null} forge install initia-labs/initia-evm-contracts ``` ## Implementing the Contract Before writing the contract, first rename the template contract to `NewInitiaERC20.sol`. ```sh theme={null} mv src/Counter.sol src/NewInitiaERC20.sol ``` Then update the contract from the template to be your custom ERC20 contract. Start by importing the `InitiaCustomERC20` contract from the `@initia/initia-evm-contracts` package. ```solidity src/NewInitiaERC20.sol theme={null} // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import "initia-evm-contracts/src/InitiaCustomERC20.sol"; ``` Next, extend the `InitiaCustomERC20` contract and add the constructor to initialize the contract with the name, symbol, and decimals of your custom ERC20. For this tutorial, you will simply customize the base contract by adding a logic to mint tokens to the contract deployer during deployment. ```solidity src/NewInitiaERC20.sol theme={null} // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import "initia-evm-contracts/src/InitiaCustomERC20.sol"; /** * @title NewInitiaERC20 * @dev Demo extension of InitiaERC20 token contract with initial minting functionality */ contract NewInitiaERC20 is InitiaERC20 { /** * @dev Constructor for creating a new InitiaERC20 token with initial minted supply * @param name_ The name of the token * @param symbol_ The symbol of the token * @param decimals_ The number of decimal places for token precision * @param mintedTokens_ The initial amount of tokens to mint to the contract deployer */ constructor(string memory name_, string memory symbol_, uint8 decimals_, uint256 mintedTokens_) InitiaERC20(name_, symbol_, decimals_) { _mint(msg.sender, mintedTokens_); } } ``` The contract implementation is now ready. However, if you try to compile the contract using `forge compile`, you will get an error. This is because the default `Counter.t.sol` and `Counter.s.sol` expect the original `Counter.sol` contract to be available. To fix this, rename `Counter.t.sol` to `NewInitiaERC20.t.sol` and `Counter.s.sol` to `NewInitiaERC20.s.sol`. ```sh theme={null} mv test/Counter.t.sol test/NewInitiaERC20.t.sol mv script/Counter.s.sol script/NewInitiaERC20.s.sol ``` Now replace the contents of the `NewInitiaERC20.t.sol` file with the following placeholder content. ```solidity test/NewInitiaERC20.t.sol theme={null} // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; import {Test, console} from "forge-std/Test.sol"; import {NewInitiaERC20} from "../src/NewInitiaERC20.sol"; contract NewInitiaERC20Test is Test { } ``` And replace the contents of the `NewInitiaERC20.s.sol` file with following placeholder content. ```solidity script/NewInitiaERC20.s.sol theme={null} // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; import {Script} from "forge-std/Script.sol"; import {NewInitiaERC20} from "../src/NewInitiaERC20.sol"; contract NewInitiaERC20Script is Script { NewInitiaERC20 public erc20; function setUp() public {} function run() public { vm.startBroadcast(); erc20 = new NewInitiaERC20("New Initia ERC20", "NIERC20", 18, 1000000 * 10 ** 18); vm.stopBroadcast(); } } ``` Now running `forge compile` should work without any errors. ```sh theme={null} forge compile ``` ### Expected Output: ```sh theme={null} [⠢] Compiling... [⠰] Compiling 27 files with 0.8.21 [⠃] Solc 0.8.21 finished in 6.25s Compiler run successful! ``` ## Deploying the Contract Now that the contract is compiled and ready, you can deploy it to the MiniEVM. To accomplish this, use Foundry's `forge create` command **Security Note:** In this tutorial, a private key is exported directly in the terminal for simplicity. This is fine for *testnet* or *throwaway* accounts. Do **not** use this method for accounts holding real funds. For production usage, place sensitive keys in a `.env` file (ignored by git) or use a secure key manager. ```sh theme={null} export PRIVATE_KEY=0x... export RPC_URL='https://jsonrpc-evm-1.anvil.asia-southeast.initia.xyz' forge create src/NewInitiaERC20.sol:NewInitiaERC20 \ --rpc-url $RPC_URL \ --private-key $PRIVATE_KEY \ --legacy \ --broadcast \ --constructor-args "MyToken" "MTK" 18 100 ``` ### Expected Output: ```sh theme={null} [⠊] Compiling... No files changed, compilation skipped Deployer: 0xc5D26D0281e28599c7790aacc810226BBDf0E431 Deployed to: 0x3cc54047D191eeeBDcde081D8708490F6df49Be8 Transaction hash: 0xed1d23b69014ee066be9b761df3c1fb28bedc46cc1c3f2188960550dbf7862a1 ``` To confirm that the contract was deployed successfully, you can try querying the balance of your deployer account using Foundry's `cast call` command. ```sh theme={null} cast call 0x3cc54047D191eeeBDcde081D8708490F6df49Be8 \ "balanceOf(address)(uint256)" 0xc5D26D0281e28599c7790aacc810226BBDf0E431 \ --rpc-url "https://jsonrpc-evm-1.anvil.asia-southeast.initia.xyz" ``` ### \[Expected Output]: ```sh theme={null} 100 ``` # Creating Standard ERC20s via ERC20Factory Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/evm/creating-erc20s/creating-standard-erc20s [Tutorial GitHub Repository](https://github.com/initia-labs/examples/tree/main/evm/erc20-factory) For developers looking to create standard ERC20 tokens on EVM rollups, the recommended approach is to use the [ERC20Factory](/resources/developer/contract-references/evm/erc20-factory) contract. ## Project Setup First, create a new project directory: ```sh theme={null} mkdir erc20-factory cd erc20-factory ``` Initialize the project and install the required dependencies: ```sh theme={null} npm init npm install viem npm install dotenv ``` Create two directories: * `src`: For your script files. * `abis`: For your contract [ABIs](https://www.alchemy.com/docs/smart-contract-abi). ```sh theme={null} mkdir src mkdir abis ``` Download the ERC20 and ERC20Factory ABIs into the `abis` directory: ```sh theme={null} curl -o abis/erc20Abi.json \ https://raw.githubusercontent.com/initia-labs/examples/main/evm/erc20-factory/abis/erc20Abi.json curl -o abis/erc20FactoryAbi.json \ https://raw.githubusercontent.com/initia-labs/examples/main/evm/erc20-factory/abis/erc20FactoryAbi.json ``` ## Setting Up Environment Variables Create a `.env` file in your project root: ```sh theme={null} touch .env ``` This file will store your private environment variables, such as your wallet's private key and the deployed ERC20Factory contract address. These values are required for signing transactions and interacting with the MiniEVM. The `ERC20Factory` contract is automatically deployed on all MiniEVM rollups as part of the chain’s bootstrapping process. To retrieve the deployed factory address, query `{ROLLUP_REST_URL}/minievm/evm/v1/contracts/erc20_factory`. `{ROLLUP_REST_URL}` refers to the REST endpoint of the rollup you are interacting with. Example: ```bash theme={null} curl -X GET "https://rest-evm-1.anvil.asia-southeast.initia.xyz/minievm/evm/v1/contracts/erc20_factory" -H "accept: application/json" ``` Example response: ```json theme={null} { "address": "0xf36924c9C2aD25d73c43F6aC59BB6D06BC944D93" } ``` Store this address in your `.env` file as `ERC20_FACTORY_ADDRESS`. Next, export an EVM-compatible private key from your Ethereum wallet. This private key will be used to sign and send transactions to the MiniEVM. Your `.env` file should look like this: ``` PRIVATE_KEY={{ETHEREUM_PRIVATE_KEY}} ERC20_FACTORY_ADDRESS={{FACTORY_CONTRACT_ADDRESS}} ``` Never share your `.env` file or private key. Anyone with this key can control your account. Keep it local and **add `.env` to your `.gitignore`** so it is never committed to Git. ## Development ### Creating the Chain Configuration File To interact with the MiniEVM using Viem, you need a chain configuration file. This file contains essential details about the chain, including the chain ID, name, native currency, and RPC URLs. Create a `chain.js` file in the `src` directory: ```sh theme={null} touch src/chain.js ``` Add the following configuration: ```js theme={null} const { defineChain } = require('viem') const miniEVM = defineChain({ id: 2594729740794688, name: 'MiniEVM', nativeCurrency: { decimals: 18, name: 'Gas Token', symbol: 'GAS', }, rpcUrls: { default: { http: ['https://jsonrpc-evm-1.anvil.asia-southeast.initia.xyz'], }, }, }) module.exports = miniEVM ``` ### Interacting with the ERC20Factory Contract Next, create a script to interact with the ERC20Factory contract: ```sh theme={null} touch src/index.js ``` Start with the imports: ```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') ``` Load the environment variables: You can also find factory addresses on the [Networks](/resources/developer/initia-l1) page or by calling the `/minievm/evm/v1/contracts/erc20_factory` endpoint on any MiniEVM rollup. ```js theme={null} 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.') } ``` To interact with the chain and contracts, create a wallet client and a public client: ```js theme={null} // 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(), }) ``` Now you can create a new ERC20 token using 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: '', }), ) 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. The deployed ERC20 token must inherit the `InitiaERC20` contract. ```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" 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/` * on an EVM-compatible chain. * - Example: "evm/9D9c32921575Fd98e67E27C0189ED4b750Cb17C5" */ 'evm/9D9c32921575Fd98e67E27C0189ED4b750Cb17C5', ), ), ] /** * 4) Create a MsgExecuteMessages message to execute the EVM parameter update. * - This message will include the MsgUpdateEvmParams message(s) we created above. * - The first argument is the wallet’s (validator’s) account address. * - The second argument is an array of messages to execute. */ const executeMsg = new MsgExecuteMessages( wallet.key.accAddress, // must be admin address msgs, ) /** * 5) Create and sign the transaction with the Wallet. * - This will create a transaction that includes the EVM param update message * and then sign it using the wallet’s (validator’s) private key. */ const signedTx = await wallet.createAndSignTx({ msgs: [executeMsg], }) /** * 6) Broadcast the transaction to the chain’s REST endpoint. * - This sends the signed transaction to be processed on-chain, * where it will update the EVM parameters if everything is valid. */ await client.tx.broadcast(signedTx) } /** * Finally, run the main() function. */ main() ``` # Building Move Module Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/movevm/building-move-modules This comprehensive guide walks you through the complete process of creating, compiling, deploying, and interacting with a Move module from scratch. You'll build a simple "Hello World" module that demonstrates core Move concepts and deployment workflows. Before starting, ensure you have set up your development environment, created an account, and funded it with testnet tokens. Follow the [Setting Up Your Development Environment](./setting-up) guide if you haven't completed these prerequisites. ## Overview In this tutorial, you'll learn to: * **Create** a new Move project and module structure * **Compile** Move source code into bytecode * **Deploy** your module to the blockchain * **Interact** with your deployed module through transactions and queries This guide supports both Initia L1 and Move rollup development. Code examples are provided for CLI tools and InitiaJS SDK to accommodate different development preferences. ## What You'll Build You'll create a simple message storage module with two functions: * `save_message`: Store a string message in the user's account * `view_message`: Retrieve the stored message from an account Configure your development environment with the necessary network parameters. ```bash theme={null} export RPC_URL=https://rpc.testnet.initia.xyz # Replace with your target network's RPC export CHAIN_ID=initiation-2 # Replace with your target network's chain ID export GAS_PRICES=0.015uinit # Replace with appropriate gas prices for your network ``` ### Network Parameters Reference | Variable | Description | | ------------ | ------------------------------------------------------------------------ | | `RPC_URL` | The RPC endpoint for blockchain interaction and transaction broadcasting | | `CHAIN_ID` | Unique identifier for the specific blockchain network you're targeting | | `GAS_PRICES` | Transaction fee rates in `{amount}{denomination}` format | Find network-specific values in our [Networks Documentation](/resources/developer/initia-l1/) for Initia L1, or the [Initia Registry](https://github.com/initia-labs/initia-registry/tree/main) for Move rollups. Start by creating a new directory and initializing it as a Move project. ### Create Project Directory ```bash theme={null} mkdir hello_world cd hello_world ``` ### Initialize Move Package Initialize your directory as a Move package, which creates the necessary project structure. ```bash Initia L1 theme={null} initiad move new hello_world ``` ```bash Move Rollups theme={null} minitiad move new hello_world ``` ### Understanding the Project Structure Your project now contains these essential components: ``` hello_world/ ├── Move.toml # Package manifest and configuration └── sources/ # Directory for Move source code files ``` The `Move.toml` file serves as your package's configuration center, containing: * **Package metadata**: name, version, and description * **Dependencies**: external packages your project requires * **Address mappings**: logical names mapped to blockchain addresses * **Build settings**: compilation options and flags The `sources` directory is where you'll write your Move smart contracts: * Contains all `.move` source files * Organizes your module implementations * Houses the core business logic of your application Create your first Move module with message storage functionality. ### Create the Module File Create a new file called `hello_world.move` in the `sources` directory: ```move hello_world.move theme={null} module hello::hello_world { use std::string::String; struct Message has key { content: String, } public entry fun save_message(account: &signer, message: String) { let message_struct = Message { content: message }; move_to(account, message_struct); } #[view] public fun view_message(account: address): String acquires Message { borrow_global(account).content } } ``` ### Understanding the Code ```move theme={null} module hello::hello_world { ``` Declares a module named `hello_world` under the `hello` address namespace. This establishes the module's identity on the blockchain. ```move theme={null} struct Message has key { content: String, } ``` Defines a `Message` resource with the `key` ability, allowing it to be stored in account storage. Resources are Move's way of representing owned data. ```move theme={null} public entry fun save_message(account: &signer, message: String) { ``` Entry functions can be called directly via transactions. The `&signer` parameter represents the transaction sender's authority. ```move theme={null} #[view] public fun view_message(account: address): String acquires Message { ``` View functions are read-only operations marked with `#[view]`. The `acquires` clause indicates this function accesses the `Message` resource. Set up your module's deployment address and compile the source code. ### Get Your Deployment Address First, retrieve your account's hexadecimal address for the Move.toml configuration: ```bash Initia L1 theme={null} initiad keys parse $(initiad keys show example --address) ``` ```bash Move Rollups theme={null} minitiad keys parse $(minitiad keys show example --address) ``` **Expected output:** ```bash theme={null} bytes: CC86AF3F776B95A7DED542035B3B666A9FDE2EE9 human: init ``` ### Configure Move.toml Update your `Move.toml` file with the deployment address and dependencies: ```toml Move.toml theme={null} [package] name = "hello_world" version = "0.0.0" [dependencies] InitiaStdlib = { git = "https://github.com/initia-labs/movevm.git", subdir = "precompile/modules/initia_stdlib", rev = "main" } [addresses] std = "0x1" hello = "0xCC86AF3F776B95A7DED542035B3B666A9FDE2EE9" # Replace with your address from above ``` **Address Configuration** Ensure you add the "0x" prefix to your address and replace the example address with your actual deployment address. This determines where your module will be deployed on the blockchain. ### Compile Your Module Build your Move module into deployable bytecode: ```bash Initia L1 theme={null} initiad move build ``` ```bash Move Rollups theme={null} minitiad move build ``` **Successful compilation output:** ```bash theme={null} Compiling, may take a little while to download git dependencies... UPDATING GIT DEPENDENCY https://github.com/initia-labs/movevm.git INCLUDING DEPENDENCY InitiaStdlib INCLUDING DEPENDENCY MoveNursery INCLUDING DEPENDENCY MoveStdlib BUILDING hello_world ``` ### Verify Build Output After compilation, you'll find a new `build/` directory containing: * Compiled bytecode modules * Dependency information * Build artifacts and metadata Deploy your compiled module to the blockchain network. ```bash Initia L1 theme={null} initiad move deploy \ --path . \ --upgrade-policy COMPATIBLE \ --from example \ --gas auto --gas-adjustment 1.5 \ --gas-prices $GAS_PRICES \ --node $RPC_URL \ --chain-id $CHAIN_ID ``` ```bash Move Rollups theme={null} minitiad move deploy \ --path . \ --upgrade-policy COMPATIBLE \ --from example \ --gas auto --gas-adjustment 1.5 \ --gas-prices $GAS_PRICES \ --node $RPC_URL \ --chain-id $CHAIN_ID ``` ```ts InitiaJS SDK theme={null} import { isTxError, MnemonicKey, MsgPublish, RESTClient, Wallet } from '@initia/initia.js' import fs from 'fs' import path from 'path' const REST_URL = 'https://rest.testnet.initia.xyz' const MNEMONIC = '' // Replace with your mnemonic const MODULE_NAME = 'hello_world' const MODULE_PATH = path.join(\_\_dirname, `./build/movevm/bytecode_modules/${MODULE_NAME}.mv`) function buildMsg(wallet: Wallet): MsgPublish { const packageBytes = fs.readFileSync(MODULE_PATH).toString('base64') return new MsgPublish(wallet.key.accAddress, [packageBytes], MsgPublish.Policy.COMPATIBLE) } async function main() { const wallet = new Wallet( new RESTClient(REST_URL, { gasPrices: '0.015uinit' }), new MnemonicKey({ mnemonic: MNEMONIC }) ) const msg = buildMsg(wallet) const signedTx = await wallet.createAndSignTx({ msgs: [msg] }) const result = await wallet.rest.tx.broadcast(signedTx) if (isTxError(result)) { console.error(`❌ Tx failed (code ${result.code})`, result.raw_log) } else { console.log(`✅ Success! Tx hash: ${result.txhash}`) console.log('Result:', result) } } main().catch(console.error) ``` ### Understanding Deployment Options The `--upgrade-policy` flag controls future module updates: * **`COMPATIBLE`**: Allows backward-compatible upgrades that don't break existing functionality * **`IMMUTABLE`**: Prevents any future modifications to the deployed module Select based on whether you anticipate needing to update your module after deployment. Gas settings control transaction costs: * `--gas auto`: Automatically estimates required gas * `--gas-adjustment 1.5`: Adds 50% buffer to gas estimate * `--gas-prices`: Sets the price per unit of gas These settings help ensure your transaction succeeds while managing costs. **Successful Deployment** Once deployed successfully, your module will be stored at the address specified in your `Move.toml` file and can be interacted with by any user on the network. Test your module by executing transactions and querying stored data. ### Execute Transactions Call your module's `save_message` function to store data on-chain: ```bash Initia L1 theme={null} export MODULE_ADDRESS=0xcc86af3f776b95a7ded542035b3b666a9fde2ee9 # Replace with your deployer address initiad tx move execute $MODULE_ADDRESS hello_world save_message \ --args '["string:Hello from Move!"]' \ --node $RPC_URL \ --from example \ --gas-prices $GAS_PRICES \ --chain-id $CHAIN_ID ``` ```bash Move Rollups theme={null} export MODULE_ADDRESS=0xcc86af3f776b95a7ded542035b3b666a9fde2ee9 # Replace with your deployer address minitiad tx move execute $MODULE_ADDRESS hello_world save_message \ --args '["string:Hello from Move!"]' \ --node $RPC_URL \ --from example \ --gas-prices $GAS_PRICES \ --chain-id $CHAIN_ID ``` ```ts InitiaJS SDK theme={null} import { bcs, isTxError, MnemonicKey, MsgExecute, RESTClient, Wallet, } from '@initia/initia.js' const REST_URL = 'https://rest.testnet.initia.xyz' const MNEMONIC = '' // Replace with your mnemonic const MODULE_ADDRESS = '0xcc86af3f776b95a7ded542035b3b666a9fde2ee9' // Replace with your deployer address const MODULE_NAME = 'hello_world' async function main() { const wallet = new Wallet( new RESTClient(REST_URL, { gasPrices: '0.015uinit' }), new MnemonicKey({ mnemonic: MNEMONIC }), ) const msg = new MsgExecute( wallet.key.accAddress, // tx sender MODULE_ADDRESS, // module address MODULE_NAME, // module name 'save_message', // function name [], // type args [ bcs.string().serialize('Hello from Move!').toBase64(), // function args ], ) const signedTx = await wallet.createAndSignTx({ msgs: [msg] }) const result = await wallet.rest.tx.broadcast(signedTx) if (isTxError(result)) { console.error(`❌ Tx failed (code ${result.code})`, result.raw_log) } else { console.log(`✅ Success! Tx hash: ${result.txhash}`) console.log('Result:', result) } } main().catch(console.error) ``` ### Query Stored Data Retrieve the message you just saved using the `view_message` function: ```bash Initia L1 theme={null} initiad query move view $MODULE_ADDRESS hello_world view_message \ --args '["address:0xcc86af3f776b95a7ded542035b3b666a9fde2ee9"]' \ --node $RPC_URL ``` ```bash Move Rollups theme={null} minitiad query move view $MODULE_ADDRESS hello_world view_message \ --args '["address:0xcc86af3f776b95a7ded542035b3b666a9fde2ee9"]' \ --node $RPC_URL ``` ```ts InitiaJS SDK theme={null} import { bcs, RESTClient } from '@initia/initia.js' const REST_URL = 'https://rest.testnet.initia.xyz' const MODULE_ADDRESS = '0xcc86af3f776b95a7ded542035b3b666a9fde2ee9' // Replace with your deployer address const MODULE_NAME = 'hello_world' async function main() { const restClient = new RESTClient(REST_URL, { gasPrices: '0.015uinit' }) const result = await restClient.move.view( MODULE_ADDRESS, MODULE_NAME, 'view_message', [], [ bcs.address().serialize('0xcc86af3f776b95a7ded542035b3b666a9fde2ee9').toBase64() ] ) console.log('Result:', result) } main().catch(console.error) ``` ### Expected Results If both operations succeed, your query should return: ```json theme={null} { "data": "\"Hello from Move!\"", "events": [], "gas_used": "1071" } ``` **Success!** You've successfully created, deployed, and interacted with your first Move module. The message is now permanently stored on the blockchain and can be retrieved by anyone. # Using Connect Oracle Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/movevm/connect-oracles To query prices from Connect oracle on MoveVM, you need to use the `oracle` module in InitiaStdLib found at `0x1::oracle` ([explorer link](https://scan.testnet.initia.xyz/initiation-2/modules/0x1/oracle)). This module provides a `get_price` function that you can use to fetch the price of an asset pair. The asset pair is specified using the `pair_id`, which is a string of the format `"ASSET1/ASSET2"`. For example, the example module below fetches the price of BTC/USD from Connect oracle. ```java theme={null} module example::examples { use std::string::String; use initia_std::oracle::get_price; #[view] public fun get_price_example(pair_id: String): (u256, u64, u64) { let (price, timestamp, decimals) = get_price(pair_id); (price, timestamp, decimals) } #[test] public fun test_get_price_example(): (u256, u64, u64) { let btc_usd_pair_id = string::utf8(b"BITCOIN/USD"); let (price, timestamp, decimals) = get_price_example(btc_usd_pair_id); (price, timestamp, decimals) } } ``` The response from the `get_price` function is then a tuple of `(price, timestamp, decimals)`, where: * `price` is the price of the asset pair multiplied by $10^{decimals}$ * `timestamp` is the timestamp of the last update * `decimals` is the number of decimals in the price # Creating Move Coin Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/movevm/creating-move-coin This tutorial guides you through the process of creating and minting your own coin using the `0x1::managed_coin` module on the Initia blockchain. It includes initializing your coin, obtaining metadata, minting coins, and checking the balances. # Step 1: Initialize Your Coin To initialize your coin, you must call the `0x1::managed_coin::initialize` function. ```move theme={null} public entry fun initialize( account: &signer, maximum_supply: Option, name: String, symbol: String, decimals: u8, icon_uri: String, project_uri: String, ) ``` ```bash CLI theme={null} initiad tx move execute 0x1 managed_coin initialize \ --args '["option:null", "string:my_coin", "string:MYCOIN", "u8:6", "string:ICON_URI", "string:PROJECT_URI"]' \ --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' async function createCoin() { 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', 'initialize', [], [ // max supply, if you want to set max supply, insert number instead of null bcs.option(bcs.u128()).serialize(null).toBase64(), bcs.string().serialize('my_coin').toBase64(), // name bcs.string().serialize('MYCOIN').toBase64(), // symbol // decimal point (raw value 1 consider to 10 ** (- decimalPoint)) bcs.u8().serialize(6).toBase64(), bcs.string().serialize('').toBase64(), // icon uri bcs.string().serialize('').toBase64(), // project uri ], ), ] // sign tx const signedTx = await wallet.createAndSignTx({ msgs }) // send(broadcast) tx restClient.tx.broadcastSync(signedTx).then((res) => console.log(res)) // { // height: 0, // txhash: '40E0D5633D37E207B2463D275F5B479FC67D545B666C37DC7B121ED551FA18FC', // raw_log: '[]' // } } createCoin() ``` # Step 2: Mint Coin To mint coins, you will use the `0x1::managed_coin::mint_to` function. ```move theme={null} public entry fun mint_to( account: &signer, dst_addr: address, metadata: Object, amount: u64, ) ``` Before minting, you need to obtain the metadata for your coin, which can be done through the `0x1::coin::metadata` view function or by using `sha3_256(creator+symbol+0xFE)`. ## Obtaining Metadata ```bash CLI theme={null} initiad query move view 0x1 coin metadata \ --args '["address:0x...", "string:MYCOIN"]' \ --node [rpc-url]:[rpc-port] # data: '"0x2d81ce0b6708fccc77a537d3d1abac8c9f1f674f4f76390e3e78a89a52d4aacb"' ``` ```ts InitiaJS theme={null} import { bcs, RESTClient, MnemonicKey } from '@initia/initia.js' import * as crypto from 'crypto' async function getCoinMetadata() { const restClient = new RESTClient('https://rest.testnet.initia.xyz', { gasPrices: '0.015uinit', gasAdjustment: '1.5', }) const key = new MnemonicKey({ mnemonic: 'beauty sniff protect ...', }) // Method 1: use view function restClient.move .viewFunction( '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') } ``` ## Minting Coins ```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') } ``` 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, 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
, 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
, module_name_list: vector, function_name_list: vector, type_args_list: vector>, args_list: vector>>, expiry_duration: Option ) ``` * `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 duration ].map((v) => v.toBase64()), ) ``` ## Vote Proposal Members of the multisig account can vote on active proposals. Each member can choose to approve or reject a proposal. The proposal passes once it receives the minimum number of approvals defined by the threshold. ```move theme={null} public entry fun vote_proposal( account: &signer, multisig_addr: address, proposal_id: u64, vote_yes: bool ) ``` ```ts InitiaJS theme={null} const msgVoteProposal1 = new MsgExecute( multisigMember1.key.accAddress, '0x1', 'multisig_v2', 'vote_proposal', [], [ bcs.address().serialize(multisigAddress), bcs.u64().serialize(1), bcs.bool().serialize(true), ].map((v) => v.toBase64()), ) ``` ## Execute Proposal After a proposal has received enough approvals, it can be executed. This action carries out the transactions or changes specified in the proposal. ```move theme={null} public entry fun execute_proposal( account: &signer, multisig_addr: address, proposal_id: u64 ) ``` * `multisig_addr`: The address of the multisig account where the proposal is created. * `proposal_id`: The ID of the approved proposal to execute. ```ts InitiaJS theme={null} const msgExecuteProposal = new MsgExecute( multisigCreator.key.accAddress, '0x1', 'multisig_v2', 'execute_proposal', [], [ bcs.address().serialize(AccAddress.toHex(multisigAddress)), bcs.u64().serialize(proposalId), ].map((v) => v.toBase64()), ) ``` ## Full Example Below are two summarized examples demonstrating how to create a multisig account, create a proposal, vote on it, and execute it using `InitiaJS`: * Token Transfer: Focuses on creating and executing a proposal that transfers tokens from the multisig account. * Move Module Upgrade: Showcases how to propose and publish (or upgrade) a Move module via a multisig proposal. ```ts InitiaJS theme={null} // This example demonstrates how to use InitiaJS to: // 1. Create a multisig account // 2. Create a proposal // 3. Vote on the proposal // 4. Execute the proposal // // Steps are annotated with comments for clarity. import { AccAddress, bcs, Coins, MnemonicKey, MsgExecute, MsgSend, RESTClient, Tx, WaitTxBroadcastResult, Wallet } from '@initia/initia.js' import { sha3_256 } from '@noble/hashes/sha3' // A helper function to deterministically derive a multisig address export function getMultisigAddress(creator: string, name: string) { // The address scheme used when generating from seed const OBJECT_FROM_SEED_ADDRESS_SCHEME = 0xfe // Serialize the creator address into bytes via BCS const addrBytes = Buffer.from(bcs.address().serialize(creator).toBytes()).toJSON().data // Build a seed from the 'multisig_v2' definition and the given name const seed = Buffer.from(`0x1::multisig_v2::MultisigWallet${name}`, 'ascii').toJSON().data // Concatenate the address bytes, the seed, and append the scheme byte const bytes = addrBytes.concat(seed) bytes.push(OBJECT_FROM_SEED_ADDRESS_SCHEME) // Hash the combined bytes using sha3_256, then convert to hex string const sum = sha3_256.create().update(Buffer.from(bytes)).digest() return Buffer.from(sum).toString('hex') } // Configure the REST client for Initia, including gas price/adjustment const restClient = new RESTClient('https://rest.testnet.initia.xyz', { gasPrices: '0.015uinit', gasAdjustment: '1.5' }) // Example mnemonic keys: 3 participants (multisigCreator, multisigMember1, multisigMember2) const keys = [ 'lawn gentle alpha display brave luxury aunt spot resource problem attend finish clown tilt outer security strike blush inspire gallery mesh law discover mad', // multisig creator 'leisure minimum grow fringe hamster divide leaf evidence bread lift maple rather matrix budget loop envelope warrior hill exotic raven access prevent pottery this', // multisig member 1 'game gown scorpion discover erase various crash nut ill leisure candy resemble tissue roast close dizzy dune speak rug exhaust body boss trip cherry' // multisig member 2 ] // Convert each mnemonic key to a Wallet instance const accounts = keys.map((mnemonic) => new Wallet(restClient, new MnemonicKey({ mnemonic }))) async function main() { let signedTx: Tx let res: WaitTxBroadcastResult // Destructure the accounts array for convenience const [multisigCreator, multisigMember1, multisigMember2] = accounts // // =========================== // Step 1: CREATE MULTISIG ACCOUNT // =========================== // const multisigName = 'multisig_name' // Create a MsgExecute to call 'create_non_weighted_multisig_account' const msgCreateNonWeightedMultisigAccount = new MsgExecute( multisigCreator.key.accAddress, '0x1', 'multisig_v2', 'create_non_weighted_multisig_account', [], [ // 1. Multisig name (used in deterministic address generation) bcs.string().serialize(multisigName), // 2. Vector of members (3 participants) bcs .vector(bcs.address()) .serialize([ multisigCreator.key.accAddress, multisigMember1.key.accAddress, multisigMember2.key.accAddress ]), // 3. Threshold (e.g., require 2 out of 3 approvals) bcs.u64().serialize(2) ].map((v) => v.toBase64()) ) // Sign and broadcast the TX signedTx = await multisigCreator.createAndSignTx({ msgs: [msgCreateNonWeightedMultisigAccount] }) res = await restClient.tx.broadcast(signedTx) console.log('Multisig account created. Tx hash:', res.txhash) // The actual multisig address can be obtained from 'CreateMultisigAccountEvent' // or from the helper function getMultisigAddress: const multisigAddress = getMultisigAddress( AccAddress.toHex(multisigCreator.key.accAddress), multisigName ) // // =========================== // Step 2: CREATE PROPOSAL // =========================== // // 1) First, fund the multisig so it has enough balance to execute future transactions const msgFundtoMultisig = new MsgSend( multisigCreator.key.accAddress, AccAddress.fromHex(multisigAddress), new Coins({ uinit: 5_000_000 }) ) signedTx = await multisigCreator.createAndSignTx({ msgs: [msgFundtoMultisig] }) res = await restClient.tx.broadcast(signedTx) console.log('Funded the multisig address. Tx hash:', res.txhash) // 2) Create proposals // Proposal 1: send tokens using `0x1::cosmos::stargate` function const recipient = 'init1nu7ujl76zac4pkdck8r2zve5zkjaus2xuz8thx' const msgMiultiSigProposal1 = new MsgSend( AccAddress.fromHex(multisigAddress), recipient, new Coins({ uinit: 1_000_000 }) ) // Proposal 2: send tokens using `0x1::coin::transfer` function // We need to serialize the arguments in BCS const msgMiultiSigProposal2Args = [ bcs.address().serialize(recipient), // recipient bcs.object().serialize('0x8e4733bdabcf7d4afc3d14f0dd46c9bf52fb0fce9e4b996c939e195b8bc891d9'), // coin metadata bcs.u64().serialize(1_000_000) // amount ] // Use create_proposal to bundle both proposals 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([[], []]), // no type args bcs.vector(bcs.vector(bcs.vector(bcs.u8()))).serialize([ [ [ // Arguments for the first proposal (stargate) ...bcs .vector(bcs.u8()) .serialize(Buffer.from(JSON.stringify(msgMiultiSigProposal1.toData()))) .toBytes() ] ], // Arguments for the second proposal (coin::transfer) msgMiultiSigProposal2Args.map((v) => v.toBytes()) ]), bcs.option(bcs.u64()).serialize(null) // optional expiry duration (null) ].map((v) => v.toBase64()) ) // Broadcast the proposal creation signedTx = await multisigCreator.createAndSignTx({ msgs: [msgCreateProposal] }) res = await restClient.tx.broadcast(signedTx) console.log('Proposal created. Tx hash:', res.txhash) // // =========================== // Step 3: VOTE ON PROPOSAL // =========================== // // Assume the proposal ID is 1 const proposalId = 1 const msgVoteProposal1 = new MsgExecute( multisigMember1.key.accAddress, '0x1', 'multisig_v2', 'vote_proposal', [], [ bcs.address().serialize(multisigAddress), bcs.u64().serialize(proposalId), bcs.bool().serialize(true) // yes vote ].map((v) => v.toBase64()) ) signedTx = await multisigMember1.createAndSignTx({ msgs: [msgVoteProposal1] }) res = await restClient.tx.broadcast(signedTx) console.log('Member 1 voted YES. Tx hash:', res.txhash) // Member 2 also votes YES const msgVoteProposal2 = new MsgExecute( multisigMember2.key.accAddress, '0x1', 'multisig_v2', 'vote_proposal', [], [ bcs.address().serialize(multisigAddress), bcs.u64().serialize(proposalId), bcs.bool().serialize(true) ].map((v) => v.toBase64()) ) signedTx = await multisigMember2.createAndSignTx({ msgs: [msgVoteProposal2] }) res = await restClient.tx.broadcast(signedTx) console.log('Member 2 voted YES. Tx hash:', res.txhash) // // =========================== // Step 4: EXECUTE PROPOSAL // =========================== // // Since we have 2 out of 3 votes, the threshold is met, so we can execute. const msgExecuteProposal = new MsgExecute( multisigCreator.key.accAddress, '0x1', 'multisig_v2', 'execute_proposal', [], [ bcs.address().serialize(multisigAddress), bcs.u64().serialize(proposalId) ].map((v) => v.toBase64()) ) signedTx = await multisigCreator.createAndSignTx({ msgs: [msgExecuteProposal] }) res = await restClient.tx.broadcast(signedTx) console.log('Proposal executed. Tx hash:', res.txhash) } main() ``` ```ts InitiaJS theme={null} // This example also uses InitiaJS to demonstrate: // 1. Creating a multisig account // 2. Creating a proposal (in this case, publishing or upgrading a Move module) // 3. Voting on the proposal // 4. Executing the proposal // // Comments are included to clarify each step. import { bcs, MnemonicKey, MsgExecute, RESTClient, Wallet, } from '@initia/initia.js'; import { SHA3 } from 'sha3'; import * as fs from 'fs'; // Configure the REST client const restClient = new RESTClient('https://rest.testnet.initia.xyz', { chainId: 'initiation-2', gasPrices: '0.015uinit', gasAdjustment: '2.0', }); // Three sample keys (3 participants) const keys = [ new MnemonicKey({ mnemonic: '0...', }), new MnemonicKey({ mnemonic: '1...', }), new MnemonicKey({ mnemonic: '2...', }), ]; // Convert each to a Wallet const wallets = keys.map(key => new Wallet(restClient, key)); // A readable name for the multisig const multisigName = 'multisig account'; // ------------------------------------------------------------------------------------ // getMultisigAccountAddress: A helper to derive the multisig address deterministically // ------------------------------------------------------------------------------------ function getMultisigAccountAddress(creator: string, name: string) { const seed = [ ...Buffer.from('0x1::multisig_v2::MultisigWallet'), ...Buffer.from(name), ]; // Combine the creator address (serialized) + seed + scheme(0xfe) and SHA3_256 hash them const address = bcs.address().fromBase64( sha3_256( Buffer.from([ ...bcs.address().serialize(creator).toBytes(), ...seed, 0xfe, // OBJECT_FROM_SEED_ADDRESS_SCHEME ]) ).toString('base64') ); return address; } // A simple wrapper for sha3_256 hashing export function sha3_256(value: Buffer): Buffer { return new SHA3(256).update(value).digest(); } // ------------------------------------------------------------------------------------ // createMultisigAccount: Example of creating a non-weighted multisig // ------------------------------------------------------------------------------------ async function createMultisigAccount() { const msgs = [ new MsgExecute( keys[0].accAddress, // The creator of the multisig '0x1', 'multisig_v2', 'create_non_weighted_multisig_account', // Alternatively: create_weighted_multisig_account [], [ // 1. The multisig name (used for deterministic address) bcs.string().serialize(multisigName).toBase64(), // 2. All members in this multisig bcs .vector(bcs.address()) .serialize(keys.map(key => key.accAddress)) .toBase64(), // 3. The threshold. e.g., 2 out of 3 bcs.u64().serialize(2).toBase64(), ] ), ]; // Sign and broadcast const signedTx = await wallets[0].createAndSignTx({ msgs }); const broadcastRes = await restClient.tx.broadcastSync(signedTx); console.log('[createMultisigAccount] broadcastRes:', broadcastRes); // You can obtain the multisig address from the transaction event. } // ------------------------------------------------------------------------------------ // createProposal: Example of creating a proposal to publish/upgrade a Move module // ------------------------------------------------------------------------------------ async function createProposal() { const multisigAddr = getMultisigAccountAddress( keys[0].accAddress, multisigName ); // Example: reading a compiled Move module file to be published const codeBytes = fs.readFileSync('./test.mv'); // Replace with your actual module file // Construct the MsgExecute for creating the proposal const msgs = [ new MsgExecute( keys[0].accAddress, '0x1', 'multisig_v2', 'create_proposal', [], [ bcs.address().serialize(multisigAddr).toBase64(), // multisig address bcs.vector(bcs.address()).serialize(['0x1']).toBase64(), // module addresses bcs.vector(bcs.string()).serialize(['code']).toBase64(), // module names bcs.vector(bcs.string()).serialize(['publish_v2']).toBase64(), // function names bcs.vector(bcs.vector(bcs.string())).serialize([[]]).toBase64(), // type args bcs .vector(bcs.vector(bcs.vector(bcs.u8()))) .serialize([ [ // 1) The code bytes bcs .vector(bcs.vector(bcs.u8())) .serialize([codeBytes]) // the actual compiled bytecode .toBytes(), // 2) The upgrade policy bcs.u8().serialize(1).toBytes(), ], ]) .toBase64(), bcs.option(bcs.u64()).serialize(null).toBase64(), // optional expiry ] ), ]; // Broadcast const signedTx = await wallets[0].createAndSignTx({ msgs }); const broadcastRes = await restClient.tx.broadcastSync(signedTx); console.log('[createProposal] broadcastRes:', broadcastRes); // Retrieve the proposal ID from the transaction event or by querying `get_proposals`. } // ------------------------------------------------------------------------------------ // vote_proposal: Another member votes on the proposal // ------------------------------------------------------------------------------------ async function vote_proposal() { const multisigAddr = getMultisigAccountAddress( keys[0].accAddress, multisigName ); // For example, we assume proposal ID = 1 const proposalId = 1; // We need 2 votes to pass. The creator might have auto-voted. So one more vote from another member. const msgs = [ new MsgExecute( keys[1].accAddress, // The second member '0x1', 'multisig_v2', 'vote_proposal', [], [ bcs.address().serialize(multisigAddr).toBase64(), bcs.u64().serialize(proposalId).toBase64(), bcs.bool().serialize(true).toBase64(), // vote YES ] ), ]; // Broadcast the vote const signedTx = await wallets[1].createAndSignTx({ msgs }); const broadcastRes = await restClient.tx.broadcastSync(signedTx); console.log('[vote_proposal] broadcastRes:', broadcastRes); } // ------------------------------------------------------------------------------------ // execute_proposal: Execute the proposal once the threshold is met // ------------------------------------------------------------------------------------ async function execute_proposal() { const multisigAddr = getMultisigAccountAddress( keys[0].accAddress, multisigName ); // We'll execute proposal ID = 1 const msgs = [ new MsgExecute( keys[0].accAddress, // The one executing '0x1', 'multisig_v2', 'execute_proposal', [], [ bcs.address().serialize(multisigAddr).toBase64(), // multisig address bcs.u64().serialize(1).toBase64(), // proposal ID ] ), ]; // Sign and broadcast const signedTx = await wallets[0].createAndSignTx({ msgs }); const broadcastRes = await restClient.tx.broadcastSync(signedTx); console.log('[execute_proposal] broadcastRes:', broadcastRes); } // Execute an example execute_proposal(); ``` # Setting Up Your Development Environment Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/movevm/setting-up This guide walks you through setting up your development environment for working with Move modules on Initia. You'll learn how to install the necessary tools, create accounts, and prepare for Move development on either Initia L1 or Move rollups. ## Prerequisites Before getting started, ensure you have: * A terminal or command prompt * Internet connection for downloading tools and accessing faucets * Basic familiarity with command-line interfaces This tutorial supports both Initia L1 and Move rollups development. The steps are similar, but we'll highlight the differences where they occur. ## Development Tools Overview You have two main options for interacting with Initia networks: CLIs provide direct access to network functionality through terminal commands. Select based on your target network: * **initiad**: For Initia L1 development * **minitiad**: For Move rollup development A TypeScript/JavaScript SDK that provides programmatic access to Initia networks. Ideal for: * Web application integration * Automated workflows * TypeScript/JavaScript developers Select and install the tools that match your development approach and target network. ### CLI Tools Command-line interface for Initia L1 development and interaction. Command-line interface for Move rollup development and interaction. ### SDK Option TypeScript/JavaScript SDK for programmatic blockchain interaction. You can install multiple tools if you plan to work across different networks or prefer having both CLI and SDK options available. After installing your chosen tools, create an account that you'll use for deploying and testing your Move modules. ```bash theme={null} initiad keys add example ``` ```bash theme={null} minitiad keys add example ``` Generate a new account with a fresh mnemonic: ```ts theme={null} import { MnemonicKey } from '@initia/initia.js' // Generate a new account with a random mnemonic const key = new MnemonicKey() console.log('mnemonic:', key.mnemonic) console.log('private key:', key.privateKey) console.log('public key:', key.publicKey) console.log('account address:', key.accAddress) ``` Or import an existing account from a mnemonic: ```ts theme={null} import { MnemonicKey } from '@initia/initia.js' // Import existing account from environment variable const key = new MnemonicKey({ mnemonic: process.env.MNEMONIC, }) console.log('account address:', key.accAddress) ``` ### Expected Output Your account creation will generate output similar to this: ```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] ``` **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: public key: Z { key: 'A2Bf8uK9RMehfDmBM3AwqZ4Y21r2H+hUMjS6++CSP' } account address: init1d7s3q7nmlzqz9v4tk6ntrvfmavu2vk656gr29j ``` **For importing existing account:** ```bash theme={null} account address: init17mq4sqemx2djc59tda76y20nwp4pfn4943x9ze ``` **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. 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: Get free testnet tokens for development and testing purposes. ### 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 Faucet tokens are only for testnet use and have no monetary value. They're designed specifically for development and testing purposes. ### Verify Your Balance After funding, verify your account has received tokens: initiad query bank balances \[your-address] minitiad query bank balances \[your-address] ## 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. Learn how to configure your CLI for different networks and environments. Understand the fundamentals of Move module structure and development. # 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, } #[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 { 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 { 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, } pub fn example_get_prices(deps: Deps) -> StdResult { 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. 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. ```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 { 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 { let mut messages: Vec = 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)) } main() ``` # Introduction Source: https://docs.initia.xyz/developers/introduction This section outlines the basics of developing on Initia and the various Interwoven Rollups. # AI Track Guidance Source: https://docs.initia.xyz/hackathon/ai-track-guidance Use this page if you are building for the AI track and want a practical model for how AI should fit into your Initia appchain architecture. You do not need to run model inference onchain. In most projects, inference will happen offchain, with the appchain handling the parts of the product that need blockchain guarantees. Generate or transform content, make recommendations, power copilots or agents, and run classification or summarization. Store ownership and state, handle rewards and payments, enforce access or reputation, and coordinate marketplaces or escrow. ## External AI Services You may use hosted model APIs in your project. If your project depends on a third-party AI provider, plan to supply your own API key or backend configuration for development and demos. For most hackathon teams, hosted APIs are the fastest and most common way to add AI features. **API key security:** If your project uses an external AI API, store secrets in a local `.env` file or another secure secret manager. Do not commit API keys to GitHub or expose them in your demo video, screenshots, or frontend code. If you need to add a model provider to your app, start with the official API docs for your chosen service: API docs API docs API docs For demos, it is acceptable to use mocked, cached, or pre-generated AI outputs if you clearly disclose that setup. Judges will evaluate the product, appchain integration, and overall user experience, not whether the model itself is hosted onchain. # Builder Guide Source: https://docs.initia.xyz/hackathon/builder-guide Use this page after [Set Up Your Appchain](/hackathon/get-started). Select a direction, prompt your AI agent, deploy, and verify real onchain behavior. Prerequisites: * **Tools ready**: `weave`, `initiad`, and `minitiad` are installed and in your PATH ([Step 6](/hackathon/get-started#step-6-ai-powered-initia-tool-setup-and-verification)). * **Infrastructure live**: your rollup and OPinit/Relayer bots are running ([Step 8](/hackathon/get-started#step-8-setup-interwoven-bots)). * **Gas Station keys imported**: your `gas-station` keys are available in the local keyrings ([Step 9](/hackathon/get-started#step-9-final-key-setup)). ## Recommended Flow 1. **Set Up Your Appchain**: Complete [Set Up Your Appchain](/hackathon/get-started) and launch your local environment. 2. **Select Your Path**: Decide whether to build your app from scratch or adapt a Blueprint. 3. **Build Your App with AI**: Implement your app and confirm it works onchain. 4. **Debug and Refine**: Fix frontend or onchain issues before packaging your project. 5. **Prepare Your Submission**: Complete [Submission Requirements](/hackathon/submission-requirements). ## Part 1: Select Your Path You can either build your app from scratch with your AI agent or start from a Blueprint that matches the native feature you want to implement. Start from a blank project and use the AI-assisted workflow below to build, deploy, and verify your app. Start from a Blueprint that already maps to a supported native feature, then adapt it into your own original project. **Blueprint Path:** If you select a Blueprint, you can jump directly into that tutorial. Come back to this page later for debugging help or official references if you need them. After you adapt the Blueprint into your own original app, use [Submission Requirements](/hackathon/submission-requirements) to confirm your final submission is complete. ### Select Your Blueprint To qualify for the hackathon prizes, your project must implement at least one supported Native Feature. These Blueprints provide implementation patterns you can adapt, or use as references while building your own concept. A high-frequency application where the blockchain handles logic silently in the background. Users approve a session once, then continue interacting without repeated wallet popups. * **Native Feature:** [`Auto-signing`](/interwovenkit/features/autosign/introduction) * **Best for:** Gaming, Microtransactions, High-frequency trading. An application that allows users to move assets between Initia L1 and an appchain without leaving the app. * **Native Feature:** [`Interwoven Bridging`](/interwovenkit/features/transfers/deposit-withdraw) * **Best for:** DeFi, Cross-chain payments, Multi-chain apps. An application that prioritizes human-readable identities, replacing complex hex addresses with personal usernames. * **Native Feature:** [`Initia Usernames`](/developers/developer-guides/integrating-initia-apps/usernames) * **Best for:** Social apps, Peer-to-peer payments, Community apps. **Originality matters:** Whether you build from scratch or adapt a Blueprint, judges will look for clear custom logic, UX, and product differentiation. ## Part 2: Build Your App with AI ### Funding Your Personal Wallet Before you can interact with your appchain via a browser wallet (like Keplr, Leap, or MetaMask), you need to fund your personal address from your Gas Station. 1. Copy your wallet address (`init1...`). 2. Ask your AI agent to fund your wallet: ```terminal title="Prompt: Fund your personal wallet" wrap theme={null} Using the `initia-appchain-dev` skill, please fund my personal wallet with 1 INIT on L1 and 100 of my appchain's native tokens on L2. ``` ### Development Workflow 1. **Describe the Goal**: Tell the AI what you want to achieve and why. **Gather Submission Metadata Early:** As you build, keep track of the deployed contract or module address and the final repo paths you plan to submit for your core logic and native feature frontend files. You will use them in the [Submission JSON](/hackathon/submission-requirements#submission-json). 2. **Build and Test**: Clearly describe your app's behavior and rules, then let the AI write the code and unit tests. ```terminal title="Prompt: Create and test the contract" wrap theme={null} Using the `initia-appchain-dev` skill, please create a new contract project in a directory named , implement the core logic for with the following requirements: Please also create and run unit tests that verify both success and failure paths. ``` 3. **Deploy to Your Appchain**: Instruct the AI to deploy your contract/module to your appchain. ```terminal title="Prompt: Deploy to your appchain" wrap theme={null} Using the `initia-appchain-dev` skill, please build and deploy my contract/module from the directory to my appchain using my Gas Station account. If this VM requires instantiate after deploy, run that too, then return the deployed address. ``` 4. **Verify Onchain Behavior**: Ask the AI to verify your live deployment with interactions and state queries. ```terminal title="Prompt: Smoke test live deployment" wrap theme={null} Using the `initia-appchain-dev` skill, I want to smoke test my live on my appchain. Please run 2-3 realistic user actions, then query state after each step and confirm the observed results match expected behavior. ``` 5. **Integrate the Frontend**: Ask the AI to build or update your frontend and connect it to your appchain. ```terminal title="Prompt: Build the frontend" wrap theme={null} Using the `initia-appchain-dev` skill, please create or update my frontend in to connect to my appchain with `InterwovenKit`, integrate my deployed , and implement the core user flow for . ``` **Run the Frontend Locally:** After the frontend is implemented, follow your AI agent's instructions to start the app locally and verify the core user flow in the browser. 6. **Add a Native Feature**: Ask the AI to implement one supported native feature and wire it into your app flow. **Supported Native Features:** To be eligible for prizes, your project should implement at least one supported native feature. Select one of the following: * `auto-signing` * `interwoven-bridge` * `initia-usernames` These features are covered in the Blueprint tutorials, but you can also add them to a project you build from scratch. ```terminal title="Prompt: Add a native feature" wrap theme={null} Using the `initia-appchain-dev` skill, please add support to my app. Please update the frontend and any required configuration so this native feature works in the core user flow. ``` ## Part 3: Debugging & Troubleshooting ### Debugging Workflow Whether you are building from scratch or adapting a Blueprint, errors are inevitable. 1. **Open the Browser Console**: Press `F12` or `Cmd+Option+J` to see the exact error logs. 2. **Provide Project Context**: Ensure your AI agent is open in your project root. This allows it to reference your `package.json`, your `interwovenkit` initialization, and your specific chain configuration. 3. **Evaluate and Fix the Error**: Ask your AI agent to fix the issue directly, and include the exact console error in your prompt. ```terminal title="Prompt: Fix the error in my codebase" wrap theme={null} Please find and fix this error directly in my codebase, then tell me what changed. [PASTE_CONSOLE_ERROR] ``` ## Part 4: Prepare Your Submission Use [Submission Requirements](/hackathon/submission-requirements) to complete your final submission files and confirm your project is eligible. ### Official References * **Official Docs**: Visit [docs.initia.xyz](https://docs.initia.xyz/) for architectural details and API references. * **Initia Examples**: Reference the [initia-labs/examples](https://github.com/initia-labs/examples) repository for working code across all VMs (EVM, Move, Wasm). * **Core Repositories**: Explore [initia-labs](https://github.com/initia-labs) on GitHub to see the underlying implementation of the SDKs and CLI tools. * **Initia L1**: [initia-labs/initia](https://github.com/initia-labs/initia) contains the core Layer 1 source code. * **Weave CLI**: [initia-labs/weave](https://github.com/initia-labs/weave) is the main CLI for launching and managing appchains. * **InterwovenKit**: [initia-labs/interwovenkit](https://github.com/initia-labs/interwovenkit) is the standard React SDK for Initia frontends. * **Initia.js**: [initia-labs/initia.js](https://github.com/initia-labs/initia.js) is the primary JavaScript library for blockchain interactions. #### Useful Endpoints * **Local Rollup Indexer:** `http://localhost:8080` * **L1 Indexer Swagger:** `https://indexer.initia.xyz/swagger/index.html` * **L1 Testnet RPC:** `https://rpc.testnet.initia.xyz` * **L1 Testnet REST:** `https://rest.testnet.initia.xyz` * **Faucet:** `https://faucet.testnet.initia.xyz` # MiniBank - EVM Source: https://docs.initia.xyz/hackathon/examples/evm-bank This tutorial will guide you through building a liquidity-ready digital piggy bank on your EVM appchain. Users can deposit tokens, withdraw them, and access the broader Initia ecosystem via native bridging. By the end of this tutorial, you will have: * Generated and verified a Solidity smart contract for the bank logic. * Deployed the contract to your live appchain. * Scaffolded and connected a React frontend. * Verified the on-chain functionality. ## Your Project Structure The following steps will instruct your AI agent to create these directories inside your `my-initia-project` folder: ```text wrap Project Structure theme={null} my-initia-project/ ├── minibank/ # Solidity smart contract project └── minibank-frontend/ # React frontend application ``` **Prerequisite:** Ensure you have an EVM-compatible appchain running locally. If you haven't launched one yet, complete the [Set Up Your Appchain](../get-started) first. ### Readiness Check Before you start, verify that your local infrastructure is healthy. ```terminal title="Prompt: Check local infrastructure health" wrap theme={null} Using the `initia-appchain-dev` skill, please verify that my appchain, executor bot, and relayer are running and that my Gas Station account has a balance. ``` ## Step 1: Create and Unit Test the Smart Contract Instruct your AI agent to create the Solidity contract using the `initia-appchain-dev` skill. Your AI agent will generate the contract and automatically run unit tests to ensure the logic is sound. ```terminal title="Prompt: Create and test the MiniBank contract" wrap theme={null} Using the `initia-appchain-dev` skill, please create a Solidity smart contract project for our MiniBank in a new directory named `minibank`. The contract should: - Allow users to deposit native tokens. - Allow users to withdraw their own deposited tokens. - Keep track of each user's total savings. - Include a function to view the caller's current balance. Please also create and run unit tests to verify these features. ``` Your AI agent will generate the `minibank` project and confirm that the tests (likely using Foundry or Hardhat) pass successfully. Initialize a Foundry project first: ```bash wrap Initialize Foundry Project theme={null} # Use --no-git to avoid nested repos if you're already in a git project. forge init minibank --no-git cd minibank ``` If you prefer to create the contract manually, here is the Solidity code your AI agent would generate. Save this as MiniBank.sol in your `minibank/src` directory. ```solidity wrap src/MiniBank.sol theme={null} // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; contract MiniBank { mapping(address => uint256) private balances; event Deposited(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); function deposit() public payable { require(msg.value > 0, "Cannot deposit 0"); balances[msg.sender] += msg.value; emit Deposited(msg.sender, msg.value); } function withdraw(uint256 amount) public { require(amount > 0, "Withdrawal amount must be greater than zero"); require(balances[msg.sender] >= amount, "Insufficient balance"); balances[msg.sender] -= amount; (bool success, ) = payable(msg.sender).call{value: amount}(""); require(success, "Transfer failed"); emit Withdrawn(msg.sender, amount); } function myBalance() public view returns (uint256) { // NOTE: This returns the balance for the CALLER (msg.sender). // In tests or frontend calls, ensure the correct account is the caller. return balances[msg.sender]; } function totalSavingsOf(address user) public view returns (uint256) { // Helper to check the balance of any user without needing a 'from' address. return balances[user]; } receive() external payable { deposit(); } } ``` ### Unit Testing with Foundry To verify your contract's logic, create a test file named `MiniBank.t.sol` in the `test` directory. ```solidity wrap test/MiniBank.t.sol theme={null} // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import "forge-std/Test.sol"; import "../src/MiniBank.sol"; contract MiniBankTest is Test { MiniBank public bank; address public user = address(0x123); function setUp() public { bank = new MiniBank(); vm.deal(user, 10 ether); } function testDeposit() public { vm.prank(user); bank.deposit{value: 1 ether}(); assertEq(bank.totalSavingsOf(user), 1 ether); } function testWithdraw() public { vm.startPrank(user); bank.deposit{value: 2 ether}(); bank.withdraw(1 ether); assertEq(bank.totalSavingsOf(user), 1 ether); vm.stopPrank(); } function testWithdrawInsufficientBalance() public { vm.prank(user); bank.deposit{value: 1 ether}(); vm.prank(user); vm.expectRevert("Insufficient balance"); bank.withdraw(2 ether); } } ``` Run your tests: ```bash wrap Run Foundry Tests theme={null} forge test ``` ## Step 2: Deploy to Your Appchain Now that the logic is verified, build and publish the contract to your live appchain using the Gas Station account. ```terminal title="Prompt: Deploy the MiniBank contract" wrap theme={null} Using the `initia-appchain-dev` skill, please build, publish, and instantiate the MiniBank Solidity contract located in the `minibank` directory to my appchain using my Gas Station account, then return the deployed contract address. ``` First, compile your contract and extract the hex bytecode: ```bash wrap Compile And Extract Bytecode theme={null} # Navigate to the contract directory cd minibank # Compile with Foundry forge build # Extract bytecode (requires jq) # Ensure NO '0x' prefix and NO trailing newlines jq -r '.bytecode.object' out/MiniBank.sol/MiniBank.json | tr -d '\n' | sed 's/^0x//' > minibank.bin ``` Then deploy the binary. **Find your Chain ID first** if you don't know it: ```bash wrap Get Chain ID theme={null} # Query the appchain ID directly curl -s http://localhost:26657/status | jq -r '.result.node_info.network' ``` Now deploy: ```bash wrap Deploy Contract theme={null} # Replace `` with the ID from the command above minitiad tx evm create minibank.bin \ --from gas-station \ --keyring-backend test \ --chain-id \ --node http://localhost:26657 \ --gas auto --gas-adjustment 1.4 --yes --output json > deploy.json ``` **Retrieve your contract address:** The output will provide a `txhash`. Wait a few seconds for indexing, then find your contract address: ```bash wrap Get Contract Address theme={null} # Replace with the hash from deploy.json minitiad q tx --node http://localhost:26657 --output json | jq -r '.events[] | select(.type=="contract_created") | .attributes[] | select(.key=="contract") | .value' ``` ## Step 3: Smoke Test the Deployed Contract On-Chain Before moving to frontend integration, smoke test the deployed contract directly on chain from the CLI. This isolates contract-level issues before UI work. ```terminal title="Prompt: Smoke test the MiniBank contract" wrap theme={null} Using the `initia-appchain-dev` skill, I want to smoke test our live MiniBank contract. Using my Gas Station account on my appchain, please: 1. Deposit 1 token. 2. Check my balance. 3. Withdraw 0.5 tokens. 4. Check my balance again. ``` Call `deposit()` and send exactly `1` token in base units (`1e18` wei). ```bash wrap Deposit 1 Token theme={null} DATA=$(cast calldata "deposit()") minitiad tx evm call $DATA \ --from gas-station \ --keyring-backend test \ --chain-id \ --node http://localhost:26657 \ --value 1000000000000000000 \ --gas auto --gas-adjustment 1.4 --yes ``` Query `myBalance()` as your sender account so `msg.sender` resolves correctly. ```bash wrap Query Balance theme={null} SENDER=$(minitiad keys show gas-station -a --keyring-backend test) DATA=$(cast calldata "myBalance()") RAW=$(minitiad q evm call $SENDER $DATA --node http://localhost:26657 --output json | jq -r '.response') echo "base_units: $(cast to-dec $RAW)" echo "tokens: $(cast --from-wei $(cast to-dec $RAW) ether)" ``` Call `withdraw(uint256)` with `0.5` token in base units (`5e17` wei). ```bash wrap Withdraw 0.5 Tokens theme={null} DATA=$(cast calldata "withdraw(uint256)" 500000000000000000) minitiad tx evm call $DATA \ --from gas-station \ --keyring-backend test \ --chain-id \ --node http://localhost:26657 \ --gas auto --gas-adjustment 1.4 --yes ``` Query `myBalance()` again to confirm the post-withdraw balance. ```bash wrap Query Balance Again theme={null} SENDER=$(minitiad keys show gas-station -a --keyring-backend test) DATA=$(cast calldata "myBalance()") RAW=$(minitiad q evm call $SENDER $DATA --node http://localhost:26657 --output json | jq -r '.response') echo "base_units: $(cast to-dec $RAW)" echo "tokens: $(cast --from-wei $(cast to-dec $RAW) ether)" ``` ## Step 4: Create a Frontend Let's create a simple UI to interact with our bank. **1. Scaffold the Frontend:** ```terminal title="Prompt: Scaffold the MiniBank frontend" wrap theme={null} Using the `initia-appchain-dev` skill, please scaffold a new Vite + React application named `minibank-frontend` in my current directory using the `scaffold-frontend` script. Create a component named Bank.jsx with Deposit and Withdraw buttons and an input field for the amount. ``` **2. Connect to Appchain:** ```terminal title="Prompt: Connect the frontend to the MiniBank contract" wrap theme={null} Using the `initia-appchain-dev` skill, modify the Bank.jsx component in the `minibank-frontend` directory to connect to our MiniBank contract on my appchain. Use the `@initia/interwovenkit-react` package for wallet connection and transaction signing. ``` If you prefer to set up the frontend manually, follow these steps: **1. Create the Project and Install Dependencies:** ```bash wrap Create React App theme={null} npm create vite@latest minibank-frontend -- --template react cd minibank-frontend npm install npm install @initia/interwovenkit-react wagmi viem @tanstack/react-query @initia/initia.js npm install --save-dev vite-plugin-node-polyfills npm install buffer util ``` **2. Verify `index.html`:** Vite scaffolding already creates `index.html`. Confirm it has this minimal structure in the root of your `minibank-frontend` directory: ```html wrap index.html theme={null} MiniBank Frontend
``` **3. Configure Vite Polyfills:** Update `vite.config.js` to include the Node polyfills: ```javascript wrap vite.config.js theme={null} import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { nodePolyfills } from 'vite-plugin-node-polyfills' export default defineConfig({ resolve: { dedupe: ['react', 'react-dom', 'wagmi', '@tanstack/react-query', 'viem'], }, optimizeDeps: { include: ['wagmi', '@tanstack/react-query', 'viem'], }, plugins: [ react(), nodePolyfills({ globals: { Buffer: true, process: true, }, }), ], }) ``` **4. Gather Runtime Values for Frontend Config:** Before creating `.env`, collect the values you will use: ```bash wrap Gather Frontend Values theme={null} APPCHAIN_ID=$(curl -s http://localhost:26657/status | jq -r '.result.node_info.network') NATIVE_DENOM=$(minitiad q evm params --output json | jq -r '.params.fee_denom') NATIVE_SYMBOL=$(minitiad q bank denoms-metadata --output json \ | jq -r --arg denom "$NATIVE_DENOM" ' .metadatas[] | select(.base==$denom or .display==$denom) | .symbol ' \ | head -n1) [ -z "$NATIVE_SYMBOL" ] && NATIVE_SYMBOL="$NATIVE_DENOM" # Use the contract address you retrieved in Step 2. MINIBANK_CONTRACT= echo "APPCHAIN_ID=$APPCHAIN_ID" echo "NATIVE_DENOM=$NATIVE_DENOM" echo "NATIVE_SYMBOL=$NATIVE_SYMBOL" echo "MINIBANK_CONTRACT=$MINIBANK_CONTRACT" ``` **5. Create `.env` from Runtime Values:** ```bash wrap Create Frontend Env theme={null} cat > .env < , ) ``` **7. Create the `App.jsx` Layout:** ```javascript wrap src/App.jsx theme={null} import React from 'react' import { useInterwovenKit } from '@initia/interwovenkit-react' import Bank from './Bank' function App() { const { initiaAddress, openConnect, openWallet } = useInterwovenKit() const containerStyle = { fontFamily: 'system-ui, -apple-system, sans-serif', minHeight: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', backgroundColor: '#f1f5f9', padding: '20px', } const cardStyle = { backgroundColor: '#ffffff', borderRadius: '16px', boxShadow: '0 10px 25px -5px rgba(0, 0, 0, 0.1)', padding: '40px', width: '100%', maxWidth: '500px', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', } const buttonStyle = { backgroundColor: '#3b82f6', color: 'white', border: 'none', padding: '12px 24px', borderRadius: '8px', fontSize: '16px', fontWeight: '600', cursor: 'pointer', width: '100%', } const secondaryButtonStyle = { backgroundColor: '#f1f5f9', border: '1px solid #e2e8f0', color: '#64748b', padding: '12px 24px', borderRadius: '10px', fontSize: '14px', fontWeight: '600', cursor: 'pointer', marginTop: '20px', width: '100%', } return (

MiniBank

{!initiaAddress ? ( <>

Connect your wallet to manage your savings.

) : ( <> )}
) } export default App ``` **8. Create the `Bank.jsx` Component:** Create `src/Bank.jsx` and add the contract interaction logic. **`msg.sender` in `view` Calls:** For `view` functions that depend on `msg.sender` (like `myBalance`), provide a `from` address in your `eth_call` params so the appchain resolves the correct user balance. This tutorial assumes 18 decimals, so `parseEther`/`formatEther` are used. ```javascript wrap src/Bank.jsx theme={null} import React, { useState, useEffect } from 'react' import { useInterwovenKit } from '@initia/interwovenkit-react' import { encodeFunctionData, parseEther, formatEther } from 'viem' import { AccAddress } from '@initia/initia.js' const MINI_BANK_ADDRESS = import.meta.env.VITE_MINIBANK_CONTRACT const CHAIN_ID = import.meta.env.VITE_APPCHAIN_ID const NATIVE_DENOM = import.meta.env.VITE_NATIVE_DENOM const NATIVE_SYMBOL = import.meta.env.VITE_NATIVE_SYMBOL const JSON_RPC_URL = import.meta.env.VITE_JSON_RPC_URL ?? 'http://localhost:8545' const MINI_BANK_ABI = [ { name: 'deposit', type: 'function', stateMutability: 'payable', inputs: [] }, { name: 'withdraw', type: 'function', inputs: [{ name: 'amount', type: 'uint256' }], }, { name: 'myBalance', type: 'function', stateMutability: 'view', inputs: [], outputs: [{ type: 'uint256' }], }, { name: 'totalSavingsOf', type: 'function', stateMutability: 'view', inputs: [{ name: 'user', type: 'address' }], outputs: [{ type: 'uint256' }], }, ] const Bank = () => { const [amount, setAmount] = useState('') const [balance, setBalance] = useState('0') const [isPending, setIsPending] = useState(false) const { initiaAddress, requestTxBlock } = useInterwovenKit() const fetchBalance = async () => { if (!initiaAddress) return try { const hex = AccAddress.toHex(initiaAddress) const userHex = hex.startsWith('0x') ? hex : `0x${hex}` const data = encodeFunctionData({ abi: MINI_BANK_ABI, functionName: 'myBalance', }) const response = await fetch(JSON_RPC_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_call', params: [{ from: userHex, to: MINI_BANK_ADDRESS, data }, 'latest'], id: 1, }), }) const result = await response.json() if (result.result && result.result !== '0x') { setBalance(formatEther(BigInt(result.result))) } } catch (error) { console.error('Error fetching balance:', error) } } useEffect(() => { fetchBalance() const interval = setInterval(fetchBalance, 10000) return () => clearInterval(interval) }, [initiaAddress]) const handleDeposit = async () => { if (!amount || !initiaAddress) return const data = encodeFunctionData({ abi: MINI_BANK_ABI, functionName: 'deposit', }) setIsPending(true) try { await requestTxBlock({ chainId: CHAIN_ID, messages: [ { typeUrl: '/minievm.evm.v1.MsgCall', value: { sender: initiaAddress.toLowerCase(), contractAddr: MINI_BANK_ADDRESS, input: data, value: parseEther(amount).toString(), accessList: [], authList: [], }, }, ], }) alert('Deposit successful!') setAmount('') fetchBalance() } catch (error) { console.error('Deposit error:', error) alert('Transaction failed or was cancelled.') } finally { setIsPending(false) } } const handleWithdraw = async () => { if (!amount || !initiaAddress) return const data = encodeFunctionData({ abi: MINI_BANK_ABI, functionName: 'withdraw', args: [parseEther(amount)], }) setIsPending(true) try { await requestTxBlock({ chainId: CHAIN_ID, messages: [ { typeUrl: '/minievm.evm.v1.MsgCall', value: { sender: initiaAddress.toLowerCase(), contractAddr: MINI_BANK_ADDRESS, input: data, value: '0', accessList: [], authList: [], }, }, ], }) alert('Withdrawal successful!') setAmount('') fetchBalance() } catch (error) { console.error('Withdraw error:', error) alert('Transaction failed or was cancelled.') } finally { setIsPending(false) } } const balanceContainerStyle = { backgroundColor: '#f1f5f9', padding: '30px', borderRadius: '16px', marginBottom: '30px', border: '1px solid #e2e8f0', } const balanceValueStyle = { fontSize: '42px', fontWeight: '800', color: '#2563eb', margin: '10px 0', fontFamily: 'monospace', } const inputStyle = { width: '100%', padding: '14px', marginBottom: '20px', borderRadius: '10px', border: '2px solid #e2e8f0', fontSize: '16px', boxSizing: 'border-box', } const buttonContainerStyle = { display: 'flex', gap: '15px' } const actionButtonStyle = { flex: 1, padding: '14px', borderRadius: '10px', border: 'none', fontWeight: '700', fontSize: '16px', cursor: 'pointer', color: 'white', } return (
Your Savings Balance
{balance} {NATIVE_SYMBOL}
setAmount(e.target.value)} placeholder="0.00" style={inputStyle} />
) } export default Bank ```
## Step 5: Wallet Funding and UI Verification Ask your AI agent to fund your browser wallet, then verify frontend behavior manually in the browser: 1. Start the frontend: ```bash wrap Start Vite Dev Server theme={null} cd minibank-frontend npm run dev ``` Check the **browser console** if you encounter issues. 2. Open your browser wallet and copy your address (`init1...`). 3. Give this prompt to your AI agent, replacing `` with the address you just copied: ```terminal wrap theme={null} Using the `initia-appchain-dev` skill, please fund my wallet address with 100 of my appchain's native tokens on L2. ``` 4. Connect your wallet in `minibank-frontend`. 5. Test the full flow by depositing and withdrawing from the UI, then confirm the displayed savings state updates correctly after each action. If you get stuck, see the [Debugging Workflow guide](../builder-guide#debugging-workflow). # 🪢 Native Feature: Interwoven Bridge Adding bridge support allows users to bring liquidity from the broader Initia ecosystem into your rollup. This transforms your appchain from an isolated sandbox into a connected part of the Interwoven Stack, providing users with a seamless UI to bridge tokens into your application for use. **Local Dev Limitation:** The Interwoven UI only resolves registered chain IDs, so your local appchain and token may not appear during local testing. You can still add bridge functionality now. In your hackathon submission, explain the user flow (for example: bridge INIT or other assets from L1 to your appchain, then deposit them in MiniBank) and why this matters (faster onboarding, easier liquidity access, and immediate utility in your app). ## Step 6: Update the Frontend The `useInterwovenKit()` hook provides `openBridge`, which opens the bridge modal for moving assets between chains. ```terminal title="Prompt: Add Interwoven Bridge support" wrap theme={null} Using the `initia-appchain-dev` skill, please enable Interwoven Bridge support in my MiniBank so I can move funds between chains on Initia. ``` To implement this, update your `src/Bank.jsx` to include the bridge logic and UI: ```tsx wrap Bridge Logic theme={null} // 1. Extract bridge functions from the hook const { initiaAddress, openConnect, openBridge } = useInterwovenKit() // 2. Add bridge handler const handleBridge = () => { if (!initiaAddress) { openConnect() return } openBridge({ srcChainId: 'initiation-2', // Public testnet ID srcDenom: 'uinit', // Native INIT }) } // 3. Add the Bridge UI section to your render (conditionally) const bridgeContainerStyle = { marginTop: '2rem', padding: '1.5rem', backgroundColor: '#fffbeb', borderRadius: '24px', border: '1px solid #fef3c7', textAlign: 'left', } const bridgeButtonStyle = { width: '100%', padding: '0.85rem', backgroundColor: '#d97706', color: 'white', border: 'none', borderRadius: '14px', fontSize: '13px', fontWeight: '800', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '0.5rem', } // Inside return (showing it only when connected)... { initiaAddress && (
Interwoven Ecosystem

Access the broader Initia network to move assets between chains.

) } ```
If you want a complete end-state after the manual steps above, use the consolidated reference below. This reference combines: * runtime config from `.env`, * InterwovenKit provider wiring in `main.jsx`, * wallet connect/display in `App.jsx`, and * live MiniBank interactions plus bridge entry point in `Bank.jsx`. **.env** ```bash wrap .env theme={null} VITE_APPCHAIN_ID= VITE_NATIVE_DENOM= VITE_NATIVE_SYMBOL= VITE_NATIVE_DECIMALS=18 VITE_JSON_RPC_URL=http://localhost:8545 VITE_MINIBANK_CONTRACT= VITE_BRIDGE_SRC_CHAIN_ID=initiation-2 VITE_BRIDGE_SRC_DENOM=uinit ``` **src/main.jsx** ```jsx wrap src/main.jsx theme={null} import { Buffer } from 'buffer' window.Buffer = Buffer window.process = { env: { NODE_ENV: 'development' } } import React from 'react' import ReactDOM from 'react-dom/client' import "@initia/interwovenkit-react/styles.css"; import { injectStyles, InterwovenKitProvider, TESTNET } from "@initia/interwovenkit-react"; import InterwovenKitStyles from "@initia/interwovenkit-react/styles.js"; import { WagmiProvider, createConfig, http } from "wagmi"; import { mainnet } from "wagmi/chains"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import App from './App.jsx' injectStyles(InterwovenKitStyles); const queryClient = new QueryClient(); const wagmiConfig = createConfig({ chains: [mainnet], transports: { [mainnet.id]: http() }, }); const customChain = { chain_id: import.meta.env.VITE_APPCHAIN_ID, chain_name: 'minibank', pretty_name: 'MiniBank Appchain', network_type: 'testnet', bech32_prefix: 'init', logo_URIs: { png: 'https://raw.githubusercontent.com/initia-labs/initia-registry/main/testnets/initia/images/initia.png', svg: 'https://raw.githubusercontent.com/initia-labs/initia-registry/main/testnets/initia/images/initia.svg', }, apis: { rpc: [{ address: 'http://localhost:26657' }], rest: [{ address: 'http://localhost:1317' }], indexer: [{ address: 'http://localhost:8080' }], 'json-rpc': [{ address: import.meta.env.VITE_JSON_RPC_URL ?? 'http://localhost:8545' }], }, fees: { fee_tokens: [{ denom: import.meta.env.VITE_NATIVE_DENOM, fixed_min_gas_price: 0, low_gas_price: 0, average_gas_price: 0, high_gas_price: 0, }], }, staking: { staking_tokens: [{ denom: import.meta.env.VITE_NATIVE_DENOM }] }, metadata: { is_l1: false, minitia: { type: 'minievm', }, }, native_assets: [ { denom: import.meta.env.VITE_NATIVE_DENOM, name: 'Native Token', symbol: import.meta.env.VITE_NATIVE_SYMBOL, decimals: Number(import.meta.env.VITE_NATIVE_DECIMALS ?? 18) } ] } ReactDOM.createRoot(document.getElementById('root')).render( , ) ``` **src/App.jsx** ```jsx wrap src/App.jsx theme={null} import React from 'react' import { useInterwovenKit } from "@initia/interwovenkit-react"; import Bank from './Bank.jsx'; function App() { const { initiaAddress, openConnect, openWallet } = useInterwovenKit(); const shortenAddress = (addr) => { if (!addr) return ""; return `${addr.slice(0, 8)}...${addr.slice(-4)}`; }; return (

MiniBank

{!initiaAddress ? ( ) : ( )}
) } export default App ``` **src/Bank.jsx** ```jsx wrap src/Bank.jsx theme={null} import React, { useEffect, useState } from 'react' import { useInterwovenKit } from '@initia/interwovenkit-react' import { AccAddress } from '@initia/initia.js' import { encodeFunctionData, formatUnits, parseUnits } from 'viem' const CHAIN_ID = import.meta.env.VITE_APPCHAIN_ID const NATIVE_DENOM = import.meta.env.VITE_NATIVE_DENOM const NATIVE_SYMBOL = import.meta.env.VITE_NATIVE_SYMBOL const NATIVE_DECIMALS = Number(import.meta.env.VITE_NATIVE_DECIMALS ?? 18) const JSON_RPC_URL = import.meta.env.VITE_JSON_RPC_URL ?? 'http://localhost:8545' const MINI_BANK_ADDRESS = import.meta.env.VITE_MINIBANK_CONTRACT const BRIDGE_SRC_CHAIN_ID = import.meta.env.VITE_BRIDGE_SRC_CHAIN_ID ?? 'initiation-2' const BRIDGE_SRC_DENOM = import.meta.env.VITE_BRIDGE_SRC_DENOM ?? 'uinit' const MINI_BANK_ABI = [ { name: 'deposit', type: 'function', stateMutability: 'payable', inputs: [] }, { name: 'withdraw', type: 'function', stateMutability: 'nonpayable', inputs: [{ name: 'amount', type: 'uint256' }], }, { name: 'myBalance', type: 'function', stateMutability: 'view', inputs: [], outputs: [{ type: 'uint256' }], }, ] export default function Bank() { const { initiaAddress, openConnect, openBridge, requestTxBlock } = useInterwovenKit() const [amount, setAmount] = useState('') const [balance, setBalance] = useState('0') const [isPending, setIsPending] = useState(false) const [status, setStatus] = useState('') const fetchBalance = async () => { if (!initiaAddress) { setBalance('0') return } const data = encodeFunctionData({ abi: MINI_BANK_ABI, functionName: 'myBalance' }) const from = AccAddress.toHex(initiaAddress).toLowerCase() const response = await fetch(JSON_RPC_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_call', params: [{ from, to: MINI_BANK_ADDRESS, data }, 'latest'], id: 1, }), }) const result = await response.json() if (result.error) throw new Error(result.error.message || 'eth_call failed') const baseUnits = BigInt(result.result || '0x0') setBalance(formatUnits(baseUnits, NATIVE_DECIMALS)) } useEffect(() => { fetchBalance().catch((err) => setStatus(String(err.message || err))) }, [initiaAddress]) const handleDeposit = async () => { if (!initiaAddress || !amount || Number(amount) <= 0) return setIsPending(true) setStatus('Submitting deposit...') try { const input = encodeFunctionData({ abi: MINI_BANK_ABI, functionName: 'deposit' }) const value = parseUnits(amount, NATIVE_DECIMALS).toString() const tx = await requestTxBlock({ chainId: CHAIN_ID, messages: [{ typeUrl: '/minievm.evm.v1.MsgCall', value: { sender: initiaAddress.toLowerCase(), contractAddr: MINI_BANK_ADDRESS, input, value, accessList: [], authList: [], }, }], }) setStatus(`Deposit confirmed: ${tx?.txhash ?? 'submitted'}`) setAmount('') await fetchBalance() } catch (err) { setStatus(`Deposit failed: ${String(err.message || err)}`) } finally { setIsPending(false) } } const handleWithdraw = async () => { if (!initiaAddress || !amount || Number(amount) <= 0) return setIsPending(true) setStatus('Submitting withdrawal...') try { const input = encodeFunctionData({ abi: MINI_BANK_ABI, functionName: 'withdraw', args: [parseUnits(amount, NATIVE_DECIMALS)], }) const tx = await requestTxBlock({ chainId: CHAIN_ID, messages: [{ typeUrl: '/minievm.evm.v1.MsgCall', value: { sender: initiaAddress.toLowerCase(), contractAddr: MINI_BANK_ADDRESS, input, value: '0', accessList: [], authList: [], }, }], }) setStatus(`Withdraw confirmed: ${tx?.txhash ?? 'submitted'}`) setAmount('') await fetchBalance() } catch (err) { setStatus(`Withdraw failed: ${String(err.message || err)}`) } finally { setIsPending(false) } } const handleBridge = async () => { if (!initiaAddress) { openConnect() return } await openBridge({ srcChainId: BRIDGE_SRC_CHAIN_ID, srcDenom: BRIDGE_SRC_DENOM, }) } return (

My Savings: {balance} {NATIVE_SYMBOL}

setAmount(e.target.value)} placeholder="Enter amount" />
{status ?

{status}

: null}
) } ``` This reference assumes: * the deployed contract address is stored in `.env` as `VITE_MINIBANK_CONTRACT`, * `sender` in `MsgCall` uses bech32 (`initiaAddress`) lowercased, * EVM balance reads use JSON-RPC `eth_call` with a `from` hex address, and * the Vite dev server is restarted after any `.env` change.
### Native Feature Verification 1. Connect your wallet in `minibank-frontend`. 2. Click `Bridge Funds`. 3. Confirm the Interwoven Bridge modal opens. ## Next Steps Now that you've mastered an EVM application, you're ready to build your own idea! Ensure your project meets all the [Submission Requirements](../submission-requirements) before submitting. # BlockForge Game - Move Source: https://docs.initia.xyz/hackathon/examples/move-game This tutorial will guide you through building a high-frequency on-chain game on your Move appchain. BlockForge is a crafting engine that demonstrates Invisible UX: allowing players to interact with the blockchain seamlessly without constant wallet popups. By the end of this tutorial, you will have instructed your AI agent to: * Generate and verify a Move smart contract for the game logic. * Deploy the contract to your live appchain. * Scaffold and connect a React frontend for players to interact with the game. * Verify the on-chain functionality. ## Your Project Structure The following steps will instruct your AI agent to create these directories inside your `my-initia-project` folder: ```text wrap Project Structure theme={null} my-initia-project/ ├── blockforge/ # Move smart contract project └── blockforge-frontend/ # React frontend application ``` **Prerequisite:** Ensure you have a Move-compatible appchain running locally. If you haven't launched one yet, complete the [Set Up Your Appchain](../get-started) first. ### Readiness Check Before you start, verify that your local infrastructure is healthy. ```terminal title="Prompt: Check local infrastructure health" wrap theme={null} Using the `initia-appchain-dev` skill, please verify that my appchain, executor bot, and relayer are running and that my Gas Station account has a balance. ``` ## Step 1: Create and Unit Test the Smart Contract Instead of writing the code yourself, instruct your AI agent to do it for you using the `initia-appchain-dev` skill. Your AI agent will generate the contract and automatically run unit tests to ensure the logic is sound. ```terminal title="Prompt: Create and test the BlockForge module" wrap theme={null} Using the `initia-appchain-dev` skill, please create a Move module project for our BlockForge game in a new directory named `blockforge`. Name the module `items` in the `blockforge` package. The game has the following rules: - Players can mint basic items called shards. - Players can craft relics by burning 2 shards. - Players should have an inventory to store their items. - I need a way to view a player's inventory. Please also create and run unit tests to verify these rules. ``` Your AI agent will generate the `blockforge` project, including the `items.move` module and a test script, and confirm that everything passes. If you prefer to create the Move module and project manually, follow these steps in your `blockforge` directory. This is what your AI agent would generate for you. First, create a new Move package named `blockforge`: ```bash wrap Create Move Package theme={null} mkdir -p blockforge cd blockforge minitiad move new blockforge ``` `minitiad move new blockforge` creates a package named `blockforge` in the current working directory. Creating and entering the `blockforge/` directory first keeps the generated package in the expected place. Now, update the `Move.toml` file to use the Initia stdlib dependency directly. Replace the content of `blockforge/Move.toml` with the following: ```toml wrap Move.toml theme={null} [package] name = "blockforge" version = "0.0.1" [dependencies] InitiaStdlib = { git = "https://github.com/initia-labs/movevm.git", subdir = "precompile/modules/initia_stdlib", rev = "main" } [addresses] blockforge = "_" # Supply via --named-addresses during build/test. Replace with the deployer hex before publishing if needed. std = "0x1" ``` Next, create `blockforge/sources/items.move` with the following content. ```move wrap sources/items.move theme={null} module blockforge::items { use std::error; use std::signer; const E_INSUFFICIENT_SHARDS: u64 = 1; const E_INVALID_INVENTORY_STATE: u64 = 2; struct Inventory has key { shards: u64, relics: u64, } struct InventoryView has copy, drop, store { shards: u64, relics: u64, } fun ensure_inventory(account: &signer) { let addr = signer::address_of(account); if (!exists(addr)) { move_to(account, Inventory { shards: 0, relics: 0 }); }; } public entry fun mint_shard(account: &signer) acquires Inventory { ensure_inventory(account); let inventory = borrow_global_mut(signer::address_of(account)); inventory.shards = inventory.shards + 1; } public entry fun craft_relic(account: &signer) acquires Inventory { ensure_inventory(account); let inventory = borrow_global_mut(signer::address_of(account)); assert!(inventory.shards >= 2, error::invalid_argument(E_INSUFFICIENT_SHARDS)); inventory.shards = inventory.shards - 2; inventory.relics = inventory.relics + 1; } #[view] public fun inventory_of(addr: address): InventoryView acquires Inventory { if (!exists(addr)) { return InventoryView { shards: 0, relics: 0 } }; let inventory = borrow_global(addr); InventoryView { shards: inventory.shards, relics: inventory.relics, } } #[view] public fun shard_count(addr: address): u64 acquires Inventory { inventory_of(addr).shards } #[view] public fun relic_count(addr: address): u64 acquires Inventory { inventory_of(addr).relics } } ``` Add the following unit tests inside the same `module blockforge::items { ... }` block, immediately before the final closing `}` of `items.move`, so you can verify minting, crafting, and the insufficient-shards failure path: ```move wrap Unit Tests theme={null} #[test(account = @blockforge)] fun test_mint_shard_creates_inventory(account: &signer) acquires Inventory { mint_shard(account); let inventory = inventory_of(signer::address_of(account)); assert!(inventory.shards == 1, E_INVALID_INVENTORY_STATE); assert!(inventory.relics == 0, E_INVALID_INVENTORY_STATE); } #[test(account = @blockforge)] fun test_craft_relic_burns_two_shards(account: &signer) acquires Inventory { mint_shard(account); mint_shard(account); craft_relic(account); let inventory = inventory_of(signer::address_of(account)); assert!(inventory.shards == 0, E_INVALID_INVENTORY_STATE); assert!(inventory.relics == 1, E_INVALID_INVENTORY_STATE); } #[test(account = @blockforge)] #[expected_failure(abort_code = 0x10001, location = blockforge::items)] fun test_craft_relic_requires_two_shards(account: &signer) acquires Inventory { mint_shard(account); craft_relic(account); } ``` Once the files are created, verify everything is correct by building and testing the project. Replace `` with your deployment address hex (`0x...`). ```bash wrap Build Move Package theme={null} minitiad move build --language-version=2.1 --named-addresses blockforge= minitiad move test --language-version=2.1 --named-addresses blockforge= ``` If the build succeeds and the tests pass, BlockForge is ready to deploy. ## Step 2: Deploy to Your Appchain Now that the logic is verified, build and publish the contract to your live appchain using the Gas Station account. ```terminal title="Prompt: Deploy the BlockForge module" wrap theme={null} Using the `initia-appchain-dev` skill, please build and publish the blockforge Move module located in the `blockforge` directory to my appchain using my Gas Station account, then return the deployed module address. ``` First, get your Gas Station address and convert it to hex: ```bash wrap Get Gas Station Hex Address theme={null} GAS_STATION_BECH32=$(minitiad keys show gas-station -a --keyring-backend test) minitiad keys parse "$GAS_STATION_BECH32" ``` Then, build and publish the compiled module to your appchain. Substitute `` with `0x` + the `bytes` value from the previous command. ```bash wrap Publish Move Module theme={null} cd blockforge # 1. Update Move.toml so [addresses].blockforge matches your deployer hex address. # 2. Build the module with the correct hex named address and version. minitiad move build --language-version=2.1 --named-addresses blockforge= # 3. Deploy the package. minitiad move deploy --build \ --language-version=2.1 \ --named-addresses blockforge= \ --from gas-station \ --keyring-backend test \ --chain-id \ --gas auto --gas-adjustment 1.4 --yes ``` Move modules do not have a separate instantiate transaction. For this tutorial, the first gameplay call (for example `mint_shard`) initializes per-player inventory state on demand. **Redeploy Compatibility Rules:** If you are redeploying from the same account, Initia enforces backward compatibility for the existing module. Preserve public function signatures and public struct abilities, or rename the module before republishing. If you see `BACKWARD_INCOMPATIBLE_MODULE_UPDATE`, this account already has a non-compatible prior version of the module. Use a fresh funded deployer account on the same chain, update `blockforge` named-address values to its hex, and deploy with `--from `. ## Step 3: Smoke Test the Deployed Contract On-Chain Before frontend work, smoke test the deployed module directly on chain. This keeps contract/module debugging separate from UI integration. ```terminal title="Prompt: Smoke test the BlockForge module" wrap theme={null} Using the `initia-appchain-dev` skill, I want to smoke test our live BlockForge game. Using my Gas Station account on my appchain, please: 1. Mint 3 shards. 2. Check my inventory. 3. Craft a relic. 4. Check my inventory again. ``` Here are the equivalent `minitiad` commands to interact with the module. ```bash wrap Mint 3 Shards theme={null} for i in {1..3}; do minitiad tx move execute items mint_shard \ --from gas-station \ --keyring-backend test \ --chain-id \ --gas auto --gas-adjustment 1.4 --yes \ --args '[]' --type-args '[]' sleep 2 done ``` ```bash wrap Query Inventory theme={null} minitiad query move resource ::items::Inventory ``` ```bash wrap Craft Relic theme={null} minitiad tx move execute items craft_relic \ --from gas-station \ --keyring-backend test \ --chain-id \ --gas auto --gas-adjustment 1.4 --yes \ --args '[]' --type-args '[]' ``` ```bash wrap Query Inventory Again theme={null} minitiad query move resource ::items::Inventory ``` ## Step 4: Create a Frontend A game needs a user interface. Let's create one using the `initia-appchain-dev` skill. **1. Scaffold the Frontend:** ```terminal title="Prompt: Scaffold the BlockForge frontend" wrap theme={null} Using the `initia-appchain-dev` skill, please scaffold a new Vite + React application named `blockforge-frontend` in my current directory using the `scaffold-frontend` script. Then, create a component named Game.jsx with Mint Shard and Craft Relic buttons and add it to the main App.jsx file. ``` **2. Connect to Appchain:** ```terminal title="Prompt: Connect the frontend to the BlockForge module" wrap theme={null} Using the `initia-appchain-dev` skill, modify the Game.jsx component in the `blockforge-frontend` directory to connect to our BlockForge module on my appchain. Use the `@initia/interwovenkit-react` package for wallet connection and transaction signing. The Mint Shard button should call the mint_shard function, and the Craft Relic button should call the craft_relic function. Also, please display the player's current inventory of shards and relics. ``` If you prefer to set up the frontend manually, follow these steps: **1. Create the Project and Install Dependencies:** Create a new Vite + React app and install the dependencies used by the working BlockForge frontend: ```bash wrap Create Frontend Project theme={null} npm create vite@latest blockforge-frontend -- --template react cd blockforge-frontend npm install npm install @initia/initia.js @initia/interwovenkit-react @tanstack/react-query wagmi buffer util npm install -D vite-plugin-node-polyfills ``` Then update `vite.config.js` so browser builds have the required Node polyfills: ```js wrap vite.config.js theme={null} import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { nodePolyfills } from 'vite-plugin-node-polyfills' export default defineConfig({ plugins: [ react(), nodePolyfills({ globals: { Buffer: true, process: true, }, }), ], }) ``` **2. Gather Runtime Values for Frontend Config:** Collect the values you will use for frontend configuration: ```bash wrap Gather Frontend Values theme={null} APPCHAIN_ID=$(curl -s http://localhost:26657/status | jq -r '.result.node_info.network') NATIVE_DENOM=$(minitiad q bank denoms-metadata --output json | jq -r '.metadatas[0].base // empty') [ -z "$NATIVE_DENOM" ] && NATIVE_DENOM=$(minitiad q bank total --output json | jq -r '.supply[0].denom') NATIVE_SYMBOL=$(minitiad q bank denoms-metadata --output json | jq -r '.metadatas[0].symbol // empty') [ -z "$NATIVE_SYMBOL" ] && NATIVE_SYMBOL="$NATIVE_DENOM" # By default this tutorial deploys from gas-station, so module owner = gas-station. # If you used the fresh account fallback in Step 2, query that deployer instead. BLOCKFORGE_MODULE_ADDRESS=$(minitiad keys show gas-station -a --keyring-backend test) echo "APPCHAIN_ID=$APPCHAIN_ID" echo "NATIVE_DENOM=$NATIVE_DENOM" echo "NATIVE_SYMBOL=$NATIVE_SYMBOL" echo "BLOCKFORGE_MODULE_ADDRESS=$BLOCKFORGE_MODULE_ADDRESS" ``` **3. Create `.env` from Runtime Values:** ```bash wrap Create Frontend Env theme={null} cat > .env < , ) ``` **5. Add the Game Component:** Then create `src/Game.jsx`: ```jsx wrap Game.jsx theme={null} import React, { useEffect, useState } from 'react' import { AccAddress, RESTClient } from '@initia/initia.js' import { MsgExecute } from '@initia/initia.proto/initia/move/v1/tx' import { useInterwovenKit } from '@initia/interwovenkit-react' const CHAIN_ID = import.meta.env.VITE_APPCHAIN_ID const REST_URL = import.meta.env.VITE_INITIA_REST_URL const MODULE_ADDRESS = import.meta.env.VITE_BLOCKFORGE_MODULE_ADDRESS const MODULE_ADDRESS_HEX = AccAddress.toHex(MODULE_ADDRESS) const INVENTORY_STRUCT_TAG = `${MODULE_ADDRESS_HEX}::items::Inventory` const rest = new RESTClient(REST_URL, { chainId: CHAIN_ID }) const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) const EMPTY_INVENTORY = { shards: 0, relics: 0 } export default function Game() { const { initiaAddress, openConnect, requestTxSync } = useInterwovenKit() const [inventory, setInventory] = useState(EMPTY_INVENTORY) const [loading, setLoading] = useState(false) const loadInventory = async (walletAddress) => { if (!walletAddress) { setInventory(EMPTY_INVENTORY) return } setLoading(true) try { const resource = await rest.move.resource(walletAddress, INVENTORY_STRUCT_TAG) setInventory({ shards: Number(resource.data?.shards ?? 0), relics: Number(resource.data?.relics ?? 0), }) } catch (error) { const message = String(error?.response?.data?.message || error?.message || '') if (message.includes('not found')) { setInventory(EMPTY_INVENTORY) } else { throw error } } finally { setLoading(false) } } useEffect(() => { loadInventory(initiaAddress) }, [initiaAddress]) const execute = async (functionName) => { if (!initiaAddress) { openConnect() return } await requestTxSync({ chainId: CHAIN_ID, messages: [ { typeUrl: '/initia.move.v1.MsgExecute', value: MsgExecute.fromPartial({ sender: initiaAddress, moduleAddress: MODULE_ADDRESS, moduleName: 'items', functionName, typeArgs: [], args: [], }), }, ], }) await sleep(2000) await loadInventory(initiaAddress) } return (

Shards: {loading ? '...' : inventory.shards}

Relics: {loading ? '...' : inventory.relics}

) } ``` Render `` from `src/App.jsx`. **Refresh Delay After Transactions:** local Move state queries can lag briefly after a successful `requestTxSync`. Wait about 2 seconds before reloading inventory so the new state is visible.
## Step 5: Wallet Funding and UI Verification Ask your AI agent to fund your browser wallet, then verify frontend behavior manually in the browser: 1. Start the frontend: ```bash wrap Start Vite Dev Server theme={null} cd blockforge-frontend npm run dev ``` Check the **browser console** if you encounter issues. 2. Open your browser wallet and copy your address (`init1...`). 3. Give this prompt to your AI agent, replacing `` with the address you just copied: ```terminal wrap theme={null} Using the `initia-appchain-dev` skill, please fund my wallet address with 1 INIT on L1 and 100 of my appchain's native tokens on L2. ``` 4. Connect your wallet in `blockforge-frontend`. 5. Test the gameplay flow by minting shards, crafting a relic, and confirming the displayed inventory state updates correctly after each action. If you get stuck, see the [Debugging Workflow guide](../builder-guide#debugging-workflow). # 🪢 Native Feature: Auto-signing To make your BlockForge game natively integrated with the Initia stack, you can enable Auto-signing to create a frictionless experience where players don't see wallet popups for every game action. Auto-signing works by deriving a unique, application-specific `Ghost Wallet` from a one-time signature. Your primary wallet then grants this `Ghost Wallet` permission (`Authz`) to execute specific functions and use its balance for fees (`Feegrant`), allowing for seamless, session-based gameplay. ## Step 6: Update the Frontend You can enable session-based signing by modifying your provider configuration and adding a toggle in your UI. ```terminal title="Prompt: Add auto-signing support" wrap theme={null} Using the `initia-appchain-dev` skill, please modify my InterwovenKit configuration in `main.jsx` to enable `enableAutoSign`. Then, update `Game.jsx` to include a button that toggles auto-signing on and off for the player using the `autoSign` methods from `useInterwovenKit`. ``` First, enable the feature in your provider: ```tsx wrap main.jsx theme={null} ``` Then, use the `useInterwovenKit` hook in your component to manage the session: ```tsx wrap Game.jsx theme={null} const { initiaAddress, autoSign, requestTxSync } = useInterwovenKit() const CHAIN_ID = '' // Check if auto-sign is active for this chain const isAutoSignEnabled = autoSign?.isEnabledByChain?.[CHAIN_ID] const toggleAutoSign = async () => { if (isAutoSignEnabled) { try { await autoSign?.disable(CHAIN_ID) } catch (error) { const message = String(error?.response?.data?.message || error?.message || '') if (message.includes('authorization not found')) { await autoSign?.enable(CHAIN_ID, { permissions: ["/initia.move.v1.MsgExecute"] }) await autoSign?.disable(CHAIN_ID) } else { throw error } } } else { // Permissions are required for the session key to sign specific message types await autoSign?.enable(CHAIN_ID, { permissions: ["/initia.move.v1.MsgExecute"] }) } } const handleAction = async () => { await requestTxSync({ chainId: CHAIN_ID, autoSign: isAutoSignEnabled, // Enables headless signing flow feeDenom: isAutoSignEnabled ? '' : undefined, // MANDATORY for invisible UX messages: [ { typeUrl: "/initia.move.v1.MsgExecute", value: { sender: initiaAddress, moduleAddress: "", moduleName: "items", functionName: "mint_shard", typeArgs: [], // MANDATORY: Even if empty args: [], // MANDATORY: Even if empty }, } ] }) } return (
) ``` **Session Expiration:** You can check the exact expiration of the current session using `autoSign.expiredAtByChain[chainId]`.
If you want the complete finished frontend after applying the manual steps above, use the consolidated reference below. If you want a single copyable end-state after completing the manual steps above, use this consolidated reference. It combines: * runtime config from `.env`, * InterwovenKit provider wiring in `main.jsx`, * wallet connect/display in `App.jsx`, and * live Move inventory, actions, and auto-sign toggle flow in `Game.jsx`. **.env** ```bash wrap .env theme={null} VITE_BLOCKFORGE_MODULE_ADDRESS= ``` **src/main.jsx** ```jsx wrap src/main.jsx theme={null} import { Buffer } from 'buffer' window.Buffer = Buffer window.process = { env: { NODE_ENV: 'development' } } import React from 'react' import ReactDOM from 'react-dom/client' import "@initia/interwovenkit-react/styles.css"; import { injectStyles, InterwovenKitProvider, TESTNET } from "@initia/interwovenkit-react"; import InterwovenKitStyles from "@initia/interwovenkit-react/styles.js"; import { WagmiProvider, createConfig, http } from "wagmi"; import { mainnet } from "wagmi/chains"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import App from './App.jsx' import './index.css' injectStyles(InterwovenKitStyles); const queryClient = new QueryClient(); const wagmiConfig = createConfig({ chains: [mainnet], transports: { [mainnet.id]: http() }, }); const customChain = { chain_id: '', chain_name: 'blockforge', pretty_name: 'BlockForge', network_type: 'testnet', bech32_prefix: 'init', logo_URIs: { png: 'https://raw.githubusercontent.com/initia-labs/initia-registry/main/testnets/initia/images/initia.png', svg: 'https://raw.githubusercontent.com/initia-labs/initia-registry/main/testnets/initia/images/initia.svg', }, apis: { rpc: [{ address: 'http://localhost:26657' }], rest: [{ address: 'http://localhost:1317' }], indexer: [{ address: 'http://localhost:8080' }], 'json-rpc': [{ address: 'http://localhost:8545' }], }, fees: { fee_tokens: [{ denom: '', fixed_min_gas_price: 0, low_gas_price: 0, average_gas_price: 0, high_gas_price: 0 }], }, staking: { staking_tokens: [{ denom: '' }] }, metadata: { is_l1: false, minitia: { type: 'minimove', }, }, native_assets: [ { denom: '', name: 'Native Token', symbol: '', decimals: Number(import.meta.env.VITE_NATIVE_DECIMALS ?? 6) } ] } ReactDOM.createRoot(document.getElementById('root')).render( , ) ``` **src/App.jsx** ```jsx wrap src/App.jsx theme={null} import React from 'react' import { useInterwovenKit } from "@initia/interwovenkit-react"; import Game from './Game.jsx'; function App() { const { initiaAddress, openConnect, openWallet } = useInterwovenKit(); const shortenAddress = (addr) => { if (!addr) return ""; return `${addr.slice(0, 8)}...${addr.slice(-4)}`; }; return (

BlockForge

{!initiaAddress ? ( ) : ( )}

Local Rollup

Items Workshop

Connect a wallet to mint shards and craft relics against the deployed items module.

) } export default App ``` **src/Game.jsx** ```jsx wrap src/Game.jsx theme={null} import React, { useEffect, useState } from 'react' import { AccAddress, RESTClient } from '@initia/initia.js' import { MsgExecute } from '@initia/initia.proto/initia/move/v1/tx' import { useInterwovenKit } from '@initia/interwovenkit-react' const CHAIN_ID = '' const REST_URL = 'http://localhost:1317' const MODULE_ADDRESS = import.meta.env.VITE_BLOCKFORGE_MODULE_ADDRESS const MODULE_ADDRESS_HEX = AccAddress.toHex(MODULE_ADDRESS) const INVENTORY_STRUCT_TAG = `${MODULE_ADDRESS_HEX}::items::Inventory` const rest = new RESTClient(REST_URL, { chainId: CHAIN_ID }) const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) const EMPTY_INVENTORY = { shards: 0, relics: 0 } function Game() { const { initiaAddress, openConnect, requestTxSync, autoSign } = useInterwovenKit() const [inventory, setInventory] = useState(EMPTY_INVENTORY) const [isLoadingInventory, setIsLoadingInventory] = useState(false) const [pendingAction, setPendingAction] = useState('') const [isTogglingAutoSign, setIsTogglingAutoSign] = useState(false) const [error, setError] = useState('') const [txHash, setTxHash] = useState('') const isConnected = Boolean(initiaAddress) const isAutoSignEnabled = Boolean(autoSign?.isEnabledByChain?.[CHAIN_ID]) const loadInventory = async (address) => { if (!address) { setInventory(EMPTY_INVENTORY) return } setIsLoadingInventory(true) try { const resource = await rest.move.resource(address, INVENTORY_STRUCT_TAG) setInventory({ shards: Number(resource.data?.shards ?? 0), relics: Number(resource.data?.relics ?? 0), }) setError('') } catch (fetchError) { const message = String(fetchError?.response?.data?.message || fetchError?.message || '') const notFound = fetchError?.response?.status === 500 && message.includes('not found') if (notFound) { setInventory(EMPTY_INVENTORY) setError('') } else { setError(message || 'Failed to load inventory.') } } finally { setIsLoadingInventory(false) } } useEffect(() => { if (!initiaAddress) { setInventory(EMPTY_INVENTORY) setError('') setTxHash('') return } loadInventory(initiaAddress) }, [initiaAddress]) const submitAction = async (functionName) => { if (!initiaAddress) { openConnect() return } setPendingAction(functionName) setError('') setTxHash('') try { const result = await requestTxSync({ chainId: CHAIN_ID, autoSign: isAutoSignEnabled, feeDenom: isAutoSignEnabled ? '' : undefined, messages: [ { typeUrl: '/initia.move.v1.MsgExecute', value: MsgExecute.fromPartial({ sender: initiaAddress, moduleAddress: MODULE_ADDRESS, moduleName: 'items', functionName, typeArgs: [], args: [], }), }, ], }) await sleep(2000) await loadInventory(initiaAddress) const responseHash = result?.txhash || result?.tx_response?.txhash || result?.transactionHash || '' setTxHash(responseHash) } catch (submitError) { setError( String( submitError?.response?.data?.message || submitError?.message || 'Transaction failed.', ), ) } finally { setPendingAction('') } } const toggleAutoSign = async () => { if (!initiaAddress) { openConnect() return } setIsTogglingAutoSign(true) setError('') try { if (isAutoSignEnabled) { try { await autoSign?.disable(CHAIN_ID) } catch (disableError) { const disableMessage = String( disableError?.response?.data?.message || disableError?.message || '', ) if (disableMessage.includes('authorization not found')) { await autoSign?.enable(CHAIN_ID, { permissions: ['/initia.move.v1.MsgExecute'], }) await autoSign?.disable(CHAIN_ID) } else { throw disableError } } } else { await autoSign?.enable(CHAIN_ID, { permissions: ['/initia.move.v1.MsgExecute'], }) } } catch (toggleError) { setError( String( toggleError?.response?.data?.message || toggleError?.message || 'Failed to update auto-sign.', ), ) } finally { setIsTogglingAutoSign(false) } } return (

BlockForge

Forge items on your appchain

Auto-Sign

{isAutoSignEnabled ? 'Enabled for Move execute messages on this chain.' : 'Disabled. Wallet approval is required for each transaction.'}

Inventory

{isConnected ? initiaAddress : 'Connect a wallet to view your items.'}

{!isConnected ? ( ) : ( )}

Shards: {isLoadingInventory ? '...' : inventory.shards}

Relics: {isLoadingInventory ? '...' : inventory.relics}

{txHash ?

Latest tx: {txHash}

: null} {error ?

{error}

: null}
) } export default Game ``` This reference assumes: * your module owner is stored in `.env` as bech32, * `moduleAddress` in `MsgExecute` uses that bech32 value, * inventory reads use `rest.move.resource` with a hex struct tag.
### Native Feature Verification 1. Connect your wallet in `blockforge-frontend`. 2. Enable Auto-sign and approve the one-time Auto-sign setup. 3. Click `Mint Shard` and confirm the transaction completes without a new wallet signature prompt. 4. Disable Auto-sign. 5. Click `Mint Shard` again and confirm a wallet signature prompt is required. ## Next Steps Now that you've mastered a Move application, you're ready to build your own idea! Ensure your project meets all the [Submission Requirements](../submission-requirements) before submitting. # MemoBoard - Wasm Source: https://docs.initia.xyz/hackathon/examples/wasm-social This tutorial will guide you through building an on-chain guestbook called MemoBoard. Users can post public messages, and the application prioritizes human-readable identity by resolving `.init` usernames. By the end of this tutorial, you will have: * Generated and verified a Rust smart contract for the guestbook. * Deployed the contract to your live appchain. * Scaffolded and connected a React frontend. * Verified the on-chain functionality. ## Your Project Structure The following steps will instruct your AI agent to create these directories inside your `my-initia-project` folder: ```text wrap Project Structure theme={null} my-initia-project/ ├── memoboard/ # Rust smart contract project └── memoboard-frontend/ # React frontend application ``` **Prerequisite:** Ensure you have a Wasm-compatible appchain running locally. If you haven't launched one yet, complete the [Set Up Your Appchain](../get-started) first. ### Readiness Check Before you start, verify that your local infrastructure is healthy. ```terminal title="Prompt: Check local infrastructure health" wrap theme={null} Using the `initia-appchain-dev` skill, please verify that my appchain, executor bot, and relayer are running and that my Gas Station account has a balance. ``` ## Step 1: Create and Unit Test the Smart Contract Instruct your AI agent to create the Rust (Wasm) contract using the `initia-appchain-dev` skill. Your AI agent will generate the contract and automatically run unit tests to ensure the logic is sound. ```terminal title="Prompt: Create and test the MemoBoard contract" wrap theme={null} Using the `initia-appchain-dev` skill, please create a Rust smart contract project for our MemoBoard in a new directory named `memoboard`. The contract should: - Allow users to post a message (string). - Store a list of all messages with the sender's address. - Include a function to query all messages on the board. Please also create and run unit tests to verify these features. ``` Your AI agent will generate the `memoboard` project and confirm that the Rust tests pass. If you prefer to see the Rust logic, here is a simplified but schema-accurate version of what your AI agent would generate. If doing this manually, save the following code in `src/contract.rs` inside your `memoboard` directory (ensure `src/lib.rs` exports the `contract` module). First create and enter the project directory: ```bash wrap theme={null} cargo new --lib --edition 2021 memoboard cd memoboard ``` **Important:** Ensure your `Cargo.toml` includes the following `[lib]` section to correctly generate the Wasm binary: ```toml wrap Cargo.toml theme={null} [lib] crate-type = ["cdylib", "rlib"] ``` Also ensure `Cargo.toml` includes these dependencies and features required by the example contract: ```toml wrap Cargo.toml theme={null} [features] library = [] [dependencies] cosmwasm-schema = "2.0.4" cosmwasm-std = "2.0.4" cw-storage-plus = "2.0.0" thiserror = "1.0.31" ``` ```rust wrap src/contract.rs theme={null} use cosmwasm_schema::{cw_serde, QueryResponses}; use cosmwasm_std::{entry_point, to_json_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, StdError}; use cw_storage_plus::Item; use thiserror::Error; #[derive(Error, Debug)] pub enum ContractError { #[error("{0}")] Std(#[from] StdError), } #[cw_serde] pub struct Memo { pub sender: String, pub message: String, } pub const MESSAGES: Item> = Item::new("messages"); #[cw_serde] pub struct InstantiateMsg {} #[cw_serde] pub enum ExecuteMsg { PostMessage { message: String }, } #[cw_serde] pub struct MessagesResponse { pub messages: Vec, } #[cw_serde] #[derive(QueryResponses)] pub enum QueryMsg { #[returns(MessagesResponse)] GetMessages {}, } #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate(deps: DepsMut, _env: Env, _info: MessageInfo, _msg: InstantiateMsg) -> Result { MESSAGES.save(deps.storage, &vec![])?; Ok(Response::new().add_attribute("action", "instantiate")) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute(deps: DepsMut, _env: Env, info: MessageInfo, msg: ExecuteMsg) -> Result { match msg { ExecuteMsg::PostMessage { message } => { let mut messages = MESSAGES.load(deps.storage)?; messages.push(Memo { sender: info.sender.to_string(), message: message.clone(), }); MESSAGES.save(deps.storage, &messages)?; Ok(Response::new() .add_attribute("action", "post_message") .add_attribute("sender", info.sender) .add_attribute("message", message)) } } } #[cfg_attr(not(feature = "library"), entry_point)] pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult { match msg { QueryMsg::GetMessages {} => { let messages = MESSAGES.load(deps.storage)?; to_json_binary(&MessagesResponse { messages }) } } } #[cfg(test)] mod tests { use super::*; use cosmwasm_std::testing::{message_info, mock_dependencies, mock_env}; use cosmwasm_std::Addr; use cosmwasm_std::from_json; #[test] fn test_post_and_query() { let mut deps = mock_dependencies(); let env = mock_env(); // Instantiate let info = message_info(&Addr::unchecked("creator"), &[]); instantiate(deps.as_mut(), env.clone(), info, InstantiateMsg {}).unwrap(); // Post Message let info = message_info(&Addr::unchecked("user1"), &[]); let msg = ExecuteMsg::PostMessage { message: "Hello!".to_string() }; execute(deps.as_mut(), env.clone(), info, msg).unwrap(); // Query let res = query(deps.as_ref(), env, QueryMsg::GetMessages {}).unwrap(); let val: MessagesResponse = from_json(&res).unwrap(); assert_eq!(val.messages.len(), 1); assert_eq!(val.messages[0].message, "Hello!"); assert_eq!(val.messages[0].sender, "user1"); } } ``` ## Step 2: Deploy to Your Appchain Now that the logic is verified, build and publish the contract to your appchain using the Gas Station account. ```terminal title="Prompt: Deploy the MemoBoard contract" wrap theme={null} Using the `initia-appchain-dev` skill, please build, publish, and instantiate the MemoBoard Rust contract located in the `memoboard` directory to my appchain using my Gas Station account, then return the deployed contract address. ``` **1. Build and Store the Code:** Standard `cargo build` binaries often fail validation on-chain. For WasmVM deployment, it is strongly recommended to use the CosmWasm Optimizer. **Note for Apple Silicon (M1/M2/M3):** Use `cosmwasm/optimizer-arm64:0.17.0`. ```bash wrap Optimizer Build Command theme={null} # Run from the root of your project # Use 'optimizer' for x86_64 or 'optimizer-arm64' for Apple Silicon OPTIMIZER_IMAGE="cosmwasm/optimizer-arm64:0.17.0" docker run --rm -v "$(pwd)/memoboard":/code \ --mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \ --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ $OPTIMIZER_IMAGE ``` The optimized binary will be located in `./memoboard/artifacts/memoboard.wasm`. Now, store the code: ```bash wrap Store Wasm Code theme={null} # If the chain requires fees, add the --fees flag (e.g., --fees 1000000umin) minitiad tx wasm store ./memoboard/artifacts/memoboard.wasm \ --from gas-station \ --keyring-backend test \ --chain-id \ --gas auto --gas-adjustment 1.4 --yes ``` **2. Retrieve the Code ID and Instantiate:** If the `code_id` is not returned directly, wait for 5 seconds for indexing and then query the transaction hash: ```bash wrap Get Code ID theme={null} # Retrieve Code ID minitiad q tx --output json | jq -r '.events[] | select(.type=="store_code") | .attributes[] | select(.key=="code_id") | .value' ``` Then, instantiate the contract: ```bash wrap Instantiate Contract theme={null} minitiad tx wasm instantiate '{}' \ --label "memoboard" \ --from gas-station \ --keyring-backend test \ --chain-id \ --gas auto --gas-adjustment 1.4 \ --no-admin --yes ``` **3. Retrieve the Contract Address:** Wait for 5 seconds for indexing and then query the transaction hash: ```bash wrap Get Contract Address theme={null} # Retrieve Contract Address minitiad q tx --output json | jq -r '.events[] | select(.type=="instantiate") | .attributes[] | select(.key=="_contract_address") | .value' ``` ## Step 3: Smoke Test the Deployed Contract On-Chain Before frontend integration, smoke test your deployed contract directly on chain. ```terminal title="Prompt: Smoke test the MemoBoard contract" wrap theme={null} Using the `initia-appchain-dev` skill, I want to smoke test our live MemoBoard contract. Using my Gas Station account on my appchain, please: 1. Post a message: "Hello from Initia!" 2. Query the board to see all messages. ``` Submit one message transaction, then query contract state to confirm it was persisted on chain. ```bash wrap Post Message theme={null} # If the chain requires fees, add the --fees flag (e.g., --fees 1000000umin) minitiad tx wasm execute '{"post_message":{"message":"Hello!"}}' \ --from gas-station \ --keyring-backend test \ --chain-id \ --gas auto --gas-adjustment 1.4 --yes ``` ```bash wrap Query Messages theme={null} sleep 5 minitiad query wasm contract-state smart '{"get_messages":{}}' ``` ## Step 4: Create a Frontend Let's create a UI to display and post messages. **1. Scaffold the Frontend:** ```terminal title="Prompt: Scaffold the MemoBoard frontend" wrap theme={null} Using the `initia-appchain-dev` skill, please scaffold a new Vite + React application named `memoboard-frontend` in my current directory using the `scaffold-frontend` script. Create a component named Board.jsx that displays a list of messages and a text input to post a new one. ``` **2. Connect to Appchain:** ```terminal title="Prompt: Connect the frontend to the MemoBoard contract" wrap theme={null} Using the `initia-appchain-dev` skill, modify the Board.jsx component in the `memoboard-frontend` directory to connect to our MemoBoard contract on my appchain. Use the `@initia/interwovenkit-react` package for wallet connection and transaction signing. ``` If you prefer to set up the frontend manually, follow these steps: **1. Create the Project and Install Dependencies:** ```bash wrap theme={null} npm create vite@latest memoboard-frontend -- --template react cd memoboard-frontend npm install npm install @initia/interwovenkit-react wagmi viem @tanstack/react-query @initia/initia.js npm install --save-dev vite-plugin-node-polyfills npm install buffer util ``` **2. Configure Vite Polyfills:** Update `vite.config.js` to include the Node polyfills: ```javascript wrap vite.config.js theme={null} import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import { nodePolyfills } from 'vite-plugin-node-polyfills' export default defineConfig({ plugins: [ react(), nodePolyfills({ globals: { Buffer: true, process: true, }, }), ], }) ``` Create the frontend files in this order so the imports line up cleanly: 1. `vite.config.js` 2. `.env` 3. `src/main.jsx` 4. `src/Board.css` 5. `src/Board.jsx` 6. `src/App.jsx` **3. Gather Runtime Values for Frontend Config:** Right before creating `.env`, collect the values you will use: ```bash wrap Gather Frontend Values theme={null} APPCHAIN_ID=$(curl -s http://localhost:26657/status | jq -r '.result.node_info.network') NATIVE_DENOM=$(minitiad q bank denoms-metadata --output json | jq -r '.metadatas[0].base // empty') [ -z "$NATIVE_DENOM" ] && NATIVE_DENOM=$(minitiad q bank total --output json | jq -r '.supply[0].denom') NATIVE_SYMBOL=$(minitiad q bank denoms-metadata --output json | jq -r '.metadatas[0].symbol // empty') [ -z "$NATIVE_SYMBOL" ] && NATIVE_SYMBOL="$NATIVE_DENOM" # Use the contract address you retrieved in Step 2. MEMOBOARD_CONTRACT_ADDRESS= echo "APPCHAIN_ID=$APPCHAIN_ID" echo "NATIVE_DENOM=$NATIVE_DENOM" echo "NATIVE_SYMBOL=$NATIVE_SYMBOL" echo "MEMOBOARD_CONTRACT_ADDRESS=$MEMOBOARD_CONTRACT_ADDRESS" ``` **4. Add Runtime Configuration:** Create a `.env` file in `memoboard-frontend` so the chain metadata, endpoints, and live contract address are explicit: ```bash wrap .env theme={null} VITE_APPCHAIN_ID=$APPCHAIN_ID VITE_CHAIN_NAME=social VITE_CHAIN_PRETTY_NAME=Social 1 VITE_INITIA_RPC_URL=http://localhost:26657 VITE_INITIA_REST_URL=http://localhost:1317 VITE_INITIA_INDEXER_URL=http://localhost:8080 VITE_INITIA_JSON_RPC_URL=http://localhost:8545 VITE_NATIVE_DENOM=$NATIVE_DENOM VITE_NATIVE_SYMBOL=$NATIVE_SYMBOL VITE_NATIVE_DECIMALS=6 VITE_MEMOBOARD_CONTRACT_ADDRESS=$MEMOBOARD_CONTRACT_ADDRESS ``` **5. Set up Providers in `main.jsx`:** ```javascript wrap src/main.jsx theme={null} import { Buffer } from 'buffer' window.Buffer = Buffer window.process = { env: { NODE_ENV: 'development' } } import React from 'react' import ReactDOM from 'react-dom/client' import '@initia/interwovenkit-react/styles.css' import { injectStyles, InterwovenKitProvider, TESTNET, } from '@initia/interwovenkit-react' import InterwovenKitStyles from '@initia/interwovenkit-react/styles.js' import { WagmiProvider, createConfig, http } from 'wagmi' import { mainnet } from 'wagmi/chains' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import App from './App.jsx' // Inject styles for the InterwovenKit drawer injectStyles(InterwovenKitStyles) const queryClient = new QueryClient() const wagmiConfig = createConfig({ chains: [mainnet], transports: { [mainnet.id]: http() }, }) const customChain = { chain_id: import.meta.env.VITE_APPCHAIN_ID, chain_name: import.meta.env.VITE_CHAIN_NAME, pretty_name: import.meta.env.VITE_CHAIN_PRETTY_NAME, network_type: 'testnet', bech32_prefix: 'init', logo_URIs: { png: 'https://raw.githubusercontent.com/initia-labs/initia-registry/main/testnets/initia/images/initia.png', svg: 'https://raw.githubusercontent.com/initia-labs/initia-registry/main/testnets/initia/images/initia.svg', }, apis: { rpc: [{ address: import.meta.env.VITE_INITIA_RPC_URL }], rest: [{ address: import.meta.env.VITE_INITIA_REST_URL }], indexer: [{ address: import.meta.env.VITE_INITIA_INDEXER_URL }], // Placeholder REQUIRED for stability 'json-rpc': [{ address: import.meta.env.VITE_INITIA_JSON_RPC_URL }], }, fees: { fee_tokens: [ { denom: import.meta.env.VITE_NATIVE_DENOM, fixed_min_gas_price: 0, low_gas_price: 0, average_gas_price: 0, high_gas_price: 0, }, ], }, staking: { staking_tokens: [{ denom: import.meta.env.VITE_NATIVE_DENOM }], }, metadata: { minitia: { type: 'miniwasm' }, is_l1: false, // REQUIRED for local appchains }, native_assets: [ { denom: import.meta.env.VITE_NATIVE_DENOM, name: 'Minitia', symbol: import.meta.env.VITE_NATIVE_SYMBOL, decimals: Number(import.meta.env.VITE_NATIVE_DECIMALS ?? 6), }, ], } ReactDOM.createRoot(document.getElementById('root')).render( , ) ``` **6. Create the `Board.jsx` Component:** Create `src/Board.jsx` and `src/Board.css` with the following content: **src/Board.css:** ```css wrap src/Board.css theme={null} .board-container { max-width: 600px; margin: 40px auto; padding: 32px; font-family: sans-serif; } .board-title { font-size: 2.5rem; font-weight: 800; margin-bottom: 24px; text-align: center; } .section-header { font-size: 0.85rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.1em; color: #888; margin-bottom: 16px; display: block; } .auth-section { display: flex; justify-content: center; margin-bottom: 24px; } .wallet-info { background: #f0f0f0; padding: 12px 16px; border-radius: 12px; display: flex; justify-content: space-between; align-items: center; width: 100%; } .message-card { background: white; padding: 16px; border-radius: 12px; border: 1px solid #eee; margin-bottom: 16px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02); } .message-sender { font-family: monospace; font-size: 0.75rem; color: #999; } .message-content { margin-top: 8px; font-size: 1.1rem; } .input-group { display: flex; gap: 12px; margin-top: 16px; } .memo-input { flex: 1; padding: 12px 16px; border-radius: 8px; border: 1px solid #ddd; outline: none; } .btn-primary { background: #000; color: #fff; border: none; padding: 12px 24px; border-radius: 8px; font-weight: 600; cursor: pointer; } ``` **src/Board.jsx:** ```javascript wrap src/Board.jsx theme={null} import React, { useState, useEffect } from 'react' import { useInterwovenKit } from '@initia/interwovenkit-react' import { RESTClient } from '@initia/initia.js' import './Board.css' const CHAIN_ID = import.meta.env.VITE_APPCHAIN_ID const MEMO_BOARD_ADDRESS = import.meta.env.VITE_MEMOBOARD_CONTRACT_ADDRESS const rest = new RESTClient(import.meta.env.VITE_INITIA_REST_URL) const Board = () => { const [messages, setMessages] = useState([]) const [content, setContent] = useState('') const { initiaAddress, requestTxSync } = useInterwovenKit() const truncate = (addr) => `${addr.slice(0, 10)}...${addr.slice(-6)}` const fetchMessages = async () => { try { // Wasm queries via REST MUST be base64 encoded const queryData = Buffer.from( JSON.stringify({ get_messages: {} }), ).toString('base64') const res = await rest.wasm.smartContractState( MEMO_BOARD_ADDRESS, queryData, ) setMessages([...(res?.messages ?? [])].reverse()) } catch (e) { console.error('Failed to fetch messages', e) } } useEffect(() => { fetchMessages() // Poll for new messages every 5 seconds const interval = setInterval(fetchMessages, 5000) return () => clearInterval(interval) }, []) const handlePostMessage = async () => { if (!content || !initiaAddress || !MEMO_BOARD_ADDRESS) return // Encode execute msg to Uint8Array (bytes) const msg = new TextEncoder().encode( JSON.stringify({ post_message: { message: content } }), ) try { // Use requestTxSync for local development transactions // ALWAYS include CHAIN_ID to avoid RPC routing errors await requestTxSync({ chainId: CHAIN_ID, messages: [ { typeUrl: '/cosmwasm.wasm.v1.MsgExecuteContract', value: { sender: initiaAddress, contract: MEMO_BOARD_ADDRESS, msg, funds: [], }, }, ], }) setContent('') // Small delay to allow block inclusion setTimeout(fetchMessages, 2000) } catch (e) { console.error('Transaction failed', e) } } return (

MemoBoard

{!initiaAddress && (
Connect your wallet from the app header to post a memo.
)} {initiaAddress && (

Post a Memo

setContent(e.target.value)} placeholder="Write a memo..." />
)}

Board Feed

{messages.map((m, i) => (
{truncate(m.sender)}
{m.message}
))}
) } export default Board ``` **7. Create `App.jsx`:** Create the app shell that renders the board and owns the wallet button: ```javascript wrap src/App.jsx theme={null} import React from 'react' import { useInterwovenKit } from '@initia/interwovenkit-react' import Board from './Board.jsx' function shortenAddress(addr) { if (!addr) return '' return `${addr.slice(0, 8)}...${addr.slice(-4)}` } function App() { const { initiaAddress, openConnect, openWallet } = useInterwovenKit() return (

Initia Wasm Appchain

MemoBoard

{!initiaAddress ? ( ) : ( )}
) } export default App ```
## Step 5: Wallet Funding and UI Verification Ask your AI agent to fund your browser wallet, then verify frontend behavior manually in the browser: 1. Start the frontend: ```bash wrap Start Vite Dev Server theme={null} cd memoboard-frontend npm run dev ``` Check the **browser console** if you encounter issues. 2. Open your browser wallet and copy your address (`init1...`). 3. Give this prompt to your AI agent, replacing `` with the address you just copied: ```terminal wrap theme={null} Using the `initia-appchain-dev` skill, please fund my wallet address with 1 INIT on L1 and 100 of my appchain's native tokens on L2. ``` 4. Connect your wallet in `memoboard-frontend`. 5. Post a message from the UI. 6. Confirm it appears in the message list after refresh. 7. If your UI supports it, verify sender identity rendering matches expectations. If you get stuck, see the [Debugging Workflow guide](../builder-guide#debugging-workflow). # 🪢 Native Feature: Initia Usernames To make your MemoBoard natively integrated with the Initia stack, you can replace long, complex addresses with human-readable Initia Usernames (e.g., `vitalik.init`). ## Step 6: Register Your .init Name Before updating your code, you should register a `primary username` for your wallet on the Initia testnet. 1. Navigate to [app.testnet.initia.xyz/usernames](https://app.testnet.initia.xyz/usernames) and connect your browser wallet. 2. In the `Find a username` search box, enter your desired name. If it is available, you will see a green `Available` checkmark. 3. Crucial: Ensure the `Set as primary name` checkbox is selected. 4. Click `Register` and approve the transaction. Once resolved, your new `.init` name will appear in the top-right corner of the Initia App. ## Step 7: Update the Frontend Your AI agent knows how to integrate Initia Usernames. Simply ask it to update your board. ```terminal title="Prompt: Add Initia username support" wrap theme={null} Using the `initia-appchain-dev` skill, please add Initia username support to my MemoBoard. ``` The `useInterwovenKit()` hook provides the `username` for the currently connected wallet, and `useUsernameQuery(address)` resolves usernames for other sender addresses. This requires `@initia/interwovenkit-react` `2.4.6` or newer. To implement this, update your wallet button component (for example `src/App.jsx`) and your board message list like this: ```tsx wrap theme={null} import { useInterwovenKit, useUsernameQuery } from '@initia/interwovenkit-react' function MessageRow({ message }) { const { initiaAddress, username } = useInterwovenKit() const { data: senderUsername } = useUsernameQuery(message.sender) const senderLabel = message.sender === initiaAddress ? username ? username : truncate(message.sender) : senderUsername ? senderUsername : truncate(message.sender) return (
{senderLabel}
) } // 1. Extract username from the hook const { initiaAddress, username, openConnect, openWallet } = useInterwovenKit() // 2. Update the connected wallet button to show the username
// 3. Update the feed rows to resolve usernames for sender addresses messages.map((message, index) => ( )) ``` **Hook Placement:** Keep `useUsernameQuery(address)` inside a child row component like `MessageRow`. Do not call it directly inside a parent component's `.map()` callback.
If you want the complete finished frontend after applying the manual steps above, use the consolidated reference below. If you want a single copyable end-state after completing the manual steps above, use this consolidated reference. It combines: * live Wasm contract query and execute flow, * wallet connect/display via `App.jsx`, * runtime config from `.env`, and * Initia username support for the connected wallet and sender rows. **src/Board.jsx** ```jsx wrap src/Board.jsx theme={null} import React, { useEffect, useMemo, useState } from 'react' import { RESTClient } from '@initia/initia.js' import { useInterwovenKit, useUsernameQuery } from '@initia/interwovenkit-react' import './Board.css' const CHAIN_ID = import.meta.env.VITE_APPCHAIN_ID const REST_URL = import.meta.env.VITE_INITIA_REST_URL const CONTRACT_ADDRESS = import.meta.env.VITE_MEMOBOARD_CONTRACT_ADDRESS function truncate(value) { if (!value) return '' if (value.length < 18) return value return `${value.slice(0, 10)}...${value.slice(-6)}` } function MessageRow({ message, index, initiaAddress, username }) { const { data: senderUsername } = useUsernameQuery(message.sender) const senderLabel = message.sender === initiaAddress ? username ? username : truncate(message.sender) : senderUsername ? senderUsername : truncate(message.sender) return (
{senderLabel}
{message.message}
Message #{index + 1}
) } export default function Board() { const { initiaAddress, username, requestTxSync } = useInterwovenKit() const [messages, setMessages] = useState([]) const [draft, setDraft] = useState('') const [loading, setLoading] = useState(true) const [posting, setPosting] = useState(false) const [error, setError] = useState('') const rest = useMemo(() => new RESTClient(REST_URL), []) const fetchMessages = async () => { if (!CONTRACT_ADDRESS) { setError('Missing VITE_MEMOBOARD_CONTRACT_ADDRESS in .env') setLoading(false) return } setLoading(true) try { const queryData = Buffer.from( JSON.stringify({ get_messages: {} }), ).toString('base64') const res = await rest.wasm.smartContractState(CONTRACT_ADDRESS, queryData) setMessages(Array.isArray(res.messages) ? res.messages : []) setError('') } catch (e) { console.error('Failed to fetch messages', e) setError('Failed to load board messages') } finally { setLoading(false) } } useEffect(() => { fetchMessages() }, []) const handlePostMessage = async (event) => { event.preventDefault() const trimmed = draft.trim() if (!trimmed || !initiaAddress || !CONTRACT_ADDRESS) return setPosting(true) setError('') try { const msg = new TextEncoder().encode( JSON.stringify({ post_message: { message: trimmed } }), ) await requestTxSync({ chainId: CHAIN_ID, messages: [ { typeUrl: '/cosmwasm.wasm.v1.MsgExecuteContract', value: { sender: initiaAddress, contract: CONTRACT_ADDRESS, msg, funds: [], }, }, ], }) setDraft('') await new Promise((resolve) => setTimeout(resolve, 1200)) await fetchMessages() } catch (e) { console.error('Transaction failed', e) setError('Posting the message failed') } finally { setPosting(false) } } return (

MemoBoard

{!initiaAddress && (
Connect your wallet from the app header to post a memo.
)} {initiaAddress && (

Post a Memo

Posting as {username ? username : truncate(initiaAddress)}

setDraft(e.target.value)} placeholder="Write a memo..." />
)}

Board Feed

{error && (
{error}
)} {loading ? (
Loading board state...
) : messages.length === 0 ? (
No messages yet.
) : ( messages.map((message, index) => ( )) )}
) } ``` **src/App.jsx** ```jsx wrap src/App.jsx theme={null} import React from 'react' import { useInterwovenKit } from '@initia/interwovenkit-react' import Board from './Board.jsx' function shortenAddress(addr) { if (!addr) return '' return `${addr.slice(0, 8)}...${addr.slice(-4)}` } export default function App() { const { initiaAddress, username, openConnect, openWallet } = useInterwovenKit() return (

Initia Wasm Appchain

MemoBoard

{!initiaAddress ? ( ) : ( )}
) } ```
### Native Feature Verification 1. Connect your wallet in `memoboard-frontend`. 2. Confirm the header button shows your `.init` username (not only a truncated address). 3. Post a message and confirm the sender label for your message uses your username. ## Next Steps Now that you've mastered a Wasm application, you're ready to build your own idea! Ensure your project meets all the [Submission Requirements](../submission-requirements) before submitting. # Set Up Your Appchain Source: https://docs.initia.xyz/hackathon/get-started ## Build an Appchain with Your AI Agent Welcome to the hackathon! This guide will walk you through building an appchain from scratch. You'll go from a simple idea to a functioning appchain and frontend efficiently. ## Step 1: Prepare Your Workspace Before installing tools or initializing your appchain, create a dedicated directory for your project. This keeps your configuration files, VM binaries, and smart contracts organized in one place. **Run the following commands in your terminal:** ```bash wrap theme={null} mkdir my-initia-project cd my-initia-project ``` ## Step 2: Install Your AI Skill Your AI agent needs the `Initia Appchain Dev` skill to help you manage your appchain, write smart contracts, and build your frontend. **Run the following command in your terminal:** ```bash wrap theme={null} npx skills add initia-labs/agent-skills ``` ## Step 3: Select an AI Agent These guides assume you are using a code-aware AI agent that can access your project directory, read files, run commands, and help you edit code. Any equivalent tool is fine. ### Terminal Agents (CLI) * [OpenAI Codex](https://help.openai.com/en/articles/11096431-openai-codex-ci-getting-started) * [Claude Code](https://code.claude.com/docs/en/setup) * [Gemini CLI](https://geminicli.com/docs/get-started/installation/) ### AI-Powered IDEs * [Cursor](https://cursor.com/download) * [VS Code](https://code.visualstudio.com/download) Keep your AI agent open in your project root so it can use your local context when you paste the prompts in this guide. **Recommended setup:** Use two terminal tabs or a split-screen layout: 1. **AI agent**: For high-level tasks, contract generation, and troubleshooting. 2. **Standard terminal**: For interactive CLI commands like `weave init` and long-running builds. ## Step 4: Select Your Track & VM Before installing tools, decide what you want to build. This choice determines which `Virtual Machine (VM)` your AI agent will set up for you. | Track | Recommended VM | Reason | | :--------------------- | :--------------- | :----------------------------------------------------------- | | `Gaming / Consumer` | `Move` | Best for complex onchain logic and object-oriented assets. | | `DeFi / Institutional` | `EVM` (Solidity) | Best for leveraging existing Ethereum tooling and libraries. | | `AI / Tooling` | `Wasm` (Rust) | Best for backend-heavy apps, agents, and tooling. | If you are building for the AI track and want guidance on where AI should live in your architecture, see [AI Track Guidance](/hackathon/ai-track-guidance). ## Step 5: Prerequisites Checklist To ensure a smooth setup, verify you have the following system tools installed: * **[Docker Desktop](https://www.docker.com/products/docker-desktop/)**: Required for running the bridge bots and relayer. **Must be running.** * **[Go (1.22+)](https://go.dev/doc/install)**: Required to build the appchain binaries. * **Track Specifics**: * **Move**: No extra tools required. * **EVM**: **[Foundry](https://book.getfoundry.sh/getting-started/installation)** (Forge) is recommended for contract development. * **Wasm**: **[Rust & Cargo](https://rustup.rs/)** are required for contract development. ## Step 6: AI-Powered Initia Tool Setup and Verification Now, ask your AI agent to handle the Initia-specific tools. It will install the core CLIs (`weave`, `initiad`, `jq`), build your chosen VM binary (`minitiad`), and verify everything is in your `PATH`. Replace `` with your selected track from Step 4 (`Move`, `EVM`, or `Wasm`). ```terminal title="Prompt: Set up my environment" wrap theme={null} Using the `initia-appchain-dev` skill, please set up my environment for the track. ``` ### Verify Installation & PATH After setup completes, your AI agent can verify the tools are accessible from anywhere on your system. ```terminal title="Prompt: Verify tool installation" wrap theme={null} Using the `initia-appchain-dev` skill, please verify that `initiad`, `weave`, and `minitiad` are properly installed and accessible in my PATH. ``` ## Step 7: Initial Setup With `weave init` Your AI agent is your partner in this hackathon, but the `weave` CLI requires an interactive setup flow to prepare your environment and launch your appchain. You can run it whenever you need to initialize or reconfigure your setup. **Resetting Existing Local State:** If you already ran `weave init` and want to create a new appchain, run the following commands first. This clears your existing local Initia, Minitia, OPinit, and relayer setup: ```bash wrap theme={null} rm -rf ~/.weave ~/.initia ~/.minitia ~/.opinit docker rm -f weave-relayer || true ``` **Run the following command in your terminal:** ```bash wrap theme={null} weave init ``` Here's a guide on how to navigate the interactive setup: ### Generate Gas Station Account The Gas Station is an account on the Initia L1 that will fund your rollup's infrastructure. **Prompt:** ```terminal wrap theme={null} How would you like to set up your Gas Station account? ``` **Action:** Select `Generate new account (recommended)`. **Result:** You will see your new Gas Station Address. Copy this address. ### Fund Your Gas Station Account **Action:** Go to the [Initia Testnet Faucet](https://app.testnet.initia.xyz/faucet). **Action:** Paste your address and click **Submit** to receive testnet INIT tokens. **Prompt:** ```terminal wrap theme={null} Type `continue` to proceed. ``` **Action:** Type `continue` and press Enter. ### Select Your Action **Prompt:** ```terminal wrap theme={null} What do you want to do? ``` **Action:** Select `Launch a new rollup`. **Switching VMs?** Reinstall the correct `minitiad` binary first (Step 6). If you have existing rollup data, type `confirm` when prompted to clean it and proceed. ### Select L1 Network **Prompt:** ```terminal wrap theme={null} Select the Initia L1 network ``` **Action:** Select `Testnet (initiation-2)`. ### Select Virtual Machine (VM) **Prompt:** ```terminal wrap theme={null} Select the Virtual Machine (VM) ``` **Action:** Select your desired VM (e.g., `Move`). ### Specify Rollup Chain ID **Prompt:** ```terminal wrap theme={null} Specify rollup chain ID ``` **Action:** Enter a unique ID (e.g., `mygame-1`). **Save your Chain ID!** You'll need this unique identifier for your final submission. ### Specify Rollup Gas Denom **Prompt:** ```terminal wrap theme={null} Specify rollup gas denom ``` **Action:** Press `Tab` for default (`umin`) or enter your own. ### Specify Rollup Node Moniker **Prompt:** ```terminal wrap theme={null} Specify rollup node moniker ``` **Action:** Press `Tab` for default (`operator`). ### Submission Interval **Prompt:** ```terminal wrap theme={null} Specify OP bridge config: Submission Interval ``` **Action:** Press `Tab` for default (`1m`). ### Finalization Period **Prompt:** ```terminal wrap theme={null} Specify OP bridge config: Output Finalization Period ``` **Action:** Press `Tab` for default (`168h`). ### Data Availability **Prompt:** ```terminal wrap theme={null} Where should the rollup blocks data be submitted? ``` **Action:** Select `Initia L1`. ### Enable Oracle Price Feed **Prompt:** ```terminal wrap theme={null} Would you like to enable oracle price feed from L1? ``` **Action:** Select `Enable`. ### Setup Method for System Keys **Prompt:** ```terminal wrap theme={null} Select a setup method for the system keys ``` **Action:** Select `Generate new system keys`. ### System Accounts Funding Option **Prompt:** ```terminal wrap theme={null} Select system accounts funding option ``` **Action:** Select `Use the default preset`. ### Specify Fee Whitelist Addresses **Prompt:** ```terminal wrap theme={null} Specify fee whitelist addresses ``` **Action:** Press `Enter` to leave empty. ### Add Gas Station Account to Genesis **Prompt:** ```terminal wrap theme={null} Would you like to add the Gas Station account to genesis accounts? ``` **Action:** Select `Yes`. ### Specify Genesis Balance **Prompt:** ```terminal wrap theme={null} Specify the genesis balance for the Gas Station account ``` **Action:** Enter `1000000000000000000000000` (10^24). This ensures you have plenty of tokens for testing, especially for EVM. **Move Track Balance Limit:** Use `10000000000000000000` (10^19) to avoid `u64` overflows. ### Add Additional Genesis Accounts **Prompt:** ```terminal wrap theme={null} Would you like to add genesis accounts? ``` **Action:** Select `No`. ### Verify System Keys & Continue **Prompt:** ```terminal wrap theme={null} Type 'continue' to proceed. ``` **Action:** Type `continue` and press Enter. ### Confirm Transactions **Prompt:** ```terminal wrap theme={null} Confirm to proceed with signing and broadcasting the following transactions? [y]: ``` **Action:** Type `y` and press Enter. Your appchain will now launch and start producing blocks! ## Step 8: Setup Interwoven Bots To enable the Optimistic bridge and cross-chain communication (IBC) between Initia L1 and your appchain, you need to start the `OPinit Executor` and the `IBC Relayer`. These bots manage the cross-chain connectivity of your chain. **Prerequisite:** Your appchain must be running before configuring these bots. Because `weave init` runs your chain in the background, you can continue using the same terminal window. ### 8.1 Start the OPinit Executor The executor handles the submission of rollup data and bridge operations. **Run the following command:** ```bash wrap theme={null} weave opinit init executor ``` Follow the interactive guide: **Prompt:** ```terminal wrap theme={null} Existing keys in config.json detected. Would you like to add these to the keyring before proceeding? ``` **Action:** Select `Yes, use detected keys`. **Prompt:** ```terminal wrap theme={null} Please select an option for the system key for Oracle Bridge Executor ``` **Action:** Select `Generate new system key`. **Prompt:** ```terminal wrap theme={null} Existing config.json detected. Would you like to use the data in this file to pre-fill some fields? ``` **Action:** Select `Yes, prefill`. **Prompt:** ```terminal wrap theme={null} Specify listen address of the bot ``` **Action:** Press `Tab` to use `localhost:3000` (ensure nothing else is running on this port). **Action:** Press `Enter` for L1 RPC, Chain ID, and Gas Denom. For Rollup RPC, press `Tab` to use `http://localhost:26657`. Once initialized, start the bot in the background: ```bash wrap theme={null} weave opinit start executor -d ``` ### 8.2 Start the IBC Relayer The relayer enables asset transfers (like INIT) between the L1 and your appchain. Docker Desktop must be running to launch the relayer. **Run the following command:** ```bash wrap theme={null} weave relayer init ``` Follow the interactive guide: **Prompt:** ```terminal wrap theme={null} Select the type of Interwoven rollup you want to relay ``` **Action:** Select `Local Rollup ()`. **Action:** Press `Tab` for both **RPC** (`http://localhost:26657`) and **REST** (`http://localhost:1317`) endpoints. **Prompt:** ```terminal wrap theme={null} Select method to set up IBC channels for the relayer ``` **Action:** Select `Subscribe to only transfer and nft-transfer IBC Channels (minimal setup)`. **Prompt:** ```terminal wrap theme={null} Select the IBC channels you would like to relay ``` **Action:** Press `Space` to select all (transfer and nft-transfer), then press `Enter`. **Prompt:** ```terminal wrap theme={null} Do you want to set up relayer with the challenger key ``` **Action:** Select `Yes (recommended)`. Start the relayer process: ```bash wrap theme={null} weave relayer start -d ``` You can view relayer logs at any time by running `weave relayer log` in your terminal. **Persistence After Restart:** After restarting your computer, the relayer remains managed by Docker. As long as Docker Desktop is open, it should still be running. You still need to restart your rollup full node and executor: ```bash wrap theme={null} weave rollup start -d weave opinit start executor -d ``` ## Step 9: Final Key Setup **Why:** The `Gas Station` account acts as your `Universal Developer Key`. Importing it allows you to sign transactions manually via the CLI, and it enables your AI co-pilot to deploy contracts and interact with your appchain. **Action:** Run these commands to import your account into both the L1 (`initiad`) and L2 (`minitiad`) keychains: ```bash wrap theme={null} # Extract your mnemonic from the weave config MNEMONIC=$(jq -r '.common.gas_station.mnemonic' ~/.weave/config.json) # Import into initiad (L1) initiad keys add gas-station --recover --keyring-backend test --coin-type 60 --key-type eth_secp256k1 --source <(echo -n "$MNEMONIC") # Import into minitiad (L2) minitiad keys add gas-station --recover --keyring-backend test --coin-type 60 --key-type eth_secp256k1 --source <(echo -n "$MNEMONIC") ``` **Action:** Verify the import by listing your keys to ensure `gas-station` appears in both: ```bash wrap theme={null} # Verify L1 keys initiad keys list --keyring-backend test # Verify L2 keys minitiad keys list --keyring-backend test ``` **Production Security:** This workflow is for rapid prototyping only. * **Insecure Storage:** `config.json` and `--keyring-backend test` are for convenience, not production. * **Mainnet:** Use secure keyrings (OS keychain, hardware wallet) and never store mnemonics in plaintext. * **Best Practice:** Use separate accounts for `Gas Station`, `Validator`, and `Developer` roles on Mainnet. ## Step 10: Verifying Your Appchain After completing the infrastructure setup, verify that everything is healthy. ```terminal title="Prompt: Verify my appchain is healthy" wrap theme={null} Using the `initia-appchain-dev` skill, please verify that my appchain, executor bot, and relayer are running and that my Gas Station account has a balance. ``` ## Step 11: Build Your App Congratulations! You have successfully launched your first appchain. Next, head to the [Builder Guide](/hackathon/builder-guide) to select whether to build from scratch or start from a Blueprint, then build your app with AI, debug issues, and prepare your submission. # Lotteria Source: https://docs.initia.xyz/hackathon/lotteria This guide walks through building **[Lotteria](https://lotteria-five.vercel.app/)**, an onchain lottery machine, as a working example of how to build a full-stack appchain on Initia. It covers writing Move modules, connecting a frontend with InterwovenKit, and deploying to your rollup. The full source code is available in the [Lotteria reference repository](https://github.com/yonnie-park/lotteria). This is a demo repository built as a reference for hackathon participants. If you get stuck on any step, from writing Move modules to wiring up your frontend, use the reference implementation as a working example to compare against. # Prerequisites Before you begin, make sure you have completed the [Set Up Your Appchain](/hackathon/get-started) setup, including: * A running appchain via `weave init` * `initiad` and `minitiad` installed and in your PATH. This should already be installed when you set up your appchain * OPinit Executor and IBC Relayer running connected to your appchain * A funded Weave Gas Station account imported into your local keyring ### Project Structure ```text theme={null} lotteria/ ├── move/ # Move smart contract modules ├── frontend/ # React frontend application ├── interwovenkit # InterwovenKit submodule └── package.json ``` # 1. Move Modules Move is the smart contract language for the MoveVM track on Initia. In Lotteria, the Move module handles all the core lottery logic: creating rounds, buying tickets, drawing winners, and distributing prizes. ### Setting Up the Move Package Create a `move/` directory in your project root with the following structure: ``` move/ ├── sources/ │ ├── lottery.move │ └── lottery_random.move └── Move.toml ``` The lottery module depends on a helper module `lottery_random` for onchain randomness (winner selection). Both source files are required for compilation. Copy both from the [reference repo](https://github.com/yonnie-park/lotteria/tree/main/move/sources). Your `Move.toml` defines the package metadata, dependencies, and the address your module will be published under. You need to convert your Initia address to its hex representation: ```bash theme={null} initiad keys parse # Output: bytes: ``` Then configure `Move.toml`: ```toml title="move/Move.toml" theme={null} [package] name = "lotteria" version = "0.0.0" [dependencies] InitiaStdlib = { git = "https://github.com/initia-labs/movevm.git", subdir = "precompile/modules/initia_stdlib", rev = "main" } [addresses] lottery = "" std = "0x1" initia_std = "0x1" ``` The `InitiaStdlib` dependency gives you access to core modules like `coin`, `signer`, `event`, and `object`, which are essential building blocks for any onchain application. ### Writing the Lottery Module The lottery module manages the full lifecycle of a lottery round. Here is a breakdown of the key components. **Module declaration and imports:** ```move theme={null} module lottery::lottery { use std::signer; use std::vector; use std::error; use lottery::lottery_random; use initia_std::fungible_asset::Metadata; use initia_std::object::{Self, ExtendRef}; use initia_std::primary_fungible_store; use initia_std::block; use initia_std::table::{Self, Table}; } ``` **Data structures:** Define the resources that will live onchain. A lottery needs to track the current round state, ticket purchases, and prize pool: ```move theme={null} struct LotteryConfig has key { admin: address, current_draw_id: u64, ticket_price: u64, total_tickets_sold: u64, extend_ref: ExtendRef, vault_addr: address, } ``` The `has key` ability means this struct can be stored as a top-level resource in global storage, which is how Move manages persistent onchain state. **Core entry functions:** Entry functions are the public interface that users and frontends call via transactions: * `initialize`: Creates the initial lottery config and first draw * `buy_ticket`: Validates six picked numbers and transfers the ticket price * `execute_draw`: Generates winning numbers for a draw * `finalize_draw`: Calculates prize amounts per winner tier * `get_ticket_price`: A view function that returns the configured ticket price without modifying state ```move theme={null} public entry fun buy_ticket( buyer: &signer, numbers: vector, ) acquires LotteryConfig, DrawStore, TicketCollection { let buyer_addr = signer::address_of(buyer); assert!(vector::length(&numbers) == NUMBERS_TO_PICK, error::invalid_argument(EINVALID_NUMBERS)); validate_numbers(&numbers); let config = borrow_global_mut(@lottery); let draw_store = borrow_global_mut(@lottery); let metadata = object::address_to_object(@0x9759eac00e068b4e8adc206d17c6a8477f00ae41f824f0e2e81b3832cc8065ae); primary_fungible_store::transfer(buyer, metadata, config.vault_addr, config.ticket_price); let (_, current_time) = block::get_block_info(); let draw_id = config.current_draw_id; let ticket_entry = TicketEntry { owner: buyer_addr, numbers }; let draw_ticket_list = table::borrow_mut(&mut draw_store.draw_tickets, draw_id); vector::push_back(draw_ticket_list, ticket_entry); } ``` **Replace the Reference Metadata Address:** The `Metadata` object address in `lottery.move` is specific to the token used by the reference deployment and will not exist on your local rollup. Before building, query the metadata object for the token you want to use for ticket payments: ```bash theme={null} minitiad query move metadata --denom --node http://localhost:26657 # metadata: 0x... ``` Replace every hardcoded `object::address_to_object(@0x...)` occurrence in `lottery.move` with the returned metadata address. **View functions:** View functions let the frontend query onchain state without submitting a transaction: ```move theme={null} #[view] public fun get_ticket_price(): u64 { TICKET_PRICE } ``` ### Building and Deploying the Module Build the module to check for compilation errors: ```bash theme={null} initiad move build --path ./move ``` Deploy to your running appchain: ```bash theme={null} export MODULE_OWNER=gas-station # or your key name export L2_CHAIN_ID= export FEE_DENOM=umin # replace with your rollup's configured fee token denom minitiad move deploy \ --path ./move \ --upgrade-policy COMPATIBLE \ --from $MODULE_OWNER \ --keyring-backend test \ --gas auto --gas-adjustment 1.5 \ --gas-prices 0.15$FEE_DENOM \ --node http://localhost:26657 \ --chain-id $L2_CHAIN_ID \ --yes ``` Use `minitiad` (not `initiad`) here because you are deploying to your Layer 2 rollup, not the Initia L1. The fee denom (`umin` above) depends on the fee token you configured during `weave init`. To confirm the correct denom for your rollup, run: ```bash theme={null} minitiad query bank total --node http://localhost:26657 ``` and use the denom shown for your rollup's native token. To verify the deployment, query a view function: ```bash theme={null} export MODULE_ADDRESS= minitiad query move view $MODULE_ADDRESS lottery get_ticket_price \ --args '[]' \ --node http://localhost:26657 ``` **Required Empty Args:** Even for view functions that take no arguments, `--args '[]'` is required. Omitting it will cause a CLI parse error. To execute a function, for example to initialize the module state after deployment: ```bash theme={null} minitiad tx move execute $MODULE_ADDRESS lottery initialize \ --from $MODULE_OWNER \ --keyring-backend test \ --gas auto --gas-adjustment 1.5 \ --gas-prices 0.15$FEE_DENOM \ --node http://localhost:26657 \ --chain-id $L2_CHAIN_ID \ --yes ``` # 2. Using InterwovenKit [InterwovenKit](https://github.com/initia-labs/interwovenkit) is a React library that provides components and hooks for connecting dApps to Initia and Interwoven Rollups. It handles wallet connections, transaction signing, and chain interactions out of the box. ### Installation Install the InterwovenKit React package: ```bash theme={null} npm install @initia/interwovenkit-react ``` If you are starting from scratch, scaffold a new React project with Vite: ```bash theme={null} npm create vite@latest frontend -- --template react-ts cd frontend npm install npm install @initia/interwovenkit-react ``` ### Setting Up the Provider Wrap your application with `InterwovenKitProvider`. This is the top-level context that makes wallet state and transaction methods available throughout your component tree. In your `main.tsx` or `App.tsx`: ```tsx theme={null} import { QueryClient, QueryClientProvider } from "@tanstack/react-query" import { createConfig, http, WagmiProvider } from "wagmi" import { mainnet } from "wagmi/chains" import { InterwovenKitProvider, TESTNET, injectStyles, } from "@initia/interwovenkit-react" import InterwovenKitStyles from "@initia/interwovenkit-react/styles.js" const queryClient = new QueryClient() const wagmiConfig = createConfig({ chains: [mainnet], transports: { [mainnet.id]: http() }, }) const feeDenom = "" const customChain = { chain_id: "", chain_name: "My Appchain", network_type: "testnet", bech32_prefix: "init", apis: { rpc: [{ address: "http://localhost:26657" }], rest: [{ address: "http://localhost:1317" }], indexer: [{ address: "http://localhost:8080" }], }, fees: { fee_tokens: [{ denom: feeDenom, fixed_min_gas_price: 0, low_gas_price: 0, average_gas_price: 0, high_gas_price: 0 }] }, staking: { staking_tokens: [{ denom: feeDenom }] }, native_assets: [{ denom: feeDenom, name: "Token", symbol: "TKN", decimals: 6 }], metadata: { is_l1: false, minitia: { type: "minimove" } }, } injectStyles(InterwovenKitStyles) function App() { return ( ) } ``` ### Connecting a Wallet The `useInterwovenKit` hook provides everything you need for wallet connection. Here is a simplified wallet connection component based on the wallet controls in Lotteria's `Header.tsx`: ```tsx theme={null} import { useInterwovenKit } from "@initia/interwovenkit-react" // truncate is a simple display utility — inline it or use your own preferred implementation const truncate = (str: string, maxLength = 12): string => str.length > maxLength ? `${str.slice(0, 6)}...${str.slice(-4)}` : str const Connection = () => { const { address, username, openWallet, openConnect } = useInterwovenKit() if (!address) { return } return ( ) } export default Connection ``` When no wallet is connected, the component renders a "Connect" button that calls `openConnect` to launch the wallet connection drawer. Once connected, it displays the user's Initia username (if they have one) or a truncated version of their address. Clicking the button calls `openWallet` to open the wallet detail panel. ### Depositing Assets Users need tokens on your appchain to interact with it. InterwovenKit provides a built-in deposit flow that handles cross-chain bridging. Here is the `openDeposit` pattern used by Lotteria: ```tsx theme={null} import { useInterwovenKit } from "@initia/interwovenkit-react" const Deposit = () => { const { address, openDeposit } = useInterwovenKit() if (!address) return null return ( ) } export default Deposit ``` The `openDeposit` method opens a drawer that lets users bridge tokens from Initia L1 (or other connected chains) to your appchain. The `denoms` array specifies which token denominations are accepted. The `chainId` should match your appchain's chain ID. If you want to support deposits from Initia L1, include `uinit` in the allowed denoms. Initia L1 uses `initiation-2` on testnet and `interwoven-1` on mainnet. The component only renders when a wallet is connected (`address` is truthy), since depositing requires an active wallet session. ### Sending Transactions To interact with your Move module from the frontend, use `requestTxSync` to construct and send transactions: ```tsx theme={null} import { useInterwovenKit } from '@initia/interwovenkit-react' function encodeVectorU8(numbers: number[]): Uint8Array { const bytes = new Uint8Array(numbers.length + 1) bytes[0] = numbers.length for (let i = 0; i < numbers.length; i++) { bytes[i + 1] = numbers[i] } return bytes } function BuyTicketButton() { const { initiaAddress, requestTxSync } = useInterwovenKit() const handleBuyTicket = async () => { if (!initiaAddress) return const selectedNumbers = [1, 2, 3, 4, 5, 6] // replace with numbers chosen in your UI try { const txHash = await requestTxSync({ chainId: '', messages: [ { typeUrl: "/initia.move.v1.MsgExecute", value: { sender: initiaAddress, moduleAddress: "", moduleName: "lottery", functionName: "buy_ticket", typeArgs: [], args: [encodeVectorU8(selectedNumbers)], }, }, ], }) console.log("Transaction hash:", txHash) } catch (error) { console.error("Transaction failed:", error) } } return } ``` The `requestTxSync` method prompts the user's wallet to sign and broadcast the transaction. It returns the transaction hash on success. ### Querying Onchain State To query and read data using the view functions of your Move module, you can utilize the chain's REST endpoint as follows: ```tsx theme={null} async function fetchTicketPrice() { const res = await fetch( `http://localhost:1317/initia/move/v1/accounts//modules/lottery/view_functions/get_ticket_price`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ type_args: [], args: [] }), } ) const data = await res.json() return data } ``` You can wrap this in a React hook with polling or use a library like TanStack Query for automatic refetching. # 3. Connecting to the Chain ### Chain Configuration Your appchain runs locally after `weave init`. The default endpoints are: | Service | URL | | ------- | ------------------------ | | RPC | `http://localhost:26657` | | REST | `http://localhost:1317` | These endpoints are what your frontend uses to query state and broadcast transactions. ### Bridging Assets via IBC Once the IBC Relayer is running (see [Set Up Your Appchain](/hackathon/get-started)), you can bridge INIT tokens from the L1 testnet to your appchain. This is how users fund their accounts on your rollup. The bridge flow works through IBC transfer channels that the relayer establishes between Initia L1 and your rollup. Users can send tokens from L1 to your chain, and the tokens arrive as IBC-denominated assets. ### Frontend Development Workflow A practical development loop looks like this: 1. Write or update your Move module in `move/sources/` 2. Build and deploy with `minitiad move deploy` 3. Test the module via CLI with `minitiad tx move execute` and `minitiad query move view` 4. Build your frontend components using InterwovenKit hooks 5. Run the frontend dev server and test end-to-end # Summary Building an appchain on Initia with the Move track involves three layers: 1. **Move modules** define your onchain logic. Write your structs and entry functions, build with `initiad move build`, and deploy with `minitiad move deploy`. 2. **InterwovenKit** connects your React frontend to the chain. Wrap your app in `InterwovenKitProvider`, use `useInterwovenKit` for wallet connection and `requestTxSync` for transactions. 3. **Chain connectivity** is handled by the Interwoven Stack. Your local rollup exposes RPC and REST endpoints, and the IBC Relayer enables cross-chain token transfers. For the full working example, check out the [Lotteria repository](https://github.com/yonnie-park/lotteria). Happy building. # Submission Requirements Source: https://docs.initia.xyz/hackathon/submission-requirements Use this page to prepare your final submission. Complete the required submission files and fill in any missing details before you submit. ## Requirements If you followed [Set Up Your Appchain](/hackathon/get-started) and completed one of the Blueprint tutorials, you likely already satisfy the first three requirements below: appchain deployment, frontend experience, and native feature. Use this section to verify those pieces and complete the required submission files. Your project should run as its own Initia appchain, with its own rollup identity and deployed application logic. Your frontend should use `InterwovenKit` for wallet connection and transaction flows so the app reflects the core Initia user experience. Your project should implement at least one supported Native Feature: * `auto-signing` * `interwoven-bridge` * `initia-usernames` Your repository should include: * `.initia/submission.json` * `README.md` at the repository root **Showcase your app's originality:** Projects that only reproduce a Blueprint without meaningful customization are not eligible for prizes. Your submission should include clear custom logic, UX, or product differentiation. ## Submission JSON Required file path: `.initia/submission.json` Use this exact structure: ```json title=".initia/submission.json" theme={null} { "project_name": "My Project", "repo_url": "https://github.com//", "commit_sha": "0123456789abcdef0123456789abcdef01234567", "rollup_chain_id": "my-game-1", "deployed_address": "0x...", "vm": "move", "native_feature": "auto-signing", "core_logic_path": "blockforge/sources/items.move", "native_feature_frontend_path": "blockforge-frontend/src/Game.jsx", "demo_video_url": "https://youtu.be/..." } ``` ## Submission JSON Field Reference All fields in `.initia/submission.json` are required. | Field | Expected value | | :----------------------------- | :----------------------------------------------------------------------------------------------------------------------- | | `project_name` | Non-empty string | | `repo_url` | Reachable public GitHub repository URL | | `commit_sha` | 40-character hex Git commit SHA | | `rollup_chain_id` | Non-empty string | | `deployed_address` | Primary deployed address for your application logic. Use your contract address, or your module address for Move projects | | `vm` | `move`, `evm`, or `wasm` | | `native_feature` | `auto-signing`, `interwoven-bridge`, or `initia-usernames` | | `core_logic_path` | Repo-relative file path that must exist at `commit_sha` | | `native_feature_frontend_path` | Repo-relative file path that must exist at `commit_sha` | | `demo_video_url` | Public Loom or YouTube URL for a 1 to 3 minute walkthrough video | ## Project Description Required file path: `README.md` at the repository root Copy this block near the top of your `README.md` and fill it in: ```markdown title="README.md" theme={null} ## Initia Hackathon Submission - **Project Name**: [Your Project Name] ### Project Overview [Provide a 2-3 sentence description of your application, the problem it solves, who it is for, and why it is valuable to users.] ### Implementation Detail - **The Custom Implementation**: Briefly describe the unique logic you added. What original functionality did you design and implement? - **The Native Feature**: Which Interwoven feature did you use, and exactly how does it improve the user experience? ### How to Run Locally [Provide 3-4 clear steps for a judge to run your frontend and connect it to a local environment if necessary.] ``` # Introduction Source: https://docs.initia.xyz/home/core-concepts/enshrined-liquidity/introduction Enshrined Liquidity is Initia’s solution to address some inherent challenges of the Proof of Stake (PoS) and rollup models. These challenges include: 1. Trade-offs between chain security and liquidity 2. Lack of capital efficiency 3. Liquidity fragmentation This solution allows governance-whitelisted InitiaDEX INIT-TOKEN liquidity positions to be used as staking assets with validators, in addition to the native INIT token. This approach helps alleviate the aforementioned issues in several ways. ## Maximizing Chain Security and Liquidity In traditional PoS models, token holders can stake their assets with validators to secure the chain and earn rewards. However, this creates a tradeoff: the more assets staked, the more secure the chain, but fewer assets are available as liquidity within the application layer. This tradeoff impacts both chain security and liquidity. By enabling liquidity positions to be staked, you can simultaneously increase the chain's security and promote liquidity growth while earning rewards from both staking and liquidity provision. ## Enhancing Capital Efficiency From your perspective, having to choose between staking assets and providing liquidity also means sacrificing either trading fees or staking rewards. If you aim to earn both rewards, you need to split your capital into multiple positions, reducing your overall capital efficiency. By using liquidity positions as staking assets, Enshrined Liquidity eliminates the need to choose between staking and liquidity provision. You can now earn both staking rewards and trading fees from a single position, leading to improved capital efficiency and a streamlined approach to capital allocation. # Whitelisting and Rewards Source: https://docs.initia.xyz/home/core-concepts/enshrined-liquidity/whitelisting-and-rewards ## Eligibility To be eligible for staking and earning rewards on InitiaDEX, L1 governance must whitelist the LP pair. Before whitelisting, the LP token must meet the following prerequisites: 1. The LP token must include INIT as part of its pair. 2. For Balancer pool positions, the INIT weight within the pool must be equal to or greater than 50%. ## Determining Rewards and Reward Weights When a new LP token $a$ is whitelisted, the proposal must also include a suggested reward weight $w_a$ for the token. This weight represents the relative amount of rewards allocated to the token per block compared to the overall distribution among all whitelisted tokens. Governance can later adjust this weight once the asset is whitelisted. To determine the distribution of rewards per token per block for a stakable asset $a$ among $N$ total stakable assets, we use the following formula that incorporates individual reward weights: $$ r_a = \frac{w_a \cdot r_{\text{total}}}{\sum_{i=1}^{N} w_i} $$ where: * $r_a$ represents the inflationary INIT rewards for the asset $a$. * $r_{\text{total}}$ denotes the total INIT rewards allocated for a given block. * $w_a$ is the governance-set reward weight parameter for the asset $a$. * $\sum_{i=1}^{N} w_i$ is the sum of reward weights for all $N$ whitelisted tokens. # Tokenomics Source: https://docs.initia.xyz/home/core-concepts/init-token/tokenomics ## Introduction Initia's native token, \$INIT, has a fixed supply of 1 billion (1,000,000,000) tokens. These tokens are split across eight major categories as outlined below. | Category | Amount | % of Supply | Vesting | | ----------------------------- | ------ | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Foundation | 77.5M | 7.75% | 50% upfront, remaining 50% vested every 6 months over 48 months | | Protocol Developers | 150M | 15.00% | 25% after 12 month cliff, remaining 75% linearly vested over 36 months | | Protocol Sales (Investors) | 152.5M | 15.25% | 25% after 12 month cliff, remaining 75% linearly vested over 36 months | | Enshrined Liquidity & Staking | 250M | 25.00% | 5% will be released each year on a block-by-block basis, with a slightly shortened schedule due to [accelerated emissions](https://forum.initia.xyz/t/inflation-correction-and-unstaking-subsidy-plan) in the first month. | | VIP Rewards | 250M | 25.00% | 7% released per year, linearly distributed over 12 months | | Binance Launch Campaign | 60M | 6.00% | 100% unlocked | | Airdrop | 50M | 5.00% | 100% unlocked | | Echo.xyz Community Sale | 10M | 1.00% | 25% of the total amount on the 12/15/18/24th month post TGE | ## Breakdown ### Foundation **77,500,000 INIT (7.75% of total supply)** The Initia Foundation's main goal is to advance the Interwoven Economy, help redefine the boundaries of multichain capabilities, and ensure a vibrant ecosystem of diverse applications. To this end, 7.75% of the total token supply is set aside for the Initia Foundation. This covers initial liquidity bootstrapping for Enshrined Liquidity, genesis validator delegations, and future strategic initiatives and ecosystem grants. ### Protocol Developers (Team) **150,000,000 INIT (15% of total supply)** Protocol developers, including current and future Initia team members and contributors, have been allocated 15% of the supply in aggregate. All recipients of tokens from this category are subject to a 4 year vesting period that includes a 12 month lock and a 36 month unlocking period. ### Protocol Sales (Investors) **Amount: 152,500,000 INIT (15.25% of total supply)** The Interwoven Economy's progress would not have been possible without the early backing of Initia by its investors. Across three total rounds of fundraises, Initia has maintained dilution to investors at 15.25% of the total supply. This marks a distinct departure from many other L1 chains with high investor allocations. Similar to tokens allocated to Protocol Developers, tokens in the Protocol Sales category are subject to a 4 year vesting period that includes a 12 month lock and a 36 month unlocking period. ### Enshrined Liquidity & Staking Rewards **250,000,000 INIT (25% of total supply)** At the core of the Interwoven Economy is Initia's Enshrined Liquidity mechanism, which replaces the typical L1 PoS system. In Enshrined Liquidity, capital is put to effective use through liquidity provision. Users can simultaneously provide L1 economic security while earning staking rewards, trading fees, and external ecosystem incentives allocated for voting in VIP gauge votes. Initially, EL & staking rewards have a block-by-block release rate of 5% per year (12,500,000 INIT per year). Due to a [governance proposal](https://forum.initia.xyz/t/inflation-correction-and-unstaking-subsidy-plan/201/10) to fix inflation rate, the overall emission schedule has been shortened slightly to stay within the 250M INIT cap. ### Vested Interest Program (VIP) Rewards **250,000,000 INIT (25% of total supply)** The Vested Interest Program is Initia's novel incentive mechanism that aligns the interests of all participants in the Interwoven Economy. This includes application end users, application builders, and L1 stakeholders. These rewards are wholly allocated to the community of users. VIP rewards are distributed in escrowed form and can be vested through maintaining VIP KPIs over several epochs. Similar to staking rewards, VIP rewards have an initial release rate of 7% per year (17,500,000 INIT per year). ### Binance Launch Campaign **60,000,000 INIT (6% of total supply)** For the initial CEX liquidity bootstrapping, 6% of the total supply is allocated towards Binance's Launch Campaign. ### Airdrop **50,000,000 INIT (5% of total supply)** Initia's airdrop distributes 50,000,000 INIT tokens (5% of the total network supply) to network testers, advocates, and early contributors. These tokens are immediately available on genesis for eligible participants to claim. ### Echo.xyz Community Sale **10,000,000 INIT (1% of total supply)** Tokens in this category have been allocated to the community of users who participated in Echo.xyz's investment round. Tokens in this category unlock in four equal tranches 12/15/18/24 months post-genesis. ## Release Schedule The monthly and annual release schedules for the Initia token for the first four years are shown below. **Annual Release Schedule** INIT Release Schedule Annual **Monthly Release Schedule** INIT Release Schedule Monthly # High Level Architecture Source: https://docs.initia.xyz/home/core-concepts/initia-and-rollups/high-level-architecture Initia's architecture is composed of three main components: * **Initia L1**: Initia L1 is the base layer and central liquidity hub for all Interwoven Rollups. * **Interwoven Rollups**: An ecosystem of blockchain rollups built atop Initia L1. * **Interwoven Stack**: Initia's framework for easily and painlessly building rollups and applications. ## Components ### Initia L1 Initia L1 is a Layer 1 blockchain designed to serve as the coordination layer and central hub for all Initia rollups. This layer provides essential services to rollups, including: * Network Security * Governance * Liquidity Solutions * Bridging and Interoperability ### Interwoven Rollups Interwoven Rollups are an ecosystem of Layer 2 blockchains built atop Initia L1, offering a scalable, customizable, and secure infrastructure for any application. Developers have the flexibility to deploy and customize their own rollup, tailoring various aspects such as: * Smart Contract Virtual Machine * Gas Tokens * Other Customizable Features ### The Interwoven Stack The [Interwoven Stack](/home/core-concepts/interwoven-stack) is Initia's framework for building rollups and applications. It offers a seamless, integrated experience for developers. The Interwoven Stack aims to simplify the process of building and operating blockchain applications by providing native, out-of-the-box solutions for common tasks. All the tools and features that appchain developers typically need are built directly into the core Interwoven Stack, making them accessible from day one. By reducing choice overload, Initia minimizes fragmentation and allows teams to concentrate on creating the best applications. # Initia L1 Source: https://docs.initia.xyz/home/core-concepts/initia-and-rollups/initia-l1 ## Overview Initia L1 is a custom-built Layer 1 blockchain that serves as the central coordination layer for all Interwoven Rollups. The L1 is built on the [Cosmos SDK](https://docs.cosmos.network) and is responsible for: 1. **Security**: Rollups leverage Initia L1's security for various purposes including token bridging, state commitments, and fraud proofs. 2. **Liquidity**: The [InitiaDEX](/home/core-concepts/initiadex) on L1 acts as a central liquidity hub for the ecosystem, providing a seamless experience for token liquidity, cross-rollup bridging, and swaps. 3. **Interoperability**: L1 functions as a central hub and router for rollups, enabling seamless communication and state transitions both between rollups and with the broader blockchain ecosystem. 4. **Incentives**: L1 powers various incentive schemes including the [Vested Interest Program (VIP)](/home/core-concepts/vip/introduction) and the [Enshrined Liquidity](/home/core-concepts/enshrined-liquidity/introduction). # Introduction Source: https://docs.initia.xyz/home/core-concepts/initia-and-rollups/rollups/introduction Interwoven Rollups are Layer 2 rollups built using Initia's [Interwoven Stack](/home/core-concepts/interwoven-stack/introduction). These rollups are scalable, highly interoperable, and fully customizable. * **Virtual Machines**: Rollup teams can choose among EVM, Move, or Wasm as the virtual machine for their rollup to best suit their application and needs. * **Gas Tokens & Fees**: Each rollup can choose its own gas token and fee structure. This can include INIT, stablecoins, their native token, or even multiple tokens. * **Transaction Ordering**: If needed, rollups can also implement their own transaction ordering mechanism. # EVM Compatibility Source: https://docs.initia.xyz/home/core-concepts/initia-and-rollups/rollups/vms/minievm/evm-compatibility-and-changes ## Compatibility The MiniEVM framework is compatible with all standard EVM developer workflows, tooling, and libraries that developers are already familiar with. This includes popular tools like [Foundry](https://github.com/foundry-rs/foundry), [Hardhat](https://hardhat.org/), and [Remix IDE](https://remix.ethereum.org/). However, there are minor differences in the way the MiniEVM operates that may require some adjustments to your existing development workflows. ## Changes ### General **EIP-1559 Transactions** MiniEVM currently does not support EIP-1559 transactions. This means that when using tools like Foundry to deploy or interact with contracts, or to generally send transactions, you will need to use the legacy transaction type. ### Cosmos SDK Integrations #### Token Representation By default, any new Cosmos coins created on the chain, whether they are fee denomination tokens, tokens minted via IBC, or other tokens created at genesis will also have an ERC20 representation on the MiniEVM. This allows developers and users to interact with these tokens using both the Cosmos Coin interface and messages, as well as the EVM ERC20 interface. #### Fee Tokens While the Cosmos SDK and rollup design supports multiple fee denominations on a single network, the MiniEVM's EVM module uses a single fee token denomination for all transactions. This denomination must be one of those set on the Cosmos side. Once set, the EVM fee denomination effectively becomes the equivalent of native tokens (e.g. ETH) on other EVM networks. This denomination will then be used for transaction fees sent via the EVM's JSON-RPC, as well as for any funds attached to EVM transactions via `msg.value`. However, as mentioned above, unlike other EVM networks, the MiniEVM's native token is also represented by an ERC20 interface. This means that for any transaction or logic, you can also interact with it using the ERC20 interface. ## Tool Compatibility ### Foundry **EIP-1559 Transactions** When using Foundry to deploy or interact with contracts, or to send transactions in general, you will need to use the legacy transaction type. This can be done by using the `--legacy` flag. **Precompiles and Foundry Scripts** Foundry's forge script feature always simulates all script transactions on a local standard EVM (without precompiles), and there is currently [no way to skip this simulation](https://github.com/foundry-rs/foundry/issues/5776). Consequently, any contract deployment or transaction that relies on MiniEVM precompiles will fail. # MiniEVM Introduction Source: https://docs.initia.xyz/home/core-concepts/initia-and-rollups/rollups/vms/minievm/introduction ## Overview MiniEVM is a variant of Initia's rollup framework with Ethereum Virtual Machine ([EVM](https://ethereum.org/en/developers/docs/evm/)) integration. With MiniEVM, developers can deploy and interact with Solidity and other EVM-based smart contracts just as they would on other EVM networks. All the tools such as wallets, explorers, and developer tools that you are familiar with also work out of the box with MiniEVM. In addition to EVM compatibility, MiniEVM provides a number of unique features, including: * **Cosmos Integration** * **Single Token Standard** * **IBC Compatibility** ## Cosmos Integration MiniEVM interacts with the Cosmos blockchain through a set of custom precompiles. This integration allows the EVM to: * **Read the underlying Cosmos chain state**: Access and read the state of the Cosmos blockchain directly from the EVM. * **Send Cosmos transactions**: Initiate and send transactions on the Cosmos blockchain. ### Notable Features * **Query native Connect price data**: Retrieve price data from the native Connect oracle. * **Query all tokens held by an account**: Obtain a comprehensive list of tokens held by a specific account. ## Single Token Standard MiniEVM revolves around a single token standard by implementing a custom Bank Interface that provides an ERC20 interface for all tokens on the chain. This includes: * **Native tokens**: Tokens that are native to the Cosmos blockchain. * **Fee-denom tokens**: Tokens used for transaction fees. * **Tokens bridged via IBC**: Tokens transferred through the Inter-Blockchain Communication (IBC) protocol. * **ERC20 tokens created on the rollup**: Standard ERC20 tokens created within the rollup framework. ### Benefits * **Unified balance querying**: Ability to query all tokens held by an account in a single query. * **Simplified token handling**: No need to handle different token standards in smart contracts, making development more straightforward. *** For more detailed information, please refer to the specific sections of this documentation. # MiniMove Introduction Source: https://docs.initia.xyz/home/core-concepts/initia-and-rollups/rollups/vms/minimove/introduction ## Overview MiniMove is a [MoveVM](https://move-language.github.io/move)-based variant of Initia's rollup framework, designed to support the deployment of and interaction with MoveVM smart contracts. Specifically, the MoveVM is based on the [Aptos variant](https://aptos.dev/en/build/smart-contracts) of the MoveVM. It includes additions and changes to improve performance and enable compatibility with the rollup's underlying Cosmos SDK stack and the wider Initia ecosystem. # MiniWasm Introduction Source: https://docs.initia.xyz/home/core-concepts/initia-and-rollups/rollups/vms/miniwasm/introduction ## Overview MiniWasm is a variant of Initia's rollup framework with [CosmWasm](https://cosmwasm.com/) integration, enabling developers to deploy and interact with CosmWasm smart contracts. # InitiaDEX Source: https://docs.initia.xyz/home/core-concepts/initiadex The InitiaDEX is a decentralized exchange (DEX) built on the Initia L1. It serves as a Balancer-style weighted pool for diverse asset pairs and a StableSwap pool for assets with closely correlated prices. This design ensures an optimal trading experience across various asset types. The DEX aims to be the central liquidity hub for all Interwoven Rollups, facilitating daily trading and more complex cross-rollup interactions and swaps. The InitiaDEX is essential for promoting the growth, stability, and alignment of the entire Initia ecosystem. To support these goals, the DEX features [Enshrined Liquidity](/home/core-concepts/enshrined-liquidity/introduction). This allows you to use certain governance-whitelisted liquidity pairs as staking assets for the Initia L1. # Introduction Source: https://docs.initia.xyz/home/core-concepts/interwoven-stack/introduction ## Overview The **Interwoven Stack** is Initia's comprehensive, all-in-one solution designed to empower developers and teams in building and deploying rollups with unmatched ease and efficiency. Historically, building a rollup requires developers to research, select, and piece together numerous components and services. These include: * Choosing the right scaling solution while considering VM compatibility for each option. * Sourcing or building wallets, explorers, bridges, and other essential tools. * Integrating various services such as oracles, bridges, fiat on-ramps, and more. All of these tasks divert time and resources from developers, preventing them from focusing on building their applications. The Interwoven Stack aims to address these challenges by focusing on the following key areas: 1. **Comprehensive Product Suite:** The Stack provides developers and teams with everything needed to launch and operate a rollup, including bridges, wallets, explorers, and a multi-VM compatible [rollup framework](/home/core-concepts/interwoven-stack/opinit-framework). 2. **Seamless Interoperability:** The tools built into the Stack facilitate easy communication for the rollup, whether it's between rollups, with Initia L1, or with other blockchain ecosystems. 3. **Enhanced Security:** Robust security measures are integrated into the Stack, providing a solid foundation for building secure and trustworthy applications. With this approach, developers can focus solely on building, improving, and shipping their applications. The Interwoven Stack handles the heavy lifting of selecting the right tools and components for a performant and secure rollup. # Challenger Source: https://docs.initia.xyz/home/core-concepts/interwoven-stack/opinit-framework/components/challenger The Challenger is a process distinct from the Executor, responsible for monitoring the Executor's output proposals and challenging any invalid submissions. This ensures the integrity of the rollup's state and prevents malicious actions by the Executor. The primary responsibilities of the Challenger include: 1. **Verifying Deposits**: * Ensure that the `MsgInitiateTokenDeposit` event is relayed correctly to the `MsgFinalizeTokenDeposit` event. * Check if `MsgInitiateTokenDeposit` was relayed within the required time frame. 2. **Verifying Oracle Updates**: * Confirm that Oracle data is correctly relayed to `MsgUpdateOracle`. * Ensure that Oracle updates are processed on time. 3. **Validating Outputs**: * Check that the `OutputRoot` submitted with `MsgProposeOutput` is accurate. * Ensure that the next `MsgProposeOutput` is submitted within the expected time frame. ## Detailed Architecture The Challenger architecture is designed to ensure that interactions between Initia (L1) and rollup (L2) are correctly validated, securing internal processes within the Initia ecosystem. Each part of the architecture is tailored to handle specific challenges while maintaining the security and reliability of the Initia-rollup interactions. ### Deposit Challenges Deposits from L1 to L2 must follow a strict verification process to ensure that tokens are correctly transferred between chains. The Challenger plays a critical role in this by confirming that `MsgInitiateTokenDeposit` is not only correctly triggered but also completed within a specific timeframe by matching it to `MsgFinalizeTokenDeposit`. This prevents potential discrepancies or fraud, ensuring that deposits are secure. When a `MsgInitiateTokenDeposit` event is detected on the L1 chain, it is recorded as a **Deposit** challenge. The system checks if it matches the `MsgFinalizeTokenDeposit` event for the same sequence. ```go theme={null} // Deposit is the challenge event for deposit data type Deposit struct { EventType string `json:"event_type"` Sequence uint64 `json:"sequence"` L1BlockHeight uint64 `json:"l1_block_height"` From string `json:"from"` To string `json:"to"` L1Denom string `json:"l1_denom"` Amount string `json:"amount"` Time time.Time `json:"time"` Timeout bool `json:"timeout"` } ``` ### Output Challenges **Outputs**, which represent state changes in the L2 chain, must be correctly submitted to maintain the synchronization between L1 and L2. The Challenger ensures that the OutputRoot of the submitted `MsgProposeOutput` matches the system’s expectations and that future proposals are made within the designated timeframe. This process prevents any incorrect or malicious outputs from being finalized, ensuring the integrity of the system. When a `MsgProposeOutput` event is detected on the L1 chain, it triggers an **Output** challenge. The system replays up to the L2 block number and verifies whether the `OutputRoot` matches the one submitted. ```go theme={null} // Output is the challenge event for output data type Output struct { EventType string `json:"event_type"` L2BlockNumber uint64 `json:"l2_block_number"` OutputIndex uint64 `json:"output_index"` OutputRoot []byte `json:"output_root"` Time time.Time `json:"time"` Timeout bool `json:"timeout"` } ``` ### Oracle Challenges Oracles serve as external data providers for the blockchain, and any failure in updating their data can lead to inaccuracies within the system. The Challenger ensures that oracle updates happen in a timely manner and are properly relayed from L1 to L2 through `MsgUpdateOracle`, safeguarding the accuracy of external data within the Initia ecosystem. If the `oracle_enable` setting is turned on in bridge config, the 0th transaction's bytes are saved as an **Oracle** challenge event. This data is verified against the `MsgUpdateOracle` for the same L1 height. ```go theme={null} // Oracle is the challenge event for oracle data type Oracle struct { EventType string `json:"event_type"` L1Height uint64 `json:"l1_height"` Data []byte `json:"data"` Time time.Time `json:"time"` Timeout bool `json:"timeout"` } ``` ### Rollback Challenges (TBA) If a challenge is created and the event is not finalized within the timeout period, it is possible to rollback before the challenge is finalized. This feature will be announced in a future release. # Executor Source: https://docs.initia.xyz/home/core-concepts/interwoven-stack/opinit-framework/components/executor The OPinit Bot Executor is a critical component in maintaining the communication and operational integrity between the Initia L1 and rollup blockchains. It handles and automates key tasks related to the OPinit Bridge, which facilitates cross-chain interactions and ensures that both blockchains remain synchronized and secure. The primary responsibilities of the Executor include: 1. **Executing Token Transfers:** Executing token transfers between Initia L1 and a rollup 2. **Submitting Output Proposals:** Submitting output proposals to the Initia L1 3. **Transaction Batch DA Submission:** Submitting rollup transaction batches to the DA layer 4. **Relaying Oracle Update (Optional):** Relaying oracle price feed updates to the rollup ## Detailed Architecture ### Transfer Token from L1 to L2 (Deposit) The token deposit process begins when a user submits a deposit transaction on the Initia L1 chain. Once the transaction is confirmed, the Bridge Executor retrieves the latest block data (including the deposit) from the L1 node. It then submits a message to the rollup node to finalize the deposit. After the L2 node confirms the finalized deposit, it mints the corresponding opINIT tokens on the specified rollup. ```mermaid theme={null} sequenceDiagram participant User participant IL1 as Initia L1 participant OPH as OPhost Module participant OPB as OPinit Bot participant OPC as OPchild Module participant R as Rollup User->>IL1: Initiate token deposit IL1->>OPH: Process deposit OPH->>OPB: Emit deposit event OPB->>OPB: Process deposit event OPB->>OPC: Relay deposit transaction OPC->>R: Finalize deposit R->>R: Mint tokens to user on L2 ``` ### Transfer Token from L2 to L1 (Withdrawal) The token withdrawal process begins when a user submits a withdrawal transaction on the rollup. Once the transaction is confirmed, the Bridge Executor retrieves the latest block data (including the withdrawal) from the L2 node. It then submits a message to the Initia L1 node to finalize the withdrawal. After the L1 node confirms the finalized withdrawal, it burns the corresponding opINIT tokens on the specified rollup. The withdrawal then enters a withdrawal period during which the transaction can be challenged and potentially canceled. If no challenge is submitted by the end of this period, the user can claim the withdrawal on Initia L1. ```mermaid theme={null} sequenceDiagram participant User participant R as Rollup participant OPC as OPchild Module participant OPB as OPinit Bot participant OPH as OPhost Module participant IL1 as Initia L1 User->>R: Initiate token withdrawal R->>OPC: Process withdrawal request OPC->>OPC: Lock tokens and emit event OPC->>OPB: Notify of withdrawal event OPB->>OPB: Update Merkle tree OPB->>OPH: Submit updated L2 output root OPH->>IL1: Store L2 output root Note over OPB,IL1: Wait for finalization period User->>OPB: Request withdrawal proof OPB->>OPB: Generate Merkle proof OPB->>User: Provide withdrawal proof User->>IL1: Submit proof & finalize withdrawal IL1->>OPH: Verify proof OPH->>IL1: Approve token release IL1->>User: Transfer withdrawn tokens ``` The withdrawal period is designed to allow for a challenge period during which any malicious activity can be detected and addressed. If a challenge is submitted, the withdrawal is canceled. If no challenge is submitted, the transaction is finalized and the tokens are released to the user on Initia L1. ### Oracle Updates The executor process is, when enabled on the rollup, also responsible for relaying the latest [Connect](https://github.com/skip-mev/connect) oracle data to the rollup. When relayed, the bot submits a `MsgUpdateOracle` to the L2 node. ```mermaid theme={null} sequenceDiagram participant SO as Connect Oracle participant ORM as Oracle Module (L1) participant IL1 as Initia L1 participant OPB as OPinit Bot participant OPC as OPchild Module participant R as Rollup loop Continuous update cycle SO->>ORM: Update oracle data ORM->>IL1: Store updated data IL1->>OPB: Emit oracle update event OPB->>ORM: Read new oracle data OPB->>OPC: Relay oracle data OPC->>R: Update L2 oracle state end ``` ### DA Batch Submission Lastly, the Executor is responsible for batching and submitting transaction data to Celestia. ```mermaid theme={null} sequenceDiagram participant R as Rollup participant OPC as OPchild Module participant OPB as OPinit Bot participant DA as Data Availability Layer participant IL1 as Initia L1 loop For each L2 block R->>OPC: Generate block OPC->>OPB: Provide block data OPB->>OPB: Compress and batch data OPB->>DA: Submit batched data DA->>DA: Store data and generate proof OPB->>IL1: Submit DA proof (if required) end ``` # Introduction Source: https://docs.initia.xyz/home/core-concepts/interwoven-stack/opinit-framework/components/introduction The OPinit Framework consists of three main components: the OPinit Bridge, the Executor, and the Challenger. ## OPinit Bridge The [OPinit Bridge](/home/core-concepts/interwoven-stack/opinit-framework/components/opinit-bridge) is a set of Cosmos SDK modules that enable the transfer of INIT and other tokens between the Initia L1 and rollup L2 using an optimistic bridge model. ## OPinit Bots The OPinit Bots are a set of processes responsible for executing and monitoring the various actions necessary to operate and secure the rollup. Currently, there are two bots in this system: the Executor and the Challenger. ### Executor The [Executor](/home/core-concepts/interwoven-stack/opinit-framework/components/executor) is a set of processes responsible for executing the various actions necessary to operate and secure the rollup. These include: * **Token Transfers**: The Executor handles the OPinit Bridge token deposits and withdrawals between Initia L1 and the various rollups. * **Output Submission**: The Executor submits the rollup's transaction outputs to the Initia L1 to finalize the rollup's state. * **DA Batch Submission**: The Executor submits the rollup's transaction batches to the Celestia DA layer. * **Oracle Data**: The Executor can be configured to relay the Connect oracle price data on the Initia L1 to the rollup L2 for its applications to use. ### Challenger The [Challenger](/home/core-concepts/interwoven-stack/opinit-framework/components/challenger) is a process separate from the Executor, responsible for monitoring the Executor's output proposals and challenging any invalid proposals. This helps maintain the integrity of the rollup's state and ensure that the Executor is not acting maliciously. # OPinit Bridge Source: https://docs.initia.xyz/home/core-concepts/interwoven-stack/opinit-framework/components/opinit-bridge ## Overview The OPinit Bridge is an implementation of the optimistic rollup bridge, implemented as two Cosmos SDK modules; the **OPchild Module** and the **OPhost Module**. ## OPhost Module The OPhost Module is integrated into the Initia L1 chain. This module is responsible for: * **Bridge Management:** Creating, updating, and managing bridges between Initia L1 and rollups. * **Output Proposal Handling:** Managing and finalizing L2 output proposals. ## OPchild Module The OPchild Module acts as a counter-party to the OPhost Module and is integrated into all Interwoven Rollup implementations. This module is responsible for: * **Operator Management:** Adding, removing, and managing operators for a given rollup. * **Bridge Message Execution:** Processing messages received from the Initia L1. * **Oracle Updates:** Managing oracle price feed updates relayed by the OPinit Executor. The [OPinit Bot Executor](/home/core-concepts/interwoven-stack/opinit-framework/components/executor) normally handles actions related to both of these modules. # Minitswap Architecture Source: https://docs.initia.xyz/home/core-concepts/minitswap/architecture ## Goals * **Manipulation Resistance**: The architecture of the rollup and related systems themselves already has safeguards in place to prevent various forms of manipulation from malicious actors. The Minitswap DEX is further designed to ensure that, in unforeseen events, any subsequent damages are minimized. * **Capital Efficiency**: As the number of rollups continues to increase, naively, the same number of DEX pairs must also exist. This results in liquidity fragmentation, high slippage and volatility, and subpar user experience. ## Design Minitswap itself is designed as a virtual pool DEX between INIT and the various IbcOpINIT tokens for each of the rollups. The [StableSwap](https://docs.curve.finance/stableswap-exchange/overview/) formula determines the exchange rates on each swap. To achieve the above goals, Minitswap makes two main improvements to the base StableSwap pool design: * **Rate Limiting**: To protect against manipulation, the net amount of IbcOpINIT tokens that can be swapped back into INIT tokens is limited. This means that even if a malicious actor acquires or creates a large amount of IbcOpINIT tokens on their rollup, the number of tokens that can be swapped back into regular INIT tokens remains restricted. * **Single INIT Token Pool**: To minimize liquidity fragmentation, there is a single INIT token pool that can be paired with multiple IbcOpINIT token pools, instead of having separate INIT token pools for each rollup. ## Swap Mechanisms ### Initia L1 to Rollups Initia L1 to Rollups Minitswap Flow In this scenario, a user wants to efficiently bridge their $INIT$ tokens on the Initia L1 to a rollup $m$ and ends up with the $OpINIT_m$ token for that rollup. And while bridging from Initia L1 to a rollup is instantaneous, users may occasionally be able to obtain a more favorable rate by utilizing Minitswap as part of the bridging process as shown below. 1. **Initiate Swap on Minitswap DEX**: The user sends a transaction to the Minitswap DEX to swap their $INIT$ tokens into $IbcOpINIT_m$ tokens. 2. **Simulate Swap**: The DEX simulates swapping the user’s $INIT$ tokens into $IbcOpINIT_m$ tokens. 3. **Compare Swap and Direct Bridging**: The DEX compares the simulated amount of $IbcOpINIT_m$ tokens with the amount the user would receive if they bridged directly through the OP Bridge. 4. **Perform Optimal Action** * If the amount of $IbcOpINIT_m$ tokens from the swap is greater, the DEX performs the swap. The output $IbcOpINIT_m$ tokens are then bridged to the destination L2 through IBC. * If the direct bridging through the OP bridge provides a better amount, the DEX initiates a direct transfer to the destination rollup $m$ for the user using the OP bridge. 5. **Minitswap Swap Process** * **Calculate $IbcOpINIT_m$ Received**: Minitswap calculates how much $IbcOpINIT_m$ the user will receive based on the current Virtual Pool state, updating the state in the process. * **Fee Deduction**: Minitswap deducts a fee based on a predefined value and an additional fee from any extra $IbcOpINIT_m$ that the user receives. * **Peg Keeper Swap Check**: Once the user’s swap action and fee calculation are complete, Minitswap checks if a [Peg Keeper Swap](#peg-keeper-swaps) should be performed based on the latest Virtual Pool state. * **Internal Rebalancing Check**: After completing the Peg Keeper Swap, Minitswap checks if [Internal Rebalancing](#internal-rebalancing) is possible based on the Peg Keeper’s $IbcOpINIT$ balance. If balancing is possible, it is initiated. 6. **Final Outcome**: In both cases, once the OP Bridge or IBC transfer is complete, the user receives the most amount of $OpINIT_m$ tokens in their wallet on the destination rollup possible. ### Rollup to Initia L1 Rollup to Initia L1 Minitswap Flow When bridging from a rollup to Initia L1, the user is currently holding $OpINIT_m$ tokens on a rollup $m$ and would like to bridge it back to $INIT$ tokens on the Initia L1. In this scenario, utilizing Minitswap will enable them to bridge their INIT back to the Initia L1 instantaneously without waiting for the challenge period to expire. 1. **Transfer to Initia L1 via IBC**: The user begins by transferring their $OpINIT_m$ tokens on the rollup $m$ back to Initia L1 using IBC. As a result, they receive $IbcOpINIT_m$ tokens on the Initia L1. 2. **Swap on Minitswap DEX**: Once the IBC transfer is complete and the user has $IbcOpINIT_m$ tokens on Initia L1, they initiate a swap transaction on the Minitswap DEX to convert their $IbcOpINIT_m$ tokens into $INIT$ tokens. 3. **Minitswap Swap Process** * **Peg Keeper Swap Check**: Minitswap first checks if a Peg Keeper Swap can be performed. If this is possible, the swap is executed directly through the Peg Keeper. * **Calculate $INIT$ Received**: If the Peg Keeper Swap is not applicable, Minitswap calculates the amount of $INIT$ the user will receive based on the updated state of the Virtual Pool. * **Fee Deduction**: Minitswap deducts a predefined fee amount from the transaction. * **Internal Rebalancing Check**: After completing the user’s swap transaction, Minitswap checks if [Internal Rebalancing](#internal-rebalancing) is possible based on the Peg Keeper’s $IbcOpINIT$ balance. If balancing is possible, it is executed to maintain market stability. 4. **Final Outcome**: If the swap is successful, the user receives $INIT$ tokens in their wallet on Initia L1. ### Direct Swap In addition to the standard directional swap explained above, Minitswap also offers a unique **Direct Swap** option. As more [Peg Keeper Swaps](#peg-keeper-swaps) are performed, the Peg Keeper's $INIT$ balance decreases. The Direct Swap aims to incentivize users to help replenish the Peg Keeper's $INIT$ token balance, which gets depleted over time. This serves as an additional method of replenishing the Peg Keeper's $INIT$ balance alongside the [Internal Rebalancing](#internal-rebalancing). The Direct Swap allows any user to directly exchange their $INIT$ tokens for the Peg Keeper’s $IbcOpINIT$ tokens. This exchange occurs at the average price at which the Peg Keeper purchased $INIT$ tokens. This price could sometimes be lower than what you would get through the traditional swap process. Initially, the Direct Swap might not seem attractive due to the Target Ratio being close to 0.5. However, as the Peg Keeper’s balance of OP-bridged tokens increases, the Direct Swap option becomes more appealing to users. ## Swap Logic ### Parameters * **Max Ratio**: The Max Ratio, $R_{max}$, is an Initia L1 governance-controlled parameter that dictates the maximum pool ratio between IbcOpINIT and regular INIT. * **Fully Recovered Ratio**: The Fully Recovered Ratio, $R_{fr}$, then uses the Max Ratio and the Flexibility to calculate the final target IbcOpINIT:INIT ratio for the pool. The ratio is calculated as follows: $$ R_{fr}=0.5+(R_{max}-0.5) \cdot \frac{(fI)^3}{(1+|fI|^3)} $$ ### Mechanisms #### Peg Keeper Swaps Peg Keeper Swaps The Peg Keeper Swap is a mechanism designed to keep the exchange rate between $INIT$ and $IbcOpINIT$ close to 1:1. This ensures that users always receive the best swap rates. When users move their INIT tokens from a rollup back to Initia L1 using Minitswap, they are essentially selling their $IbcOpINIT$ tokens for $INIT$ tokens. As more users do this, the supply of $IbcOpINIT$ increases relative to $INIT$, which raises the price of future rollup -> Initia L1 swaps. To address this, the Peg Keeper Swap executes a ($INIT$ -> $IbcOpINIT$) swap to balance the effect. When a user makes a swap, Minitswap checks the Fully Recovered Ratio against the current pool ratio. If the current ratio exceeds the Fully Recovered Ratio, a Peg Keeper Swap is triggered to restore balance. When run, the Peg Keeper swap follows this procedure: 1. Calculate the current $R_{fr}$ and the `max_recover_amount`, which defines the maximum size of the Peg Keeper Swap that can be performed in this swap. This is to prevent a huge Peg Keeper Swap from happening. 2. Check if another Peg Keeper Swap has been run in the same block. Continue if no swaps have been run. 3. Calculate the $INIT$ amount the Peg Keeper needs to reach $R_{fr}$. Let's call this `swap_amount_to_reach_fr`. 4. Check if `swap_amount_to_reach_fr > max_recover_amount` * If true, swap only `max_recover_amount`. * If false, swap `swap_amount_to_reach_fr` Note that the Peg Keeper Swap check is done * *before* an L2 -> L1 swap to make sure the user gets the best rate possible * *after* an L1 -> L2 swap to make sure the user's swap rate doesn't get affected by the Peg Keeper Swap #### Internal Rebalancing Internal Rebalancing As more Peg Keeper Swaps are performed, the $INIT$ balance of the Peg Keeper gradually decreases. To replenish its $INIT$ balance, the system has an internal rebalancing procedure that converts the Peg Keeper's $IbcOpINIT$ back into $INIT$ using IBC and OP Bridge. The rebalancing process follows these steps: 1. Bridge the Peg Keeper's $IbcOpINIT_m$ back to the rollup $m$ using IBC, converting it into $OpINIT_m$. 2. Use the OP Bridge to convert $OpINIT_m$ back into $INIT$. This process, combined with the [Direct Swap](#direct-swap), ensures that the Peg Keeper's $INIT$ balance is replenished, allowing it to continue performing Peg Keeper Swaps. # Minitswap Introduction Source: https://docs.initia.xyz/home/core-concepts/minitswap/introduction Minitswap is Initia's proprietary solution to address the user experience challenges posed by the lengthy withdrawal [challenge periods](https://docs.optimism.io/builders/app-developers/bridging/messaging#understanding-the-challenge-period) of [optimistic bridges](https://medium.com/connext/optimistic-bridges-fb800dc7b0e0). Furthermore, while a longer challenge period increases the duration in which a challenge can be made, it simultaneously increases the wait time required for withdrawals. ## Motivation While optimistic token bridges between a Layer 1 (L1) and a Layer 2 (L2) chain provide a secure way of transferring assets between chains, it comes with various downsides. * **Long Withdrawal Times**: Transferring tokens from L1 to L2 is usually instantaneous, but the reverse direction involves long wait times, often days, before receiving assets on L1. * **Single Sequencer Risks**: Creating a DEX pair between the original token on L1 and the bridged tokens can mitigate long withdrawal times. However, most L2s currently operate with a single sequencer, raising security, reliability, and centralization concerns for liquidity providers. * **Lack of Liquidity**: The sequencer risk issues can result in insufficient liquidity in the token pool, leading to unfavorable swap prices, high volatility, and significant [slippage](https://www.coinbase.com/learn/crypto-glossary/what-is-slippage-in-crypto-and-how-to-minimize-its-impact#:~:text=Understanding%20Slippage%20in%20Crypto\&text=It%20refers%20to%20the%20difference,placed%20and%20when%20it's%20executed.) for users bridging tokens back to L1. ## Solution The Minitswap DEX is designed to let you freely, quickly, and efficiently bridge tokens between Initia L1 and rollups. If you want to bridge back to Initia L1 from a rollup, you can use Minitswap (along with IBC) to swap your tokens back to INIT without waiting for the challenge period to expire. The full architecture, design decisions, and how the above risks are mitigated are detailed in the following section. # Minitswap Terminology Source: https://docs.initia.xyz/home/core-concepts/minitswap/terminology ## INIT Token Variants | Term | Definition | | ----------- | ---------- | | $INIT$ | | | $m$ | | | $OpINIT$ | | | $IbcOpINIT$ | | ## Bridges | Term | Description | | ------------- | ----------- | | IBC Bridge | | | OPINIT Bridge | | ## Actors | **Term** | **Description** | | ---------------------- | --------------- | | **Virtual Pool** | | | **Liquidity Provider** | | | **Peg Keeper** | | | **User** | | ## Parameters | Symbol | Term | Description | | --------- | -------------------------------------- | ----------- | | $V$ | Virtual Pool size | | | $B$ | Peg Keeper's $IbcOpINIT$ token balance | | | $I$ | Virtual Pool imbalance | | | $R_{fr}$ | Fully Recovered Ratio | | | $R_{max}$ | Max Ratio | | | $f$ | Flexibility | | # VIP Architecture Source: https://docs.initia.xyz/home/core-concepts/vip/architecture At genesis, the protocol sets aside a portion of the total INIT token supply as rewards for the VIP program, distributing them over several years. Let's call this portion of the supply $R$. These rewards are given out at regular intervals, or **stage** $t$, throughout the distribution period. The system first distributes total rewards to each rollup, then subsequently to the rollup's users and operators. Before a rollup can qualify for VIP rewards, it must first achieve a minimum INIT TVL and then be whitelisted by the Initia L1 governance through an on-chain proposal. See the [VIP Eligibility](/home/core-concepts/vip/eligibility) page for more details. For details on the specific VIP parameters such as stage and cycle duration, see the [VIP Parameters](/resources/developer/initia-l1#vip-parameters) section. ## Rewards Distribution At each rewards distribution stage $t$, the total VIP rewards for that stage $R_t$ are distributed amongst each rollup ecosystem. The distribution is split into multiple steps: 1. Splitting the total rewards allocated for that stage, $R_t$, between all whitelisted rollups. 2. Distributing the rewards to each rollup's users. 3. Distributing the rewards to each rollup's operators. ### Rewards Split Between Rollups At each stage $t$, the total VIP rewards for that stage $R_t$ are distributed amongst each rollup ecosystem. The total rewards are then split into two pools: the **Balance Pool $R_B$** and the **Weight Pool $R_W$**. VIP Rewards Distribution These two pools aim to incentivize and reward different aspects of rollup operations. The ratio between $R_B$ and $R_W$, called `poolSplitRatio`, is set by the Initia L1 governance and can be changed through on-chain proposals. The sum follows the equation: $$ R_t = R_B + R_W $$ The rewards for each rollup $m$ are then calculated as follows: $$ R_{m,t} = R_{B,m,t} + R_{W,m,t} $$ Where: * $R_{B,m,t}$ represents the portion of rewards from the Balance Pool $R_B$ allocated to rollup $m$ at stage $t$. * $R_{W,m,t}$ represents the portion of rewards from the Weight Pool $R_W$ allocated to rollup $m$ at stage $t$. #### Balance Pool The Balance Pool aims to encourage rollups to find new and interesting uses for the INIT token by distributing rewards based on the proportion of INIT supply on the rollup. Specifically, at each stage $t$, the rewards are allocated according to the amount of INIT locked on each rollup's OPinit bridge address $m$ relative to the total amount locked across all rollups. $$ R_{B,m,t} = R_{B,t} \frac{I_{m,t}}{\sum_{i=1}^{N,t} I_{i,t}} $$ Where: * $R_{B,t}$ is the total rewards from the Balance Pool for the stage. * $I_{m,t}$ is the amount of INIT tokens locked by rollup $m$ during the stage. * $N_{t}$ is the total number of rollups in the stage. #### Weight Pool The Weight Pool ($R_W$) rewards rollups based on their weight value, which is determined by a gauge weight voting process similar to protocols such as Curve's. $$ R_{W,m,t} = R_{W,t} \frac{W_{m,t}}{\sum_{i=1}^{N,t} W_{i,t}} $$ Where: * $R_{W,t}$ is the total rewards from the Weight Pool for the stage. * $W_{m,t}$ is the weight of rollup $m$ during the stage. * $N_{t}$ is the total number of rollups in the stage. ### Distribution to Rollup Users Once the rewards each rollup receives for a given stage are known, these rewards are then further distributed to the users of the rollup. The rollup team defines each user's VIP reward amount through a scoring methodology. The scoring method could be based on factors such as: * Number of transactions a user makes on the rollup. * Value of assets a user borrows. * Trading volume or liquidity provided by the user. VIP User Rewards Distribution At the end of each stage, the rewards for each user are calculated and stored. Once the rewards for each rollup are known, the rewards are then directly distributed to the users of the rollup. If a user $u$ on rollup $m$ has a score of $S_{u,m,t}$, their rewards are: $$ R_{u,m,t} = R_{m,t} \frac{S_{u,m,t}}{\sum_{i=1}^{N_{u,m,t}} S_{i,m,t}} $$ Where: * $R_{m,t}$ is the total rewards from the VIP program for the stage. * $S_{u,m,t}$ is the score of the user on rollup $m$ during stage $t$. * $N_{u,m,t}$ is the total number of users on rollup $m$ during stage $t$. ### Distribution to Rollup Operators To ensure that rollup operators are also incentivized to keep their rollups active and useful, they can set an `operatorCommissionRate`, $c$. This rate allows them to take a portion of the rewards for their rollup. VIP Operator Rewards
Distribution The rewards for an operator $o$ of rollup $m$ during a stage are: $$ R_{o,m,t} = R_{m,t} c_{m} $$ The commission rate is set when the rollup is first approved for VIP rewards and can be changed later, but only by a fixed amount each stage to prevent abuse. Taking into account the operator commissions, the total rewards distributed to a user on a rollup is then: $$ R_{u,m,t} = (1-c_{m}) R_{m,t} \frac{S_{u,m,t}}{\sum_{i=1}^{N_{u,m,t}} S_{i,m,t}} $$ ## Rewards Vesting Rewards from the VIP program are given in the form of escrowed INIT tokens (esINIT). These tokens are initially non-transferable and can be vested in multiple ways depending on whether the receiver is the user or rollup operator. ### User Vesting These tokens are initially non-transferable and can be vested in two ways: 1. **Maintain a VIP Score:** Keep a certain score over a number of `vestingPeriod`, with each period lasting `stageDuration`. 2. **Convert into LP Lock-Staked Position:** Convert the escrowed tokens into a whitelisted INIT:TOKEN staking position. VIP User Vesting #### Maintaining a VIP Score **Vesting Process** VIP esINIT rewards are converted into regular INIT tokens over multiple `vestingPeriod`, denoted as $p$, with each period lasting one stage. For instance, if the vesting period is 26 stages, the user will receive $\frac{1}{26}$ of their esINIT at each stage. **Achieving the Required Score** To fully convert their rewards into INIT tokens, users must maintain a certain score over the vesting periods, $p$, as determined by Initia L1 governance. The minimum required score is set by a `threshold` factor $f$, also determined by the L1 governance. The score calculation is as follows: $$ S_{\text{target},m,t} = S_{u,m,t} \cdot f $$ Where: * $S_{u,m,t}$ is the user's score on rollup $m$ during stage $t$. * $S_{\text{target},m,t}$ is the target score for rollup $m$ during stage $t$. **Calculating the Target Score** The target score $S_{\text{target},m,t}$ is the user's score for stage $t$ multiplied by the factor $f$. For example, if a user $u$ has a score of 100 at stage $t$, their target score to fully vest their esINIT after $p$ stages is $100 \cdot f$. **Failing to Meet Target Score** If a user fails to meet the target score at a certain stage $t$, they will only vest and receive a portion of their esINIT, calculated by the formula: $$ c_{\text{user}} = \frac{S_{u,m,t}}{S_{\text{target},m,t}} $$ For instance, if $f$ is 0.5, a user with a score of 100 must maintain a score of at least $S_{\text{target},m,t} = 100 \cdot 0.5 = 50$ for the next $p$ stages to fully vest their esINIT. If after $p$ stages, their score $S_{u,m,t}$ is only 30, their $c_{\text{user}}$ will be $\frac{30}{50} = 0.6$, and they will only be able to vest 60% of their esINIT. **Example Scenario** Parameters * **Vesting Period ((p))**: 50 stages * **Minimum Score Factor ((f))**: 0.5 Stage 1 ((t = 1)) * **User Score**: 100 * **esINIT Received for Stage 1**: 100 * **Vesting Rate**: $\frac{100 \text{ esINIT}}{50 \text{ stages}} = 2 \text{ INIT per stage}$ Stage 2 ((t = 2)) * **Minimum Score Needed from Stage 1**: $100 \times 0.5 = 50$ * **User Score**: 60 * **Vesting from Stage 1**: Since $60 \geq 50$, the user vests the full 2 INIT * **Vesting Rate for Stage 2**: $\frac{60 \text{ esINIT}}{50 \text{ stages}} = 1.2 \text{ INIT per stage}$ * **esINIT Received for Stage 2**: 60 Stage 3 ((t = 3)) * **Minimum Score Needed from Stage 1**: $100 \times 0.5 = 50$ * **Minimum Score Needed from Stage 2**: $60 \times 0.5 = 30$ * **User Score**: 40 * **Vesting from Stage 1**: Since $40 < 50$, the user vests $\frac{40}{50} \times 2 = 1.6 \text{ INIT}$ * **Vesting from Stage 2**: Since $40 \geq 30$, the user vests the full 1.2 INIT * **Total Vesting for Stage 3**: $1.6 \text{ INIT (from Stage 1)} + 1.2 \text{ INIT (from Stage 2)} = 2.8 \text{ INIT}$ Summary Table | Stage | User Score | esINIT Received | Vesting Rate (per stage) | Min Score Needed | Actual Vesting | | ----- | ---------- | --------------- | ------------------------ | -------------------------- | -------------------- | | 1 | 100 | 100 | 2 INIT | - | - | | 2 | 60 | 60 | 1.2 INIT | 50 (Stage 1) | 2 INIT | | 3 | 40 | - | - | 50 (Stage 1), 30 (Stage 2) | 1.6 + 1.2 = 2.8 INIT | Explanation 1. **Stage 1**: The user scores 100 and receives 100 esINIT, which will be unlocked at a rate of 2 INIT per stage over 50 stages. 2. **Stage 2**: The user needs to score at least 50 to unlock the full 2 INIT from Stage 1. They score 60, so they unlock the full 2 INIT and receive 60 esINIT for Stage 2, which will be unlocked at a rate of 1.2 INIT per stage. 3. **Stage 3**: The user needs to score at least 50 to unlock the full 2 INIT from Stage 1 and at least 30 to unlock the full 1.2 INIT from Stage 2. They score 40, so they unlock 1.6 INIT from Stage 1 and the full 1.2 INIT from Stage 2, totaling 2.8 INIT. #### Converting to LP Lock-Staked Position Maintaining the score over several periods can be challenging for some users. Therefore, VIP allows you to convert your esINIT into a locked, stake-locked INIT:TOKEN LP position on the InitiaDEX for pairs whitelisted on Enshrined Liquidity. You provide the TOKEN side of the pair. When creating a lock-staked position, users can choose the duration for locking their LP position. The length of this lock will determine their voting power on VIP gauge votes. However, when lock-staking through VIP, a minimum lock duration of 26 weeks is enforced. ### Operator Vesting VIP Operator Vesting Similarly, rollup operators' esINIT rewards are also vested, but the process is slightly different. Operator esINIT rewards are released linearly over a number of `operatorVestingStages`. For example, if the operator vesting period consists of 10 stages, the operator will receive $\frac{1}{10}$ of their esINIT at each stage. # VIP Eligibility Source: https://docs.initia.xyz/home/core-concepts/vip/eligibility For a rollup and its users to be eligible for VIP rewards, they first need to be whitelisted. The whitelisting process comprises 2 steps: 1. Reaching the minimum INIT TVL threshold 2. Whitelisting via Initia L1 governance ## Minimum INIT TVL Threshold To be considered for whitelisting on VIP, rollups must first meet a minimum INIT TVL (Total Value Locked) threshold. * Rollups that somehow manage to get whitelisted without reaching the minimum INIT TVL threshold will still not be eligible for rewards until they meet this requirement. * Rollups that have been whitelisted and successfully reached the minimum INIT TVL threshold will forfeit any VIP rewards if their TVL subsequently falls below this threshold. ## Governance Whitelisting Once the minimum INIT TVL threshold is reached, the rollup needs to then submit a whitelisting proposal to the Initia L1 governance. As with all governance proposals, INIT and Enshrined Liquidity stakers vote on the whitelisting proposal. The following types of rollups are unlikely to be approved:
  • Rollups that add little value to the ecosystem, such as rollups that only accumulate TVL with no productive use case
  • Rollups that exist solely to allow the corresponding app to qualify for VIP rewards, such as rollups where the app is otherwise completely off-chain
# VIP Gauge Voting Source: https://docs.initia.xyz/home/core-concepts/vip/gauges To decide how much of the total [Weight Pool](/home/core-concepts/vip/architecture#weight-pool) rewards each rollup receives in a given stage, the system uses a gauge weight voting process. This is similar to the one pioneered by Curve Finance for use with their liquidity pools. ### Voting Cycles Voting on VIP gauges occurs at regular intervals called **cycles**. Every VIP-whitelisted rollup has a "gauge" that determines the ratio of total Weight Pool rewards it can receive. INIT and Enshrined Liquidity stakers can then use their voting power to increase the weight of the gauges for their preferred rollups. They can allocate their entire voting power to a single rollup's gauge or distribute it across multiple gauges. All gauge voting occurs on Initia L1. ### Gauge Voting Power For VIP Gauge Votes, a user's voting power depends on their staking position. For INIT staking, their VIP voting power matches their voting power in the Initia L1 governance. However, for Enshrined Liquidity staking positions, the system applies an adjustment factor to their voting power. This adjustment factor varies for each staked LP token pair. #### Example Scenario Consider a case with 3 users and 3 rollups: | User | Total Voting Power | | ------ | ------------------ | | User 1 | 30% | | User 2 | 50% | | User 3 | 20% | Each user decides to vote on the gauges as follows: | User | Rollup 1 Gauge | Rollup 2 Gauge | Rollup 3 Gauge | | ------ | -------------- | -------------- | -------------- | | User 1 | 10% | 15% | 5% | | User 2 | 25% | 25% | 0% | | User 3 | 20% | 0% | 0% | \*Percentages represent the portion of each user's total voting power allocated to each rollup. After the voting period ends, the final Weight Pool reward distribution is calculated as follows: | Rollup | Percentage of Total Rewards | | -------- | --------------------------- | | Rollup 1 | 55% | | Rollup 2 | 40% | | Rollup 3 | 5% | In this case, the Weight Pool rewards for the cycle will then be split 55:40:5. VIP Gauge Voting # VIP Introduction Source: https://docs.initia.xyz/home/core-concepts/vip/introduction In an ecosystem with a growing number of rollups, aligning the incentives of all participants is crucial. Although there have been attempts to achieve this, most encounter a few common core problems: * Misalignment of incentives for dApps that generate high levels of on-chain activity and value * Economic underutilization of the native token * Inefficient distribution of protocol-level grants and incentives to foster long-term value and alignment Initia aims to address these issues for Interwoven Rollups through a novel incentive alignment mechanism known as the Vested Interest Program (VIP). The VIP achieves this by programmatically rewarding valuable economic activities: * Rollups receive reward allocations for creating innovative apps and new use cases for the INIT token * Users earn INIT tokens from performing beneficial actions or meeting criteria set by the L2s. Finally, the VIP allocates a portion of overall rewards directly to the rollups. This ensures that rollup teams, rollup users, and INIT holders are long-term aligned with the success of the ecosystem. # VIP Scoring Source: https://docs.initia.xyz/home/core-concepts/vip/scoring ## Introduction The VIP Program employs a scoring system designed to allocate esINIT rewards to users. This system evaluates users based on their activities and contributions within a specific rollup. The specific scoring policy varies between each rollup, and the respective rollup team conducts the scoring process on-chain directly. ### Scoring Phase First, during each epoch, rollup teams score their users based on their activity through a `vip_score` contract. To score users, the rollup operator must first register the `deployer` account on the `vip_score` contract using their operator key. Once registered, the deployer can add and remove user scores based on the determined criteria. See [this page](/developers/developer-guides/integrating-initia-apps/vip) for more information on how scoring works. All future scoring actions can only be performed by the deployer until the deployer is changed or removed. Once the scoring for an epoch is complete, the scores must be finalized by calling a function on the `vip_score` contract. ### Snapshotting Phase Once finalized, the VIP Agent snapshots and submits the scores from all rollups, storing them in the Initia L1 VIP module. The Agent is an actor selected through Initia L1 governance. After all snapshots have been taken and stored, the esINIT rewards are distributed to the users. ### Claiming Phase Finally, the user can claim the distributed rewards. ### VIP Criteria & Scoring Policies #### Transparency 1. All scoring methodologies must be clearly listed and published in the rollup's VIP whitelisting proposal in full detail, both on the forums and in the on-chain proposal. 2. VIP scoring details outlined in the proposal must include all eligible user actions, criteria, distribution methodologies, and any calculations involved. 3. All scoring methodologies need to be transparent and verifiable by anyone. #### Scoring Criteria 4. Points may be allocated based on a user's usage of other chains within the Interwoven Economy, provided that the usage is relevant and beneficial to the rollup conducting the scoring. 5. VIP scores must only be allocated based on actions or metrics that are on-chain, such as users performing specific actions or transactions, holding assets, or other positions. 6. Actions performed off-chain, such as referrals and social media posts or engagements, cannot be used for scoring. This also includes incentivizing usage of specific tools, frontends, wallets, or other applications. #### Restrictions 7. VIP scores cannot be granted directly to rollup operators, team members, or their associated accounts. 8. Rollup teams cannot use VIP scores to incentivize users to vote for them on the VIP gauges. 9. Incentivizing users to hold naked assets such as BTC, ETH, USDC, and governance tokens, or to provide liquidity for any pair on any DEX, is prohibited. 10. If a rollup wants to incentivize holding specific assets, those assets must be ones where the underlying token is used productively (for example, LST, staking token variants, yield-bearing assets, etc.). All whitelisting proposals and scoring criteria are reviewed by the VIP Committee. This committee consists of stewards who uphold Initia VIP requirements and prioritize the sustainable success of the Interwoven Economy. Final approval for whitelisting rollups comes from Initia L1 governance through an on-chain vote. Any changes to a rollup's criteria must be submitted to the forums for review and approval by the VIP Committee before implementation. **Any attempts to bypass, circumvent, or abuse the VIP scoring system may result in the removal of the offending rollup from the VIP Program.** # VIP Timelines Source: https://docs.initia.xyz/home/core-concepts/vip/timelines ## Timelines ### Gauge Voting Cycles The Vested Interest Program always begins with a [gauge voting](/home/core-concepts/vip/gauges) cycle. During this cycle, Initia L1 stakers vote on the gauge weights that will determine the VIP [Weight Pool](/home/core-concepts/vip/architecture#weight-pool) rewards distribution for the next rewards stage. ### Reward Distribution Stages Reward Distribution Stages After the first gauge voting cycle concludes, the first reward distribution stage begins. During a stage, the individual rollup teams will begin to keep track of scores for all of their users based on their scoring criteria. During a stage, the system also takes a snapshot of each rollup's INIT balance to determine the VIP [Balance Pool](/home/core-concepts/vip/architecture#balance-pool) rewards. There are two ways the snapshot is done: 1. **For Stage 1**: Two snapshots are taken: a single snapshot at the beginning of the stage to determine the VIP Balance Pool rewards for Stage 1, and multiple snapshots throughout the stage to determine the VIP Balance Pool rewards for Stage 2+. 2. **For Stage 2+**: Multiple snapshots are taken throughout the stage to determine the VIP Balance Pool rewards for the next stage. At the end of the stage, each rollup finalizes user scores, and the system distributes the final rewards. The combined timelines of the gauge voting cycle and rewards distribution stage are as follows: Gauge Voting and Rewards Distribution Timelines ### Challenge Period When a rollup finalizes its scores, it enters a **challenge period**. This period allows users and other parties to audit the scores submitted by the rollup, ensuring their accuracy and compliance with both the VIP scoring policy and the rollup's own scoring criteria. If someone finds an incorrect scoring, they can submit a challenge through an expedited or emergency governance proposal on Initia L1. If a challenge succeeds, the following changes occur: 1. The system replaces the VIP scoring agent and transfers authority to a new agent. 2. The system recalculates rewards for the stage. Note that the challenge period happens alongside the start of the next stage and does not delay its commencement, as seen in the timeline above. # Welcome to Initia Source: https://docs.initia.xyz/home/general/welcome Hero Initia's core philosophy is to make opinionated decisions on the underlying infrastructure such as data availability, interoperability, and oracles. By reducing decision fatigue, the Interwoven Stack gives you the tools to craft application-specific environments while maintaining seamless access to the broader ecosystem. ## Learn More About Initia Discover the framework that powers all of Initia's rollups. Initia's solution to bootstrapping cross-chain liquidity while maintaining network security. Initia's incentive program that aims to foster long-term ecosystem-wide alignment. ## Start Developing Learn how to easily deploy your own rollup on your own computer. Deploy and interact with contracts on Interwoven Rollups on the various VMs. The set of components for building on the Interwoven Stack. # Bridge Source: https://docs.initia.xyz/home/tools/bridge The Initia Bridge allows you to transfer tokens between the Initia L1, all Interwoven Rollups, and other ecosystems. You can access it directly from the Initia Wallet through its Bridge/Swap page, and across all Interwoven Rollups that have deployed the Wallet. Using Skip Go API's routing, the Bridge aggregates bridging protocols such as LayerZero, CCTP, IBC, and the Interwoven Stack's native optimistic bridge to find the best price and fastest route. It also combines these with DEXs including Initia DEX, enabling swaps as part of the bridging process in a single action. This enables various use cases and flows, including: 1. Bridging and swapping from USDC on Ethereum to INIT on Initia L1 (via [CCTP](https://www.circle.com/cross-chain-transfer-protocol), [IBC](https://cosmos.network/ibc), and Initia DEX) 2. Bridging and swapping from ETH on Optimism to Kamigotchi (via [LayerZero](https://layerzero.network/) and IBC) 3. Instantly bridging INIT from an Interwoven Rollup to Initia L1 (via IBC and Minitswap) # Wallet Source: https://docs.initia.xyz/home/tools/wallet One major barrier when onboarding into a new ecosystem has always been the need to download and install a new wallet. With the Initia Wallet, you can sign in to any application using your existing EVM-compatible wallet, regardless of the VM or smart contract language the application uses. If you don't have an existing wallet, the Initia Wallet also allows you to create a new account using your email address or social media accounts (Google or X), powered by [Privy](https://privy.io/). # Changelog Source: https://docs.initia.xyz/interwovenkit/changelog Additions, updates, and fixes to InterwovenKit ## Strat perp and vault positions in portfolio The portfolio now displays Strat perpetual futures positions and vault deposits alongside other positions. Vault deposits appear inline (without a rewards breakdown) since they don't accrue claimable rewards, while perp positions are shown by market. ## Exported `EnableAutoSignOptions` type Minor improvements ## Configurable default duration when enabling autosign [`autoSign.enable()`](/interwovenkit/features/autosign/api-reference) now accepts an optional `defaultDuration` so apps can preselect how long autosign stays active when the enable dialog opens. ## Smarter wallet ordering on sign-in The wallet connection screen now sorts sign-in wallets by popularity and recency. Your most recently used wallet appears first, followed by widely used wallets, so connecting is faster on repeat visits. ## Improved bridge route refresh experience Bridge and [deposit](/interwovenkit/features/transfers/deposit-withdraw) flows now show inline status messages (such as "Refreshing route..." and "Estimating gas...") while routes are being updated in the background. The confirm button is disabled until fresh data is ready, and stale route errors automatically retry when a new quote arrives. ## Bug fixes * Bridge fee warnings now correctly account for the gas token balance remaining after the swap, preventing false warnings on large non-max inputs. * The bridge now warns when the source gas token balance would be insufficient to cover fees after executing a transfer. * Preview fee checks in the bridge are now guarded for external chains, preventing incorrect fee validation on non-Initia sources. * Tokens with no available price data now display `$-` instead of `$0` in the bridge. * The bridge now shows an insufficient-balance error for tokens with a zero balance instead of allowing submission. * The withdraw button in the deposit flow is now disabled when the balance is zero. * The deposit flow now warns when sending the max amount of a gas token would leave no balance to cover the transaction fee. * Hex addresses are now accepted as bridge recipients on Initia EVM chains. * Fixed a browser compatibility issue where `.toSorted()` was not available in some environments. ## Bug fixes * Fixed [autosign](/interwovenkit/features/autosign/introduction) failing to verify the derived wallet account on MiniEVM rollups. The account existence check now uses the correct Initia address format instead of the EVM hex address. ## Accessibility improvements The widget now includes comprehensive accessibility attributes across all interactive elements. Forms, sections, icon-only buttons, collapsible triggers, and loading states all carry appropriate ARIA labels and roles. Decorative icons are marked as hidden, and semantic landmarks (`