Skip to content

TestWallet

A wallet a test controls, over a node: an EIP-1193 provider that behaves as a browser wallet does. The test says what the user answers to each prompt, and changes the account or the chain as a user would. It holds no key: it uses the accounts the node has unlocked.

It answers as EIP-5792 writes it, or, with like, as one real wallet does: Ambire, MetaMask, Rainbow or Rabby, each read in its source.

import { TestWallet } from "@ethect/core/testing";
Export Kind Description
TestWallet.make(options) function A wallet over the node of the transport in context.
TestWallet.Options type accounts, and optionally atomic, approve, chains, like and silent.
TestWallet.TestWallet type The wallet: its provider, and what a test drives and reads it with.
TestWallet.profiles constant The wallets read so far: ambire, metamask, rainbow, rabby.
TestWallet.Profile type One of them: _tag, release, sources, and MetaMask’s eip7702.

A transfer, sent when the user approves and not sent when they refuse.

transfer.test.ts
import { NodeServices } from "@effect/platform-node";
import { assert, layer } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { Transport } from "@ethect/core";
import { Eth, Wallet } from "@ethect/core/rpc";
import { AnvilNode, TestWallet } from "@ethect/core/testing";
// A fresh anvil per test, and an HTTP transport that reaches it.
const Node = AnvilNode.layer().pipe(Layer.provide(NodeServices.layer));
const Http = Layer.unwrap(
Effect.map(AnvilNode.AnvilNode, (node) => Transport.http(node.httpUrl)),
).pipe(Layer.provide(FetchHttpClient.layer));
const Chain = Layer.provideMerge(Http, Node);
layer(Chain, { buildPerTest: true, excludeTestServices: true })("a transfer", (it) => {
it.effect("is sent when the user approves", () =>
Effect.gen(function* () {
const [alice, bob] = yield* Eth.accounts();
const wallet = yield* TestWallet.make({ accounts: [alice!] });
// the app talks to the wallet, as it does to `window.ethereum`
const App = Transport.eip1193(wallet.provider);
const hash = yield* Wallet.sendTransaction({ to: bob!, value: 1n }).pipe(Effect.provide(App));
assert.strictEqual((yield* Eth.getTransactionByHash(hash))?.from, alice);
}),
);
it.effect("is not sent when the user refuses", () =>
Effect.gen(function* () {
const [alice, bob] = yield* Eth.accounts();
const wallet = yield* TestWallet.make({
accounts: [alice!],
approve: (request) => request.method !== "eth_sendTransaction",
});
const sent = yield* Wallet.sendTransaction({ to: bob!, value: 1n }).pipe(
Effect.as(true),
Effect.catchReason("RpcError", "UserRejectedRequest", () => Effect.succeed(false)),
Effect.provide(Transport.eip1193(wallet.provider)),
);
assert.isFalse(sent);
assert.strictEqual(yield* Eth.getTransactionCount(alice!, "pending"), 0);
}),
);
});

The wallet is made inside the test, over the test’s node. wallet.provider goes wherever a provider goes: Transport.eip1193 here. The examples below leave the node out.

A wallet that batches takes wallet_sendCalls. The calls run as one transaction: all of them, or none.

import { Effect } from "effect";
import { type Address, type Hex, Transport } from "@ethect/core";
import { Eth, Wallet } from "@ethect/core/rpc";
import { TestWallet } from "@ethect/core/testing";
const batch = (calls: ReadonlyArray<{ readonly to: Address.Address; readonly data: Hex.Hex }>) =>
Effect.gen(function* () {
const [alice] = yield* Eth.accounts();
const wallet = yield* TestWallet.make({ accounts: [alice!], atomic: "supported" });
// the app talks to the wallet, as it does to `window.ethereum`
const asked = Effect.provide(Transport.eip1193(wallet.provider));
const { id } = yield* Wallet.sendCalls({
version: "2.0.0",
chainId: 31337,
atomicRequired: true,
calls,
}).pipe(asked);
// 100 until a block is mined. Then 200 with one receipt, or 500 when a call reverted.
return yield* Wallet.getCallsStatus(id).pipe(asked);
});
atomic wallet_getCapabilities says wallet_sendCalls
"supported", the default supported runs the calls as one transaction
"ready" ready, then supported once the account agreed first asks approve with a request named "upgrade"
"unsupported" unsupported answers 5760
"none" -32601: the method does not exist -32601, and so does wallet_getCallsStatus

Real wallets do not all answer as EIP-5792 writes it. With like, the wallet answers as one of them does, read in that wallet’s source: what each changes is under Profiles. The rest is answered as above.

import { Effect } from "effect";
import type { Address } from "@ethect/core";
import { TestWallet } from "@ethect/core/testing";
// one wallet for each wallet read
const wallets = (alice: Address.Address) =>
Effect.forEach(Object.values(TestWallet.profiles), (like) =>
TestWallet.make({ accounts: [alice], like }),
);
// an Ambire that is locked: wallet_getCapabilities waits for a password
const locked = (alice: Address.Address) =>
TestWallet.make({
accounts: [alice],
like: TestWallet.profiles.ambire,
silent: ["wallet_getCapabilities"],
});

A request for a method in silent is taken, and answered once the test calls wallet.unlock: the user typed the password. Every other request is answered meanwhile.

setAccounts, setChain and disconnect do what a user does in the wallet, and emit the event a wallet emits.

import { Effect } from "effect";
import type { Address } from "@ethect/core";
import { TestWallet } from "@ethect/core/testing";
const user = (alice: Address.Address, bob: Address.Address) =>
Effect.gen(function* () {
const wallet = yield* TestWallet.make({ accounts: [alice] });
// the user picks another account: `accountsChanged` with [bob]
yield* wallet.setAccounts([bob]);
// the user picks another chain: `chainChanged` with "0x1"
yield* wallet.setChain(1);
// the wallet loses every chain: `disconnect`, and every request is refused with 4900
yield* wallet.disconnect;
// the user picks a chain again: `connect`, then `chainChanged`
yield* wallet.setChain(31337);
});

A listener only receives what is emitted after it registered. A stream of Eip1193 registers its listener when it starts to run: wait for wallet.listenerCount("chainChanged") to be above zero before changing the chain.

requests gives every request the wallet received, as it came.

import { Effect } from "effect";
import { Transport } from "@ethect/core";
import { Eth, Wallet } from "@ethect/core/rpc";
import { TestWallet } from "@ethect/core/testing";
const sent = Effect.gen(function* () {
const [alice] = yield* Eth.accounts();
const wallet = yield* TestWallet.make({ accounts: [alice!] });
yield* Wallet.requestAccounts().pipe(Effect.provide(Transport.eip1193(wallet.provider)));
yield* Eth.blockNumber().pipe(Effect.provide(Transport.eip1193(wallet.provider)));
return yield* wallet.requests;
// [{ method: "eth_requestAccounts", params: [] }, { method: "eth_blockNumber", params: [] }]
});

Effect<TestWallet.TestWallet, never, Transport | Scope>

The wallet, over the node of the Transport in context. It needs a scope: an it.effect test of @effect/vitest has one, and Effect.scoped gives one anywhere else.

Member Type Does
provider Eip1193.Provider What an app uses: request, on, removeListener.
wallet Wallets.Wallet The same, as a wallet of a list: its id is "test.wallet".
requests Effect<ReadonlyArray<{ method, params? }>> Every request received, in order.
listenerCount(event) Effect<number> How many listeners an event has.
setAccounts(accounts) Effect<void> Changes the accounts, and emits accountsChanged.
setChain(chainId) Effect<void> Changes the chain, which it then knows, and emits chainChanged.
disconnect Effect<void> Emits disconnect. Every request is refused with 4900 until setChain.
unlock Effect<void> Answers the requests held for silent, and every request from then on. Done once those are answered.
  • Type: ReadonlyArray<Address.Address>

The accounts the wallet holds, the first being the one it sends from when a request names none. The node must have them unlocked: anvil’s ten are, and so is an account passed to Anvil.impersonateAccount.

  • Type: "supported" | "ready" | "unsupported" | "none"
  • Default: "supported"

What the wallet does with several calls: see the table above.

  • Type: (request: { method: string; params?: unknown }) => boolean
  • Default: yes to everything

What the user answers to a prompt. It gets the request as the app sent it. A false refuses the request with 4001, and nothing reaches the node.

import { Effect } from "effect";
import type { Address } from "@ethect/core";
import { TestWallet } from "@ethect/core/testing";
const cautious = (alice: Address.Address) => {
const prompts: Array<string> = [];
// signs messages, and refuses to send anything
const approve = ({ method }: { readonly method: string }) =>
prompts.push(method) > 0 && method === "personal_sign";
return Effect.map(TestWallet.make({ accounts: [alice], approve }), (wallet) => ({
wallet,
prompts, // every prompt the user saw, in order
}));
};
  • Type: ReadonlyArray<number>
  • Default: the chain of the node

The chains the wallet knows. It starts on the first. Given a list, it knows those chains and no other, not even the node’s: chains: [1] is a wallet on mainnet that answers 4902 when asked to switch to the chain of the test.

The wallet it answers as, where that wallet differs from EIP-5792: one of TestWallet.profiles.

  • Type: ReadonlyArray<string>
  • Default: none

Methods it takes and does not answer until wallet.unlock. A locked Ambire holds every request until its password is typed, wallet_getCapabilities included: silent: ["wallet_getCapabilities"] is that wallet, for a test of what a plan does without its answer.

TestWallet.profiles holds the wallets read so far. Each is a TestWallet.Profile: the wallet (_tag), the release read (release), and a link to each file it was read in, at the commit of that release (sources). A weekly check fetches those files at each wallet’s latest release, and fails when one has changed: the profile is then read again.

Only what a profile names differs from what it answers as EIP-5792 writes it. atomic keeps its meaning, and atomic: "none" is still a wallet with no EIP-5792.

Ambire v7.0.2: extension 93b1edbf, ambire-common f3167486.

Request It answers
wallet_getCapabilities The account by its EIP-55 checksum, and no other case: in lowercase, -32602 “account with address … does not exist”. Every chain it knows, whatever was asked, each with atomicBatch and atomic.
wallet_sendCalls Needs from: without it, 4100. Its id is Transaction: and the hash of the transaction it sent. The id the app gave is not read.
wallet_getCallsStatus { status: 100 } while pending, { status: 400 } once dropped: the status alone. In a block, 200 whether it reverted or not: its receipt’s status is "0x0" or "0x1". id is the object { type, identifier, bundler }, there is no chainId, blockNumber is a JSON number, gasUsed is hex in whole bytes and logs is empty.
the same, after a switch -32602 “invalid identifier passed”: a status is looked up under the chain and the account the app is on now.

Read in ProviderController.ts, requests.ts, submittedAccountOp.ts, 5792.ts and activity.ts. Locked, it holds every request until its password is typed (rpcFlow.ts): that is silent.

MetaMask’s @metamask/eip-5792-middleware 4.1.1, with @metamask/transaction-controller 74.6.0. It runs several calls as one only on the chains of its signed EIP-7702 list, which is eip7702: none in profiles.metamask, as for any chain of a test.

Request It answers
wallet_getCapabilities A chain off the list is left out, and so is a chain where the account can neither batch nor be upgraded.
wallet_sendCalls of several calls Off the list, 5710, even when atomic is not required.
wallet_sendCalls for another chain than the app’s -32602, before anything else.

On a chain of its list it answers as EIP-5792 writes it: { ...TestWallet.profiles.metamask, eip7702: [31337] }.

Read in processSendCalls.ts, getCapabilities.ts and batch.ts.

Rainbow v1.6.11, with @rainbow-me/provider 0.2.0. It batches only through an EIP-7702 delegation, and has EIP-5792 behind a remote flag.

Request It answers
wallet_sendCalls Needs version, chainId, calls, from and atomicRequired: without one, -32602.
wallet_getCapabilities, wallet_sendCalls, for an account it cannot delegate -32004, its “method not supported”, where EIP-5792 says unsupported: atomic: "unsupported" is that account.
all three, atomic: "none" -32004: its flag is off.

Read in handleProviderRequest.ts and errorCodes.ts of the provider, and in the extension’s handleProviderRequest.ts and featureStatus.ts.

Rabby v0.94.18. It has no EIP-5792: -32601 for wallet_getCapabilities, wallet_sendCalls and wallet_getCallsStatus, whatever atomic says. Brave and Frame have none either, and answer the same.

Read in rpcFlow.ts and controller.ts.

Request It does
eth_requestAccounts Asks approve. Yes: the accounts.
eth_accounts, eth_chainId Answers without asking.
eth_sendTransaction Asks approve, then sends to the node. Without a from, the first account sends.
personal_sign, eth_signTypedData_v4 Asks approve, then has the node sign.
wallet_switchEthereumChain A chain it knows: asks approve, switches and emits chainChanged.
wallet_addEthereumChain Asks approve, then knows the chain. It does not switch to it.
wallet_getCapabilities atomic as configured, for each chain it knows among those asked.
wallet_sendCalls Asks approve, then runs the calls as one transaction. Its id is the one given, or the hash of that transaction.
wallet_getCallsStatus 100 until the transaction is mined, then 200, or 500 when it reverted, with its receipt. 400 when it left the pool. Every answer has the id, the chainId and a list of receipts, empty until the batch is mined, as EIP-5792 writes them.
eth_subscribe, eth_unsubscribe Answers 4200: the wallet pushes nothing.
anything else Sends the request to the node, and answers what the node answers.
  • A batch really is one transaction. The wallet puts a small contract at the account’s own address, has the account send itself one transaction that carries the calls, and puts the account’s own code back. Every call sees the account as msg.sender and as tx.origin. One hash, all or nothing.
  • The account has code while its batch is pending. It gets its own back the next time the wallet is asked anything once the transaction is mined or dropped, and at the latest when the scope closes. With that code the account takes tokens (ERC-721, ERC-1155) and validates its own signatures (ERC-1271), as a wallet that batches does. A contract that refuses callers with code refuses a call of a batch.
  • A reorg does not run a batch again. Once the batch is mined, the account has its own code back. The same transaction mined again in another block finds no code to run the calls: it succeeds and does nothing. A test of a reorg uses a plain transaction.
  • A batch that reverts is still sent. anvil mines a transaction that reverts, so the status is 500 and nothing of the batch is kept. A single eth_sendTransaction that reverts is mined as well.
  • A batch is one transaction or nothing. The wallet never sends the calls of a batch one by one: atomicRequired: false changes nothing, and an "unsupported" wallet refuses every batch.
  • A batch deploys nothing. A call without a to is refused with -32602.
  • The wallet’s chain is what it says, not where it sends. setChain(1) changes what eth_chainId answers. Transactions still go to the node of the test.
  • "ready" asks once per account. After a yes the account is upgraded: the wallet says supported for it and does not ask again.
  • Nothing is shared. Each wallet has its own accounts, chain, batches and listeners.

make cannot fail. A request the wallet refuses is rejected with the error object a wallet answers, which a program sees as an RpcError with a reason.

Code Reason When
4001 UserRejectedRequest approve answered false
4100 Unauthorized the request names an account the wallet does not hold
4200 UnsupportedMethod eth_subscribe and eth_unsubscribe
4900 Disconnected any request after disconnect, until setChain
4902 UnrecognizedChain wallet_switchEthereumChain to a chain it does not know
5700 UnsupportedNonOptionalCapability a batch asks for a capability without marking it optional: the wallet has none
5710 UnsupportedChainId a batch for another chain than the one the wallet is on
5720 DuplicateId a batch with an id the wallet already has
5730 UnknownBundleId wallet_getCallsStatus for an id it does not have
5750 AtomicReadyWalletRejectedUpgrade a "ready" wallet whose user refused the upgrade
5760 AtomicityNotSupported a batch for an "unsupported" wallet
-32601 MethodNotFound a batch method on a wallet with atomic: "none"
-32004 MethodNotSupported like Rainbow: an account it cannot delegate, or atomic: "none"
-32602 InvalidParams params the method does not take, or a batch call without a to
-32603 InternalError the node could not be reached

An error of the node, for a request passed on to it, comes back as the node gave it. A wallet like one of the profiles refuses with that wallet’s codes and messages: see Profiles.

Every request is answered by the wallet or passed to the node of its transport.

  1. eth_requestAccounts, eth_accounts

    1. the walletanswers, with no request
  2. eth_chainId

    1. the walletanswers
    2. given no chains

      1. your nodeeth_chainIdonce
  3. eth_sendTransaction

    1. your programapprove
    2. your nodeeth_sendTransactionthen
  4. personal_sign, eth_signTypedData_v4

    1. your programapprove
    2. your nodethen the same request
  5. wallet_sendCalls

    1. your programapprovethen
    2. your nodeeth_getCode(account)its own code, kept
    3. your nodeanvil_setCode(account, batch)the code that runs them
    4. your nodeeth_sendTransaction({ from: account, to: account, data })
  6. wallet_getCallsStatus

    1. your nodeeth_getTransactionReceipt(hash)
    2. none

      1. your nodeeth_getTransactionByHash(hash)pending or dropped
  7. before any request, a batch being out

    1. your nodethe same two requests
    2. mined or dropped

      1. your nodeanvil_setCode(account, its own code)
  8. when the scope closes

    1. your nodeanvil_setCode(account, its own code)for each account left
  9. eth_subscribe, eth_unsubscribe

    1. the walletrefuses
  10. a method in silent

    1. the walletholds it until unlock, then answers as above
  11. anything else

    1. your nodethe same request

The calls of a batch are packed one after the other in the data of its transaction: [to (20 bytes) | value (32) | length of data (4) | data].