> ## 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 चलाएँ

> Smart accounts, sponsored gas, और EIP-7702 test करने के लिए Virtual Environment पर Docker में Pimlico का Alto ERC-4337 bundler और mock paymaster चलाएँ।

[Virtual Environment](https://docs.tenderly.co/virtual-environments/overview.md) पर ERC-4337 smart accounts को test करने के लिए, Pimlico के open-source bundler [Alto](https://github.com/pimlicolabs/alto) और Pimlico के mock paymaster को Docker में चलाएँ, और दोनों को Virtual Environment के RPC URLs पर point करें। Parent network पर deployed EntryPoint contracts और account factories forked state का हिस्सा हैं, और हर bundle एक transaction है जिसे आप [Virtual Environment Explorer](https://docs.tenderly.co/virtual-environments/explorer.md) में खोल सकते हैं।

यह गाइड UserOperations को चार तरीकों से भेजती है: paymaster द्वारा sponsored, account द्वारा भुगतान किए गए, ERC-20 token में भुगतान किए गए, और EIP-7702 account से। यह Alto 1.2.8, permissionless 0.5.0, और viem 2.57.7 के साथ, Ethereum Mainnet, Base, OP Mainnet, और Arbitrum One से fork किए गए Virtual Environments पर, EntryPoint 0.6, 0.7, और 0.8 के साथ test की गई थी।

पूरा example GitHub पर [tenderly-pimlico-bundler](https://github.com/Tenderly/tenderly-pimlico-bundler) repository में है। इस पेज के setup के अलावा, इसमें एक policy paymaster, EntryPoint 0.7 और 0.8 के लिए examples, और सभी examples चलाने वाला एक smoke test है।

## हर service किस RPC URL का उपयोग करती है?

Virtual Environment का एक **Public RPC** URL और एक **[Admin RPC](https://docs.tenderly.co/virtual-environments/admin-rpc.md)** URL होता है। Alto Public RPC पर चलता है। Funding job, mock paymaster, और accounts को fund करने वाला test code Admin RPC का उपयोग करते हैं।

```mermaid theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
flowchart TB
  app["आपका app या 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 -- "bundles simulate और submit करता है" --> pub
  funder -- "Alto की keys fund करता है" --> adm
  pm -- "paymasters deploy करता है" --> adm
```

| Service | किससे connect होती है | क्यों |
| - | - | - |
| `funder` | Admin RPC | एक one-shot job जो Alto के शुरू होने से पहले Alto की keys को fund करता है। यह Virtual Environment के pre-funded accounts से unsigned [`eth_sendTransaction`](https://docs.tenderly.co/virtual-environments/admin-rpc#eth_sendtransaction) transfers भेजता है। |
| Alto | Public RPC | Standard JSON-RPC methods के साथ UserOperations को simulate करता है और bundles submit करता है। |
| Mock paymaster | Admin RPC, Alto | Startup पर अपने paymaster contracts deploy करता है और अपने deployer account को `anvil_setBalance` से top up करता है, जिसे Admin RPC स्वीकार करता है और Public RPC reject करता है। |
| आपका app या tests | Public RPC, Alto, mock paymaster | Reads Virtual Environment पर जाते हैं, UserOperations Alto पर जाते हैं, और sponsorship requests paymaster पर जाते हैं। इस पेज की scripts test accounts को Admin RPC के माध्यम से fund भी करती हैं। |

## शुरू करने से पहले

* एक Virtual Environment, जो किसी ऐसे network से fork किया गया हो जहाँ ERC-4337 EntryPoint contracts deployed हैं, जैसे Ethereum Mainnet, Base, OP Mainnet, या Arbitrum One। यह parent network का chain ID रख सकता है या किसी custom chain ID का उपयोग कर सकता है। Virtual Environment बनाने के लिए, [Virtual Environment quickstart](https://docs.tenderly.co/virtual-environments/quickstart.md) का पालन करें।
* Virtual Environment के **Public RPC** और **Admin RPC** URLs, जो **Home** tab पर **Integrate Virtual RPC** card में सूचीबद्ध हैं (देखें [dashboard संदर्भ](https://docs.tenderly.co/virtual-environments/dashboard.md))
* Docker Compose के साथ Docker
* Node.js 20.6 या बाद का version और npm
* `jq`, [snapshot उदाहरण](#test-runs-के-बीच-state-reset-करें) के लिए

## Alto और mock paymaster चलाएँ

**1. Project और उसकी .env file बनाएँ**

यह command एक project folder और bundler के लिए तीन नई private keys वाली एक `.env` file बनाता है।

```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` खोलें, दोनों placeholder URLs को Virtual Environment के Public RPC और Admin RPC URLs से बदलें, और parent network के लिए `ALTO_CHAIN_TYPE` सेट करें:

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

> [!WARNING]
>
> नई keys generate करें। Anvil या Hardhat के डिफ़ॉल्ट जैसी जानी-मानी test keys का उपयोग न करें। Live networks के forks पर, वे addresses EIP-7702 के माध्यम से एक ऐसे contract को delegate किए गए हैं जो उन्हें मिलने वाला कोई भी ETH forward कर देता है, इसलिए उनके पास कभी कोई balance नहीं रहता।

**2. Funding script जोड़ें**

शुरू होने से पहले Alto को अपनी keys पर ETH की आवश्यकता होती है। Alto के पहली बार शुरू होने पर utility key उसके simulation contracts deploy करती है, और executor keys bundle transactions के लिए भुगतान करती हैं।

Virtual Environment pre-funded accounts के साथ शुरू होता है, जिन्हें `eth_accounts` लौटाता है। Admin RPC unsigned [`eth_sendTransaction`](https://docs.tenderly.co/virtual-environments/admin-rpc#eth_sendtransaction) requests स्वीकार करता है, इसलिए script हर key को उन accounts में से किसी एक से किए गए transfer से fund करती है।

Script को `fund-accounts.mjs` के रूप में save करें:

```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 file जोड़ें**

File को `docker-compose.yml` के रूप में save करें:

```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 | इसे इस तरह क्यों सेट किया गया है |
| - | - |
| `ALTO_RPC_URL` | Public RPC URL। Alto केवल standard JSON-RPC methods का उपयोग करता है। |
| `ALTO_SAFE_MODE: "false"` | Safe mode में, Alto हर validation को एक custom JavaScript tracer के साथ `debug_traceCall` के माध्यम से trace करता है, जिसे Virtual Environment RPCs serve नहीं करते। Safe mode बंद होने पर, Alto ERC-7562 validation rules (restricted opcodes और storage access) लागू नहीं करता, इसलिए जो account या paymaster Virtual Environment पर पास हो जाता है, उसे कोई production bundler फिर भी reject कर सकता है। |
| `ANVIL_RPC` | Admin RPC URL। इस variable का नाम Anvil के नाम पर रखा गया है। Public RPC URL के साथ, mock paymaster startup पर exit हो जाता है। |
| Image versions | दोनों images उन versions पर pinned हैं जिनके साथ यह गाइड test की गई थी। |

> [!NOTE]
>
> Mock paymaster केवल testing के लिए है। यह हर request को sponsor करता है और सार्वजनिक रूप से ज्ञात key से sign करता है।

**4. Stack शुरू करें**

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

पहले funder चलता है, फिर Alto, फिर mock paymaster। Stack आमतौर पर 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"]}
```

फिर paymaster को ping करें:

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

Virtual Environment पर पहली बार शुरू होने पर, mock paymaster नीचे दिए गए contracts deploy करता है। ये addresses हर network पर समान हैं।

| Contract | Address |
| - | - |
| EntryPoint 0.6 के लिए paymaster | `0x20a2ED5AAdc0d87488dbc238A5Eb83A6955BD598` |
| EntryPoint 0.7 के लिए paymaster | `0x38aef040CEB057B62E1598F5C265946A4E4BaB4C` |
| EntryPoint 0.8 के लिए paymaster | `0xe276558647476dC0f409B25a1AFCbCed730128D9` |
| Gas के भुगतान के लिए test ERC-20 token | `0x68e13372AE8FAaDDaf32cC08ee44C5ef5A002c69` |

हर paymaster को अपने EntryPoint में 50 ETH का deposit मिलता है।

## Sponsored UserOperation भेजें

**1. viem और permissionless install करें**

[viem](https://viem.sh) और [permissionless](https://github.com/pimlicolabs/permissionless.js) install करने के लिए project folder में ये commands चलाएँ:

```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` में वे clients और constants हैं जिन्हें इस पेज की सभी scripts साझा करती हैं।

```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 बनाएँ**

यह script एक ऐसा smart account बनाती है जिसके पास कोई ETH नहीं है, और एक ऐसा UserOperation भेजती है जिसके लिए mock paymaster भुगतान करता है।

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

Account एक ही UserOperation में deploy हुआ और उसने अपना call किया, और उसके पास अब भी कोई ETH नहीं है। Bundle का पूरा trace देखने के लिए, [Virtual Environment Explorer](https://docs.tenderly.co/virtual-environments/explorer.md) में transaction hash खोजें।

किसी दूसरे EntryPoint version का उपयोग करने के लिए, `entryPoint` constant को बदलें, उदाहरण के लिए `{ address: entryPoint08Address, version: "0.8" }` में। Alto को EntryPoint 0.6, 0.7, और 0.8 के लिए configure किया गया है, और mock paymaster हर एक के लिए एक paymaster deploy करता है।

> [!NOTE]
>
> तीनों endpoints को अलग-अलग रखें। Alto केवल bundler methods का उत्तर देता है: यदि आप उसे `eth_call` जैसा कोई read भेजते हैं, तो viem `The method "eth_call" does not exist / is not available` report करता है। `pm_getPaymasterStubData` जैसे paymaster methods paymaster URL पर जाते हैं।

## Gas के भुगतान के अन्य तरीके

नीचे दी गई हर script पूर्ण है और `setup.ts` को reuse करती है। इसे `sponsored.ts` की तरह ही चलाएँ, उदाहरण के लिए `npx tsx --env-file=.env erc20.ts`।

### Account के balance से gas का भुगतान करें

Paymaster के बिना, account को अपने पहले UserOperation से पहले ETH की आवश्यकता होती है। `getFundedWallet` इसे Admin RPC के माध्यम से एक pre-funded account से भेजता है।

```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 token में gas का भुगतान करें

Mock paymaster अपने खुद के test token को gas के भुगतान के रूप में स्वीकार करता है। कोई भी `sudoMint` से यह token mint कर सकता है।

```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]
>
> Script पहले भुगतान से पहले paymaster की treasury में token का 1 wei mint करती है। इसके बिना, नए Virtual Environment पर पहला ERC-20 UserOperation `AA50 postOp reverted` के साथ fail हो जाता है। Alto, paymaster की `postOp` gas को 1 wei की fees के साथ मापता है, जहाँ token fee round होकर शून्य हो जाती है। वास्तविक fees के साथ, खाली treasury में पहले transfer को Alto द्वारा मापी गई gas से लगभग 22,600 अधिक gas की आवश्यकता होती है, और `postOp` की gas खत्म हो जाती है।

### EIP-7702 account से UserOperation भेजें

एक externally owned account (EOA) `Simple7702Account` implementation को delegate करके smart account की तरह काम कर सकता है। इसके लिए EntryPoint 0.8 आवश्यक है। पहले UserOperation में signed authorization होता है, और Alto उसे एक EIP-7702 transaction में submit करता है।

```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 का code `0xef0100` और उसके बाद implementation address होता है। उसी account के बाद के UserOperations को `authorization` field की आवश्यकता नहीं होती।

## Test runs के बीच state reset करें

Test runs के बीच Virtual Environment को किसी ज्ञात state पर वापस लाने के लिए, [`evm_snapshot`](https://docs.tenderly.co/virtual-environments/admin-rpc#evm_snapshot) से snapshot लें, Admin RPC पर [`evm_revert`](https://docs.tenderly.co/virtual-environments/admin-rpc#evm_revert) से उस पर revert करें, और हर revert के बाद Alto को restart करें। यह उदाहरण `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
```

आप उसी snapshot पर जितनी बार आवश्यकता हो उतनी बार revert कर सकते हैं। Dashboard flow और revert distance सीमा के लिए, देखें [Virtual Environment state को revert करें](https://docs.tenderly.co/virtual-environments/develop/revert-state.md)।

> [!WARNING]
>
> हर `evm_revert` के बाद Alto को restart करें। Alto submit किए गए bundles, pending account deployments, और हाल की receipts को memory में रखता है, और revert के बाद वह state ऐसे blocks का वर्णन करती है जो अब मौजूद नहीं हैं। Restart के बिना, हो सकता है कि UserOperations `AA10 ... Another deployment operation for this sender is already being processed` के साथ fail हों, कभी confirm न हों, या उन UserOperations की receipts लौटाएँ जो revert किए गए थे। `debug_bundler_clearState` से Alto का mempool clear करना restart की जगह नहीं लेता।

## Time travel और paymaster validity windows

Paymaster signatures में आमतौर पर एक validity window होती है, और दो clocks उसे जाँचते हैं: EntryPoint उसकी तुलना block timestamp से करता है, और Alto उसकी तुलना उस machine के clock से करता है जिस पर वह चलता है। Virtual Environment पर, ये दोनों अलग हो सकते हैं:

* [`evm_increaseTime`](https://docs.tenderly.co/virtual-environments/admin-rpc#evm_increasetime) के बाद, block timestamps machine के clock से आगे चलते हैं (देखें [Virtual Environments पर timestamps के साथ काम करना](https://docs.tenderly.co/virtual-environments/develop/timestamps.md))।
* `evm_revert` के बाद, block timestamps snapshot के timestamp से जारी रहते हैं, इसलिए वे machine के clock से उतने समय पीछे चलते हैं जितना समय snapshot के बाद से बीत चुका है।

Mock paymaster हर sponsorship को machine के clock से 60,000 सेकंड के लिए sign करता है। यदि आप time को इससे अधिक आगे बढ़ाते हैं, तो उसकी sponsorships chain पर पहले ही expire हो चुकी होती हैं: UserOperation कभी confirm नहीं होता, और जब तक आप Alto को restart नहीं करते, वह fail हो रहे bundle को resubmit करता रहता है। इससे अधिक आगे jump करने वाले tests के लिए, paymaster के बिना UserOperations भेजें, या [अपनी paymaster service का उपयोग करें](#अपनी-paymaster-service-का-उपयोग-करें)।

## अपनी paymaster service का उपयोग करें

अपने खुद के sponsorship rules को test करने के लिए, अपनी paymaster service को उसी Virtual Environment पर चलाएँ और `PAYMASTER_URL` की जगह उसका URL paymaster client को pass करें। ERC-7677 (`pm_getPaymasterStubData` और `pm_getPaymasterData`) को implement करने वाली कोई भी service इस पेज की scripts के साथ काम करती है।

तीन बातें Virtual Environment के लिए विशिष्ट हैं:

* **Paymaster को Admin RPC के माध्यम से fund करें।** Paymaster contract को EntryPoint deposit की आवश्यकता होती है, और उसे deploy करने वाले account को ETH की आवश्यकता होती है। दोनों को एक pre-funded account से भेजें, जैसा `getFundedWallet` करता है।
* **Validity windows को दोनों clocks में से आगे वाले clock से sign करें।** `validUntil` को latest block timestamp और service के अपने clock में से जो आगे हो, उससे compute करें। केवल block timestamp पर आधारित signature तब fail हो जाता है जब Virtual Environment का clock पीछे हो: Alto `UserOperation expires too soon` के साथ UserOperation को reject कर देता है।
* **Service को Public RPC URL दें।** Chain को पढ़ने और signed transactions भेजने के लिए Admin RPC की आवश्यकता नहीं होती।

Example repository का [policy paymaster](https://github.com/Tenderly/tenderly-pimlico-bundler/tree/main/policy-paymaster) ये तीनों बातें करता है, और केवल उन्हीं UserOperations को sponsor करता है जो उसकी API key जाँच, sender और target allowlists, और प्रति sender spending cap को पास करते हैं।

## समस्या निवारण

| लक्षण | कारण | समाधान |
| - | - | - |
| `docker compose up` `dependency failed to start` report करता है, और fail हुई service के log में `The request took too long to respond` दिखता है | जब service एक startup transaction भेज रही थी, तब Virtual Environment को भेजा गया एक request time out हो गया। | `docker compose up -d` फिर से चलाएँ। Startup को दोहराना सुरक्षित है: हर service वह सब skip कर देती है जो पहले से deployed और funded है। |
| `Bundler used an invalid aggregator for handling aggregated User Operations`, जिसकी `Details:` line में `debug_traceCall` है | Alto safe mode में चल रहा है। viem यह message Alto से Virtual Environment को भेजे गए किसी भी fail हुए request के लिए दिखाता है, और कारण `Details:` line में होता है। | `ALTO_SAFE_MODE: "false"` सेट करें। |
| वही error, जिसकी `Details:` line में `gasEstimateL1Component` है | `ALTO_CHAIN_TYPE` `arbitrum` है। उस mode में Alto, Arbitrum के `NodeInterface` contract से L1 gas component माँगता है। | Arbitrum One के लिए `ALTO_CHAIN_TYPE=default` सेट करें। |
| Alto `Failed to deploy PimlicoSimulations contract` के बाद `insufficient funds for gas * price + value` के साथ exit हो जाता है | Alto की utility key के पास कोई ETH नहीं है। | `docker compose logs funder` से जाँचें कि funder पूरा हो गया है, और यह कि `TENDERLY_ADMIN_RPC_URL` Admin RPC URL है। |
| Mock paymaster `Access forbidden by access rules, try Admin RPC URL` के साथ exit हो जाता है | `ANVIL_RPC` Public RPC URL पर सेट है। Startup पर mock paymaster `anvil_setBalance` call करता है। | `.env` में `TENDERLY_ADMIN_RPC_URL` को Admin RPC URL पर सेट करें। |
| Test token में gas का भुगतान करते समय `AA50 postOp reverted` | Paymaster की treasury के पास यह token बिल्कुल नहीं है। | प्रति Virtual Environment एक बार `0xD8Baa107006C93a030d1455A2eF43261b384F21c` को token का 1 wei mint करें, जैसा `erc20.ts` करती है। |
| `The method "eth_call" does not exist / is not available` | Bundler URL पर एक read भेजा गया। `pm_getPaymasterStubData` के लिए इसी error का मतलब है कि paymaster client Alto पर point करता है। | Public client को Public RPC URL से बनाएँ, bundler URL का उपयोग केवल `bundlerTransport` के रूप में करें, और paymaster client को paymaster URL से बनाएँ। |
| `evm_revert` के बाद UserOperations `AA10 ... Another deployment operation for this sender is already being processed` के साथ fail हो जाते हैं या कभी confirm नहीं होते | Alto के पास उन blocks की state है जिन्हें revert ने हटा दिया। | `docker compose restart alto` चलाएँ। देखें [Test runs के बीच state reset करें](#test-runs-के-बीच-state-reset-करें)। |
| `evm_increaseTime` के बाद sponsored UserOperations कभी confirm नहीं होते | Mock paymaster की sponsorship chain पर expire हो गई। | अटके हुए UserOperation को drop करने के लिए Alto को restart करें। देखें [Time travel और paymaster validity windows](#time-travel-और-paymaster-validity-windows)। |
| अपनी paymaster service के साथ `UserOperation expires too soon` | Service ने `validUntil` को block timestamp से sign किया, जबकि Virtual Environment का clock पीछे है। | दोनों clocks में से आगे वाले clock से sign करें। देखें [अपनी paymaster service का उपयोग करें](#अपनी-paymaster-service-का-उपयोग-करें)। |
| किसी address को वह ETH कभी नहीं मिलता जो आप उसे भेजते हैं | वह address किसी जानी-मानी test key का है। Live networks के forks पर, वे addresses उन्हें मिलने वाला कोई भी ETH forward कर देते हैं। | नई key generate करें। |

## यह भी देखें

* GitHub पर [tenderly-pimlico-bundler](https://github.com/Tenderly/tenderly-pimlico-bundler): policy paymaster और smoke test के साथ पूरा example
* `eth_sendTransaction`, `evm_snapshot`, `evm_revert`, और `evm_increaseTime` के लिए [Admin RPC संदर्भ](https://docs.tenderly.co/virtual-environments/admin-rpc.md)
* Snapshots या dashboard के साथ [Virtual Environment state को revert करें](https://docs.tenderly.co/virtual-environments/develop/revert-state.md)
* [Virtual Environments पर timestamps के साथ काम करना](https://docs.tenderly.co/virtual-environments/develop/timestamps.md)
* Virtual Environment पर [Viem](https://docs.tenderly.co/virtual-environments/libraries/viem.md): custom chains और custom RPC methods
* Bundle transaction को step through करने के लिए [Debugging Transactions](https://docs.tenderly.co/virtual-environments/develop/debug-transactions.md)


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