---
name: build-with-viem-eip8130
description: >-
  Build apps on Base's native account abstraction (EIP-8130) and payer
  sponsorship (ERC-8168) using the viem `eip8130` module. Use when writing
  code that creates or operates 8130 smart accounts, authorizes session-key
  actors or policies, sends batched calls, rotates owners, sponsors gas with a
  payer, or wires a frontend/script against the vibenet devnet or Base Sepolia.
---

# Build with viem — EIP-8130 (native account abstraction)

EIP-8130 puts account abstraction **in the protocol**. Accounts are portable
across EVM chains, support multiple signer types (secp256k1, P-256, WebAuthn),
key rotation without changing address, scoped session-key actors, on-chain
policies, and native ERC-8168 gas sponsorship. Tooling lives in
`viem/eip8130` (payer: `viem/eip8168`).

> **When something misbehaves, read the guide.** The `eip-8130-web` guide (repo
> `github.com/chunter-cb/eip-8130-web`, chapters under `/guide/*`, source in
> `src/lib/guide`) is the deep reference — narrative walkthroughs, runnable
> examples, and step-by-step troubleshooting for everything below. This skill is
> the quick-start; the guide has far more detail when something goes wrong.

## Where the code lives

- **Spec:** https://eip.tools/eip/8130 · payer: https://eip.tools/eip/8168
- **viem fork/branch:** `github.com/chunter-cb/viem`, branch `feat/eip-8130-production`
  (module: `src/eip8130`, payer: `src/eip8168`). Not
  yet in npm `viem` — install the fork branch.
- **RPC endpoints (Vibenet), chain id `84538453`:**
  - Public execution RPC — `https://rpc.vibes.base.org`. This **is** 8130-capable
    (`AA_TX_TYPE` / `0x79`); use for reads, estimates, and broadcasts from
    Node/scripts.
  - Browser proxy — `https://vibes.base.org/api/vibenet/account/rpc`. Same
    upstream chain, same-origin Next.js proxy for browser `eth_*` (CORS). Prefer
    this from the browser; from Node either URL works.
  - Hosted payer — `https://vibes.base.org/api/vibenet/account/payer`.
  - Faucet — `POST https://api.vibes.base.org/api/vibenet/faucet/drip` with
    `{ "address": "0x…" }`.
- **Base Sepolia** — `https://sepolia.base.org`, chain id `84532`.

```bash
bun add "viem@github:chunter-cb/viem#feat/eip-8130-production"
```

```ts
import { privateKeyToAccount } from "viem/accounts";
import { newSmartAccount, sendTransaction } from "viem/eip8130";
import { createPayerClient, sendSponsoredCalls } from "viem/eip8168";
```

### Two integration styles

- **Standalone actions** (used throughout this skill): every action takes a viem
  `Client` as its first arg — `sendTransaction(client, { … })`.
- **Native core** (`eip8130ChainConfig`): spread it into `defineChain({ ...eip8130ChainConfig, id, … })`
  and core `client.sendTransaction` / `client.getTransactionReceipt` speak the
  native AA tx type (`0x79`) for an 8130 account automatically. A
  `client.extend(eip8130Actions())` decorator exposes `client.eip8130.*`.
  Sponsored (payer) sends stay on the `viem/eip8168` path.

## Signer vs actor identity (do not mix these up)

| Helper | Input | Returns | Use for |
| --- | --- | --- | --- |
| `privateKeyToAccount(pk)` / `toP256Signer` / `toWebAuthnSigner` | private key / credential | a **signer** (`signTransaction`) | `newSmartAccount({ signer })` |
| `key.k1(address)` / `key.p256(pubKey)` / `key.webAuthn(pubKey)` | address or public key | an **actor identity** (`{ actorId, authenticator }`) | `initialActors` / `authorizeActor` / `revokeActor` |

Passing a private key to `key.k1(...)` is wrong — it builds an actor id via
`pad(address)`, not a signer, and fails with an opaque `pad()` TypeError.
`newSmartAccount` derives `key.k1(signer.address)` for the primary actor
internally; you only call `key.*` yourself to authorize extra actors.

## Core concepts

- **Account** — viem-style object with `.address` (CREATE2-derived),
  `.create()` / `.createChange`, `.change(...)`, and `signTransaction`. Create
  via `newSmartAccount` / `toAccount` / `toEoaAccount`.
- **Signer** — produces `sender_auth`. K1: `privateKeyToAccount(pk)`. P-256 /
  WebAuthn: `toP256Signer` / `toWebAuthnSigner`.
- **Actor** — on-chain identity (`{ actorId, authenticator }`) from `key.*`,
  with a **scope** bitfield and optional **policy**.
- **Scope** (`actorScope`) — `scopeUnrestricted` (0x00) is admin. Bits (uint16):
  `operator` (0x01, ungated initiation — formerly "sender"), `selfPayer` (0x02),
  `sponsorPayer` (0x04), `policy` (0x08, gated initiation), `nonce` (0x10).
  **OPERATOR and POLICY are mutually exclusive.** A policy-bearing actor must be
  restricted (non-zero scope), or `authorizeActor` throws. When a send fails
  `actor scope insufficient`, a required bit is missing.
- **Nonce mode** — admin (`0x00`) or an actor with the `nonce` bit
  (`actorScope.nonce`) may use **ordered** (sequenced, expiry-free) or nonce-free
  (expiring) nonces; sends default to ordered. Only a restricted actor
  **without** the `nonce` bit is confined to nonce-free.
- **Policy** — on-chain rules (e.g. `SessionPolicy`), built with
  `defineSessionPolicy` + `encodeSessionPolicyConfig`.
- **Calls** — batch of `{ to, value?, data? }` (flat) or phases (nested `AaCalls`).
  Optional signed `metadata` (top-level tx field) via `dataSuffix` on send.
- **Payer (ERC-8168)** — co-signs `payer_auth` to pay gas. Client:
  `createPayerClient`.

## Create an account and send a batch

Verified live against Vibenet (self-paid path).

```ts
import { createPublicClient, http, parseEther, toHex } from "viem";
import { privateKeyToAccount, generatePrivateKey } from "viem/accounts";
import {
  newSmartAccount, sendTransaction, estimateGas,
  waitForTransactionReceipt, allPhasesSucceeded,
} from "viem/eip8130";

const RPC_URL = "https://rpc.vibes.base.org";
const client = createPublicClient({
  chain: {
    id: 84538453, // Vibenet (Base Sepolia = 84532)
    name: "vibenet",
    nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
    rpcUrls: { default: { http: [RPC_URL] } },
  },
  transport: http(RPC_URL),
});
// Browser apps: use https://vibes.base.org/api/vibenet/account/rpc instead.

// 1) Signer = LocalAccount (NOT key.k1).
const signer = privateKeyToAccount(generatePrivateKey());
// P-256: toP256Signer({ privateKey }) · WebAuthn: toWebAuthnSigner(...)

// 2) Deterministic account — address exists before any tx. Owner is admin
//    (scope 0x00), so sends default to ORDERED (sequenced) nonces.
const account = newSmartAccount({ signer });

// 3) Fund, estimate, send. First tx deploys the account AND runs the batch.
await fetch("https://api.vibes.base.org/api/vibenet/faucet/drip", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ address: account.address }),
});

const calls = [{ to: "0x…recipient", value: parseEther("0.001") }];
const gas = await estimateGas(client, {
  sender: account.address,
  accountChanges: [account.createChange],
  calls: [calls],
});
const hash = await sendTransaction(client, {
  account,
  accountChanges: [account.createChange], // omit on later txs
  calls,
  dataSuffix: toHex("invoice #4242"), // optional signed metadata (top-level tx field)
  gas: (gas * 120n) / 100n,
});

const receipt = await waitForTransactionReceipt(client, { hash });
if (!allPhasesSucceeded(receipt)) throw new Error("a phase reverted");
// Need the receipt inline? `sendTransactionSync(client, { … })` returns it.
```

Vibenet is alpha — expect occasional builder lag. Floor `gas` generously.

The **Keystore is enshrined** and identical on every chain — import
`keystoreAddress` from `viem/eip8130` (do not read it from a deployment).
Resolve the remaining, bytecode-derived addresses with
`getEip8130Deployment(chainId)` (or `canonicalEip8130Deployment`):
`accounts.{ default, defaultHighRate, erc4337, upgradeable? }`,
`authenticators.{ k1, p256, webAuthn, delegate }`,
`policies.{ manager, sessionPolicy }`. `accounts.upgradeable`
(CoinbaseSmartWalletV2) is pending deployment. Never borrow another chain's
deployment.

## Sponsor gas with a payer (ERC-8168)

Verified live: hosted payer supports **both** modes.

- `mode: "send"` (default) — payer co-signs and submits (`payer_sendTransaction`).
- `mode: "sign"` — payer co-signs only; you broadcast with `eth_sendRawTransaction`.

```ts
import { createPayerClient, sendSponsoredCalls } from "viem/eip8168";

const payer = createPayerClient({
  url: "https://vibes.base.org/api/vibenet/account/payer",
});

// Default mode:"send" — payer co-signs and broadcasts.
const { transactionHash: hash } = await sendSponsoredCalls(client, {
  account,
  payerClient: payer,
  accountChanges: [account.createChange], // optional on first tx
  calls: [{ to: account.address, value: 0n, data: "0x" }],
  gas: 2_000_000n,               // floor: payer estimates from calls only
  context: { flow: "transact" }, // budgets free grants per (sender, flow)
});
const receipt = await waitForTransactionReceipt(client, { hash });
```

For self-submit (custom RPC / retry control), pass `mode: "sign"` and broadcast
the returned `signedTransaction` yourself.

## Authorize a policy-gated session actor

A session key is **POLICY-scoped**, not `operator`-scoped: `actorScope.policy`
grants gated initiation while every call is routed through its manager. Grant
`actorScope.nonce` too for a sequenced channel, and `actorScope.selfPayer` if the
key pays its own gas. Register the PolicyManager as a **K1 operational actor**
(`key.k1(manager)`, `actorScope.operator`) in the **same** change: DefaultAccount
only lets a live k1 operator (or the account itself) drive `executeBatch`.

```ts
import { zeroAddress } from "viem";
import {
  actorScope, authorizeActor, key,
  defineSessionPolicy, encodeSessionPolicyConfig,
  getConfigSequence, getEip8130Deployment,
} from "viem/eip8130";

const dep = getEip8130Deployment(client.chain.id)!;
const policyConfig = encodeSessionPolicyConfig({
  tokenLimits: [
    { token: usdv, limit: 100_000_000n, period: 604_800n }, // 100 USDV / week
    // Native ETH is fail-closed: to move ETH (value > 0) add a zero-address
    // limit. Absent → no ETH (reverts NativeValueNotAllowed). ERC-20s differ:
    // an absent token limit is unbounded (the callScope is the gate).
    { token: zeroAddress, limit: 100_000_000_000_000_000n, period: 604_800n }, // 0.1 ETH / week
  ],
  callScopes: [{ target: usdv, selectorRules: [{ selector: "0xa9059cbb" }] }], // transfer only
});
const session = defineSessionPolicy({
  account: account.address,
  policy: dep.policies.sessionPolicy,
  policyConfig,
  manager: dep.policies.manager,
  validUntil: 1_900_000_000n,
});

const sessionKey = key.k1(sessionSigner.address); // actor identity, not a signer
const manager = key.k1(dep.policies.manager); // drive-only contract: K1 + operator

// Read the LIVE local sequence — never hardcode it. The Keystore is enshrined,
// so getConfigSequence needs only the account (no keystore arg).
const { local } = await getConfigSequence(client, {
  account: account.address,
});

const change = await account.change(
  [
    authorizeActor(manager, { scope: actorScope.operator }),
    authorizeActor(sessionKey, {
      scope: actorScope.policy | actorScope.nonce, // POLICY (+ NONCE); NOT operator
      expiry: 1_900_000_000n,
      policy: session.actorPolicy,
    }),
  ],
  { chainId: client.chain.id, sequence: Number(local) },
);
// Include `change` in accountChanges of a sendTransaction / sendSponsoredCalls
// signed by an admin actor.
```

Drive a policy-gated call with the session signer bound to the account address
(do **not** redeclare scope on this handle — `prepare` reads it from chain):

```ts
import { canonicalAuthenticators, toAccount } from "viem/eip8130";

const sessionAccount = toAccount({
  signer: sessionSigner,
  address: account.address,
  authenticator: canonicalAuthenticators.k1,
});
const executeCall = session.executeCall({
  target: usdv, value: 0n, data: transferData,
});
// send via sendTransaction / sendSponsoredCalls with account: sessionAccount
```

## Rotate an owner (config change)

```ts
import {
  actorScope, authorizeActor, revokeActor, key,
  getConfigSequence, sendTransaction,
} from "viem/eip8130";

const { local } = await getConfigSequence(client, {
  account: account.address,
});
const rotate = await account.change(
  [
    authorizeActor(key.k1("0x…newOwnerAddress"), { scope: actorScope.operator }),
    revokeActor(key.k1("0x…oldOwnerAddress")),
  ],
  { chainId: client.chain.id, sequence: Number(local) },
);
await sendTransaction(client, {
  account, accountChanges: [rotate], calls: [], gas: 200_000n,
});
```

> **Rotation caveat (upgraded EOAs).** An EOA you delegate to 8130 keeps its
> native key powers, so "rotating it away" isn't real security — prefer a
> **fresh** 8130 account for key-rotation guarantees. You also can't revoke the
> actor you're signing with in the same tx (`Key A revokes A` is rejected;
> the misleading error is `actor is not bound`), so rotating an upgraded EOA
> takes two txs.

## Verifying a config change

Signed actor/account changes are applied as a **transaction-validity
precondition**, before any call phase — think of it as **"call phase −1"**. Two
consequences follow, and they rule out the "silent no-op" mental model:

- **If the tx is included, the actor changes applied.** Phase −1 is a
  **validity gate**: an invalid account change (stale sequence, wrong `actorId`,
  revoking the key you're signing with, etc.) makes the whole tx invalid, so it
  is **rejected at validation and never mines** — you don't get a receipt with
  the authorize "silently skipped." Conversely, a mined tx guarantees the actor
  changes are in.
- **Valid actor changes persist even if the calls revert.** Because they apply
  at phase −1, a revert in call phase 0 does **not** roll them back. Valid
  account changes take effect regardless of what the call phases do.

Account changes emit their own events — **`ActorAuthorized` / `ActorRevoked`** —
which are the canonical, off-chain actor-enumeration mechanism. So a successful
authorize/revoke **does** show up in `receipt.logs`; confirm from there, or read
the applied state back directly:

- **`receipt.logs` carry an `ActorAuthorized` / `ActorRevoked` per applied
  change** — that's your receipt-level confirmation of a config change.
- **`allPhasesSucceeded` / `phaseStatuses` only cover CALL phases**, not
  account-change application (which happened at phase −1) — don't use them to
  check an authorize; use the events or a state read.
- **State read (belt-and-suspenders):** `isActor`, `getActorConfig`, or
  a bumped `getConfigSequence`. Poll ~1 block (~2s) if state lags the
  receipt.

Sequence correctness matters because the digest binds
`(account, chainId, sequence)`. A wrong sequence makes the change invalid, which
(per above) fails the whole tx rather than no-op'ing it — so always read the
live counter. Session-key auth uses the **local** channel
(`chainId = chain.id`); owner changes use the **multichain** channel
(`chainId = 0`).

### Debugging a `0x0` receipt

Because phase −1 is a validity gate, a **mined** receipt with `status: 0x0` is
always a **call-phase** failure — never the actor changes. No trace/replay
needed; the receipt already localizes it and the logs carry the detail:

```ts
const receipt = await waitForTransactionReceipt(client, { hash });

if (!allPhasesSucceeded(receipt)) {
  // phaseStatuses is per-phase 0x1/0x0; first 0x0 is the phase that reverted
  // (every phase after it is skipped and also reported 0x0).
  const failedPhase = receipt.eip8130.phaseStatuses.findIndex((s) => s === "0x0");
  // receipt.logs (from phases that committed before the revert) carry the detail
  // you need — inspect/decode them rather than re-simulating.
}
```

Rules of thumb:
- **Included ⇒ actor changes applied.** Never debug phase −1 from a receipt; a
  bad one never lands.
- **`status: 0x0` ⇒ a call phase failed** — use `phaseStatuses` to find which.
- **`logs` provide more data** if the phase index alone isn't enough.

| Deploy path | First local sequence |
|---|---|
| `newSmartAccount` (`account.createChange`) | `1` (create bumps local 0→1) |
| Explicit `importAccount` | `1` |
| Bare 7702 delegation (`account.delegate`) | `0` (delegation does not initialize state) |

## Reading account state (viem actions)

All take `(client, params)`:
`getActorConfig`, `isActor`, `getPolicy`, `getSessionSpend`,
`getLockStatus` / `isLocked`, `getConfigSequence`,
`getTransactionCount`, `getTransaction`, `getTransactionReceipt`,
`waitForTransactionReceipt`.

## Account creation modes

- `newSmartAccount({ signer })` — CREATE2 smart account (most common).
  `signer` must be a signing account — **not** `key.k1(...)`.
- `toAccount({ signer, userSalt, code, initialActors, … })` — full control.
- `toAccount({ signer, address, authenticator })` — configured actor on an
  existing/delegated account.
- `toEoaAccount(signer)` — EOA as its own default K1 actor; EIP-7702 via
  `account.delegate(impl)`.

## Locking

Lock/unlock are single-op `SignedAccountChanges` on the **local** channel:
build the op with `lockChange({ unlockDelay })` / `unlockChange()`, sign it with
an admin (scope 0) actor via `signAccountChanges({ …, channel: 'local' })`, then
apply it with `encodeApplySignedAccountChangesData({ account, ...entry })` (as a
standalone call to the enshrined **Keystore** (`keystoreAddress`), or folded into
a tx's `accountChanges`). Read state with `getLockStatus` / `isLocked`.
`unlockDelay` is a `uint16` (`1…65535` seconds). Node support is currently
deferred — the builders are contract-accurate but a native tx carrying one is
still rejected.

## Sign a message (ERC-1271)

`account.signMessage({ message })` and `account.signTypedData(typedData)` now
work — they emit a **SignedMessageEnvelope** (`sigType(1) || authenticator(20) ||
data`) over a replay-safe digest, so any authenticator (k1/P-256/WebAuthn) and
session keys can sign. `sigType` is **multichain** by default (`signatureType.multichain`,
binds `chainId 0` — valid everywhere); pass `signatureType.local` to bind
`block.chainid`.

```ts
import { validateSignature, wrapCounterfactualSignature } from "viem/eip8130";

const signature = await account.signMessage({ message: "gm" });

// Verify via ERC-1271 (core action) …
const ok = await client.verifyMessage({ address: account.address, message: "gm", signature });
// … or canonically against the Keystore (returns which actor/scope signed).
const { valid, actorId, scope } = await validateSignature(client, {
  account: account.address, message: "gm", signature,
});
```

For a **counterfactual** (not-yet-deployed) account, wrap with
`wrapCounterfactualSignature({ signature, … })` (ERC-6492) so verifiers can
validate before the first tx. Standalone helpers: `signMessageEnvelope` /
`signTypedDataEnvelope`, `replaySafeHash`, `wrapSignatureEnvelope` /
`parseSignatureEnvelope`.

## Gotchas

- **`key.k1` ≠ signer.** Passing a private key (or `key.k1(...)`) as `signer`
  to `newSmartAccount` fails with an opaque `pad()` TypeError — use
  `privateKeyToAccount(pk)`.
- Fund `account.address` **before** a self-paid first tx (unless a payer
  sponsors it).
- Only the **first** tx includes `account.createChange`.
- Never hardcode the config sequence — always read it live.
- Session keys: authorize as `actorScope.policy | actorScope.nonce` (NOT
  `operator`; the two are mutually exclusive), and register the PolicyManager as
  `key.k1(manager)` with `actorScope.operator` in the same change.
- Hosted payer: default `mode: "send"` works; `mode: "sign"` for self-submit.
- **Nonce-free (expiring) sends** are verified working on the node. The signed
  `expiry` must sit inside the mempool's nonce-free window
  (`nonceFreeMaxExpiryWindow`), so base it on the node's latest block timestamp
  (not the local clock) with a small margin. Ordered (expiry-free) sends remain
  the default for admin and `SCOPE_NONCE` actors.
- Contract addresses are bytecode-derived — mismatched solc vs
  `canonicalEip8130Deployment` causes "create address mismatch".
- Outside built-in `eip8130ChainIds`, call `register8130Chains` /
  `is8130Enabled`.

## Reference

- **Guide (read this when stuck):** `github.com/chunter-cb/eip-8130-web` —
  chapters at `/guide/getting-started`, `/guide/creating-accounts`,
  `/guide/sending-transactions`, `/guide/keys-and-scopes`, `/guide/session-keys`,
  `/guide/gas-and-payers` (source under `src/lib/guide`). Narrative walkthroughs,
  runnable examples, and troubleshooting for everything above.
- **API:** `src/eip8130/index.ts` on the viem fork
  (`github.com/chunter-cb/viem`, branch `feat/eip-8130-production`).
- **Session-key + policy walkthrough:**
  https://gist.github.com/chunter-cb/bf70c53a5ab6d8361ce7f4215b776114
