> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tenderly.co/llms.txt
> Use this file to discover all available pages before exploring further.

# 在 Virtual Environment 上运行 Pimlico bundler 和 paymaster

> 在 Virtual Environment 上运行 Alto bundler 和 mock paymaster，测试智能账户、gas 赞助和 EIP-7702。

要在 [Virtual Environment](https://docs.tenderly.co/virtual-environments/overview.md) 上测试 ERC-4337 智能账户，请在 Docker 中运行 Pimlico 的开源 bundler [Alto](https://github.com/pimlicolabs/alto) 和 Pimlico 的 mock paymaster，并将两者都指向该 Virtual Environment 的 RPC URL。部署在父网络上的 EntryPoint 合约和账户工厂都包含在 fork 出的状态中，每个 bundle 都是一笔您可以在 [Virtual Environment Explorer](https://docs.tenderly.co/virtual-environments/explorer.md) 中打开的交易。

本指南以四种方式发送 UserOperations：由 paymaster 赞助、由账户支付、以 ERC-20 代币支付，以及从 EIP-7702 账户发送。本指南使用 Alto 1.2.8、permissionless 0.5.0 和 viem 2.57.7，在从 Ethereum Mainnet、Base、OP Mainnet 和 Arbitrum One fork 出的 Virtual Environment 上，配合 EntryPoint 0.6、0.7 和 0.8 进行了测试。

完整示例位于 GitHub 上的 [tenderly-pimlico-bundler](https://github.com/Tenderly/tenderly-pimlico-bundler) 仓库中。除了本页的设置之外，它还包含一个策略 paymaster、适用于 EntryPoint 0.7 和 0.8 的示例，以及一个运行所有示例的冒烟测试。

## 各服务使用哪个 RPC URL

每个 Virtual Environment 都有一个 **Public RPC** URL 和一个 **[Admin RPC](https://docs.tenderly.co/virtual-environments/admin-rpc.md)** URL。Alto 在 Public RPC 上运行。注资任务、mock paymaster 以及为账户注资的测试代码使用 Admin RPC。

```mermaid theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
flowchart TB
  app["您的应用或测试"]
  subgraph docker["Docker Compose"]
    alto["Alto bundler<br/>localhost:4337"]
    funder["funder 任务"]
    pm["Mock paymaster<br/>localhost:3000"]
  end
  subgraph ve["Virtual Environment"]
    pub["Public RPC"]
    adm["Admin RPC"]
  end
  app -- "UserOperations" --> alto
  app -- "赞助请求" --> pm
  app -- "读取" --> pub
  alto -- "模拟并提交 bundle" --> pub
  funder -- "为 Alto 的密钥注资" --> adm
  pm -- "部署 paymaster 合约" --> adm
```

| 服务 | 连接到 | 原因 |
| - | - | - |
| `funder` | Admin RPC | 在 Alto 启动之前为 Alto 的密钥注资的一次性任务。它从 Virtual Environment 上预先注资的账户发送未签名的 [`eth_sendTransaction`](https://docs.tenderly.co/virtual-environments/admin-rpc#eth_sendtransaction) 转账。 |
| Alto | Public RPC | 使用标准 JSON-RPC 方法模拟 UserOperations 并提交 bundle。 |
| Mock paymaster | Admin RPC、Alto | 在启动时部署其 paymaster 合约，并使用 `anvil_setBalance` 为其部署者账户补充余额，Admin RPC 接受该方法，而 Public RPC 会拒绝该方法。 |
| 您的应用或测试 | Public RPC、Alto、mock paymaster | 读取请求发往 Virtual Environment，UserOperations 发往 Alto，赞助请求发往 paymaster。本页的脚本还会通过 Admin RPC 为测试账户注资。 |

## 开始之前

* 一个从已部署 ERC-4337 EntryPoint 合约的网络（例如 Ethereum Mainnet、Base、OP Mainnet 或 Arbitrum One）fork 出的 Virtual Environment。它可以保留父网络的链 ID，也可以使用自定义的链 ID。要创建 Virtual Environment，请按照 [Virtual Environment 快速入门](https://docs.tenderly.co/virtual-environments/quickstart.md)操作。
* 该 Virtual Environment 的 **Public RPC** 和 **Admin RPC** URL，它们列在 **Home** 选项卡的 **Integrate Virtual RPC** 卡片中（参见[仪表板参考](https://docs.tenderly.co/virtual-environments/dashboard.md)）
* Docker 及 Docker Compose
* Node.js 20.6 或更高版本以及 npm
* `jq`，用于[快照示例](#在测试运行之间重置状态)

## 运行 Alto 和 mock paymaster

**1. 创建项目及其 .env 文件**

以下命令会创建一个项目文件夹和一个 `.env` 文件，该文件包含供 bundler 使用的三个新私钥。

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
mkdir pimlico-virtual-environment && cd pimlico-virtual-environment

cat > .env <<EOF
TENDERLY_PUBLIC_RPC_URL=https://YOUR-PUBLIC-RPC-URL-HERE
TENDERLY_ADMIN_RPC_URL=https://YOUR-ADMIN-RPC-URL-HERE
ALTO_UTILITY_PRIVATE_KEY=0x$(openssl rand -hex 32)
ALTO_EXECUTOR_PRIVATE_KEYS=0x$(openssl rand -hex 32),0x$(openssl rand -hex 32)
ALTO_CHAIN_TYPE=default
EOF
```

打开 `.env`，将两个占位符 URL 替换为该 Virtual Environment 的 Public RPC 和 Admin RPC URL，并根据父网络设置 `ALTO_CHAIN_TYPE`：

| 父网络 | `ALTO_CHAIN_TYPE` |
| - | - |
| Ethereum Mainnet | `default` |
| Base、OP Mainnet | `op-stack` |
| Arbitrum One | `default` |

> [!WARNING]
>
> 请生成新密钥。不要使用众所周知的测试密钥，例如 Anvil 或 Hardhat 的默认密钥。在实时网络的 fork 上，这些密钥的地址已通过 EIP-7702 委托给一个合约，该合约会转走它们收到的任何 ETH，因此这些地址始终不持有余额。

**2. 添加注资脚本**

Alto 启动之前，其密钥需要持有 ETH。utility 密钥在首次启动时部署 Alto 的模拟合约，executor 密钥支付 bundle 交易的费用。

每个 Virtual Environment 一开始就带有预先注资的账户，`eth_accounts` 会返回这些账户。Admin RPC 接受未签名的 [`eth_sendTransaction`](https://docs.tenderly.co/virtual-environments/admin-rpc#eth_sendtransaction) 请求，因此该脚本从其中一个账户转账，为每个密钥注资。

将脚本保存为 `fund-accounts.mjs`：

```js title="fund-accounts.mjs" theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
// Tops up accounts with ETH from the Virtual Environment's pre-funded accounts.
//
// Every Tenderly Virtual Environment starts with funded accounts, which
// eth_accounts returns. The Admin RPC accepts unsigned eth_sendTransaction
// requests, so a plain transfer from one of them is all it takes.
//
//   RPC_URL            Admin RPC URL of the Virtual Environment
//   FUND_PRIVATE_KEYS  comma-separated private keys whose addresses get funded
//   FUND_ADDRESSES     comma-separated extra addresses (optional)
//   FUND_AMOUNT_ETH    balance each address is topped up to (default 10)
//
// Runs inside the Alto image to reuse the viem copy bundled there.
import { createPublicClient, formatEther, http, parseEther, toHex } from "viem"
import { privateKeyToAccount } from "viem/accounts"

const list = (value) =>
    (value ?? "")
        .split(",")
        .map((item) => item.trim())
        .filter(Boolean)

if (!process.env.RPC_URL) throw new Error("RPC_URL is not set")
const client = createPublicClient({ transport: http(process.env.RPC_URL, { timeout: 60_000 }) })
const amount = parseEther(process.env.FUND_AMOUNT_ETH || "10")
const targets = [
    ...list(process.env.FUND_PRIVATE_KEYS).map((key) => privateKeyToAccount(key).address),
    ...list(process.env.FUND_ADDRESSES)
]

// The pre-funded account that currently holds the most ETH.
const richestAccount = async () => {
    const accounts = await client.request({ method: "eth_accounts" })
    if (accounts.length === 0) throw new Error("eth_accounts returned no pre-funded accounts")
    const balances = await Promise.all(accounts.map((address) => client.getBalance({ address })))
    const index = balances.indexOf(balances.reduce((a, b) => (a > b ? a : b)))
    return { address: accounts[index], balance: balances[index] }
}

for (const to of targets) {
    const balance = await client.getBalance({ address: to })
    if (balance >= amount) {
        console.log(`ok      ${to} ${formatEther(balance)} ETH`)
        continue
    }

    const value = amount - balance
    const from = await richestAccount()
    if (from.balance < value) throw new Error(`No pre-funded account holds ${formatEther(value)} ETH`)

    const hash = await client.request({
        method: "eth_sendTransaction",
        params: [{ from: from.address, to, value: toHex(value) }]
    })
    const receipt = await client.waitForTransactionReceipt({ hash })
    if (receipt.status !== "success") throw new Error(`Funding ${to} reverted (${hash})`)
    console.log(`funded  ${to} ${formatEther(amount)} ETH (${hash})`)
}
```

**3. 添加 Compose 文件**

将文件保存为 `docker-compose.yml`：

```yaml title="docker-compose.yml" theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
services:
  # One-shot job: funds the bundler keys from the Virtual Environment's
  # pre-funded accounts. Unsigned transfers need the Admin RPC.
  funder:
    image: ghcr.io/pimlicolabs/alto:v1.2.8
    entrypoint: ["node", "/app/src/fund-accounts.mjs"]
    volumes:
      - ./fund-accounts.mjs:/app/src/fund-accounts.mjs:ro
    environment:
      RPC_URL: ${TENDERLY_ADMIN_RPC_URL}
      FUND_PRIVATE_KEYS: ${ALTO_UTILITY_PRIVATE_KEY},${ALTO_EXECUTOR_PRIVATE_KEYS}

  alto:
    image: ghcr.io/pimlicolabs/alto:v1.2.8
    entrypoint: ["node", "src/lib/cli/alto.js", "run"]
    ports: ["4337:4337"]
    environment:
      ALTO_RPC_URL: ${TENDERLY_PUBLIC_RPC_URL}
      # EntryPoint 0.6, 0.7 and 0.8
      ALTO_ENTRYPOINTS: 0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789,0x0000000071727De22E5E9d8BAf0edAc6f37da032,0x4337084D9E255Ff0702461CF8895CE9E3b5Ff108
      ALTO_UTILITY_PRIVATE_KEY: ${ALTO_UTILITY_PRIVATE_KEY}
      ALTO_EXECUTOR_PRIVATE_KEYS: ${ALTO_EXECUTOR_PRIVATE_KEYS}
      ALTO_SAFE_MODE: "false"
      ALTO_CHAIN_TYPE: ${ALTO_CHAIN_TYPE:-default}
      ALTO_PORT: "4337"
      ALTO_PUBLIC_CLIENT_LOG_LEVEL: error
      ALTO_WALLET_CLIENT_LOG_LEVEL: error
    depends_on:
      funder:
        condition: service_completed_successfully
    healthcheck:
      test: ["CMD", "wget", "-qO-", "http://127.0.0.1:4337/health"]
      interval: 2s
      timeout: 2s
      retries: 60

  mock-paymaster:
    image: ghcr.io/pimlicolabs/mock-verifying-paymaster@sha256:df79a80c01d8d9bef5c1c9a938dd10cb466f3c0a00bee6c953432c5e9435273a
    ports: ["3000:3000"]
    environment:
      ALTO_RPC: http://alto:4337
      # The variable is named for Anvil. Point it at the Admin RPC.
      ANVIL_RPC: ${TENDERLY_ADMIN_RPC_URL}
    depends_on:
      alto:
        condition: service_healthy
    restart: on-failure:3
```

| 设置 | 这样设置的原因 |
| - | - |
| `ALTO_RPC_URL` | Public RPC URL。Alto 只使用标准 JSON-RPC 方法。 |
| `ALTO_SAFE_MODE: "false"` | 在安全模式下，Alto 会通过 `debug_traceCall` 使用自定义 JavaScript tracer 追踪每次验证，而 Virtual Environment RPC 不提供这类调用。关闭安全模式后，Alto 不会强制执行 ERC-7562 验证规则（受限操作码和存储访问），因此在 Virtual Environment 上通过的账户或 paymaster 仍可能被生产环境的 bundler 拒绝。 |
| `ANVIL_RPC` | Admin RPC URL。该变量以 Anvil 命名。如果使用 Public RPC URL，mock paymaster 会在启动时退出。 |
| 镜像版本 | 两个镜像都固定为本指南测试时使用的版本。 |

> [!NOTE]
>
> mock paymaster 仅用于测试。它会赞助每个请求，并使用公开已知的密钥签名。

**4. 启动服务栈**

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
docker compose up -d
```

funder 最先运行，然后是 Alto，最后是 mock paymaster。服务栈通常不到 30 秒即可就绪。

**5. 检查 bundler 和 paymaster**

向 bundler 查询其 EntryPoints：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
curl -s http://localhost:4337 -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"eth_supportedEntryPoints","params":[]}'
```

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{"jsonrpc":"2.0","id":1,"result":["0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789","0x0000000071727De22E5E9d8BAf0edAc6f37da032","0x4337084D9E255Ff0702461CF8895CE9E3b5Ff108"]}
```

然后 ping paymaster：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
curl -s http://localhost:3000/ping
```

```json theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{"message":"pong"}
```

## Mock paymaster 合约地址

mock paymaster 在一个 Virtual Environment 上首次启动时，会部署下面的合约。这些地址在每个网络上都相同。

| 合约 | 地址 |
| - | - |
| 用于 EntryPoint 0.6 的 paymaster | `0x20a2ED5AAdc0d87488dbc238A5Eb83A6955BD598` |
| 用于 EntryPoint 0.7 的 paymaster | `0x38aef040CEB057B62E1598F5C265946A4E4BaB4C` |
| 用于 EntryPoint 0.8 的 paymaster | `0xe276558647476dC0f409B25a1AFCbCed730128D9` |
| 用于支付 gas 的测试 ERC-20 代币 | `0x68e13372AE8FAaDDaf32cC08ee44C5ef5A002c69` |

每个 paymaster 都会在其 EntryPoint 中获得 50 ETH 的存款。

## 发送受赞助的 UserOperation

**1. 安装 viem 和 permissionless**

在项目文件夹中运行以下命令，安装 [viem](https://viem.sh) 和 [permissionless](https://github.com/pimlicolabs/permissionless.js)：

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
npm init -y
npm pkg set type=module
npm install permissionless@0.5.0 viem@2.57.7
npm install --save-dev tsx
```

**2. 创建 setup.ts**

`setup.ts` 包含本页所有脚本共用的客户端和常量。

```ts title="setup.ts" theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { createPublicClient, createWalletClient, defineChain, http } from "viem"

const PUBLIC_RPC_URL = process.env.TENDERLY_PUBLIC_RPC_URL!
const ADMIN_RPC_URL = process.env.TENDERLY_ADMIN_RPC_URL!

export const BUNDLER_URL = "http://localhost:4337"
export const PAYMASTER_URL = "http://localhost:3000"
export const RECIPIENT = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"

// Read the chain ID from the Virtual Environment, so this works with the
// parent network's chain ID and with a custom one.
const id = await createPublicClient({ transport: http(PUBLIC_RPC_URL) }).getChainId()

export const chain = defineChain({
  id,
  name: "Tenderly Virtual Environment",
  nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
  rpcUrls: { default: { http: [PUBLIC_RPC_URL] } },
})

// Reads go to the Virtual Environment, never to the bundler.
export const publicClient = createPublicClient({ chain, transport: http(PUBLIC_RPC_URL) })

// A wallet for one of the Virtual Environment's pre-funded accounts. The
// Admin RPC accepts its transactions unsigned. Use it to fund accounts in tests.
export const getFundedWallet = async () => {
  const transport = http(ADMIN_RPC_URL)
  const [account] = await createWalletClient({ chain, transport }).getAddresses()
  return createWalletClient({ account, chain, transport })
}
```

**3. 创建 sponsored.ts**

该脚本会创建一个不持有 ETH 的智能账户，并发送一个由 mock paymaster 付费的 UserOperation。

```ts title="sponsored.ts" theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { createSmartAccountClient } from "permissionless"
import { toSimpleSmartAccount } from "permissionless/accounts"
import { createPimlicoClient } from "permissionless/clients/pimlico"
import { http } from "viem"
import { entryPoint07Address } from "viem/account-abstraction"
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"
import { BUNDLER_URL, PAYMASTER_URL, RECIPIENT, chain, publicClient } from "./setup"

const entryPoint = { address: entryPoint07Address, version: "0.7" } as const

// Bundler methods go to Alto. Paymaster methods go to the mock paymaster.
const bundlerClient = createPimlicoClient({ chain, transport: http(BUNDLER_URL), entryPoint })
const paymasterClient = createPimlicoClient({ chain, transport: http(PAYMASTER_URL), entryPoint })

// A new smart account. It isn't deployed yet and holds no ETH.
const account = await toSimpleSmartAccount({
  client: publicClient,
  owner: privateKeyToAccount(generatePrivateKey()),
  entryPoint,
})

const smartAccountClient = createSmartAccountClient({
  account,
  chain,
  bundlerTransport: http(BUNDLER_URL),
  paymaster: paymasterClient,
  userOperation: {
    estimateFeesPerGas: async () => (await bundlerClient.getUserOperationGasPrice()).fast,
  },
})

const hash = await smartAccountClient.sendUserOperation({
  calls: [{ to: RECIPIENT, value: 0n, data: "0x1234" }],
})
const { success, receipt, paymaster } = await smartAccountClient.waitForUserOperationReceipt({ hash })

console.log({
  account: account.address,
  success,
  transaction: receipt.transactionHash,
  paymaster,
  accountBalance: await publicClient.getBalance({ address: account.address }),
})
```

**4. 运行脚本**

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
npx tsx --env-file=.env sponsored.ts
```

```js theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{
  account: '0x592Be1302b3Cd4aABa548A44DB850D10e73E47Dc',
  success: true,
  transaction: '0x5fe5336fe2e1b1f71eae7d06f84b7a16a29d8ffd3fb8d672bf1be278ba453c7e',
  paymaster: '0x38aef040CEB057B62E1598F5C265946A4E4BaB4C',
  accountBalance: 0n
}
```

该账户在一个 UserOperation 中完成了部署并执行了调用，而且仍然不持有 ETH。要查看该 bundle 的完整 trace，请在 [Virtual Environment Explorer](https://docs.tenderly.co/virtual-environments/explorer.md) 中搜索该交易哈希。

要使用其他 EntryPoint 版本，请更改 `entryPoint` 常量，例如改为 `{ address: entryPoint08Address, version: "0.8" }`。Alto 已针对 EntryPoint 0.6、0.7 和 0.8 进行配置，mock paymaster 会为每个版本部署一个 paymaster。

> [!NOTE]
>
> 请将这三个端点区分开。Alto 只响应 bundler 方法：如果您向它发送 `eth_call` 这样的读取请求，viem 会报告 `The method "eth_call" does not exist / is not available`。`pm_getPaymasterStubData` 这样的 paymaster 方法发往 paymaster URL。

## 其他支付 gas 的方式

下面的每个脚本都是完整的，并复用 `setup.ts`。运行方式与 `sponsored.ts` 相同，例如 `npx tsx --env-file=.env erc20.ts`。

### 用账户余额支付 gas

没有 paymaster 时，账户在其第一个 UserOperation 之前需要 ETH。`getFundedWallet` 通过 Admin RPC 从预先注资的账户向其发送 ETH。

```ts title="self-funded.ts" theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { createSmartAccountClient } from "permissionless"
import { toSimpleSmartAccount } from "permissionless/accounts"
import { createPimlicoClient } from "permissionless/clients/pimlico"
import { formatEther, http, parseEther } from "viem"
import { entryPoint07Address } from "viem/account-abstraction"
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"
import { BUNDLER_URL, RECIPIENT, chain, getFundedWallet, publicClient } from "./setup"

const entryPoint = { address: entryPoint07Address, version: "0.7" } as const
const bundlerClient = createPimlicoClient({ chain, transport: http(BUNDLER_URL), entryPoint })

const account = await toSimpleSmartAccount({
  client: publicClient,
  owner: privateKeyToAccount(generatePrivateKey()),
  entryPoint,
})

// Fund the account's address. It pays for its own deployment and gas.
const fundedWallet = await getFundedWallet()
await publicClient.waitForTransactionReceipt({
  hash: await fundedWallet.sendTransaction({ to: account.address, value: parseEther("0.01") }),
})

const smartAccountClient = createSmartAccountClient({
  account,
  chain,
  bundlerTransport: http(BUNDLER_URL),
  userOperation: {
    estimateFeesPerGas: async () => (await bundlerClient.getUserOperationGasPrice()).fast,
  },
})

const hash = await smartAccountClient.sendUserOperation({
  calls: [{ to: RECIPIENT, value: parseEther("0.001") }],
})
const { success, receipt, actualGasCost } = await smartAccountClient.waitForUserOperationReceipt({ hash })

console.log({
  account: account.address,
  success,
  transaction: receipt.transactionHash,
  gasCost: `${formatEther(actualGasCost)} ETH`,
  accountBalance: `${formatEther(await publicClient.getBalance({ address: account.address }))} ETH`,
})
```

### 用 ERC-20 代币支付 gas

mock paymaster 接受用它自己的测试代币支付 gas。任何人都可以使用 `sudoMint` 铸造该代币。

```ts title="erc20.ts" theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { createSmartAccountClient } from "permissionless"
import { toSimpleSmartAccount } from "permissionless/accounts"
import { createPimlicoClient } from "permissionless/clients/pimlico"
import { prepareUserOperationForErc20Paymaster } from "permissionless/experimental/pimlico"
import { type Address, formatEther, http, parseAbi, parseEther } from "viem"
import { entryPoint07Address } from "viem/account-abstraction"
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"
import { BUNDLER_URL, PAYMASTER_URL, RECIPIENT, chain, getFundedWallet, publicClient } from "./setup"

// The mock paymaster's test token, and the address that collects the fees.
const TOKEN = "0x68e13372AE8FAaDDaf32cC08ee44C5ef5A002c69"
const TREASURY = "0xD8Baa107006C93a030d1455A2eF43261b384F21c"
const tokenAbi = parseAbi([
  "function sudoMint(address to, uint256 amount)",
  "function balanceOf(address owner) view returns (uint256)",
])

const entryPoint = { address: entryPoint07Address, version: "0.7" } as const
const bundlerClient = createPimlicoClient({ chain, transport: http(BUNDLER_URL), entryPoint })
const paymasterClient = createPimlicoClient({ chain, transport: http(PAYMASTER_URL), entryPoint })

const fundedWallet = await getFundedWallet()
const tokenBalance = (owner: Address) =>
  publicClient.readContract({ address: TOKEN, abi: tokenAbi, functionName: "balanceOf", args: [owner] })
const mint = async (to: Address, amount: bigint) =>
  publicClient.waitForTransactionReceipt({
    hash: await fundedWallet.writeContract({
      address: TOKEN,
      abi: tokenAbi,
      functionName: "sudoMint",
      args: [to, amount],
    }),
  })

// Once per Virtual Environment: give the treasury a token balance. See the
// note below.
if ((await tokenBalance(TREASURY)) === 0n) await mint(TREASURY, 1n)

const account = await toSimpleSmartAccount({
  client: publicClient,
  owner: privateKeyToAccount(generatePrivateKey()),
  entryPoint,
})
await mint(account.address, parseEther("100"))

const smartAccountClient = createSmartAccountClient({
  account,
  chain,
  bundlerTransport: http(BUNDLER_URL),
  paymaster: paymasterClient,
  userOperation: {
    estimateFeesPerGas: async () => (await bundlerClient.getUserOperationGasPrice()).fast,
    // Fetches a token quote and adds the token approval to the UserOperation.
    prepareUserOperation: prepareUserOperationForErc20Paymaster(paymasterClient),
  },
})

const hash = await smartAccountClient.sendUserOperation({
  calls: [{ to: RECIPIENT, value: 0n, data: "0x1234" }],
  paymasterContext: { token: TOKEN },
})
const { success, receipt } = await smartAccountClient.waitForUserOperationReceipt({ hash })

console.log({
  account: account.address,
  success,
  transaction: receipt.transactionHash,
  tokenBalance: formatEther(await tokenBalance(account.address)),
  ethBalance: await publicClient.getBalance({ address: account.address }),
})
```

> [!NOTE]
>
> 该脚本会在第一次支付之前，向 paymaster 的金库铸造 1 wei 的该代币。如果不这样做，新 Virtual Environment 上的第一个 ERC-20 UserOperation 会失败并报错 `AA50 postOp reverted`。Alto 以 1 wei 的费用测量 paymaster 的 `postOp` gas，此时代币费用舍入为零。使用实际费用时，向空金库的第一笔转账所需的 gas 比 Alto 测得的多约 22,600，`postOp` 会耗尽 gas。

### 从 EIP-7702 账户发送 UserOperation

外部拥有账户（EOA）可以通过委托给 `Simple7702Account` 实现来充当智能账户。这需要 EntryPoint 0.8。第一个 UserOperation 携带已签名的授权，Alto 会在一笔 EIP-7702 交易中提交它。

```ts title="eip7702.ts" theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { createSmartAccountClient } from "permissionless"
import { to7702SimpleSmartAccount } from "permissionless/accounts"
import { createPimlicoClient } from "permissionless/clients/pimlico"
import { http } from "viem"
import { entryPoint08Address } from "viem/account-abstraction"
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts"
import { BUNDLER_URL, PAYMASTER_URL, RECIPIENT, chain, publicClient } from "./setup"

// Simple7702Account, deployed at the same address on every network.
const SIMPLE_7702_ACCOUNT = "0xe6Cae83BdE06E4c305530e199D7217f42808555B"

const entryPoint = { address: entryPoint08Address, version: "0.8" } as const
const bundlerClient = createPimlicoClient({ chain, transport: http(BUNDLER_URL), entryPoint })
const paymasterClient = createPimlicoClient({ chain, transport: http(PAYMASTER_URL), entryPoint })

// A plain EOA. It holds no ETH, so the mock paymaster sponsors it.
const owner = privateKeyToAccount(generatePrivateKey())
const account = await to7702SimpleSmartAccount({ client: publicClient, owner })

const smartAccountClient = createSmartAccountClient({
  account,
  chain,
  bundlerTransport: http(BUNDLER_URL),
  paymaster: paymasterClient,
  userOperation: {
    estimateFeesPerGas: async () => (await bundlerClient.getUserOperationGasPrice()).fast,
  },
})

// Sign the authorization for the Virtual Environment's chain ID and the
// EOA's nonce.
const authorization = await owner.signAuthorization({
  address: SIMPLE_7702_ACCOUNT,
  chainId: chain.id,
  nonce: await publicClient.getTransactionCount({ address: owner.address }),
})

const hash = await smartAccountClient.sendUserOperation({
  calls: [{ to: RECIPIENT, value: 0n, data: "0x1234" }],
  authorization,
})
const { success, receipt } = await smartAccountClient.waitForUserOperationReceipt({ hash })

console.log({
  eoa: owner.address,
  success,
  transaction: receipt.transactionHash,
  code: await publicClient.getCode({ address: owner.address }),
})
```

第一个 UserOperation 之后，该 EOA 的代码为 `0xef0100` 后跟实现地址。同一账户后续的 UserOperations 不需要 `authorization` 字段。

## 在测试运行之间重置状态

要在测试运行之间将 Virtual Environment 恢复到已知状态，请使用 [`evm_snapshot`](https://docs.tenderly.co/virtual-environments/admin-rpc#evm_snapshot) 创建快照，通过 Admin RPC 使用 [`evm_revert`](https://docs.tenderly.co/virtual-environments/admin-rpc#evm_revert) 回滚到该快照，并在每次回滚后重启 Alto。该示例使用 `jq`。

```bash theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
source .env

# Take the snapshot after the stack is up, so the contracts that Alto and the
# mock paymaster deployed are part of it.
SNAPSHOT=$(curl -s "$TENDERLY_ADMIN_RPC_URL" -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"evm_snapshot","params":[]}' | jq -r .result)

# ...run your tests...

curl -s "$TENDERLY_ADMIN_RPC_URL" -H 'Content-Type: application/json' \
  -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"evm_revert\",\"params\":[\"$SNAPSHOT\"]}"

docker compose restart alto
```

您可以根据需要多次回滚到同一个快照。有关仪表板中的流程和回滚距离限制，请参见[回滚 Virtual Environment 状态](https://docs.tenderly.co/virtual-environments/develop/revert-state.md)。

> [!WARNING]
>
> 每次 `evm_revert` 之后都要重启 Alto。Alto 在内存中保存已提交的 bundle、待处理的账户部署和最近的收据，回滚之后，这些状态描述的是已不存在的区块。如果不重启，UserOperations 可能会失败并报错 `AA10 ... Another deployment operation for this sender is already being processed`、始终无法确认，或者返回已被回滚的 UserOperations 的收据。使用 `debug_bundler_clearState` 清空 Alto 的内存池不能代替重启。

## 时间旅行和 paymaster 有效时间窗口

paymaster 签名通常带有有效时间窗口，并且有两个时钟会检查它：EntryPoint 将其与区块时间戳进行比较，Alto 将其与运行它的机器的时钟进行比较。在 Virtual Environment 上，这两者可能不同：

* 在 [`evm_increaseTime`](https://docs.tenderly.co/virtual-environments/admin-rpc#evm_increasetime) 之后，区块时间戳会领先于机器的时钟（参见[在 Virtual Environments 上使用时间戳](https://docs.tenderly.co/virtual-environments/develop/timestamps.md)）。
* 在 `evm_revert` 之后，区块时间戳会从快照的时间戳继续，因此会落后于机器的时钟，落后的时长为自快照以来经过的时间。

mock paymaster 为每次赞助签署的有效期为 60,000 秒，从机器的时钟起算。如果您将时间向前推进超过这个时长，它的赞助在链上就已经过期：UserOperation 始终无法确认，Alto 会不断重新提交失败的 bundle，直到您重启它。对于向前跳得更远的测试，请发送不带 paymaster 的 UserOperations，或者[使用您自己的 paymaster 服务](#使用您自己的-paymaster-服务)。

## 使用您自己的 paymaster 服务

要测试您自己的赞助规则，请针对同一个 Virtual Environment 运行您的 paymaster 服务，并将其 URL 传给 paymaster 客户端，以代替 `PAYMASTER_URL`。任何实现了 ERC-7677（`pm_getPaymasterStubData` 和 `pm_getPaymasterData`）的服务都可以配合本页的脚本使用。

有三点是 Virtual Environment 特有的：

* **通过 Admin RPC 为 paymaster 注资。** paymaster 合约需要在 EntryPoint 中有存款，部署该合约的账户需要 ETH。请像 `getFundedWallet` 那样，从预先注资的账户发送这两笔资金。
* **以两个时钟中较晚的一个为准签署有效时间窗口。** 以最新区块时间戳和服务自身时钟中较晚的一个为基准计算 `validUntil`。当 Virtual Environment 的时钟落后时，仅基于区块时间戳的签名会失败：Alto 会以 `UserOperation expires too soon` 拒绝该 UserOperation。
* **为该服务提供 Public RPC URL。** 读取链数据和发送已签名的交易不需要 Admin RPC。

示例仓库中的[策略 paymaster](https://github.com/Tenderly/tenderly-pimlico-bundler/tree/main/policy-paymaster) 满足以上三点，并且只赞助通过其 API 密钥检查、发送者和目标允许列表以及每个发送者支出上限的 UserOperations。

## 故障排除

| 症状 | 原因 | 修复 |
| - | - | - |
| `docker compose up` 报告 `dependency failed to start`，且失败服务的日志显示 `The request took too long to respond` | 该服务发送启动交易时，发往 Virtual Environment 的一个请求超时。 | 再次运行 `docker compose up -d`。启动过程可以安全地重复：每个服务都会跳过已部署和已注资的部分。 |
| 出现 `Bundler used an invalid aggregator for handling aggregated User Operations`，且 `Details:` 行中包含 `debug_traceCall` | Alto 正在安全模式下运行。对于 Alto 发往 Virtual Environment 的任何失败请求，viem 都会显示这条消息，原因在 `Details:` 行中。 | 设置 `ALTO_SAFE_MODE: "false"`。 |
| 同样的错误，且 `Details:` 行中包含 `gasEstimateL1Component` | `ALTO_CHAIN_TYPE` 为 `arbitrum`。在该模式下，Alto 会向 Arbitrum 的 `NodeInterface` 合约查询 L1 gas 分量。 | 对于 Arbitrum One，请设置 `ALTO_CHAIN_TYPE=default`。 |
| Alto 在 `Failed to deploy PimlicoSimulations contract` 之后以 `insufficient funds for gas * price + value` 退出 | Alto 的 utility 密钥未持有 ETH。 | 使用 `docker compose logs funder` 检查 funder 是否已运行完成，并检查 `TENDERLY_ADMIN_RPC_URL` 是否为 Admin RPC URL。 |
| mock paymaster 以 `Access forbidden by access rules, try Admin RPC URL` 退出 | `ANVIL_RPC` 被设置为 Public RPC URL。mock paymaster 在启动时会调用 `anvil_setBalance`。 | 将 `.env` 中的 `TENDERLY_ADMIN_RPC_URL` 设置为 Admin RPC URL。 |
| 用测试代币支付 gas 时出现 `AA50 postOp reverted` | paymaster 的金库未持有该代币。 | 像 `erc20.ts` 那样，在每个 Virtual Environment 上向 `0xD8Baa107006C93a030d1455A2eF43261b384F21c` 铸造一次 1 wei 的该代币。 |
| `The method "eth_call" does not exist / is not available` | 有读取请求被发送到了 bundler URL。如果 `pm_getPaymasterStubData` 出现同样的错误，则说明 paymaster 客户端指向了 Alto。 | 使用 Public RPC URL 创建公共客户端，仅将 bundler URL 用作 `bundlerTransport`，并使用 paymaster URL 创建 paymaster 客户端。 |
| 在 `evm_revert` 之后，UserOperations 失败并报错 `AA10 ... Another deployment operation for this sender is already being processed`，或始终无法确认 | Alto 保留着来自已被回滚移除的区块的状态。 | 运行 `docker compose restart alto`。参见[在测试运行之间重置状态](#在测试运行之间重置状态)。 |
| 在 `evm_increaseTime` 之后，受赞助的 UserOperations 始终无法确认 | mock paymaster 的赞助已在链上过期。 | 重启 Alto 以丢弃卡住的 UserOperation。参见[时间旅行和 paymaster 有效时间窗口](#时间旅行和-paymaster-有效时间窗口)。 |
| 使用您自己的 paymaster 服务时出现 `UserOperation expires too soon` | 该服务根据区块时间戳签署了 `validUntil`，而 Virtual Environment 的时钟是落后的。 | 以两个时钟中较晚的一个为准进行签名。参见[使用您自己的 paymaster 服务](#使用您自己的-paymaster-服务)。 |
| 某个地址始终收不到您发送给它的 ETH | 该地址属于某个众所周知的测试密钥。在实时网络的 fork 上，这类地址会转走它们收到的任何 ETH。 | 生成新密钥。 |

## 相关内容

* GitHub 上的 [tenderly-pimlico-bundler](https://github.com/Tenderly/tenderly-pimlico-bundler)：包含策略 paymaster 和冒烟测试的完整示例
* [Admin RPC 参考](https://docs.tenderly.co/virtual-environments/admin-rpc.md)，涵盖 `eth_sendTransaction`、`evm_snapshot`、`evm_revert` 和 `evm_increaseTime`
* 使用快照或仪表板[回滚 Virtual Environment 状态](https://docs.tenderly.co/virtual-environments/develop/revert-state.md)
* [在 Virtual Environments 上使用时间戳](https://docs.tenderly.co/virtual-environments/develop/timestamps.md)
* 在 Virtual Environment 上使用 [Viem](https://docs.tenderly.co/virtual-environments/libraries/viem.md)：自定义链和自定义 RPC 方法
* [调试交易](https://docs.tenderly.co/virtual-environments/develop/debug-transactions.md)，用于单步执行 bundle 交易


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.