# Tx.submit

Asks for one signature and hands the calls to the network. It gives what to wait for, and does
not wait.

## Usage

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

const pay = (usdc: Address.Address, to: Address.Address) =>
  Effect.gen(function* () {
    const pending = yield* Tx.submit(Erc20.at(usdc).transfer(to, 1_000_000n));
    // Signed and sent. Whether it is in a block is another question:
    const [receipt] = yield* Tx.wait(pending, { confirmations: 5 });
    return receipt;
  });
```

`Tx.submit` is the one place where a [`Signer`](https://ethect.dev/reference/signer/) is asked to sign. What it
answers is plain data, a [`Tx.Pending`](https://ethect.dev/reference/tx/wait/#txpending): keep it, store it,
and give it to [`Tx.wait`](https://ethect.dev/reference/tx/wait/) when you want.

### A step, or calls

A [step](https://ethect.dev/reference/tx/plan/#txstep) of [`Tx.plan`](https://ethect.dev/reference/tx/plan/) is submitted as it
is. Calls are planned first, and have to fit in one signature.

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

const both = (calls: ReadonlyArray<Call.Call<unknown, unknown>>) =>
  Effect.gen(function* () {
    const [step] = yield* Tx.plan(calls);
    const fromStep = step === undefined ? undefined : yield* Tx.submit(step);
    // The same when the plan has one step. With more, `TxUnsupported` "atomic": nothing is signed.
    const fromCalls = yield* Tx.submit(calls);
    return [fromStep, fromCalls];
  });
```

| Given | The signer | It signs |
| --- | --- | --- |
| one call | any | that call |
| several calls | runs them as one | one batch, all or nothing |
| several calls | a local key | one transaction per call, sent together |
| several calls | a wallet that does not batch | nothing: `TxUnsupported` `"atomic"`. Use [`Tx.send`](https://ethect.dev/reference/tx/send/), or submit each step |

### Sign now, wait later

A pending is plain data: [written as text](https://ethect.dev/reference/tx/wait/#storing-a-pending), it survives
a reload. It says its chain, and is
[waited for on that chain](https://ethect.dev/reference/tx/wait/#on-the-chain-it-was-submitted-on).

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

const start = (usdc: Address.Address, to: Address.Address) =>
  Tx.submit(Erc20.at(usdc).transfer(to, 1n)).pipe(
    Effect.map((pending) => localStorage.setItem("transfer", Tx.toJson(pending))),
  );

// After a reload, with the same wallet connected. None: nothing was stored.
const resume = Effect.gen(function* () {
  const pending = Tx.fromJson(localStorage.getItem("transfer"));
  return Option.isSome(pending) ? yield* Tx.wait(pending.value) : [];
});
```

### An id for a wallet batch

A wallet batch is known by an id. Chosen by you and stored before the prompt, the batch can be
asked about after a reload, also when the page closed before the wallet answered. Left out,
the signer makes one.

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

const together = (calls: ReadonlyArray<Call.Call<unknown, unknown>>, id: string) =>
  // 32 bytes in hex is what every wallet takes
  Tx.submit(calls, { id });
```

### Every field set

What `transaction` sets is not estimated. With the gas and the fees set, a local signer asks
the node nothing before it sends.

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

const fast = (usdc: Address.Address, to: Address.Address, fee: bigint, tip: bigint) =>
  Tx.submit(Erc20.at(usdc).transfer(to, 1n), {
    transaction: { gas: 80_000n, maxFeePerGas: fee, maxPriorityFeePerGas: tip },
  });
```

### A stuck transaction

The same nonce, the same gas and twice the fees replace a transaction that is stuck. To cancel
it: nothing, sent to yourself, at that nonce. What the transaction went out with is in what
`Tx.submit` gave, as [`fields`](https://ethect.dev/reference/tx/wait/#txtransactions): nothing is kept aside.

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

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

/** Twice the fees it went out with: most nodes replace a transaction only a tenth above. */
const raised = ({ maxFeePerGas, maxPriorityFeePerGas, gasPrice }: Tx.Fields): Tx.Fields => ({
  maxFeePerGas: twice(maxFeePerGas),
  maxPriorityFeePerGas: twice(maxPriorityFeePerGas),
  // a transaction priced the old way has this one, and neither of the two above
  gasPrice: twice(gasPrice),
});

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

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

const transfer = (usdc: Address.Address, to: Address.Address) =>
  Effect.gen(function* () {
    const call = Erc20.at(usdc).transfer(to, 1n);
    const pending = yield* Tx.submit(call);
    // … and it is stuck. What it went out with is in what `Tx.submit` gave.
    const sent = pending._tag === "Transactions" ? pending.fields?.[0] : undefined;
    // A wallet says the hash alone: its user speeds the transaction up in the wallet.
    return sent === undefined ? pending : yield* bump(call, sent);
  });
```

A [wait](https://ethect.dev/reference/tx/wait/#a-transaction-that-is-replaced) on the first transaction then
fails with `TxDropped`, and names the one that took its nonce. A pending read back
[from storage](https://ethect.dev/reference/tx/wait/#storing-a-pending) has its `fields` too.

## Returns

`Effect<Tx.Pending, Signer.Rejected | Tx.Unsupported | Tx.Partial | Tx.Reverted<E> | AbiError | Signer.Error | Transport.Error, Signer | Transport>`

A [`Tx.Pending`](https://ethect.dev/reference/tx/wait/#txpending): transaction hashes, or a handle only the
signer can resolve. `E` is the errors the calls declare.

| The signer | One call | Several calls |
| --- | --- | --- |
| a local key | `Tx.Transactions`, with its nonce and [what it went out with](https://ethect.dev/reference/tx/wait/#txtransactions): its gas and its fees | `Tx.Transactions`: one hash per call, each with its nonce, its gas and its fees |
| a wallet | `Tx.Transactions`: one hash, and nothing else | `Tx.Handle`: the id of the batch |

## Parameters

### step

- **Type:** [`Tx.Step`](https://ethect.dev/reference/tx/plan/#txstep) `| Call.Call<A, E> | ReadonlyArray<Call.Call<any, any>>`

A step of a plan, or calls to sign as one.

### options.from (optional)

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

The account that sends, when calls are given. A step has its own `from`, which is used.

### options.id (optional)

- **Type:** `string`

The id of a wallet batch. Only a signer that gives a [handle](https://ethect.dev/reference/tx/wait/#txhandle)
uses it. The same id twice is the same batch: nothing is sent again.

### options.capabilities (optional)

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

EIP-5792 capabilities to ask of the wallet, by name. Each is an object the wallet reads, with
one field read here: `optional`.

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

const sponsored = (usdc: Address.Address, to: Address.Address, url: string) =>
  Tx.submit(Erc20.at(usdc).transfer(to, 1n), {
    capabilities: {
      // left out for a signer that cannot sponsor: the call is then a plain transaction
      paymasterService: { url, optional: true },
    },
  });
```

Without `optional`, a signer that lacks the capability fails with `TxUnsupported`
`"capability"`.

### options.transaction (optional)

- **Type:** [`Tx.Fields`](#txfields) `| ReadonlyArray<Tx.Fields>`

Fields for every transaction of the step, or a list with one set per call. This type and the
three above are `Tx.SubmitOptions`.

### Tx.Fields

Transaction fields to set, instead of leaving them to the wallet or to an estimate. All are
optional, and one left `undefined` is not set.

| Field | Type | Sets |
| --- | --- | --- |
| `nonce` | `number` | the nonce. A local signer's [counter](https://ethect.dev/reference/signer/nonces/) is not asked |
| `gas` | `bigint` | the gas limit. The call is then not estimated: a revert is found in its block |
| `maxFeePerGas` | `bigint` | the most paid per gas, base fee included |
| `maxPriorityFeePerGas` | `bigint` | the tip |
| `gasPrice` | `bigint` | the price of a legacy transaction |
| `accessList` | [`AccessList.AccessList`](https://ethect.dev/rpc/types/access-list/) | the addresses and slots it touches |
| `type` | `"legacy" \| "eip2930" \| "eip1559" \| "eip4844" \| "eip7702"`, or a chain's own | the transaction type |

## Behavior

- **It does not wait.** It returns when the signer has handed the calls to the network: in a
  pool, not in a block.
- **Calls are encoded here.** A signer never sees an ABI. An argument that does not encode
  fails with an `AbiError` before the signer is asked anything.
- **Optional capabilities are dropped here, not by the signer.** When one is marked
  `optional`, the signer is asked what it has (`Signer.capabilities`), and those it lacks are
  left out. A capability it reports with `supported: false` or `status: "unsupported"` is one
  it lacks. A signer does what it is asked, or refuses.
- **With no capability left, one call is a plain transaction.** A wallet gets
  `eth_sendTransaction`, not a batch of one.
- **A revert found while estimating sends nothing.** A local signer estimates before it signs:
  a call that would revert fails with `TxReverted`, its `call` and its typed `reason`, and
  empty `receipts`.
- **The reason is read with the errors of the call that failed, then with those of the other
  calls.** A call often reverts with an error of a contract it calls, such as the token a
  vault pulls from: another call of the step may be the one that declares it.
- **A wallet estimates nothing.** Its revert shows later, in [`Tx.wait`](https://ethect.dev/reference/tx/wait/).
- **What is not set is estimated as the node sees it.** Some nodes measure a call on their
  pending state, where a transaction that is stuck has already run. A replacement measured
  there can get less gas than it needs alone: set `gas` with the `nonce`. The `fields` of what
  was submitted have both.
- **A local signer says what it sent each transaction with.** The `fields` of a
  `Tx.Transactions` are the nonce, the gas and the fees as they were signed, estimated or
  set. A wallet decides them itself and says only the hash: its pending has no `fields`.
- **Fields on a wallet batch are refused.** EIP-5792 has no place for a nonce, a gas limit or
  fees: several calls with `transaction` set fail with `TxUnsupported` `"atomic"` on a wallet.
- **No call is nothing to sign.** A list of no call gives a `Tx.Transactions` with no hash,
  and the signer is not asked.

## Errors

| Error | Reason | When |
| --- | --- | --- |
| [`Signer.Rejected`](https://ethect.dev/reference/signer/) | | the user refused to sign. Nothing was sent |
| [`Tx.Unsupported`](https://ethect.dev/reference/tx/failures/#txunsupported) | `"atomic"` | calls that take more than one signature. Or what [the signer](https://ethect.dev/reference/signer/wallet/#errors) refuses as one |
| `Tx.Unsupported` | `"upgradeRejected"` | the user declined the upgrade a batch needs |
| `Tx.Unsupported` | `"capability"` | the signer lacks a capability that is not `optional` |
| `Tx.Unsupported` | `"gas"` | a local key, several calls with no gas set, and a node without `eth_simulateV1` |
| `Tx.Unsupported` | `"signing"` | a transaction type the signer cannot sign |
| [`Tx.Reverted`](https://ethect.dev/reference/tx/failures/#txreverted) | | a call would revert: found while estimating, nothing was sent |
| [`Tx.Partial`](https://ethect.dev/reference/tx/failures/#txpartial) | | a local key: a call after the first was refused. `sent` holds what went out |
| [`AbiError`](https://ethect.dev/reference/errors/abi-error/) | | an argument is not a value its type takes |
| [`Signer.Error`](https://ethect.dev/reference/signer/) | | 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/) | | the node refused the transaction, or could not be reached |

## Under the hood

The `Signer` is asked. What it sends is its own: see
[`Signer.wallet`](https://ethect.dev/reference/signer/wallet/#under-the-hood) and
[`Signer.privateKey`](https://ethect.dev/reference/signer/private-key/#under-the-hood).

**`Tx.submit(step, { id, capabilities, transaction })`**

  - given calls:
    - **your program** `Tx.plan(calls, { from })`: one step, or `TxUnsupported` `"atomic"`
  - a capability asked as optional:
    - **the signer** `capabilities(from, chainId)`
      - a wallet:
        - **the wallet** `wallet_getCapabilities`: once per account and chain
- **encode**: every call: selector and arguments. No request
- **the signer** `submit({ calls, atomic, from, chainId, id, capabilities, transaction })`
  - a wallet, one call:
    - **the wallet** `eth_chainId`
    - **the wallet** `eth_sendTransaction`
    - → a hash
  - a wallet, several:
    - **the wallet** `eth_chainId`
    - **the wallet** `wallet_sendCalls`
    - → a handle
  - a local key:
    - **your node**: the fees and the gas that are not set
    - **your program**: then for each call: a nonce, a signature
    - **your node** `eth_sendRawTransaction`
    - → one hash per call
