# Signer.Nonces

How a local signer hands out nonces, and how many transactions of an account may be on their
way at once.

## Usage

```ts
import { Config, Effect, Layer } from "effect";
import { Signer } from "@ethect/core";

const key = Config.Redacted("PRIVATE_KEY");

// The default: one transaction of an account is signed and sent at a time.
const Script = Layer.unwrap(Effect.map(key, (key) => Signer.privateKey(key)));

// Up to sixteen on their way at once.
const Bot = Layer.unwrap(
  Effect.map(key, (key) =>
    Signer.privateKey(key, { nonces: Signer.Nonces.pipelined({ inFlight: 16 }) }),
  ),
);
```

A wallet manages its own nonces. A signer that signs here keeps a counter: the node is asked
once where the account stands, then the counter is the truth.

| Export | Kind | Description |
| --- | --- | --- |
| [`Signer.Nonces.serial`](#serial) | strategy | One transaction of an account at a time. The default. |
| [`Signer.Nonces.pipelined(options)`](#pipelined) | function | Up to `inFlight` at a time. |
| [`Signer.Nonces`](#use) | type | A strategy: one function, `use`. |
| [`Signer.LocalOptions`](#localoptions) | type | The options of a signer that signs here: `nonces`. |

## What the node answered

A send runs under `use`, with the nonce it was handed. What the node answered decides what
becomes of that nonce.

| The node | The nonce | Then |
| --- | --- | --- |
| accepted the transaction | is used: the counter moves on | |
| refused it | is given back: the next transaction takes it | the send fails with the node's `RpcError` |
| said "nonce too low" | was used elsewhere | the count is read again, and the send is tried once more |
| said "already known" | is used | the node had the transaction: it is accepted |
| did not answer | is kept | the same signed bytes are sent again: 200 ms later, then twice as long each time up to 5 s, for 2 minutes |
| still did not answer | is kept | the send fails with the `TransportError`, and the count is read again before the next nonce is handed out |

- **A nonce is never used again on a guess.** Bytes that got no answer may have arrived.
  Sending them again is safe: the node says "already known". Signing something else at that
  nonce is not.
- **"nonce too low" after a lost answer may be your own transaction, mined.** The node is
  asked for it by its hash (`eth_getTransactionByHash`). When it has it, the send succeeded.
- **The counter never moves back on its own.** A transaction the mempool drops later leaves a
  hole below the counter. Fill it by sending at that nonce:
  `transaction: { nonce }`.

### In words, not in codes

A node says "nonce too low" and "already known" in the message of its error, and each client
has its own words. They are read in one place, as whole words in any case.

| Client | "nonce too low" | "already known" |
| --- | --- | --- |
| Geth | `nonce too low: next nonce 334, tx nonce 0` | `already known` |
| reth | `nonce too low: next nonce 11821, tx nonce 0` | `already known` |
| Erigon | `INTERNAL_ERROR: nonce too low` | `INTERNAL_ERROR: existing txn with same hash`, `ALREADY_EXISTS: already known` |
| Nethermind | `nonce too low`, once `OldNonce` | `already known`, once `AlreadyKnown` |
| Besu | `Nonce too low` | `Known transaction` |
| anvil | `nonce too low` | `transaction already imported` |

Any other answer is a refusal: the nonce is given back.

## serial

- **Type:** `Signer.Nonces`

One transaction of an account is signed and sent at a time. The lock is held while a
transaction is signed and handed to the node, and not while it is mined.

Three sends started at once. Each holds the lock only while it takes its nonce, signs and sends, so they leave in order with nonces 7, 8 and 9. All three then wait for their receipts at the same time.

- All three are pending together. Only the sending is one at a time.
- If B left before A was accepted and A was then refused, B would wait behind a nonce nobody
  used. The lock prevents that: a refused nonce is the next one handed out.
- The cost is one transaction per round trip to the node: about twenty a second at 50 ms. A
  KMS signs inside the lock, so it is slower.

```ts
import { Effect } from "effect";
import { type Address, Call, Tx } from "@ethect/core";

// Twenty transfers at once, from one key: twenty nonces in a row.
const payAll = (recipients: ReadonlyArray<Address.Address>) =>
  Effect.forEach(recipients, (to) => Tx.send(Call.make({ to, value: 1n })), {
    concurrency: 20,
  });
```

## pipelined

`Signer.Nonces.pipelined(options)` gives a strategy that lets up to `inFlight` sends of an
account run at once. The lock covers only taking the number.

```ts
import { Config, Effect, Layer } from "effect";
import { Signer } from "@ethect/core";

const Fast = Layer.unwrap(
  Effect.map(Config.Redacted("PRIVATE_KEY"), (key) =>
    Signer.privateKey(key, { nonces: Signer.Nonces.pipelined({ inFlight: 16, gap: "fill" }) }),
  ),
);
```

- **A refused nonce leaves a hole.** Transactions above it may be accepted already: a node
  mines none of them until the hole is taken. The next send takes the lowest hole first.
- **A hole nothing came to take is filled.** When no send is left and accepted transactions
  wait behind a hole, an empty transaction is sent to the account itself at that nonce, and a
  warning is logged. It costs the gas of a transfer.

### Parameters

| Parameter | Type | Description |
| --- | --- | --- |
| `options.inFlight` | `number` | How many sends of an account may be on their way at once. At least 1. |
| `options.gap` (optional) | `"fill" \| "leave"` | What to do with a hole nothing came to take. `"fill"`, the default, sends an empty transaction to self at that nonce. `"leave"` does nothing: the transactions above it wait until you send at that nonce. |

### Returns

`Signer.Nonces`

## use

- **Type:** `Signer.Nonces`

A strategy is one function. `use` runs `send` with the next nonce of the account, and gives
what `send` gave. If `send` fails, the nonce is given back.

```ts
import type { Effect } from "effect";
import type { Address, Transport } from "@ethect/core";

interface Nonces {
  readonly use: <A, E, R>(
    account: Address.Address,
    chainId: number,
    send: (nonce: number) => Effect.Effect<A, E, R>,
  ) => Effect.Effect<A, E | Transport.Error, R | Transport.Transport>;
}
```

Two processes on one key each have a counter, and collide. Write a strategy that shares one:
a row lock in a database does it.

```ts
import { Config, Effect, Layer } from "effect";
import { Signer } from "@ethect/core";

/**
 * Yours: locks the row of `key`, runs `use` with the number in it, and writes the number
 * plus one when `use` succeeded.
 */
declare const withRow: <A, E, R>(
  key: string,
  use: (next: number) => Effect.Effect<A, E, R>,
) => Effect.Effect<A, E, R>;

const shared: Signer.Nonces = {
  use: (account, chainId, send) => withRow(`${chainId}:${account}`, send),
};

const Worker = Layer.unwrap(
  Effect.map(Config.Redacted("PRIVATE_KEY"), (key) => Signer.privateKey(key, { nonces: shared })),
);
```

`send` fails with what the node answered: an `RpcError` for a refusal, a `TransportError` when
it did not answer for two minutes. A strategy of your own decides what to do with each. The
two built-in ones do what [the table above](#what-the-node-answered) says.

## LocalOptions

- **Type:** `{ readonly nonces?: Signer.Nonces }`

The options of [`Signer.privateKey`](https://ethect.dev/reference/signer/private-key/),
[`Signer.fromSign`](https://ethect.dev/reference/signer/from-sign/) and [`Signer.make`](https://ethect.dev/reference/signer/make/).

## Behavior

- **One counter per transport, chain and account.** The same key on two chains has two
  counters. So has the same key on two nodes of one chain, such as a fork and the chain it
  forks.
- **The built-in strategies share their counters.** Two signers of the same account, on the
  same transport, hand out one sequence of nonces.
- **The node is asked once.** `eth_getTransactionCount(account, "pending")` on the first use,
  and again only after a doubt: no answer, "nonce too low", or a send that was interrupted.
- **A nonce that is set does not go through the strategy.** `transaction: { nonce }` is used
  as it is. Once the node accepted it, the counter is at least that nonce plus one.
- **A stuck transaction is replaced by sending at its nonce.** The same nonce, the same gas
  and twice both fees replace it. Nothing, sent to yourself, cancels it.
  [How nonces are managed](https://ethect.dev/guides/nonces/) has both.

```ts
import { type Call, Tx } from "@ethect/core";

const twice = (fee?: bigint) => (fee === undefined ? undefined : fee * 2n);

/**
 * Sends `call` again at the nonce of a transaction that is stuck, with twice the fees. `sent`
 * is what the transaction went out with: `Tx.submit` gave it, in the `fields` of its pending.
 */
const bump = (call: Call.Call<unknown, unknown>, sent: Tx.Fields) =>
  Tx.submit(call, {
    transaction: {
      // its nonce, and its gas too: a node may measure the call on top of the transaction it
      // replaces
      ...sent,
      // most nodes replace a transaction only when both fees are at least a tenth higher
      maxFeePerGas: twice(sent.maxFeePerGas),
      maxPriorityFeePerGas: twice(sent.maxPriorityFeePerGas),
      gasPrice: twice(sent.gasPrice), // a transaction priced the old way has this one alone
    },
  });
```

## Errors

| Error | From | When |
| --- | --- | --- |
| what `send` failed with | `use` | the send failed: the nonce is given back |
| `RpcError`, `TransportError` | `use` | the account's count could not be read |

## Under the hood

Only the `Transport` in context is asked.

**`use(account, chainId, send)`, the first time for this transport, chain and account**

- **your node** `eth_getTransactionCount(account, "pending")`: where the account stands
- **your program** `send(nonce)`

**`use(account, chainId, send)`, every other time**

- **your program** `send(nonce)`: nothing is asked: the counter is the truth

**after "nonce too low"**

- **your node** `eth_getTransactionByHash(hash)`: is it our own, mined? Then it succeeded
- **your node** `eth_getTransactionCount(account, "pending")`: the count again
- **your program** `send(nonce)`: once more

**pipelined, a hole nothing came to take**

- **your node** `eth_getBlockByNumber("latest"), eth_maxPriorityFeePerGas`: the fees
- **your node** `eth_sendRawTransaction(an empty transaction to self)`: through `Tx.Broadcast`
