# Tx.send

Sends calls and waits for them to be in a block. One call gives its receipt, several give
their receipts in order.

## Usage

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

// A key and a node, both read from the environment as secrets.
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 USDC = Address.makeUnsafe("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");
const VAULT = Address.makeUnsafe("0xBEEF01735c132Ada46AA9aA4c54623cAA92A64CB");

const program = Effect.gen(function* () {
  const me = yield* Signer.address;
  const amount = 100_000_000n;

  // Signed, sent, and waited for. With a key: one receipt per call.
  const receipts = yield* Tx.send([
    Erc20.at(USDC).approve(VAULT, amount),
    Vault.at(VAULT).deposit(amount, me),
  ]);
  return receipts.map((receipt) => receipt.blockNumber);
});

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

```ts title="vault.ts"
import { Abi, Contract, Erc4626, Fn } from "@ethect/core";

// ERC-4626 is built in, and declares no error. This adds the one the vault reverts with.
export const Vault = Erc4626.extend(
  Abi.parse(["error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max)"]),
);

// Not a standard: WETH takes ether with `deposit()`.
export const Weth = Contract.make({ deposit: Fn.payable()("deposit", { inputs: [] }) });
```

`Tx.send` needs a [`Signer`](https://ethect.dev/reference/signer/) to sign and a
[`Transport`](https://ethect.dev/reference/transport/) to follow what was sent. The same line runs with a key
in a script and with a wallet in a browser. The examples below leave both out.

### One call

One call gives one receipt.

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

const pay = (usdc: Address.Address, to: Address.Address) =>
  Tx.send(Erc20.at(usdc).transfer(to, 1_000_000n));
// Effect<Receipt, Tx.Failure<never>, Signer | Transport>
```

### Several calls

Several calls give their receipts in order. How many signatures they take depends on the
signer, and the code does not change.

```ts
import { type Address, Erc20, Signer, Tx } from "@ethect/core";
import { Vault } from "./vault";

const deposit = (usdc: Address.Address, vault: Address.Address, amount: bigint, me: Address.Address) =>
  // one signature or two: the same line
  Tx.send([Erc20.at(usdc).approve(vault, amount), Vault.at(vault).deposit(amount, me)]);
```

| The signer | The calls go | You get |
| --- | --- | --- |
| a local key | together, as transactions with nonces in a row | one receipt per call |
| a wallet that batches (EIP-5792 `atomic`) | as one batch, all or nothing: one prompt | one receipt for them all |
| a wallet that does not | one prompt per call, each mined before the next is asked | one receipt per call |

[`Tx.plan`](https://ethect.dev/reference/tx/plan/) is what decides, and says so before anything is signed.

### How calls go together

`batch` says how several calls may share a signature.

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

const three = (calls: ReadonlyArray<Call.Call<unknown, unknown>>) => [
  // the default: one signature when the signer can, one per call otherwise
  Tx.send(calls, { batch: "auto" }),
  // each call is mined before the next one is signed
  Tx.send(calls, { batch: "never" }),
  // all or nothing, or `TxUnsupported` before any prompt
  Tx.send(calls, { batch: "atomic" }),
];
```

### Ether

A payable function takes a value as its last argument. A plain transfer is a raw call.

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

const wrap = (weth: Address.Address) =>
  Tx.send(Weth.at(weth).deposit({ value: 10n ** 18n }));
const tip = (to: Address.Address) =>
  Tx.send(Call.make({ to, value: 10n ** 17n }));
```

### Another account, deeper

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

const fromTreasury = (usdc: Address.Address, treasury: Address.Address, to: Address.Address) =>
  Tx.send(Erc20.at(usdc).transfer(to, 1n), { from: treasury, confirmations: "finalized" });
```

### Many at once

Each send is a signature of its own. A local signer hands out the nonces: see
[`Signer.Nonces`](https://ethect.dev/reference/signer/nonces/).

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

const payAll = (usdc: Address.Address, recipients: ReadonlyArray<Address.Address>) =>
  Effect.forEach(recipients, (to) => Tx.send(Erc20.at(usdc).transfer(to, 1n)), {
    concurrency: 20,
  });
```

### A capability

EIP-5792 capabilities go to the wallet with the calls. One marked `optional` is left out for a
signer that does not have it. Without `optional`, such a signer refuses.

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

const sponsored = (usdc: Address.Address, to: Address.Address, url: string) =>
  Tx.send(Erc20.at(usdc).transfer(to, 1n), {
    capabilities: { paymasterService: { url, optional: true } },
  });
```

### Failures

Every failure is a value with a `message`. A revert carries the error of the contract, typed
by what the calls declare. `Effect.catchReason` handles one reason of a `TxReverted`, and
leaves the other reverts in the type.

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

const deposit = (vault: Address.Address, amount: bigint, me: Address.Address) =>
  Tx.send(Vault.at(vault).deposit(amount, me)).pipe(
    Effect.catchTag("SignerRejected", () => Effect.succeed("You refused the transaction" as const)),
    // the vault's own error: its fields are typed
    Effect.catchReason("TxReverted", "ERC4626ExceededMaxDeposit", (reason) =>
      Effect.succeed(`The vault takes ${reason.max} more` as const),
    ),
  );
```

## Returns

`Effect<Receipt, Tx.Failure<E>, Signer | Transport>` for one call.

`Effect<ReadonlyArray<Receipt>, Tx.Failure<E>, Signer | Transport>` for a list of calls.

A [`Receipt`](https://ethect.dev/rpc/types/receipt/) is always a success: a transaction that reverted is a
failure. `E` is the errors the calls declare. A list of no call gives no receipt, and asks
nothing.

## Parameters

### calls

- **Type:** `Call.Call<A, E> | ReadonlyArray<Call.Call<any, any>>`

One [call](https://ethect.dev/reference/call/), or several: what [`fn.at(address)(...args)`](https://ethect.dev/reference/fn/at/)
and [`Call.make`](https://ethect.dev/reference/call/make/) build.

### options.batch (optional)

- **Type:** `"auto" | "atomic" | "never"`
- **Default:** `"auto"`

How several calls share a signature. The table is on [`Tx.plan`](https://ethect.dev/reference/tx/plan/#the-table).

### options.from (optional)

- **Type:** [`Address.Address`](https://ethect.dev/reference/primitives/address/)
- **Default:** the signer's first account

The account that sends.

### options.confirmations (optional)

- **Type:** `number | "safe" | "finalized"`
- **Default:** `1`

How deep each transaction must be before its receipt is given. See
[`Tx.wait`](https://ethect.dev/reference/tx/wait/#optionsconfirmations-optional).

### options.capabilities (optional)

- **Type:** [`WalletCapabilities.Request`](https://ethect.dev/rpc/types/wallet-capabilities/)

EIP-5792 capabilities to ask of the wallet, by name. See
[`Tx.submit`](https://ethect.dev/reference/tx/submit/#optionscapabilities-optional).

### options.transaction (optional)

- **Type:** [`Tx.Fields`](https://ethect.dev/reference/tx/submit/#txfields) `| ReadonlyArray<Tx.Fields>`

Transaction fields to set instead of leaving them to the wallet or to an estimate. One set
for every transaction, or a list with one set per call, in the order of the calls.

## Behavior

`Tx.send` is a loop over the three other functions, and one rule.

```ts title="send.ts"
import { Effect } from "effect";
import { type Call, Err, Tx } from "@ethect/core";
import type { Receipt } from "@ethect/core/rpc";

export const send = (calls: ReadonlyArray<Call.Call<unknown, unknown>>, options?: Tx.SendOptions) =>
  Effect.gen(function* () {
    const steps = yield* Tx.plan(calls, options); // one step per signature
    const receipts: Array<Receipt.Receipt> = [];
    for (const step of steps) {
      const pending = yield* Tx.submit(step, options); // one signature
      const errors = Err.of(step.calls); // what a revert may be
      receipts.push(...(yield* Tx.wait(pending, { ...options, errors }))); // in a block
    }
    return receipts;
  });
```

- **The one rule.** Under `batch: "auto"`, a step of several calls that fails with
  `TxUnsupported` is planned again with `batch: "never"`, and the loop goes on with one step
  per call. Nothing else is tried again.
- **What the rule covers.** A user who declines the upgrade a batch needs. A node that cannot
  measure the gas of calls sent together. A batch the wallet finds too large. Transaction
  fields set on a wallet batch, which has no place for them.
- **Each signature waits for the one before it.** A step is submitted once the step before it
  is in a block, as deep as `confirmations` asks.
- **A send does not fail with `TransportUnknownChain`.** [`Tx.wait`](https://ethect.dev/reference/tx/wait/#on-the-chain-it-was-submitted-on)
  refuses what was submitted on another chain than the transport's. A send waits on the
  transport it has just submitted on, so it does not compare them again.
- **Failures speak of the calls you gave.** The `call` of a `TxReverted` counts from your first
  call, whichever signature it was in. Its `receipts`, and those of a `TxDropped`, start with
  the receipts of the signatures before.
- **A list of fields follows the calls.** With `transaction` as a list, each signature gets
  the sets of its own calls.
- **`TxPartial` is passed on as it is.** With a local key, calls sent together can stop half
  way: `sent` holds what went out, and can be given to [`Tx.wait`](https://ethect.dev/reference/tx/wait/).
- **The state of a flow is yours.** `Tx.send` keeps nothing. To show each signature as a step
  of its own, call [`Tx.plan`](https://ethect.dev/reference/tx/plan/), [`Tx.submit`](https://ethect.dev/reference/tx/submit/) and
  [`Tx.wait`](https://ethect.dev/reference/tx/wait/) yourself.

## Errors

| Error | From | When |
| --- | --- | --- |
| [`Signer.Rejected`](https://ethect.dev/reference/signer/) | `submit` | the user refused to sign. Nothing was sent for that signature |
| [`Tx.Unsupported`](https://ethect.dev/reference/tx/failures/#txunsupported) | `plan`, `submit` | the signer cannot do what was asked: `reason` says what |
| [`Tx.Reverted`](https://ethect.dev/reference/tx/failures/#txreverted) | `submit`, `wait` | a call reverted, in its block or while it was estimated. `reason` is typed |
| [`Tx.Dropped`](https://ethect.dev/reference/tx/failures/#txdropped) | `wait` | a transaction left the mempool, or another one took its nonce |
| [`Tx.Partial`](https://ethect.dev/reference/tx/failures/#txpartial) | `submit` | some calls went out before one was refused |
| [`AbiError`](https://ethect.dev/reference/errors/abi-error/) | `submit` | an argument is not a value its type takes: nothing was signed |
| [`Signer.Error`](https://ethect.dev/reference/signer/) | `plan`, `submit`, `wait` | the wallet is unreachable, on another chain, or does not hold the account |
| [`RpcError`](https://ethect.dev/reference/errors/rpc-error/), [`TransportError`](https://ethect.dev/reference/errors/transport-error/) | all | the node refused, or could not be reached |

## Under the hood

Two services are asked: the `Signer` signs, the `Transport` says where things stand. The
requests are those of [`Tx.plan`](https://ethect.dev/reference/tx/plan/#under-the-hood),
[`Tx.submit`](https://ethect.dev/reference/tx/submit/#under-the-hood) and
[`Tx.wait`](https://ethect.dev/reference/tx/wait/#under-the-hood), in that order.

One call, with a local key. Seven requests when it is mined at once, as on a development
node, and four when every field is set:

- **your node** `eth_chainId`: once per transport
- **your node** `eth_getBlockByNumber("latest")`: the base fee
- **your node** `eth_maxPriorityFeePerGas`: the tip
- **your node** `eth_estimateGas`: the gas. A revert here fails the send: nothing is sent
- **your node** `eth_getTransactionCount(from, "pending")`: once per account: then the signer counts
- **your node** `eth_sendRawTransaction`: through `Tx.Broadcast`
- **your node** `eth_getTransactionReceipt`: asked first: in a block already, the send is over

On a chain with a block time, the receipt is not there yet. The wait goes on at the heads:

- **your node** `eth_getBlockByNumber("latest")`: the head: pushed over a WebSocket, shared by every wait
- **your node** `eth_getTransactionCount(from, "latest")`: was its nonce taken?, at each head with no receipt
- **your node** `eth_getTransactionReceipt`: at each head after the first, until it is in a block

One call, with a wallet. Three requests to the wallet and two to your node, then the heads as
above while it is in no block:

- **the wallet** `eth_accounts`: the sender, unless `from` is given
- **your node** `eth_chainId`: once per transport
- **the wallet** `eth_chainId`: is the wallet on that chain?
- **the wallet** `eth_sendTransaction`: the prompt
- **your node** `eth_getTransactionReceipt`: asked first, then at each head until it is in a block

Several calls:

**a local key**

- **your node** `eth_simulateV1`: in place of `eth_estimateGas`
- **your node** `eth_sendRawTransaction`: then, one per call
- **your node** `eth_getTransactionReceipt`: one per call

**a wallet that batches**

- **the wallet** `wallet_getCapabilities`
- **the wallet** `wallet_sendCalls`
- **the wallet** `wallet_getCallsStatus`: then, once, then at each head while the batch is pending
- **your node** `eth_getTransactionReceipt`: one, for the receipt

**a wallet that does not**

- **the wallet** `wallet_getCapabilities`
- **the wallet and your node**: then the requests of one call, once per call
