Initia 백서

Initia

원문

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

.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 ( <div className="board-container"> <h1 className="board-title">MemoBoard</h1> {!initiaAddress && ( <div className="message-card" style={{ marginBottom: 24, textAlign: 'center', color: '#666' }} > Connect your wallet from the app header to post a memo. </div> )} {initiaAddress && ( <div style={{ marginBottom: '32px' }}> <h3 className="section-header">Post a Memo</h3> <div className="input-group"> <input className="memo-input" value={content} onChange={(e) => setContent(e.target.value)} placeholder="Write a memo..." /> <button onClick={handlePostMessage} className="btn-primary"> Post Message </button> </div> </div> )} <div className="messages-list"> <h3 className="section-header">Board Feed</h3> {messages.map((m, i) => ( <div key={i} className="message-card"> <div className="message-sender">{truncate(m.sender)}</div> <div className="message-content">{m.message}</div> </div> ))} </div> </div> ) } 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 ( <div> <header style={{ maxWidth: 600, margin: '40px auto 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, }} > <div> <p style={{ margin: 0, color: '#666', fontSize: 12, fontWeight: 700 }}> Initia Wasm Appchain </p> <h1 style={{ margin: '8px 0 0' }}>MemoBoard</h1> </div> {!initiaAddress ? ( <button onClick={openConnect} className="btn-primary"> Connect Wallet </button> ) : ( <button onClick={openWallet} className="btn-primary"> {shortenAddress(initiaAddress)} </button> )} </header> <Board /> </div> ) } export default App ``` </Accordion> ## 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 `<YOUR_WALLET_ADDRESS>` with the address you just copied: ```terminal wrap theme={null} Using the `initia-appchain-dev` skill, please fund my wallet address <YOUR_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. ``` <Accordion title="Manual Approach: Username Resolution"> 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 ( <div className="message-sender"> {senderLabel} </div> ) } // 1. Extract username from the hook const { initiaAddress, username, openConnect, openWallet } = useInterwovenKit() // 2. Update the connected wallet button to show the username <div className="wallet-info"> <button onClick={openWallet} style={{ background: 'none', border: 'none', cursor: 'pointer' }} > {username ? username : truncate(initiaAddress)} </button> </div> // 3. Update the feed rows to resolve usernames for sender addresses messages.map((message, index) => ( <MessageRow key={`${message.sender}-${index}`} message={message} /> )) ``` <Warning> **Hook Placement:** Keep `useUsernameQuery(address)` inside a child row component like `MessageRow`. Do not call it directly inside a parent component's `.map()` callback. </Warning> </Accordion> If you want the complete finished frontend after applying the manual steps above, use the consolidated reference below. <Accordion title="Manual Approach: Final Frontend Reference"> 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 ( <div className="message-card"> <div className="message-sender">{senderLabel}</div> <div className="message-content">{message.message}</div> <div style={{ marginTop: 8, fontSize: 12, color: '#999', }} > Message #{index + 1} </div> </div> ) } 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 ( <div className="board-container"> <h1 className="board-title">MemoBoard</h1> {!initiaAddress && ( <div className="message-card" style={{ marginBottom: 24, textAlign: 'center', color: '#666' }} > Connect your wallet from the app header to post a memo. </div> )} {initiaAddress && ( <div style={{ marginBottom: 32 }}> <h3 className="section-header">Post a Memo</h3> <p style={{ color: '#777', marginBottom: 12 }}> Posting as {username ? username : truncate(initiaAddress)} </p> <form className="input-group" onSubmit={handlePostMessage}> <input className="memo-input" value={draft} onChange={(e) => setDraft(e.target.value)} placeholder="Write a memo..." /> <button type="submit" className="btn-primary" disabled={posting || !draft.trim()} > {posting ? 'Posting...' : 'Post Message'} </button> </form> </div> )} <div className="messages-list"> <h3 className="section-header">Board Feed</h3> {error && ( <div className="message-card" style={{ color: '#b42318' }}> {error} </div> )} {loading ? ( <div className="message-card">Loading board state...</div> ) : messages.length === 0 ? ( <div className="message-card">No messages yet.</div> ) : ( messages.map((message, index) => ( <MessageRow key={`${message.sender}-${index}`} message={message} index={index} initiaAddress={initiaAddress} username={username} /> )) )} </div> </div> ) } ``` **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 ( <div> <header style={{ maxWidth: 600, margin: '40px auto 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, }} > <div> <p style={{ margin: 0, color: '#666', fontSize: 12, fontWeight: 700 }}> Initia Wasm Appchain </p> <h1 style={{ margin: '8px 0 0' }}>MemoBoard</h1> </div> {!initiaAddress ? ( <button onClick={openConnect} className="btn-primary"> Connect Wallet </button> ) : ( <button onClick={openWallet} className="btn-primary"> {username ? username : shortenAddress(initiaAddress)} </button> )} </header> <Board /> </div> ) } ``` </Accordion> ### 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. <Tip> **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. </Tip> ## 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. | <Note> 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). </Note> ## 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 `<MOVE / EVM / WASM>` 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 <MOVE / EVM / WASM> 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. <Warning> **Resetting Existing Local State:** If you already ran `weave init` and want to create a new appchain, run the following commands first. Thi
프로젝트로 돌아가기