Initia 백서

Initia

원문

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

tion 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. ``` <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:** 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 <<EOF VITE_APPCHAIN_ID=$APPCHAIN_ID VITE_INITIA_RPC_URL=http://localhost:26657 VITE_INITIA_REST_URL=http://localhost:1317 VITE_INITIA_INDEXER_URL=http://localhost:8080 VITE_NATIVE_DENOM=$NATIVE_DENOM VITE_NATIVE_SYMBOL=$NATIVE_SYMBOL VITE_NATIVE_DECIMALS=6 VITE_BLOCKFORGE_MODULE_ADDRESS=$BLOCKFORGE_MODULE_ADDRESS EOF ``` **4. Set up Providers in `main.jsx`:** Wrap your application with `InterwovenKitProvider` to enable wallet connectivity. Ensure the `customChain` includes `fee_tokens`, `staking`, and `bech32_prefix`. ```tsx wrap 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 { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { WagmiProvider, createConfig, http } from 'wagmi' import { mainnet } from 'wagmi/chains' import { InterwovenKitProvider, TESTNET, injectStyles, } from '@initia/interwovenkit-react' import '@initia/interwovenkit-react/styles.css' import InterwovenKitStyles from '@initia/interwovenkit-react/styles.js' 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: 'BlockForge Appchain', pretty_name: 'BlockForge', bech32_prefix: 'init', network_type: 'testnet', 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 }], }, 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: 'minimove', }, }, 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 ?? 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>, ) ``` **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 ( <div> <button onClick={() => execute('mint_shard')}>Mint Shard</button> <button onClick={() => execute('craft_relic')}>Craft Relic</button> <p>Shards: {loading ? '...' : inventory.shards}</p> <p>Relics: {loading ? '...' : inventory.relics}</p> </div> ) } ``` Render `<Game />` from `src/App.jsx`. <Tip> **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. </Tip> </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 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 `<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 `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`. ``` <Accordion title="Manual Approach: Auto-signing Logic"> First, enable the feature in your provider: ```tsx wrap main.jsx theme={null} <InterwovenKitProvider {...TESTNET} // Enables auto-signing for MoveVM transactions enableAutoSign={true} > <App /> </InterwovenKitProvider> ``` 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 = '<YOUR_APPCHAIN_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 ? '<YOUR_NATIVE_DENOM>' : undefined, // MANDATORY for invisible UX messages: [ { typeUrl: "/initia.move.v1.MsgExecute", value: { sender: initiaAddress, moduleAddress: "<YOUR_MODULE_ADDRESS>", moduleName: "items", functionName: "mint_shard", typeArgs: [], // MANDATORY: Even if empty args: [], // MANDATORY: Even if empty }, } ] }) } return ( <div> <button onClick={toggleAutoSign}> {isAutoSignEnabled ? 'Disable Auto-Sign' : 'Enable Auto-Sign'} </button> <button onClick={handleAction}> Mint With Current Auto-Sign Mode </button> </div> ) ``` <Tip> **Session Expiration:** You can check the exact expiration of the current session using `autoSign.expiredAtByChain[chainId]`. </Tip> </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: * 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=<YOUR_MODULE_OWNER_BECH32> ``` **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: '<YOUR_APPCHAIN_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: '<YOUR_NATIVE_DENOM>', fixed_min_gas_price: 0, low_gas_price: 0, average_gas_price: 0, high_gas_price: 0 }], }, staking: { staking_tokens: [{ denom: '<YOUR_NATIVE_DENOM>' }] }, metadata: { is_l1: false, minitia: { type: 'minimove', }, }, native_assets: [ { denom: '<YOUR_NATIVE_DENOM>', name: 'Native Token', symbol: '<YOUR_TOKEN_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} enableAutoSign={true} customChain={customChain} customChains={[customChain]} > <App /> </InterwovenKitProvider> </QueryClientProvider> </WagmiProvider> </React.StrictMode>, ) ``` **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 ( <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center' }}> <header style={{ width: '100%', maxWidth: '1200px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '2rem' }}> <h1 style={{ fontSize: '1.25rem', fontWeight: 800, margin: 0 }}>BlockForge</h1> {!initiaAddress ? ( <button onClick={openConnect} className="btn btn-primary">Connect Wallet</button> ) : ( <button onClick={openWallet} className="btn btn-secondary"> {shortenAddress(initiaAddress)} </button> )} </header> <main style={{ flex: 1, width: '100%', maxWidth: '760px', padding: '2rem' }}> <div style={{ display: 'grid', gap: '1.5rem' }}> <section className="card" style={{ display: 'grid', gap: '0.9rem' }}> <p style={{ margin: 0, color: 'var(--fg-muted)', fontSize: '0.8rem', letterSpacing: '0.12em', textTransform: 'uppercase' }}> Local Rollup </p> <div> <h2 style={{ fontSize: '2.2rem', margin: 0 }}>Items Workshop</h2> <p style={{ color: 'var(--fg-muted)', margin: '0.75rem 0 0', lineHeight: 1.6 }}> Connect a wallet to mint shards and craft relics against the deployed <code>items</code> module. </p> </div> </section> <Game /> </div> </main> </div> ) } 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 = '<YOUR_APPCHAIN_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 ? '<YOUR_NATIVE_DENOM>' : 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 autoS
프로젝트로 돌아가기