# Send fast

A bot that reacts to a block with a transaction in the next one. Set every field so that nothing is asked before the send, sign everything first, and send through a relay.

A bot that sees a block and has its transaction in the next one. Each new block is the
trigger, and sending is one request.

```ts title="bot.ts"
import { Config, Effect, Layer, Stream } from "effect";
import { Socket } from "effect/socket";
import { Abi, Address, Block, Fn, Signer, Transport, Tx, type _ } from "@ethect/core";

// function set(uint256 next): what the bot writes at every block, and the contract it is on
const set = Fn.nonpayable<[next: _]>()("set", { inputs: [Abi.uint256] });
const ORACLE = Address.makeUnsafe("0x5FbDB2315678afecb367f032d93F642f64180aa3");

// A WebSocket pushes each new block. The key signs here, and counts its own nonces.
const Bot = Layer.unwrap(
  Effect.gen(function* () {
    const url = yield* Config.Redacted("WS_URL");
    const key = yield* Config.Redacted("PRIVATE_KEY");
    return Layer.merge(Signer.privateKey(key), Transport.webSocket(url));
  }),
).pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal));

// Every field set: nothing is estimated, so nothing is asked before the send.
const fields = {
  gas: 60_000n,
  maxFeePerGas: 50n * 10n ** 9n, // the most you pay per gas, base fee included
  maxPriorityFeePerGas: 2n * 10n ** 9n,
};

const bot = Block.watch.pipe(
  // One request per block: eth_sendRawTransaction.
  Stream.runForEach((head) => Tx.submit(set.at(ORACLE)(head.number), { transaction: fields })),
);

await bot.pipe(Effect.provide(Bot), Effect.runPromise);
```

- **`Block.watch`** is a stream of blocks, and `Stream.runForEach` is a `for await` loop over
  it. It gives the latest block at once, then each new one.
- **`Tx.submit`** signs and sends, and does not wait for a receipt. `Tx.send` would hold the
  loop until the transaction is mined.
- **`Bot`** is what the program runs with: a signer over your key, and a node. Both secrets
  come from the environment.

The bot here writes a number at every block. A keeper, an oracle or a liquidation has the
same shape: read at `head`, decide, submit.

## Set every field

A field you leave out is asked of the node before the transaction is signed. Each one you
set is a request less.

| A send needs | Asked of the node | Not asked when |
| --- | --- | --- |
| the chain | `eth_chainId`, once per node | the program is under [`Transport.on`](https://ethect.dev/reference/transport/chains/#on) |
| the fees | `eth_getBlockByNumber("latest")` and `eth_maxPriorityFeePerGas` | `maxFeePerGas` and `maxPriorityFeePerGas` are set |
| the gas | `eth_estimateGas`. For several calls, one `eth_simulateV1` | `gas` is set |
| the nonce | `eth_getTransactionCount`, once per account | the account sent before: the signer counts |
| the send | `eth_sendRawTransaction` | never: it is the one request left |

With nothing set, a send is four requests, and six the first time. With the gas and the fees
set it is one.

- **`maxFeePerGas` is a cap, not a price.** You pay the base fee of the block plus your tip,
  and never more than the cap. A cap below the base fee leaves the transaction
  [stuck](https://ethect.dev/guides/nonces/#when-it-goes-wrong).
- **Leave the nonce to the signer.** It counts without asking: see
  [How nonces are managed](https://ethect.dev/guides/nonces/). With `Signer.Nonces.pipelined`, several sends of
  one block leave together.
- **A gas limit that is set is not checked.** A call that would revert is no longer found
  before it is sent: it is mined, reverts, and costs its gas.

## The trigger

`Block.watch` is pushed over a WebSocket and polled over HTTP: the line is the same. A reorg
is not hidden. Each block says what it follows, in `parentHash`:

| The `parentHash` of a block is the hash of | The block | A bot |
| --- | --- | --- |
| the block given before it | is the next block | acts |
| an earlier block that was given | starts a reorg: the blocks given after that one are replaced | acts again: what it sent in the replaced blocks may be gone |
| no block that was given | starts the stream over: more than 256 blocks were missed, or a very deep reorg | reads its state again before it acts |

- **Read at the block that triggered you.** `Call.read(call, { block: { blockHash: head.hash } })`
  is the state your transaction is decided on, whatever a reorg does next.
- **Do not wait inside the loop.** Blocks are buffered while the loop is busy: a bot slower
  than the chain acts on old blocks.

## Every signature first

Two calls that depend on each other, such as an approval and a deposit, cannot be estimated
one by one: the second fails until the first is mined. Measure both ahead of time, then sign
and send them in a row.

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

type Calls = ReadonlyArray<Call.Call<unknown, unknown>>;
type Fees = { readonly maxFeePerGas: bigint; readonly maxPriorityFeePerGas: bigint };

/** Ahead of time: a gas limit for each call, the second measured after the first. */
export const measure = (calls: Calls, me: Address.Address) =>
  Effect.map(Tx.simulate(calls, { from: me, method: "simulateV1" }), ({ gas }) => gas);

/** When it matters: all are signed and sent, with nonces in a row. One request per call. */
export const fire = (calls: Calls, gas: ReadonlyArray<bigint>, fees: Fees) =>
  Tx.submit(calls, { transaction: gas.map((limit) => ({ ...fees, gas: limit })) });
```

`fire` is one request per call, and gives one hash per call.
[`Tx.wait`](https://ethect.dev/reference/tx/wait/) gives the receipts afterwards, for all of them at once. Left
to `Tx.send(calls)`, the same two calls take three requests more: the fees, and one
`eth_simulateV1`. The two transactions are not atomic: the second can be mined when the first
reverted.

## A relay

A local signer hands its signed bytes to `Tx.Broadcast`. By default that is
`eth_sendRawTransaction` on your node. Replace it to send through a private relay.

```ts title="relay.ts"
import { Effect, Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { type Hex, Transport, Tx } from "@ethect/core";
import { Eth } from "@ethect/core/rpc";

const Relay = Transport.http("https://relay.example").pipe(Layer.provide(FetchHttpClient.layer));

/** Signed bytes go to the relay, which is built once. Provide it beside your signer. */
export const ViaRelay = Layer.effect(Tx.Broadcast)(
  Effect.map(Layer.build(Relay), (relay) => ({
    send: (raw: Hex.Hex) => Eth.sendRawTransaction(raw).pipe(Effect.provide(relay)),
  })),
);
```

The nonce is still counted on your node, and the receipt is still awaited there. Only the
bytes go to the relay.

A relay that takes a bundle wants the signed transactions, not a send.
`Signer.signTransaction` signs and sends nothing.

```ts title="bundle.ts"
import { Effect } from "effect";
import { type Call, Signer, type Tx } from "@ethect/core";

/** Two transactions, signed and not sent: what `eth_sendBundle` takes. */
export const bundle = (first: Call.Call<unknown>, second: Call.Call<unknown>, fields: Tx.Fields) =>
  Effect.gen(function* () {
    const one = yield* Signer.signTransaction(first, { transaction: fields });
    // Signing takes no nonce: without this, both would carry the same one.
    const two = yield* Signer.signTransaction(second, {
      transaction: { ...fields, nonce: one.nonce + 1 },
    });
    return [one.raw, two.raw];
  });
```

The counter does not know what you sent elsewhere. Once the bundle is mined, the next send
finds "nonce too low", reads the count again and goes on.

## Under the hood

Two services are asked. The `Signer` signs in your program. The `Transport` gives the blocks,
and takes the bytes unless `Tx.Broadcast` says otherwise.

**`Block.watch`, over a WebSocket**

- **your node** `eth_subscribe("newHeads")`: once: then each block is pushed
- **your node** `eth_getBlockByNumber("latest", false)`: once the node has the subscription: no block is lost

**`Tx.submit(call, { transaction: { gas, maxFeePerGas, maxPriorityFeePerGas } })`**

- **your node** `eth_chainId`: the first time only
- **your node** `eth_getTransactionCount(from, "pending")`: the first time only
- **your program**: the transaction is signed, in your program
- **your node** `eth_sendRawTransaction(raw)`: through `Tx.Broadcast`

**`Tx.wait(pending)`**

- **your node** `eth_getTransactionReceipt(hash)`: asked first, then at each new block, until it is in one

Over HTTP the blocks are polled, at half the pace of the chain: set
[`Block.Interval`](https://ethect.dev/reference/block/#interval) to ask more often. The fields are on
[`Tx.submit`](https://ethect.dev/reference/tx/submit/#txfields), the blocks on
[`Block`](https://ethect.dev/reference/block/), and the bytes on [`Tx.Broadcast`](https://ethect.dev/reference/tx/broadcast/).
