Initia 백서

Initia

원문

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

ign?.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 ( <section className="card" style={{ display: 'grid', gap: '1.25rem' }}> <div> <p style={{ margin: 0, color: 'var(--fg-muted)', fontSize: '0.8rem', letterSpacing: '0.12em', textTransform: 'uppercase' }}> BlockForge </p> <h2 style={{ margin: '0.35rem 0 0', fontSize: '1.9rem' }}>Forge items on your appchain</h2> </div> <div style={{ display: 'grid', gap: '0.9rem', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))' }}> <button className="btn btn-primary" type="button" disabled={pendingAction === 'mint_shard'} onClick={() => submitAction('mint_shard')} > {pendingAction === 'mint_shard' ? 'Minting...' : 'Mint Shard'} </button> <button className="btn btn-secondary" type="button" disabled={pendingAction === 'craft_relic'} onClick={() => submitAction('craft_relic')} > {pendingAction === 'craft_relic' ? 'Crafting...' : 'Craft Relic'} </button> </div> <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '1rem', flexWrap: 'wrap' }}> <div> <p style={{ margin: 0, color: 'var(--fg-muted)', fontSize: '0.8rem', letterSpacing: '0.12em', textTransform: 'uppercase' }}> Auto-Sign </p> <p style={{ margin: '0.35rem 0 0', color: 'var(--fg-muted)' }}> {isAutoSignEnabled ? 'Enabled for Move execute messages on this chain.' : 'Disabled. Wallet approval is required for each transaction.'} </p> </div> <button className="btn btn-secondary" type="button" onClick={toggleAutoSign} disabled={isTogglingAutoSign}> {isTogglingAutoSign ? 'Updating...' : isAutoSignEnabled ? 'Disable Auto-Sign' : 'Enable Auto-Sign'} </button> </div> <section style={{ display: 'grid', gap: '0.9rem' }}> <div style={{ display: 'flex', justifyContent: 'space-between', gap: '1rem', alignItems: 'center', flexWrap: 'wrap' }}> <div> <p style={{ margin: 0, fontSize: '0.8rem', textTransform: 'uppercase', letterSpacing: '0.12em', color: 'var(--fg-muted)' }}> Inventory </p> <p style={{ margin: '0.35rem 0 0', color: 'var(--fg-muted)' }}> {isConnected ? initiaAddress : 'Connect a wallet to view your items.'} </p> </div> {!isConnected ? ( <button className="btn btn-primary" type="button" onClick={openConnect}> Connect Wallet </button> ) : ( <button className="btn btn-secondary" type="button" onClick={() => loadInventory(initiaAddress)}> {isLoadingInventory ? 'Refreshing...' : 'Refresh Inventory'} </button> )} </div> <p>Shards: {isLoadingInventory ? '...' : inventory.shards}</p> <p>Relics: {isLoadingInventory ? '...' : inventory.relics}</p> {txHash ? <p>Latest tx: <code>{txHash}</code></p> : null} {error ? <p>{error}</p> : null} </section> </section> ) } 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. </Accordion> ### 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 ``` <Note> **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. </Note> ### 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. <Accordion title="Manual Approach: The Rust Contract"> 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<Vec<Memo>> = Item::new("messages"); #[cw_serde] pub struct InstantiateMsg {} #[cw_serde] pub enum ExecuteMsg { PostMessage { message: String }, } #[cw_serde] pub struct MessagesResponse { pub messages: Vec<Memo>, } #[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<Response, ContractError> { 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<Response, ContractError> { 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<Binary> { 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"); } } ``` </Accordion> ## 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. ``` <Accordion title="Manual Approach: Deploy via CLI"> **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 <YOUR_APPCHAIN_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 <YOUR_TX_HASH> --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 <YOUR_CODE_ID> '{}' \ --label "memoboard" \ --from gas-station \ --keyring-backend test \ --chain-id <YOUR_APPCHAIN_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 <YOUR_TX_HASH> --output json | jq -r '.events[] | select(.type=="instantiate") | .attributes[] | select(.key=="_contract_address") | .value' ``` </Accordion> ## 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. ``` <Accordion title="Manual Approach: On-Chain Interaction"> 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 <YOUR_CONTRACT_ADDRESS> '{"post_message":{"message":"Hello!"}}' \ --from gas-station \ --keyring-backend test \ --chain-id <YOUR_APPCHAIN_ID> \ --gas auto --gas-adjustment 1.4 --yes ``` ```bash wrap Query Messages theme={null} sleep 5 minitiad query wasm contract-state smart <YOUR_CONTRACT_ADDRESS> '{"get_messages":{}}' ``` </Accordion> ## 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. ``` <Accordion title="Manual Approach: Scaffold and Connect"> 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=<YOUR_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( <React.StrictMode> <WagmiProvider config={wagmiConfig}> <QueryClientProvider client={queryClient}> <InterwovenKitProvider {...TESTNET} defaultChainId={customChain.chain_id} customChain={customChain} customChains={[customChain]} > <App /> </InterwovenKitProvider> </QueryClientProvider> </WagmiProvider> </React.StrictMode>, ) ``` **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; }
프로젝트로 돌아가기