bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 38쪽 중 18쪽
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(
<React.StrictMode>
<WagmiProvider config={wagmiConfig}>
<QueryClientProvider client={queryClient}>
<InterwovenKitProvider
{...TESTNET}
defaultChainId={customChain.chain_id}
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 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 (
<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 }}>MiniBank</h1>
{!initiaAddress ? (
<button onClick={openConnect}>Connect Wallet</button>
) : (
<button onClick={openWallet}>{shortenAddress(initiaAddress)}</button>
)}
</header>
<main style={{ flex: 1, width: '100%', maxWidth: '760px', padding: '2rem' }}>
<Bank />
</main>
</div>
)
}
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 (
<section>
<p>My Savings: {balance} {NATIVE_SYMBOL}</p>
<input
type="number"
min="0"
step="any"
value={amount}
onChange={(e) => setAmount(e.target.value)}
placeholder="Enter amount"
/>
<div style={{ display: 'flex', gap: '12px', marginTop: '12px' }}>
<button onClick={handleDeposit} disabled={!initiaAddress || isPending}>Deposit</button>
<button onClick={handleWithdraw} disabled={!initiaAddress || isPending}>Withdraw</button>
<button onClick={handleBridge} disabled={isPending}>Bridge Funds</button>
</div>
{status ? <p>{status}</p> : null}
</section>
)
}
```
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.
</Accordion>
### 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
```
<Note>
**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.
</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
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.
<Accordion title="Manual Approach: The Move Module">
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
```
<Tip>
`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.
</Tip>
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<Inventory>(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<Inventory>(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<Inventory>(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<Inventory>(addr)) {
return InventoryView { shards: 0, relics: 0 }
};
let inventory = borrow_global<Inventory>(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 `<YOUR_HEX_ADDRESS_WITH_0X_PREFIX>` with your deployment
address hex (`0x...`).
```bash wrap Build Move Package theme={null}
minitiad move build --language-version=2.1 --named-addresses blockforge=<YOUR_HEX_ADDRESS_WITH_0X_PREFIX>
minitiad move test --language-version=2.1 --named-addresses blockforge=<YOUR_HEX_ADDRESS_WITH_0X_PREFIX>
```
If the build succeeds and the tests pass, BlockForge is ready to deploy.
</Accordion>
## 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.
```
<Accordion title="Manual Approach: Deploy via CLI">
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
`<YOUR_HEX_ADDRESS_WITH_0X_PREFIX>` 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=<YOUR_HEX_ADDRESS_WITH_0X_PREFIX>
# 3. Deploy the package.
minitiad move deploy --build \
--language-version=2.1 \
--named-addresses blockforge=<YOUR_HEX_ADDRESS_WITH_0X_PREFIX> \
--from gas-station \
--keyring-backend test \
--chain-id <YOUR_APPCHAIN_ID> \
--gas auto --gas-adjustment 1.4 --yes
```
<Note>
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.
</Note>
<Warning>
**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 <FRESH_ACCOUNT>`.
</Warning>
</Accordion>
## 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.
```
<Accordion title="Manual Approach: On-Chain Interaction">
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 <YOUR_MODULE_ADDRESS> items mint_shard \
--from gas-station \
--keyring-backend test \
--chain-id <YOUR_APPCHAIN_ID> \
--gas auto --gas-adjustment 1.4 --yes \
--args '[]' --type-args '[]'
sleep 2
done
```
```bash wrap Query Inventory theme={null}
minitiad query move resource <YOUR_WALLET_ADDRESS> <YOUR_MODULE_HEX_ADDRESS>::items::Inventory
```
```bash wrap Craft Relic theme={null}
minitiad tx move execute <YOUR_MODULE_ADDRESS> items craft_relic \
--from gas-station \
--keyring-backend test \
--chain-id <YOUR_APPCHAIN_ID> \
--gas auto --gas-adjustment 1.4 --yes \
--args '[]' --type-args '[]'
```
```bash wrap Query Inventory Again theme={null}
minitiad query move resource <YOUR_WALLET_ADDRESS> <YOUR_MODULE_HEX_ADDRESS>::items::Inventory
```
</Accordion>
## 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 connec프로젝트로 돌아가기