# How nonces are managed

Send twenty transactions at once from one key. The signer keeps one counter per account, asks the node once, and knows what to do with each answer of the node.

Send many transactions at once from one key. You write no nonce code: the signer counts.

```ts title="pay.ts"
import { Config, Effect, Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { Address, Call, Signer, Transport, Tx } from "@ethect/core";

// The key and the URL of the node are secrets: both are read from the environment.
const Script = Layer.unwrap(
  Effect.gen(function* () {
    const url = yield* Config.Redacted("RPC_URL");
    const key = yield* Config.Redacted("PRIVATE_KEY");
    return Layer.merge(Signer.privateKey(key), Transport.http(url));
  }),
).pipe(Layer.provide(FetchHttpClient.layer));

const TO = Address.makeUnsafe("0x70997970C51812dc3A010C7d01b50e0d17dc79C8");

const program = Effect.gen(function* () {
  // Twenty transfers, all at once.
  const receipts = yield* Effect.forEach(
    Array.from({ length: 20 }, () => Call.make({ to: TO, value: 10n ** 15n })),
    (transfer) => Tx.send(transfer),
    { concurrency: 20 },
  );
  return receipts.map((receipt) => receipt.transactionHash);
});

const hashes = await program.pipe(Effect.provide(Script), Effect.runPromise);
```

- **`Effect.forEach` with `concurrency: 20`** is `Promise.all` over a list. `yield*` is `await`.
- **`Tx.send`** signs a transfer, sends it and waits for its receipt.
- **`Script`** is what the program runs with: a signer over your key, and a node.

The twenty transfers get the nonces `n` to `n + 19`, and are pending together. With viem,
twenty `sendTransaction` at once each read the account's pending count and get the same nonce,
unless the account was given a `nonceManager`. Here the counter is the default.

## One counter, one lock

The signer keeps one counter per account, on each chain and each node it sends through. It
asks the node once where the account stands, with
`eth_getTransactionCount(account, "pending")`. Then it counts by itself.

A lock is held while one transaction is signed and handed to the node. It is not held while
the transaction 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.

- **Fees and gas are estimated before the lock.** Only the signature and the send are inside.
- **Why a lock.** A node mines the transactions of an account in the order of their nonces.
  If B left before A was accepted, and A was then refused, B would wait behind a nonce nobody
  used: a hole. With the lock, a refused nonce is the next one handed out.
- **The cost.** One transaction per round trip to the node: about twenty a second when a
  round trip takes 50 ms.

## What the node answers

What the node answers to a send decides what becomes of its nonce.

| The node | The nonce | Your send |
| --- | --- | --- |
| accepts the transaction | is used: the counter moves on | goes on to wait for its receipt |
| refuses it: no funds, a fee too low | is given back: the next send takes it | fails with the node's `RpcError` |
| says "nonce too low" | was used elsewhere | is tried once more, after the count is read again |
| does not answer | is kept | sends the same bytes again, for two minutes. Then it fails with a `TransportError` |

- **A nonce is never used again on a guess.** A send that got no answer may have arrived. The
  same bytes sent twice are safe: the node says "already known", which counts as accepted.
  Another transaction at that nonce would not be.
- **"nonce too low" may be about your own transaction.** After a lost answer, the node is
  asked for the transaction by its hash. When it has it, the send succeeded.

## More at once

With the default, a transaction leaves when the one before it was accepted.
`Signer.Nonces.pipelined` lets several be on their way at once.

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

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

The lock now covers only taking the number. Sixteen transactions are signed and sent
together, and the program above does not change.

| | `Signer.Nonces.serial`, the default | `Signer.Nonces.pipelined({ inFlight })` |
| --- | --- | --- |
| On their way to the node at once | one | up to `inFlight` |
| A refused transaction | leaves nothing behind | leaves a hole: the transactions above it wait |
| The hole | cannot happen | is taken by the next send. With no send left, an empty transaction to yourself fills it |

Filling a hole costs the gas of a transfer, and logs a warning. `gap: "leave"` turns it off.

## When it goes wrong

**Two processes on one key.** Each has its own counter, and both hand out the same nonce.

| The other transaction at that nonce is | The node | What happens |
| --- | --- | --- |
| in a block | says "nonce too low" | the count is read again and the send is tried once more: it works |
| pending, with the same fees | refuses yours as an underpriced replacement | your send fails with an `RpcError` |
| pending, and yours pays a tenth more | takes yours in its place | the other process's transaction is gone |

Use one key per process. Or share the counter: a strategy is one function, and a row lock in
a database implements it. See [`Signer.Nonces`](https://ethect.dev/reference/signer/nonces/#use).

**A stuck transaction.** A transaction whose fees are too low stays pending, and every later
nonce waits behind it. Send another one at its nonce: with more fees to replace it, or with
nothing in it to cancel it. [`Tx.submit`](https://ethect.dev/reference/tx/submit/) gives what it sent each
transaction with, in `fields`: its nonce, its gas and its fees. Nothing is kept aside.

```ts title="stuck.ts"
import { type Address, Call, Tx } from "@ethect/core";

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

/** Twice the fees it went out with. */
const raised = ({ maxFeePerGas, maxPriorityFeePerGas, gasPrice }: Tx.Fields): Tx.Fields => ({
  maxFeePerGas: twice(maxFeePerGas),
  maxPriorityFeePerGas: twice(maxPriorityFeePerGas),
  gasPrice: twice(gasPrice), // a transaction priced the old way has this one alone
});

/** The same call at the same nonce and gas, with twice the fees: it takes the place of the first. */
export const bump = (call: Call.Call<unknown, unknown>, sent: Tx.Fields) =>
  // `sent` has its gas with its nonce: see below
  Tx.submit(call, { transaction: { ...sent, ...raised(sent) } });

/** Nothing, sent to yourself at that nonce: the first transaction never runs. */
export const cancel = (me: Address.Address, sent: Tx.Fields) =>
  Tx.submit(Call.make({ to: me }), {
    transaction: { nonce: sent.nonce, gas: 21_000n, ...raised(sent) },
  });

/** What the first transaction of a pending went out with. A wallet does not say: undefined. */
export const sentWith = (pending: Tx.Pending) =>
  pending._tag === "Transactions" ? pending.fields?.[0] : undefined;
```

- **Set `gas` with the `nonce`.** A field you leave out is estimated, and a node may estimate
  on its pending state, where the stuck transaction has already run. The replacement then
  gets less gas than it needs alone, and runs out of gas.
- **Most nodes replace a transaction only when both fees are at least a tenth higher.**
- **A wait on the first transaction fails with `TxDropped`.** Its `replacedBy` is the hash of
  the transaction that took its nonce: wait for that one.
- **A nonce you set does not go through the counter.** Once the node accepted it, the counter
  is at least that nonce plus one.

## Under the hood

Only the node of your `Transport` is asked. A wallet manages its own nonces: all of this is
for a signer that signs in your program, such as
[`Signer.privateKey`](https://ethect.dev/reference/signer/private-key/).

**the first send of an account**

- **your node** `eth_getTransactionCount(account, "pending")`: once: then the counter is the truth

**every send**

- **your node** `eth_sendRawTransaction(signed)`: one per transaction, under the lock

**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, and one more try

The fees, the gas and the receipt are other requests: see
[`Tx.send`](https://ethect.dev/reference/tx/send/#under-the-hood). Every answer of every node client, and the
strategy as a function of your own, are on [`Signer.Nonces`](https://ethect.dev/reference/signer/nonces/).
