> ## 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.

# Run a Pimlico bundler and paymaster on a Virtual Environment

> Run Pimlico's Alto ERC-4337 bundler and mock paymaster in Docker on a Virtual Environment to test smart accounts, sponsored gas, and EIP-7702.

To test ERC-4337 smart accounts on a [Virtual Environment](https://docs.tenderly.co/virtual-environments/overview.md), run [Alto](https://github.com/pimlicolabs/alto), Pimlico's open-source bundler, and Pimlico's mock paymaster in Docker, and point both at the Virtual Environment's RPC URLs. The EntryPoint contracts and account factories deployed on the parent network are part of the forked state, and each bundle is a transaction you can open in the [Virtual Environment Explorer](https://docs.tenderly.co/virtual-environments/explorer.md).

This guide sends UserOperations in four ways: sponsored by a paymaster, paid by the account, paid in an ERC-20 token, and from an EIP-7702 account. It was tested with Alto 1.2.8, permissionless 0.5.0, and viem 2.57.7 on Virtual Environments forked from Ethereum Mainnet, Base, OP Mainnet, and Arbitrum One, with EntryPoint 0.6, 0.7, and 0.8.

## Which RPC URL does each service use?

A Virtual Environment has a **Public RPC** URL and an **[Admin RPC](https://docs.tenderly.co/virtual-environments/admin-rpc.md)** URL. Alto runs on the Public RPC. The funding job, the mock paymaster, and test code that funds accounts use the Admin RPC.

```mermaid theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
flowchart TB
  app["Your app or tests"]
  subgraph docker["Docker Compose"]
    alto["Alto bundler<br/>localhost:4337"]
    funder["funder job"]
    pm["Mock paymaster<br/>localhost:3000"]
  end
  subgraph ve["Virtual Environment"]
    pub["Public RPC"]
    adm["Admin RPC"]
  end
  app -- "UserOperations" --> alto
  app -- "sponsorship requests" --> pm
  app -- "reads" --> pub
  alto -- "simulates and submits bundles" --> pub
  funder -- "funds Alto's keys" --> adm
  pm -- "deploys paymasters" --> adm
```

| Service | Connects to | Why |
| - | - | - |
| `funder` | Admin RPC | A one-shot job that funds Alto's keys before Alto starts. It sends unsigned [`eth_sendTransaction`](https://docs.tenderly.co/virtual-environments/admin-rpc#eth_sendtransaction) transfers from the Virtual Environment's pre-funded accounts. |
| Alto | Public RPC | Simulates UserOperations and submits bundles with standard JSON-RPC methods. |
| Mock paymaster | Admin RPC, Alto | Deploys its paymaster contracts on startup and tops up its deployer account with `anvil_setBalance`, which the Admin RPC accepts and the Public RPC rejects. |
| Your app or tests | Public RPC, Alto, mock paymaster | Reads go to the Virtual Environment, UserOperations go to Alto, and sponsorship requests go to the paymaster. The scripts on this page also fund test accounts through the Admin RPC. |

## Before you begin

* A Virtual Environment forked from a network where the ERC-4337 EntryPoint contracts are deployed, such as Ethereum Mainnet, Base, OP Mainnet, or Arbitrum One. It can keep the parent network's chain ID or use a custom one. To create one, follow the [Virtual Environment quickstart](https://docs.tenderly.co/virtual-environments/quickstart.md).
* The Virtual Environment's **Public RPC** and **Admin RPC** URLs, listed in the **Integrate Virtual RPC** card on the **Home** tab (see the [dashboard reference](https://docs.tenderly.co/virtual-environments/dashboard.md))
* Docker with Docker Compose
* Node.js 20.6 or later and npm
* `jq`, for the [snapshot example](#reset-state-between-test-runs)

## Run Alto and the mock paymaster

**1. Create the project and its .env file**

The command creates a project folder and a `.env` file with three new private keys for the 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
```

Open `.env`, replace the two placeholder URLs with the Virtual Environment's Public RPC and Admin RPC URLs, and set `ALTO_CHAIN_TYPE` for the parent network:

| Parent network | `ALTO_CHAIN_TYPE` |
| - | - |
| Ethereum Mainnet | `default` |
| Base, OP Mainnet | `op-stack` |
| Arbitrum One | `default` |

> [!WARNING]
>
> Generate new keys. Don't use well-known test keys such as the Anvil or Hardhat defaults. On forks of live networks, those addresses are delegated through EIP-7702 to a contract that forwards any ETH they receive, so they never hold a balance.

**2. Add the funding script**

Alto needs ETH on its keys before it starts. The utility key deploys Alto's simulation contracts on the first start, and the executor keys pay for bundle transactions.

A Virtual Environment starts with pre-funded accounts, which `eth_accounts` returns. The Admin RPC accepts unsigned [`eth_sendTransaction`](https://docs.tenderly.co/virtual-environments/admin-rpc#eth_sendtransaction) requests, so the script funds each key with a transfer from one of those accounts.

Save the script as `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. Add the Compose file**

Save the file as `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
```

| Setting | Why it is set this way |
| - | - |
| `ALTO_RPC_URL` | The Public RPC URL. Alto uses only standard JSON-RPC methods. |
| `ALTO_SAFE_MODE: "false"` | In safe mode, Alto traces each validation with a custom JavaScript tracer through `debug_traceCall`, which Virtual Environment RPCs don't serve. With safe mode off, Alto doesn't enforce the ERC-7562 validation rules (restricted opcodes and storage access), so an account or paymaster that passes on the Virtual Environment can still be rejected by a production bundler. |
| `ANVIL_RPC` | The Admin RPC URL. The variable is named for Anvil. With the Public RPC URL, the mock paymaster exits on startup. |
| Image versions | Both images are pinned to the versions this guide was tested with. |

> [!NOTE]
>
> The mock paymaster is for testing only. It sponsors every request and signs with a publicly known key.

**4. Start the stack**

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

The funder runs first, then Alto, then the mock paymaster. The stack is usually ready in under 30 seconds.

**5. Check the bundler and the paymaster**

Ask the bundler for its 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"]}
```

Then ping the 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 contract addresses

On its first start on a Virtual Environment, the mock paymaster deploys the contracts below. The addresses are the same on every network.

| Contract | Address |
| - | - |
| Paymaster for EntryPoint 0.6 | `0x20a2ED5AAdc0d87488dbc238A5Eb83A6955BD598` |
| Paymaster for EntryPoint 0.7 | `0x38aef040CEB057B62E1598F5C265946A4E4BaB4C` |
| Paymaster for EntryPoint 0.8 | `0xe276558647476dC0f409B25a1AFCbCed730128D9` |
| Test ERC-20 token for gas payment | `0x68e13372AE8FAaDDaf32cC08ee44C5ef5A002c69` |

Each paymaster gets a 50 ETH deposit in its EntryPoint.

## Send a sponsored UserOperation

**1. Install viem and permissionless**

Run the commands in the project folder to install [viem](https://viem.sh) and [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. Create setup.ts**

`setup.ts` holds the clients and constants that all scripts on this page share.

```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. Create sponsored.ts**

The script creates a smart account that holds no ETH and sends a UserOperation that the mock paymaster pays for.

```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. Run the script**

```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
}
```

The account was deployed and made its call in one UserOperation, and it still holds no ETH. To see the full trace of the bundle, search for the transaction hash in the [Virtual Environment Explorer](https://docs.tenderly.co/virtual-environments/explorer.md).

To use another EntryPoint version, change the `entryPoint` constant, for example to `{ address: entryPoint08Address, version: "0.8" }`. Alto is configured for EntryPoint 0.6, 0.7, and 0.8, and the mock paymaster deploys a paymaster for each.

> [!NOTE]
>
> Keep the three endpoints apart. Alto answers only bundler methods: if you send it a read such as `eth_call`, viem reports `The method "eth_call" does not exist / is not available`. Paymaster methods such as `pm_getPaymasterStubData` go to the paymaster URL.

## Other ways to pay for gas

Each script below is complete and reuses `setup.ts`. Run it the same way as `sponsored.ts`, for example `npx tsx --env-file=.env erc20.ts`.

### Pay gas from the account's balance

Without a paymaster, the account needs ETH before its first UserOperation. `getFundedWallet` sends it from a pre-funded account through the Admin RPC.

```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`,
})
```

### Pay gas in an ERC-20 token

The mock paymaster accepts its own test token as payment for gas. Anyone can mint the token with `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]
>
> The script mints 1 wei of the token to the paymaster's treasury before the first payment. Without it, the first ERC-20 UserOperation on a new Virtual Environment fails with `AA50 postOp reverted`. Alto measures the paymaster's `postOp` gas with fees of 1 wei, where the token fee rounds to zero. With real fees, the first transfer into an empty treasury needs about 22,600 more gas than Alto measured, and `postOp` runs out of gas.

### Send a UserOperation from an EIP-7702 account

An externally owned account (EOA) can act as a smart account by delegating to the `Simple7702Account` implementation. This requires EntryPoint 0.8. The first UserOperation carries the signed authorization, and Alto submits it in an EIP-7702 transaction.

```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 }),
})
```

After the first UserOperation, the EOA's code is `0xef0100` followed by the implementation address. Later UserOperations from the same account don't need the `authorization` field.

## Reset state between test runs

To return the Virtual Environment to a known state between test runs, take a snapshot with [`evm_snapshot`](https://docs.tenderly.co/virtual-environments/admin-rpc#evm_snapshot), revert to it with [`evm_revert`](https://docs.tenderly.co/virtual-environments/admin-rpc#evm_revert) over the Admin RPC, and restart Alto after every revert. The example uses `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
```

You can revert to the same snapshot as many times as you need. For the dashboard flow and the revert distance limit, see [Revert Virtual Environment state](https://docs.tenderly.co/virtual-environments/develop/revert-state.md).

> [!WARNING]
>
> Restart Alto after every `evm_revert`. Alto keeps submitted bundles, pending account deployments, and recent receipts in memory, and after a revert that state describes blocks that no longer exist. Without a restart, UserOperations can fail with `AA10 ... Another deployment operation for this sender is already being processed`, never confirm, or return receipts for UserOperations that were reverted. Clearing Alto's mempool with `debug_bundler_clearState` doesn't replace the restart.

## Time travel and paymaster validity windows

Paymaster signatures usually carry a validity window, and two clocks check it: the EntryPoint compares it with the block timestamp, and Alto compares it with the clock of the machine it runs on. On a Virtual Environment, the two can differ:

* After [`evm_increaseTime`](https://docs.tenderly.co/virtual-environments/admin-rpc#evm_increasetime), block timestamps run ahead of the machine's clock (see [Working with timestamps on Virtual Environments](https://docs.tenderly.co/virtual-environments/develop/timestamps.md)).
* After `evm_revert`, block timestamps continue from the snapshot's timestamp, so they run behind the machine's clock by the time that passed since the snapshot.

The mock paymaster signs each sponsorship for 60,000 seconds from the machine's clock. If you move time forward by more than that, its sponsorships are already expired on chain: the UserOperation never confirms, and Alto keeps resubmitting the failing bundle until you restart it. For tests that jump further ahead, send UserOperations without a paymaster, or [use your own paymaster service](#use-your-own-paymaster-service).

## Use your own paymaster service

To test your own sponsorship rules, run your paymaster service against the same Virtual Environment and pass its URL to the paymaster client in place of `PAYMASTER_URL`. Any service that implements ERC-7677 (`pm_getPaymasterStubData` and `pm_getPaymasterData`) works with the scripts on this page.

Three things are specific to a Virtual Environment:

* **Fund the paymaster through the Admin RPC.** The paymaster contract needs an EntryPoint deposit, and the account that deploys it needs ETH. Send both from a pre-funded account, as `getFundedWallet` does.
* **Sign validity windows from the later of the two clocks.** Compute `validUntil` from the later of the latest block timestamp and the service's own clock. A signature based on the block timestamp alone fails when the Virtual Environment's clock is behind: Alto rejects the UserOperation with `UserOperation expires too soon`.
* **Give the service the Public RPC URL.** Reading the chain and sending signed transactions doesn't need the Admin RPC.

## Troubleshooting

| Symptom | Cause | Fix |
| - | - | - |
| `docker compose up` reports `dependency failed to start`, and the log of the failed service shows `The request took too long to respond` | A request to the Virtual Environment timed out while the service was sending a startup transaction. | Run `docker compose up -d` again. Startup is safe to repeat: each service skips what is already deployed and funded. |
| `Bundler used an invalid aggregator for handling aggregated User Operations` with `debug_traceCall` in the `Details:` line | Alto is running in safe mode. viem shows this message for any failed request from Alto to the Virtual Environment, and the cause is in the `Details:` line. | Set `ALTO_SAFE_MODE: "false"`. |
| The same error with `gasEstimateL1Component` in the `Details:` line | `ALTO_CHAIN_TYPE` is `arbitrum`. In that mode, Alto asks Arbitrum's `NodeInterface` contract for the L1 gas component. | Set `ALTO_CHAIN_TYPE=default` for Arbitrum One. |
| Alto exits with `insufficient funds for gas * price + value` after `Failed to deploy PimlicoSimulations contract` | Alto's utility key holds no ETH. | Check that the funder finished with `docker compose logs funder`, and that `TENDERLY_ADMIN_RPC_URL` is the Admin RPC URL. |
| The mock paymaster exits with `Access forbidden by access rules, try Admin RPC URL` | `ANVIL_RPC` is set to the Public RPC URL. The mock paymaster calls `anvil_setBalance` on startup. | Set `TENDERLY_ADMIN_RPC_URL` in `.env` to the Admin RPC URL. |
| `AA50 postOp reverted` when paying gas in the test token | The paymaster's treasury holds none of the token. | Mint 1 wei of the token to `0xD8Baa107006C93a030d1455A2eF43261b384F21c` once per Virtual Environment, as `erc20.ts` does. |
| `The method "eth_call" does not exist / is not available` | A read was sent to the bundler URL. The same error for `pm_getPaymasterStubData` means the paymaster client points at Alto. | Create the public client with the Public RPC URL, use the bundler URL only as `bundlerTransport`, and create the paymaster client with the paymaster URL. |
| UserOperations fail with `AA10 ... Another deployment operation for this sender is already being processed` or never confirm after `evm_revert` | Alto holds state from blocks that the revert removed. | Run `docker compose restart alto`. See [Reset state between test runs](#reset-state-between-test-runs). |
| Sponsored UserOperations never confirm after `evm_increaseTime` | The mock paymaster's sponsorship expired on chain. | Restart Alto to drop the stuck UserOperation. See [Time travel and paymaster validity windows](#time-travel-and-paymaster-validity-windows). |
| `UserOperation expires too soon` with your own paymaster service | The service signed `validUntil` from the block timestamp while the Virtual Environment's clock is behind. | Sign from the later of the two clocks. See [Use your own paymaster service](#use-your-own-paymaster-service). |
| An address never receives the ETH you send it | The address belongs to a well-known test key. On forks of live networks, those addresses forward any ETH they receive. | Generate a new key. |

## Related

* [Admin RPC reference](https://docs.tenderly.co/virtual-environments/admin-rpc.md) for `eth_sendTransaction`, `evm_snapshot`, `evm_revert`, and `evm_increaseTime`
* [Revert Virtual Environment state](https://docs.tenderly.co/virtual-environments/develop/revert-state.md) with snapshots or the dashboard
* [Working with timestamps on Virtual Environments](https://docs.tenderly.co/virtual-environments/develop/timestamps.md)
* [Viem](https://docs.tenderly.co/virtual-environments/libraries/viem.md) on a Virtual Environment: custom chains and custom RPC methods
* [Debugging Transactions](https://docs.tenderly.co/virtual-environments/develop/debug-transactions.md) to step through a bundle transaction


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