orchestration

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

dApp Orchestration

dApp编排

What You Probably Got Wrong

你可能踩过的误区

SE2 has specific patterns you must follow. Generic "build a dApp" advice won't work. SE2 auto-generates
deployedContracts.ts
— DON'T edit it. Use Scaffold hooks, NOT raw wagmi. External contracts go in
externalContracts.ts
BEFORE building the frontend.
There are three phases. Never skip or combine them. Contracts → Frontend → Production. Each has validation gates.
Scaffold-ETH 2(简称SE2)有其特定的使用规范,必须遵循。 通用的「构建dApp」指南并不适用。SE2会自动生成
deployedContracts.ts
文件——请勿编辑该文件。请使用Scaffold提供的hooks,而非直接使用wagmi。在构建前端之前,需将所有外部合约配置在
externalContracts.ts
文件中。
整个流程分为三个阶段,绝对不要跳过或合并阶段。 合约开发 → 前端构建 → 生产部署。每个阶段都有验证关卡。

The Three-Phase Build System

三阶段构建系统

PhaseEnvironmentWhat Happens
Phase 1Local forkContracts + UI on localhost. Iterate fast.
Phase 2Live network + local UIDeploy contracts to mainnet/L2. Test with real state. Polish UI.
Phase 3ProductionDeploy frontend to IPFS/Vercel. Final QA.
阶段运行环境主要操作
阶段1本地fork环境在本地主机部署合约与UI,快速迭代。
阶段2真实网络+本地UI将合约部署到主网/L2,基于真实链上状态测试,优化UI。
阶段3生产环境将前端部署到IPFS/Vercel,完成最终QA测试。

Phase 1: Scaffold (Local)

阶段1:本地搭建

1.1 Contracts

1.1 合约开发

bash
npx create-eth@latest my-dapp
cd my-dapp && yarn install
yarn fork --network base  # Terminal 1: fork of real chain (or mainnet, your target chain)
yarn deploy               # Terminal 2: deploy contracts
Always fork, never
yarn chain
.
yarn fork
does everything
yarn chain
does AND gives you real protocol state — Uniswap, USDC, Aave, whale balances, everything already deployed.
yarn chain
gives you an empty chain that tempts you into writing mock contracts you don't need. Don't mock what already exists onchain — just fork it.
Critical steps:
  1. Write contracts in
    packages/foundry/contracts/
    (or
    packages/hardhat/contracts/
    )
  2. Write deploy script
  3. Add ALL external contracts to
    packages/nextjs/contracts/externalContracts.ts
    — BEFORE Phase 1.2
  4. Write tests (≥90% coverage)
  5. Security audit before moving to frontend
Validate:
yarn deploy
succeeds.
deployedContracts.ts
auto-generated. Tests pass.
bash
npx create-eth@latest my-dapp
cd my-dapp && yarn install
yarn fork --network base  # 终端1:创建目标链(如主网)的fork环境
yarn deploy               # 终端2:部署合约
始终使用fork模式,不要用
yarn chain
yarn fork
包含
yarn chain
的全部功能,还能为你提供真实的链上协议状态——Uniswap、USDC、Aave、巨鲸账户余额等所有已部署的合约都能直接使用。而
yarn chain
会创建一条空链,诱使你编写不必要的模拟合约。对于链上已存在的资源,无需模拟,直接fork即可。
关键步骤:
  1. packages/foundry/contracts/
    (或
    packages/hardhat/contracts/
    )目录下编写合约
  2. 编写部署脚本
  3. 在进入阶段1.2之前,将所有外部合约添加到
    packages/nextjs/contracts/externalContracts.ts
    文件中
  4. 编写测试用例(覆盖率≥90%)
  5. 在开始前端开发前完成安全审计
验证标准:
yarn deploy
执行成功,
deployedContracts.ts
文件自动生成,所有测试用例通过。

1.2 Frontend

1.2 前端构建

bash
yarn fork --network base  # Terminal 1: fork of real chain (has Uniswap, USDC, etc.)
yarn deploy --watch       # Terminal 2: auto-redeploy on changes
yarn start                # Terminal 3: Next.js at localhost:3000
USE SCAFFOLD HOOKS, NOT RAW WAGMI:
typescript
// Read
const { data } = useScaffoldReadContract({
  contractName: "YourContract",
  functionName: "balanceOf",
  args: [address],
  watch: true,
});

// Write
const { writeContractAsync, isMining } = useScaffoldWriteContract("YourContract");
await writeContractAsync({
  functionName: "swap",
  args: [tokenIn, tokenOut, amount],
  onBlockConfirmation: (receipt) => console.log("Done!", receipt),
});

// Events
const { data: events } = useScaffoldEventHistory({
  contractName: "YourContract",
  eventName: "SwapExecuted",
  fromBlock: 0n,
  watch: true,
});
bash
yarn fork --network base  # 终端1:创建目标链的fork环境(包含Uniswap、USDC等合约)
yarn deploy --watch       # 终端2:合约变更时自动重新部署
yarn start                # 终端3:启动Next.js服务,访问localhost:3000
请使用Scaffold Hooks,而非直接使用wagmi:
typescript
// 读取合约数据
const { data } = useScaffoldReadContract({
  contractName: "YourContract",
  functionName: "balanceOf",
  args: [address],
  watch: true,
});

// 写入合约数据
const { writeContractAsync, isMining } = useScaffoldWriteContract("YourContract");
await writeContractAsync({
  functionName: "swap",
  args: [tokenIn, tokenOut, amount],
  onBlockConfirmation: (receipt) => console.log("操作完成!", receipt),
});

// 监听合约事件
const { data: events } = useScaffoldEventHistory({
  contractName: "YourContract",
  eventName: "SwapExecuted",
  fromBlock: 0n,
  watch: true,
});

The Three-Button Flow (MANDATORY)

三按钮交互流程(强制要求)

Any token interaction shows ONE button at a time:
  1. Switch Network (if wrong chain)
  2. Approve Token (if allowance insufficient)
  3. Execute Action (only after 1 & 2 satisfied)
Never show Approve and Execute simultaneously.
任何代币交互操作需依次显示以下三个按钮,同一时间仅显示一个:
  1. 切换网络(当前链不符合要求时)
  2. 授权代币(代币授权额度不足时)
  3. 执行操作(仅在完成前两步后显示)
绝对不要同时显示授权和执行按钮。

UX Rules

UX设计规则

  • Human-readable amounts:
    formatEther()
    /
    formatUnits()
    for display,
    parseEther()
    /
    parseUnits()
    for contracts
  • Loading states everywhere:
    isLoading
    ,
    isMining
    on all async operations
  • Disable buttons during pending txs (blockchains take 5-12s)
  • Never use infinite approvals — approve exact amount or 3-5x
  • Helpful errors: Parse "insufficient funds," "user rejected," "execution reverted" into plain language
Validate: Full user journey works with real wallet on localhost. All edge cases handled.
  • 人类可读的金额格式: 显示时使用
    formatEther()
    /
    formatUnits()
    ,向合约传递时使用
    parseEther()
    /
    parseUnits()
  • 全局加载状态: 所有异步操作需显示
    isLoading
    isMining
    状态
  • 交易pending时禁用按钮(区块链交易通常需要5-12秒)
  • 绝对不要使用无限授权 —— 仅授权精确金额或3-5倍的所需金额
  • 友好的错误提示: 将「余额不足」「用户拒绝」「执行回滚」等错误信息转换为通俗易懂的语言
验证标准: 完整用户流程可在本地环境通过真实钱包正常运行,所有边缘场景均已处理。

🚨 NEVER COMMIT SECRETS TO GIT

🚨 绝对不要将敏感信息提交到Git仓库

Before touching Phase 2, read this. AI agents are the #1 source of leaked credentials on GitHub. Bots scrape repos in real-time and exploit leaked secrets within seconds.
This means ALL secrets — not just wallet private keys:
  • Wallet private keys — funds drained in seconds
  • API keys — Alchemy, Infura, Etherscan, WalletConnect project IDs
  • RPC URLs with embedded keys — e.g.
    https://base-mainnet.g.alchemy.com/v2/YOUR_KEY
  • OAuth tokens, passwords, bearer tokens
⚠️ Common SE2 Trap:
scaffold.config.ts
rpcOverrides
and
alchemyApiKey
in
scaffold.config.ts
are committed to Git. NEVER paste API keys directly into this file. Use environment variables:
typescript
// ❌ WRONG — key committed to public repo
rpcOverrides: {
  [chains.base.id]: "https://base-mainnet.g.alchemy.com/v2/8GVG8WjDs-LEAKED",
},

// ✅ RIGHT — key stays in .env.local
rpcOverrides: {
  [chains.base.id]: process.env.NEXT_PUBLIC_BASE_RPC || "https://mainnet.base.org",
},
Before every
git add
or
git commit
:
bash
undefined
在进入阶段2之前,请务必阅读以下内容。 AI Agent是GitHub上泄露凭证的头号来源,机器人会实时扫描仓库,并在数秒内利用泄露的敏感信息发起攻击。
这里的敏感信息包括所有机密内容,不仅限于钱包私钥:
  • 钱包私钥 —— 资金会在数秒内被盗取
  • API密钥 —— Alchemy、Infura、Etherscan、WalletConnect的项目ID
  • 包含密钥的RPC地址 —— 例如
    https://base-mainnet.g.alchemy.com/v2/YOUR_KEY
  • OAuth令牌、密码、Bearer令牌
⚠️ SE2常见陷阱:
scaffold.config.ts
文件
scaffold.config.ts
中的
rpcOverrides
alchemyApiKey
会被提交到Git仓库。绝对不要直接将API密钥粘贴到该文件中,请使用环境变量:
typescript
// ❌ 错误示例 —— 密钥会被提交到公开仓库
rpcOverrides: {
  [chains.base.id]: "https://base-mainnet.g.alchemy.com/v2/8GVG8WjDs-LEAKED",
},

// ✅ 正确示例 —— 密钥仅存储在本地.env.local文件中
rpcOverrides: {
  [chains.base.id]: process.env.NEXT_PUBLIC_BASE_RPC || "https://mainnet.base.org",
},
在执行
git add
git commit
之前,请务必执行以下检查:
bash
undefined

Check for leaked secrets

检查是否有泄露的敏感信息

git diff --cached --name-only | grep -iE '.env|key|secret|private' grep -rn "0x[a-fA-F0-9]{64}" packages/ --include=".ts" --include=".js" --include="*.sol"
git diff --cached --name-only | grep -iE '.env|key|secret|private' grep -rn "0x[a-fA-F0-9]{64}" packages/ --include=".ts" --include=".js" --include="*.sol"

Check for hardcoded API keys in config files

检查配置文件中是否有硬编码的API密钥

grep -rn "g.alchemy.com/v2/[A-Za-z0-9]" packages/ --include=".ts" --include=".js" grep -rn "infura.io/v3/[A-Za-z0-9]" packages/ --include=".ts" --include=".js"
grep -rn "g.alchemy.com/v2/[A-Za-z0-9]" packages/ --include=".ts" --include=".js" grep -rn "infura.io/v3/[A-Za-z0-9]" packages/ --include=".ts" --include=".js"

If ANYTHING matches, STOP. Move the secret to .env and add .env to .gitignore.

如果上述命令返回任何结果,请立即停止操作。将敏感信息移至.env文件,并确保.env已添加到.gitignore中。


**Your `.gitignore` MUST include:**
.env .env.* *.key broadcast/ cache/ node_modules/

**SE2 handles deployer keys by default** — `yarn generate` creates a `.env` with the deployer key, and `.gitignore` excludes it. **Don't override this pattern.** Don't copy keys into scripts, config files, or deploy logs. This includes RPC keys, API keys, and any credential — not just wallet keys.

See `wallets/SKILL.md` for full key safety guide, what to do if you've already leaked a key, and safe patterns for deployment.

**你的.gitignore文件必须包含以下内容:**
.env .env.* *.key broadcast/ cache/ node_modules/

**SE2默认已处理部署者密钥的安全问题** —— `yarn generate`命令会创建包含部署者密钥的.env文件,且.gitignore已默认排除该文件。**请勿修改此配置**,不要将密钥复制到脚本、配置文件或部署日志中。这包括RPC密钥、API密钥及任何凭证,而不仅仅是钱包密钥。

如需了解完整的密钥安全指南、泄露后的补救措施及安全部署模式,请查看`wallets/SKILL.md`文件。

Phase 2: Live Contracts + Local UI

阶段2:真实合约+本地UI

  1. Update
    scaffold.config.ts
    :
    targetNetworks: [mainnet]
    (or your L2)
  2. Fund deployer:
    yarn generate
    yarn account
    → send real ETH
  3. Deploy:
    yarn deploy --network mainnet
  4. Verify:
    yarn verify --network mainnet
  5. Test with real wallet, small amounts ($1-10)
  6. Polish UI — remove SE2 branding, custom styling
Design rule: NO LLM SLOP. No generic purple gradients. Make it unique.
Validate: Contracts verified on block explorer. Full journey works with real contracts.
  1. 更新
    scaffold.config.ts
    文件:
    targetNetworks: [mainnet]
    (或你的目标L2网络)
  2. 为部署者账户充值:执行
    yarn generate
    yarn account
    → 向显示的地址转入真实ETH
  3. 部署合约:
    yarn deploy --network mainnet
  4. 验证合约:
    yarn verify --network mainnet
  5. 使用真实钱包进行小额测试(1-10美元)
  6. 优化UI —— 移除SE2默认品牌标识,自定义样式
设计规则: 拒绝LLM生成的通用风格。不要使用千篇一律的紫色渐变,打造独特的UI设计。
验证标准: 合约已在区块浏览器上完成验证,完整用户流程可通过真实合约正常运行。

Phase 3: Production Deploy

阶段3:生产环境部署

Pre-deploy Checklist

部署前检查清单

  • onlyLocalBurnerWallet: true
    in scaffold.config.ts (CRITICAL — prevents burner wallet on prod)
  • Update metadata (title, description, OG image 1200x630px)
  • Restore any test values to production values
  • scaffold.config.ts
    中设置
    onlyLocalBurnerWallet: true
    (关键配置 —— 防止生产环境显示测试钱包)
  • 更新元数据(标题、描述、1200x630px的OG图片)
  • 将所有测试环境配置恢复为生产环境配置

Deploy

部署操作

IPFS (decentralized):
bash
yarn ipfs
IPFS(去中心化部署):
bash
yarn ipfs

**Vercel (fast):**
```bash
cd packages/nextjs && vercel

**Vercel(快速中心化部署):**
```bash
cd packages/nextjs && vercel

Production QA

生产环境QA测试

  • App loads on public URL
  • Wallet connects, network switching works
  • Read + write contract operations work
  • No console errors
  • Burner wallet NOT showing
  • OG image works in link previews
  • Mobile responsive
  • Tested with MetaMask, Rainbow, WalletConnect
  • 应用可通过公开URL正常加载
  • 钱包可正常连接,网络切换功能正常
  • 合约的读/写操作均可正常执行
  • 控制台无错误信息
  • 未显示测试钱包(burner wallet)
  • 链接预览中的OG图片正常显示
  • 移动端适配正常
  • 已通过MetaMask、Rainbow、WalletConnect测试

Phase Transition Rules

阶段回退规则

Phase 3 bug → go back to Phase 2 (fix with local UI + prod contracts) Phase 2 contract bug → go back to Phase 1 (fix locally, write regression test, redeploy) Never hack around bugs in production.
阶段3发现bug → 回到阶段2修复(使用本地UI+生产环境合约进行调试) 阶段2发现合约bug → 回到阶段1修复(在本地环境修复问题,编写回归测试用例,重新部署合约) 绝对不要在生产环境中临时修复bug。

Key SE2 Directories

SE2核心目录结构

packages/
├── foundry/contracts/          # Solidity contracts
├── foundry/script/             # Deploy scripts
├── foundry/test/               # Tests
└── nextjs/
    ├── app/                    # Pages
    ├── components/             # React components
    ├── contracts/
    │   ├── deployedContracts.ts   # AUTO-GENERATED (don't edit)
    │   └── externalContracts.ts   # YOUR external contracts (edit this)
    ├── hooks/scaffold-eth/     # USE THESE hooks
    └── scaffold.config.ts      # Main config
packages/
├── foundry/contracts/          # Solidity合约文件
├── foundry/script/             # 部署脚本
├── foundry/test/               # 测试用例
└── nextjs/
    ├── app/                    # 页面文件
    ├── components/             # React组件
    ├── contracts/
    │   ├── deployedContracts.ts   # 自动生成文件(请勿编辑)
    │   └── externalContracts.ts   # 外部合约配置文件(可编辑)
    ├── hooks/scaffold-eth/     # Scaffold提供的Hooks(请使用这些)
    └── scaffold.config.ts      # 主配置文件

AI Agent Commerce: End-to-End Flow (ERC-8004 + x402)

AI Agent商业生态:端到端流程(ERC-8004 + x402)

This is the killer use case for Ethereum in 2026: autonomous agents discovering, trusting, paying, and rating each other — no humans in the loop.
这是2026年以太坊的核心应用场景:自主Agent之间的发现、信任、支付与评级 —— 无需人工介入。

The Full Cycle

完整流程

┌─────────────────────────────────────────────────────────────┐
│  1. DISCOVER  Agent queries ERC-8004 IdentityRegistry       │
│               → finds agents with "weather" service tag      │
│                                                              │
│  2. TRUST     Agent checks ReputationRegistry                │
│               → filters by uptime >99%, quality >85          │
│               → picks best-rated weather agent               │
│                                                              │
│  3. CALL      Agent sends HTTP GET to weather endpoint       │
│               → receives 402 Payment Required                │
│               → PAYMENT-REQUIRED header: $0.10 USDC on Base  │
│                                                              │
│  4. PAY       Agent signs EIP-3009 transferWithAuthorization │
│               → retries request with PAYMENT-SIGNATURE       │
│               → server verifies via facilitator              │
│               → payment settled on Base (~$0.001 gas)        │
│                                                              │
│  5. RECEIVE   Server returns 200 OK + weather data           │
│               → PAYMENT-RESPONSE header with tx hash         │
│                                                              │
│  6. RATE      Agent posts feedback to ReputationRegistry     │
│               → value=95, tag="quality", endpoint="..."      │
│               → builds onchain reputation for next caller   │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│  1. 发现  Agent查询ERC-8004身份注册表                     │
│               → 筛选出提供「天气服务」的Agent                │
│                                                              │
│  2. 信任  Agent查询声誉注册表                                │
│               → 筛选出正常运行时间>99%、服务评分>85的Agent    │
│               → 选择评分最高的天气服务Agent                  │
│                                                              │
│  3. 请求  Agent向天气服务端点发送HTTP GET请求                │
│               → 收到402 Payment Required响应                │
│               → PAYMENT-REQUIRED头信息:Base链上支付0.10 USDC │
│                                                              │
│  4. 支付  Agent签名EIP-3009授权转账交易                      │
│               → 携带PAYMENT-SIGNATURE头信息重试请求          │
│               → 服务器通过第三方验证机构完成签名验证          │
│               → 在Base链上完成支付(手续费约0.001美元)        │
│                                                              │
│  5. 接收  服务器返回200 OK响应及天气数据                    │
│               → PAYMENT-RESPONSE头信息包含交易哈希          │
│                                                              │
│  6. 评级  Agent在声誉注册表提交反馈                          │
│               → 评分=95,标签="quality",端点="..."            │
│               → 为后续调用者积累链上声誉数据                  │
└─────────────────────────────────────────────────────────────┘

Concrete Implementation (TypeScript Agent)

具体实现(TypeScript Agent)

typescript
import { x402Fetch } from '@x402/fetch';
import { createWallet } from '@x402/evm';
import { ethers } from 'ethers';

const wallet = createWallet(process.env.AGENT_PRIVATE_KEY);
const provider = new ethers.JsonRpcProvider(process.env.BASE_RPC_URL);

const IDENTITY_REGISTRY = '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432';
const REPUTATION_REGISTRY = '0x8004BAa17C55a88189AE136b182e5fdA19dE9b63';

// 1. Discover: find agents offering weather service
const registry = new ethers.Contract(IDENTITY_REGISTRY, registryAbi, provider);
// Query events or use The Graph subgraph for indexed agent discovery

// 2. Trust: check reputation
const reputation = new ethers.Contract(REPUTATION_REGISTRY, reputationAbi, provider);
const [count, value, decimals] = await reputation.getSummary(
  agentId, trustedClients, "quality", "30days"
);
// Only proceed if value/10^decimals > 85

// 3-5. Pay + Receive: x402Fetch handles the entire 402 flow
const response = await x402Fetch(agentEndpoint, {
  wallet,
  preferredNetwork: 'eip155:8453'
});
const weatherData = await response.json();

// 6. Rate: post feedback onchain
const reputationWriter = new ethers.Contract(REPUTATION_REGISTRY, reputationAbi, signer);
await reputationWriter.giveFeedback(
  agentId, 95, 0, "quality", "weather", agentEndpoint, "", ethers.ZeroHash
);
This is the agentic economy. No API keys, no subscriptions, no invoicing, no trust assumptions. Just cryptographic identity, onchain reputation, and HTTP-native payments.
typescript
import { x402Fetch } from '@x402/fetch';
import { createWallet } from '@x402/evm';
import { ethers } from 'ethers';

const wallet = createWallet(process.env.AGENT_PRIVATE_KEY);
const provider = new ethers.JsonRpcProvider(process.env.BASE_RPC_URL);

const IDENTITY_REGISTRY = '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432';
const REPUTATION_REGISTRY = '0x8004BAa17C55a88189AE136b182e5fdA19dE9b63';

// 1. 发现:筛选提供天气服务的Agent
const registry = new ethers.Contract(IDENTITY_REGISTRY, registryAbi, provider);
// 可通过事件查询或The Graph子图实现Agent的索引式发现

// 2. 信任:查询Agent声誉
const reputation = new ethers.Contract(REPUTATION_REGISTRY, reputationAbi, provider);
const [count, value, decimals] = await reputation.getSummary(
  agentId, trustedClients, "quality", "30days"
);
// 仅当value/10^decimals > 85时继续执行

// 3-5. 支付+接收:x402Fetch自动处理完整的402流程
const response = await x402Fetch(agentEndpoint, {
  wallet,
  preferredNetwork: 'eip155:8453'
});
const weatherData = await response.json();

// 6. 评级:在链上提交反馈
const reputationWriter = new ethers.Contract(REPUTATION_REGISTRY, reputationAbi, signer);
await reputationWriter.giveFeedback(
  agentId, 95, 0, "quality", "weather", agentEndpoint, "", ethers.ZeroHash
);
这就是Agent经济体系。 无需API密钥、无需订阅、无需发票、无需信任假设,仅依靠加密身份、链上声誉和原生HTTP支付即可运行。

Key Projects Building This Stack

构建该生态的核心项目

  • ERC-8004 — agent identity + reputation (EF, MetaMask, Google, Coinbase)
  • x402 — HTTP payment protocol (Coinbase)
  • A2A — agent-to-agent communication (Google)
  • MCP — model context protocol (Anthropic)
  • The Graph — indexing agent registrations for fast discovery
  • EigenLayer — crypto-economic validation of agent work
  • ERC-8004 —— Agent身份与声誉标准(由EF、MetaMask、Google、Coinbase联合推动)
  • x402 —— HTTP原生支付协议(Coinbase开发)
  • A2A —— Agent间通信标准(Google开发)
  • MCP —— 模型上下文协议(Anthropic开发)
  • The Graph —— 为Agent注册表提供索引,实现快速发现
  • EigenLayer —— 为Agent的工作提供加密经济层面的验证

Resources

参考资源