# Custom methods

Define a JSON-RPC method the library does not have, or one whose result your chain shapes differently. A definition is written once with Method.make, typed in both directions.

A method the library does not define is one definition with
[`Method.make`](https://ethect.dev/rpc/method/make/): the names of the params, the wire name, the schemas of
the params, the schema of the result. The definition is the function you call.

```ts
import { Schema } from "effect";
import { Address } from "@ethect/core";
import { BlockId, Method } from "@ethect/core/rpc";

/** Whether an address has code. An Otterscan method, which anvil serves. */
const hasCode = Method.make<[address: unknown, block: unknown]>()(
  "ots_hasCode",
  [Address.wireSchema, BlockId.numberOrTagSchema],
  Schema.Boolean,
);

const ADDRESS = Address.makeUnsafe("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266");

const isContract = hasCode(ADDRESS, "latest"); // false
```

`hasCode` behaves like a built-in method: it works over every transport, fails with the same
three errors, and can be mocked with `MockProvider.handler`.

## Naming the params

`Method.make` is called twice. The first call takes no argument, only a type: a tuple whose
labels name the params. An editor shows them for the arguments of the method:
`hasCode(address, block)`.

| The type argument | Means |
| --- | --- |
| `[address: unknown, block: unknown]` | two params, `address` and `block` |
| `[address: unknown, block?: unknown]` | `block` is optional: its schema is `Schema.optionalKey(…)` |
| none: `Method.make()(…)` | no names: the arguments read `args_0`, `args_1` |

- **The types in the tuple are not read.** Write `unknown`: the schemas type the arguments.
- **The names are checked against the params.** One name per param, optional where the param
  is. Anything else does not compile.

## When to define one

| Situation | Define |
| --- | --- |
| your node or provider serves a method of its own | the method |
| a standard method [is not defined](https://ethect.dev/rpc/eth/#not-defined) | the method |
| your chain adds fields to blocks, transactions or receipts | a standard method again, with a wider result schema |
| a method fails with a `CodecError` on the result | the same method, with the schema of what the node really sends |

## Choosing the schemas

A schema says what a value is on the wire and what it is in your code. The library exports the
ones Ethereum needs.

| On the wire | In code | Schema |
| --- | --- | --- |
| a quantity that can be large: wei, gas, a block number, a timestamp | `bigint` | `Quantity.schema` |
| a quantity that stays small: a chain id, a nonce, an index, a count | `number` | `Quantity.numberSchema` |
| an address | `Address.Address` | `Address.wireSchema` |
| a 32-byte hash | `Hash.Hash` | `Hash.schema` |
| bytes of any length | `Hex.Hex` | `Hex.schema` |
| bytes of a fixed length | `Hex.Hex` | `Hex.sized(n)` |
| a block number or tag | `bigint` or a tag | `BlockId.numberOrTagSchema` |
| a block number, tag or hash object | `BlockId.BlockId` | `BlockId.schema` |
| a JSON number, string or boolean | the same | `Schema.Number`, `Schema.String`, `Schema.Boolean` |
| `null` | `null` | `Schema.Null`, or `Schema.Void` to accept any answer |
| an object | an object | `Schema.Struct({ … })` |
| a list | a readonly array | `Schema.Array(item)` |
| a value or `null` | `T \| null` | `Schema.NullOr(item)` |

```ts
import { Schema } from "effect";
import { Address, Hex, Quantity } from "@ethect/core";
import { BlockId, Method } from "@ethect/core/rpc";

/** An account's balance, nonce and code in one call. A method anvil serves. */
const getAccountInfo = Method.make<[address: unknown, block: unknown]>()(
  "eth_getAccountInfo",
  [Address.wireSchema, BlockId.schema],
  Schema.Struct({
    balance: Quantity.schema, // bigint
    nonce: Quantity.numberSchema, // number
    code: Hex.schema,
  }),
);
// (address, block) => Effect<{ balance: bigint; nonce: number; code: Hex }, …>
```

- **Read the wire, not the documentation.** Some nodes send a JSON number where the
  specification says a quantity. A schema that does not match fails with a `CodecError` that
  names the field.
- **An optional param** is `Schema.optionalKey(schema)`, at the end of the list, under an
  optional name (`block?: unknown`). A required param after an optional one does not compile.
  Make a param optional only when the node accepts the request without it: anvil refuses
  `eth_getAccountInfo` with one param.
- **An address is `Address.wireSchema`.** It reads what a node sends in any letter case, and
  sends the EIP-55 form. [`Address.schema`](https://ethect.dev/reference/primitives/address/#schema) also checks
  the EIP-55 checksum, which is for an address a person wrote.
- **A field a node may omit** is `Schema.optionalKey(schema)` inside the struct. It refuses a
  key set to `undefined`, which only a provider in the page can send. The wire types read such
  a key as absent: to do the same, decode it from `Schema.UndefinedOr` and drop it, as
  [`Method.optional`](https://ethect.dev/rpc/method/#types) types it.

## A wider result

The wire types are `Schema.Struct`s. Spread the fields of one into a new struct to add what
your chain adds, then define the standard method with it.

```ts
import { Schema } from "effect";
import { Hash, Quantity } from "@ethect/core";
import { Method, Receipt } from "@ethect/core/rpc";

// A rollup whose receipts also report the cost of posting the transaction to L1.
const RollupReceipt = Schema.Struct({
  ...Receipt.schema.fields,
  l1Fee: Quantity.schema,
  l1GasUsed: Quantity.schema,
});

const getRollupReceipt = Method.make<[hash: unknown]>()(
  "eth_getTransactionReceipt",
  [Hash.schema],
  Schema.NullOr(RollupReceipt),
);
```

The built-in `Eth.getTransactionReceipt` still works on that chain: it decodes the standard
fields and drops the two it does not know.

## Params by name, and overloads

Two variants cover the methods that are not a plain list of params.

| The method | Use |
| --- | --- |
| takes one object as `params`, not an array | [`Method.makeByName`](https://ethect.dev/rpc/method/make-by-name/) |
| returns a different shape for a different argument | [`Method.overload`](https://ethect.dev/rpc/method/overload/) |

## A namespace of your own

Put the definitions of one API in a module and import it as a namespace, as the library does.

```ts title="acme.ts"
import { Schema } from "effect";
import { Address, Quantity } from "@ethect/core";
import { Method } from "@ethect/core/rpc";

/** The fee the sequencer charges for a transaction of this size, in wei. */
export const estimateFee = Method.make<[size: unknown]>()(
  "acme_estimateFee",
  [Quantity.numberSchema],
  Quantity.schema,
);

/** Whether an account is on the sequencer's allowlist. */
export const isAllowed = Method.make<[address: unknown]>()(
  "acme_isAllowed",
  [Address.wireSchema],
  Schema.Boolean,
);
```

```ts
import { Effect } from "effect";
import * as Acme from "./acme";

const fee = Effect.gen(function* () {
  return yield* Acme.estimateFee(1_200); // Effect<bigint, …>
});
```

A definition has no side effect: the module can be imported anywhere, and nothing is sent
until a method is called and run.

## A subscription kind

[`Subscription.make`](https://ethect.dev/rpc/subscription/make/) is the same idea for `eth_subscribe`: the
names of the params, the kind, the schemas of its params, the schema of an item.

```ts
import { Schema } from "effect";
import { Hash, Quantity } from "@ethect/core";
import { Subscription } from "@ethect/core/rpc";

/** The number and hash of each new block, and nothing else of its header. */
const newHeadIds = Subscription.make()(
  "newHeads",
  [],
  Schema.Struct({ number: Quantity.schema, hash: Hash.schema }),
);
// () => Stream<{ number: bigint; hash: Hash }, …, Subscriptions>
```

## Testing a definition

A definition of yours is mocked like a built-in one. The handler is typed from your schemas,
and the mock checks that both sides fit them.

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

const hasCode = Method.make<[address: unknown, block: unknown]>()(
  "ots_hasCode",
  [Address.wireSchema, BlockId.numberOrTagSchema],
  Schema.Boolean,
);

const provider = MockProvider.make([
  MockProvider.handler(hasCode, (address, block) =>
    Effect.succeed(address !== Address.zero && block === "latest"),
  ),
]);

const result = hasCode(Address.zero, "latest").pipe(
  Effect.provide(Transport.eip1193(provider)),
);
// false, and provider.requests holds the request as it was on the wire
```

## Next steps

- [`Method.make`](https://ethect.dev/rpc/method/make/): the parameters, and what a definition checks.
- [Values on the wire](https://ethect.dev/rpc/guides/values/): why a quantity is sometimes `bigint` and sometimes
  `number`.
- [Types](https://ethect.dev/rpc/types/): the wire types whose fields you can reuse.
- [Custom transports](https://ethect.dev/guides/custom-transports/): the other half, where calls go.
