# How it works

Two services do the work. Transport is the node and Signer is the wallet. Who is asked what, and how a function of a contract becomes a JSON-RPC request.

ethect has two services. `Transport` is the node: it reads, simulates, and says what is in a
block. `Signer` is the wallet: it holds accounts and makes them sign. Every function of the
library asks one of them or both, and its type says which.

A program asks two services. Transport is your node: reads, simulations and receipts come from it. Signer is the wallet, or a key: accounts and signatures come from it. A send asks the signer to sign, then the node for the receipt.

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

const both = (token: Address.Address, user: Address.Address) => ({
  // Effect<bigint, …, Transport>: a read asks the node
  balance: Erc20.at(token).balanceOf(user),
  // Effect<Receipt, …, Signer | Transport>: a send asks the wallet, then the node
  sent: Tx.send(Erc20.at(token).transfer(user, 1n)),
});
```

The third type of an `Effect` is what it needs. A program runs once everything it needs is
provided, and does not compile before.

## The two services

Each service is provided by a `Layer`, once, where the program runs.

| Service | Is | Provided by |
| --- | --- | --- |
| [`Transport`](https://ethect.dev/reference/transport/) | a node | `Transport.http`, `Transport.webSocket`, `Transport.ipc`, `Transport.eip1193`. Several chains: [`Transport.chains`](https://ethect.dev/reference/transport/chains/) |
| [`Signer`](https://ethect.dev/reference/signer/) | what signs | `Signer.privateKey` and `Signer.fromSign` for a key, `Signer.wallet` and `Signer.connected` for a wallet |

```ts
import { Config, Effect, Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { Connection, Signer, Transport, Wallets } from "@ethect/core";

// Reads only: a program that sends does not compile against it.
const ReadOnly = Transport.http("https://ethereum-rpc.publicnode.com");

// A script: 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));

// A page in a browser, read from the bottom up.
const App = Signer.connected().pipe( // 4. signs with the connected wallet
  Layer.provideMerge(Connection.layer()), // 3. which wallet is connected
  Layer.provideMerge(Wallets.browser), // 2. which wallets are installed
  Layer.provideMerge(Transport.http("https://ethereum-rpc.publicnode.com")), // 1. the node
  Layer.provide(FetchHttpClient.layer),
);
```

- **The chain is the transport's.** A read goes to the node of its transport, and a
  transaction is for the chain of that node. Nothing else names a chain.
- **A program never names a node or a wallet.** The same program runs with a key in a script,
  with a wallet in a browser, and with [`TestSigner`](https://ethect.dev/reference/testing/test-signer/) in a
  test.
- **A wallet is not where you read from.** In a browser, reads go to your node, and the wallet
  is asked only for what a wallet alone can do.

## Who is asked what

No function chooses between the node and the wallet. Each need has one home.

| Need | Asked to | With |
| --- | --- | --- |
| Reads, simulations, logs, blocks | `Transport` | `eth_call`, `eth_getLogs`, `eth_subscribe` |
| Accounts, and what the wallet can batch | `Signer` | `eth_accounts`, `wallet_getCapabilities` |
| Signing and sending, with a wallet | `Signer` | `eth_sendTransaction`, or `wallet_sendCalls` for several calls |
| Signing, with a key | `Signer`, in the process | no request |
| Nonce, fees and gas for a key | `Transport` | `eth_getTransactionCount`, `eth_maxPriorityFeePerGas`, `eth_estimateGas` |
| Sending what a key signed | [`Tx.Broadcast`](https://ethect.dev/reference/tx/broadcast/) | `eth_sendRawTransaction` on the `Transport`, unless you replace it |
| Where a transaction hash stands | `Transport` | `eth_getTransactionReceipt`: once, then at each new block while it is in no block |
| Where a wallet batch stands | `Signer` | `wallet_getCallsStatus` |
| The same chain on both | both | `eth_chainId`, asked once each and compared before a signature |

What [`Tx.submit`](https://ethect.dev/reference/tx/submit/) returns decides where [`Tx.wait`](https://ethect.dev/reference/tx/wait/)
asks. Transaction hashes are known to any node, so your node is asked. The id of a wallet
batch is known to that wallet only, so the wallet is asked.

A key has no node of its own. `Signer.privateKey` uses the `Transport` of whoever calls it:
the nonce is read and the receipt awaited on the same node, and one key works on several
chains.

## From a function to a request

Three layers sit on top of each other, and each is usable alone.

| Layer | You write | It is |
| --- | --- | --- |
| The main APIs | `token.balanceOf(user)`, `Tx.send(call)`, `Ev.watch(Deposit)` | contracts, calls, transactions, events, wallets. From `@ethect/core` |
| The [JSON-RPC layer](https://ethect.dev/rpc/) | `Eth.call({ to, data }, "latest")` | one typed function per method. From `@ethect/core/rpc` |
| The transport | `transport.request("eth_call", […])` | one function that sends, and returns what the node answered |

A read goes down through all three:

**`token.balanceOf(user)`**

- **encode**: the selector of `balanceOf`, then the address. No request
- **Call.Reader**: merges the reads issued together into one multicall
- **Eth.call**: params through a schema: a block number becomes hex. No request
- **Transport** `{ "jsonrpc": "2.0", "id": 0, "method": "eth_call", "params": [ … ] }`
- **Eth.call**: the result through a schema: it is hex, or the call fails
- **decode**: the bytes as a `uint256`, or the revert as a typed error. No request

What travels is plain JSON-RPC 2.0, with nothing added. A method of the JSON-RPC layer is a
value: a wire name and two schemas.

```ts
import { Eth } from "@ethect/core/rpc";

Eth.getBalance.method; // "eth_getBalance"
Eth.getBalance.params; // schema: [address, block?]
Eth.getBalance.result; // schema: a hex quantity, decoded to bigint
```

The same schema runs both ways, so a test can answer in place of a node with typed values: see
[`MockProvider`](https://ethect.dev/reference/testing/mock-provider/). A definition is a pure value, so a
bundler drops the ones a program does not call: see
[bundle size](https://ethect.dev/getting-started/installation/#bundle-size).

## The parts you can replace

Five decisions have a default and one place to change it. Each is a service with a default
value: a program provides one only to replace it.

| Part | Decides | Default |
| --- | --- | --- |
| [`Call.Reader`](https://ethect.dev/reference/call/reader/) | how reads reach the node | merged into multicalls |
| [`Tx.Broadcast`](https://ethect.dev/reference/tx/broadcast/) | how signed bytes go out | `eth_sendRawTransaction` on the transport |
| [`Signer.Nonces`](https://ethect.dev/reference/signer/nonces/) | how a key hands out nonces | one transaction signed and sent at a time |
| [`Ev.Source`](https://ethect.dev/reference/ev/source/) | how events arrive | pushed when the transport can, polled otherwise |
| [`Block.Interval`](https://ethect.dev/reference/block/#interval) | how often a transport that cannot push is asked | the pace of the blocks |

## Errors are part of the result

Each step fails with a value, never an exception. A contract that reverts, a user who
refuses, a node that does not answer: each has its own tag, and the type of a program lists
the ones it has not handled. See [Errors](https://ethect.dev/guides/errors/).

## Why its own JSON-RPC layer

Effect has an RPC module, and ethect does not use it at run time. Three behaviours of its
client, observed with `effect` 4.1.7 against anvil 1.9.0, do not fit Ethereum nodes:

- **Tracing fields in the request.** The default client adds `traceId`, `spanId` and `sampled`
  to the request, and anvil answers `-32600` to any field it does not know.
- **A schema mismatch is a defect.** A result of another shape kills the fiber instead of
  failing the call, which leaves nothing to catch.
- **Its own keep-alive.** Over a socket it sends a ping method nodes do not answer, and the
  connection closes.

ethect keeps what Effect does well underneath: `HttpClient` for requests, `Socket` for
connections, `Schema` for the boundary, `Stream` for subscriptions, `Layer` for wiring.

## Next steps

- [Read and write a contract](https://ethect.dev/guides/contracts/): the two services at work.
- [Send transactions](https://ethect.dev/guides/transactions/): every request of a send, in order.
- [The JSON-RPC layer](https://ethect.dev/rpc/): the definitions, by namespace.
- [Connection lifecycle](https://ethect.dev/concepts/connection-lifecycle/): what a socket transport does over
  time.
- [`Transport`](https://ethect.dev/reference/transport/) and [`Signer`](https://ethect.dev/reference/signer/): the two services.
