# MockProvider

An EIP-1193 provider that answers from handlers written against the method definitions: a
wallet or node double for tests. Pass it to
[`Transport.eip1193`](https://ethect.dev/reference/transport/eip1193/) to run any program against it.

```ts
import { Effect } from "effect";
import { Address, Transport } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";
import { MockProvider } from "@ethect/core/testing";

const provider = MockProvider.make([
  MockProvider.handler(Eth.chainId, () => Effect.succeed(1)),
  MockProvider.handler(Eth.sendTransaction, () =>
    Effect.fail({ code: 4001, message: "User rejected the request." }),
  ),
]);

const sent = Eth.sendTransaction({ to: Address.zero, value: 1n }).pipe(
  Effect.as(true),
  Effect.catchReason("RpcError", "UserRejectedRequest", () => Effect.succeed(false)),
  Effect.provide(Transport.eip1193(provider)),
);
// false: the mock refused, as a user would
```

## Functions

| Function | Returns | Description |
| --- | --- | --- |
| [`MockProvider.make(handlers)`](#make) | `MockProvider` | Makes a provider that answers from the handlers. |
| [`MockProvider.handler(method, respond)`](#handler) | `Handler` | A handler typed by a method definition. |

## make

Makes a provider that answers each call with the first handler for its method that accepts
the call's params.

```ts
import { Effect } from "effect";
import { Eth, Net } from "@ethect/core/rpc";
import { MockProvider } from "@ethect/core/testing";

const provider = MockProvider.make([
  MockProvider.handler(Eth.blockNumber, () => Effect.succeed(7n)),
  MockProvider.handler(Net.version, () => Effect.succeed(1)),
]);
```

- **Parameters:** `handlers` (`ReadonlyArray<Handler>`).
- **Returns:** [`MockProvider`](#the-provider).
- **A method without a handler is rejected** with the error object
  `{ code: 4200, message: "Unsupported method …" }`, which a call sees as an `RpcError` with
  the reason `UnsupportedMethod`.

## handler

Answers one method. `respond` receives the call's arguments decoded and returns the result,
both typed by the method's schemas.

```ts
import { Effect } from "effect";
import { Eth } from "@ethect/core/rpc";
import { MockProvider } from "@ethect/core/testing";

const balances = MockProvider.handler(Eth.getBalance, (address, block) =>
  // address: Address, block: BlockId | undefined, result: bigint
  Effect.succeed(block === "latest" ? 7n : 0n),
);
```

- **Parameters:** `method` (a [`Method`](https://ethect.dev/rpc/method/)), then `respond`, a function from
  the method's arguments to an `Effect` of its result that can fail with a `Failure`.
- **Returns:** `Handler`.

The mock speaks the wire format on both sides. The program sends `"latest"` and hex, the
handler sees decoded values, and its `7n` goes back as `"0x7"`.

### A method with variants

A method made with [`Method.overload`](https://ethect.dev/rpc/method/overload/), such as
`Eth.getBlockByNumber`, is mocked like any other. One handler answers every variant:
`respond` gets the arguments of the variant called and returns that variant's result.

```ts
import { Effect } from "effect";
import { Address, Hash } from "@ethect/core";
import { type Block, Eth } from "@ethect/core/rpc";
import { MockProvider } from "@ethect/core/testing";

const hash = Hash.keccak256Utf8("a block");
// Without transactions, a block has the same shape in both forms.
const empty: Block.Block & Block.Full = {
  hash,
  parentHash: hash,
  sha3Uncles: hash,
  miner: Address.zero,
  stateRoot: hash,
  transactionsRoot: hash,
  receiptsRoot: hash,
  logsBloom: "0x",
  number: 1n,
  gasLimit: 30_000_000n,
  gasUsed: 0n,
  timestamp: 1_700_000_000n,
  extraData: "0x",
  size: 0n,
  uncles: [],
  transactions: [],
};

const provider = MockProvider.make([
  // id: bigint or a tag, full: boolean, as the program passed them
  MockProvider.handler(Eth.getBlockByNumber, (id, full) =>
    Effect.succeed(id === "latest" ? empty : null),
  ),
]);
```

To answer the variants differently, give each one a handler of its own.

```ts
import { Effect } from "effect";
import { Eth } from "@ethect/core/rpc";
import { MockProvider } from "@ethect/core/testing";

const [withHashes, inFull] = Eth.getBlockByNumber.variants;

const provider = MockProvider.make([
  MockProvider.handler(withHashes, () => Effect.succeed(null)),
  MockProvider.handler(inFull, () =>
    Effect.fail({ code: -32000, message: "too large" }),
  ),
]);
```

`Eth.getBlockByNumber("latest", false)` is answered by the first, and
`Eth.getBlockByNumber("latest", true)` by the second.

### Failing

Fail with the error object a wallet or node would answer with: `MockProvider.Failure`, a
`code`, a `message` and an optional `data`.

```ts
import { Effect } from "effect";
import { Eth } from "@ethect/core/rpc";
import { MockProvider } from "@ethect/core/testing";

const reverting = MockProvider.handler(Eth.call, () =>
  Effect.fail({ code: 3, message: "execution reverted", data: "0x08c379a0" }),
);
```

The program sees an [`RpcError`](https://ethect.dev/reference/errors/rpc-error/) with the reason that code has,
here `ExecutionReverted` with its `data`.

### Anything else

A `Handler` is a plain object, so a method without a definition, or an answer you want to
control on the wire, needs no helper.

```ts
import { Effect } from "effect";
import { MockProvider } from "@ethect/core/testing";

const provider = MockProvider.make([
  // params and the result are the raw wire values here
  { method: "eth_subscribe", respond: () => Effect.succeed("0xsub") },
  { method: "eth_unsubscribe", respond: () => Effect.succeed(true) },
  { method: "eth_chainId", respond: () => Effect.succeed("not a quantity") },
]);
```

| Field of `Handler` | Type |
| --- | --- |
| `method` | `string`, the wire name |
| `respond` | `(params: unknown) => Effect<unknown, unknown>` |
| `accepts` (optional) | `(params: unknown) => boolean`: whether these params are for this handler. Left out, any are. |

## The provider

`MockProvider.MockProvider` is an [`Eip1193.Provider`](https://ethect.dev/reference/eip1193/#provider) with what
a test needs to drive and inspect it.

| Member | Type | Does |
| --- | --- | --- |
| `request`, `on`, `removeListener` | as in `Eip1193.Provider` | what a program uses |
| `requests` | `ReadonlyArray<{ method: string; params: unknown }>` | every call received, in order, as it was on the wire |
| `emit` | `(event: string, payload: unknown) => void` | emits an event to its listeners |
| `listenerCount` | `(event: string) => number` | how many listeners an event has |

```ts
import { Effect } from "effect";
import { Address, Transport } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";
import { MockProvider } from "@ethect/core/testing";

const test = Effect.gen(function* () {
  const provider = MockProvider.make([
    MockProvider.handler(Eth.getBalance, () => Effect.succeed(7n)),
  ]);

  yield* Eth.getBalance(Address.zero, "latest").pipe(
    Effect.provide(Transport.eip1193(provider)),
  );

  return provider.requests;
  // [{ method: "eth_getBalance",
  //    params: ["0x0000000000000000000000000000000000000000", "latest"] }]
});
```

### Emitting events

`emit` drives the event streams of [`Eip1193`](https://ethect.dev/reference/eip1193/), and subscription items
through the `message` event.

```ts
import { Eip1193 } from "@ethect/core";
import { MockProvider } from "@ethect/core/testing";

const provider = MockProvider.make([]);
const chains = Eip1193.chainChanged(provider); // run it, then:

provider.emit("chainChanged", "0xa"); // the stream emits 10
provider.emit("accountsChanged", ["0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"]);

// an item of the subscription the mock answered "0xsub" for
provider.emit("message", {
  type: "eth_subscription",
  data: { subscription: "0xsub", result: `0x${"11".repeat(32)}` },
});
```

A listener only receives what is emitted after it registered. Wait for
`provider.listenerCount("chainChanged") > 0` before emitting in a test.

## Behavior

- **The first handler that accepts the params answers.** Among the handlers of the method
  called, it is the first whose `accepts` says yes, or that has no `accepts`. A handler made
  with `MockProvider.handler` accepts the params its method's schemas decode.
- **Params no handler accepts go to the first handler of the method.** One made with
  `MockProvider.handler` rejects them with code `-32602`, before `respond` runs: the program
  sees an `RpcError` with the reason `InvalidParams`.
- **An overloaded method takes one handler or several.** One handler given the overloaded
  method answers every variant. Handlers given its `variants` each answer their own.
- **No latency and no connection.** A handler answers at once. Answer with `Effect.never` for
  a call that must stay pending, to test a timeout on the caller's side.

## Types

| Type | Is |
| --- | --- |
| `MockProvider.MockProvider` | the provider with `requests`, `emit` and `listenerCount` |
| `MockProvider.Handler` | how the mock answers one method: `method`, `respond` and an optional `accepts` |
| `MockProvider.Failure` | the error object a handler fails with: `code`, `message`, optional `data` |
