# Read and write a contract

Read a balance of an ERC-20 and send a transfer to it, with the contract that is built in. What a call is, how to describe a contract that is not a standard, and how to extend one.

Read from a contract, and send it a transaction. The example is an ERC-20, which is built in:
it reads your balance and sends half of it to someone.

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

// The addresses you wrote are checked when the file loads. A typo stops the program there.
const TOKEN = Address.makeUnsafe("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");
const TO = Address.makeUnsafe("0x70997970C51812dc3A010C7d01b50e0d17dc79C8");
const token = Erc20.at(TOKEN);

const program = Effect.gen(function* () {
  const me = yield* Signer.address;
  // A read: the call is the effect of reading it.
  const balance = yield* token.balanceOf(me);
  // A write: the call is plain data. `Tx.send` signs it, sends it and waits for its block.
  const receipt = yield* Tx.send(token.transfer(TO, balance / 2n));
  // The logs of the receipt, decoded with the event of the contract.
  const [transfer] = Ev.decode(Erc20.ev.Transfer, receipt.logs);
  return { balance, sent: transfer?.value, block: receipt.blockNumber };
});

// 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 result = await program.pipe(Effect.provide(Script), Effect.runPromise);
```

Three things here come from [Effect](https://ethect.dev/guides/effect-essentials/), and are all you need of it:

- **`Effect.gen(function* () { … })`** is an `async` function, and **`yield*`** is its `await`.
- **`Script`** is a `Layer`: what the program needs to run. Here a signer and a node.
- **`Effect.runPromise`** runs the program and gives a `Promise` of its result.

[`Erc20`](https://ethect.dev/reference/standards/erc20/) is the functions and the events of the standard, with
no ABI to write. [`Erc721`](https://ethect.dev/reference/standards/erc721/),
[`Erc1155`](https://ethect.dev/reference/standards/erc1155/) and [`Erc4626`](https://ethect.dev/reference/standards/erc4626/) are
built in the same way. `Erc20.at(TOKEN)` is the contract at an address: its functions build
calls.

## Read

`token.balanceOf(me)` builds a call: the function, the address, the arguments. Nothing is sent
yet. A call of a `view` function is also the effect of reading it, so `yield*` reads it.

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

const balances = (token: Address.Address, owner: Address.Address) =>
  Effect.gen(function* () {
    const now = yield* Erc20.at(token).balanceOf(owner);
    // `Call.read` is the same read, with options: a past block, a sender
    const before = yield* Call.read(Erc20.at(token).balanceOf(owner), { block: 19_000_000n });
    return now - before;
  });
```

- **The result is typed by the signature.** A `uint256` is a `bigint`, an `address` an
  [`Address`](https://ethect.dev/reference/primitives/address/), a `uint8` a `number`.
- **A read needs a node and no signer.** Leave `Signer.privateKey` out of the layer, and a
  program that only reads still compiles.
- **Several reads go out as one request.** See [Read many things at once](https://ethect.dev/guides/reading/).

## Write

`token.transfer(to, value)` builds a call too. `transfer` is not a view, so its call is plain
data and not an effect: `yield*` on it does not compile. [`Tx.send`](https://ethect.dev/reference/tx/send/)
sends it.

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

// The standard declares no error. This adds the one the token reverts with.
const Token = Erc20.extend(
  Abi.parse(["error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed)"]),
);

const pay = (token: Address.Address, to: Address.Address, amount: bigint) =>
  Tx.send(Token.at(token).transfer(to, amount)).pipe(
    Effect.map((receipt) => `Sent in block ${receipt.blockNumber}`),
    // The token reverted with its own error: the reason, with typed fields.
    Effect.catchReason("TxReverted", "ERC20InsufficientBalance", (reason) =>
      Effect.succeed(`You hold ${reason.balance} and need ${reason.needed}`),
    ),
  );
```

- **A receipt is always a success.** A transaction that reverts is a failure, `TxReverted`.
- **The failure is a value.** `Effect.catchReason` handles one reason of one failure, and the
  others stay in the type of the program. See [Errors](https://ethect.dev/guides/errors/).
- **A token may revert with a message instead.** USDC does: the reason then has the tag
  `"RevertReason"`, and its `message` is the text.
- **A write needs a signer.** Without `Signer.privateKey` in the layer, the program does not
  compile. [Send transactions](https://ethect.dev/guides/transactions/) has several calls, and every failure.

## A contract that is not a standard

A built-in contract is a contract like any other: its functions under `fn`, its events under
`ev`, its errors under `err`, and `at(address)`. Any other contract is described in one of
three ways. They give the same contract.

| Way | You write | Arguments | Use it when |
| --- | --- | --- | --- |
| [`Abi.parse`](https://ethect.dev/reference/abi/parse/) | signatures, as text | by position: `set(args_0)` | you call a few functions |
| [`Abi.fromJson`](https://ethect.dev/reference/abi/from-json/) | the JSON ABI a compiler writes, `as const` | by position | you have the artifact, or an ABI you gave viem |
| [`Contract.make`](https://ethect.dev/reference/contract/) | each definition by hand | by name: `set(next)` | you want names, or classes for events and errors |

```ts title="oracle.ts"
import { Abi, Contract, Err, Ev, Fn, type _ } from "@ethect/core";

// From its signatures, as you would write them in Solidity.
export const Oracle = Abi.parse([
  "function value() view returns (uint256)",
  "function set(uint256 next) returns (uint256 previous)",
  "event Set(address indexed sender, uint256 value)",
  "error Failed(address sender, uint256 value)",
]);

// By hand, the same contract is longer, and its arguments have names.
export class Set extends Ev.make("Set", {
  sender: Abi.indexed(Abi.address), // `indexed`, as in the contract
  value: Abi.uint256,
}) {}
export class Failed extends Err.make("Failed", { sender: Abi.address, value: Abi.uint256 }) {}

export const ByHand = Contract.make({
  value: Fn.view()("value", { inputs: [], output: Abi.uint256 }),
  set: Fn.nonpayable<[next: _]>()("set", { inputs: [Abi.uint256], output: Abi.uint256 }),
  Set,
  Failed,
});
```

`Fn.nonpayable<[next: _]>()` takes the names of the arguments as a type, and `inputs` gives
their types. See [`Fn`](https://ethect.dev/reference/fn/#names).

### Extend a standard

A token is rarely the standard alone. `extend` gives the standard and what a contract adds to
it, in one contract, as `Token` above. It takes a contract: signatures go through `Abi.parse`.

```ts
import { Abi, Erc20 } from "@ethect/core";

// ERC-20, a function this token adds, and an error it reverts with.
export const Mintable = Erc20.extend(
  Abi.parse([
    "function mint(address to, uint256 value)",
    "error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed)",
  ]),
);
```

- **Its errors are failures of every function**, those of the standard too.
- **A function of the same name takes the place of the standard's.** That is how a token
  whose `transfer` returns nothing is described. See
  [`extend`](https://ethect.dev/reference/contract/#extend).

## Under the hood

Only the lines that reach a node send something. A definition, a call and
[`Ev.decode`](https://ethect.dev/reference/ev/decode/) send nothing.

**`token.balanceOf(me)`**

- **your node** `eth_call({ to, data }, "latest")`

**`Tx.send(call)`**

- **your node**: the fees
- **your node** `eth_estimateGas`
- **your program**: the signature, in the process, with the key
- **your node** `eth_sendRawTransaction`
- **your node** `eth_getTransactionReceipt`: asked first, then at each new block, until mined

- [`Call.read`](https://ethect.dev/reference/call/read/#under-the-hood) has the request of a read, option by
  option.
- [`Tx.send`](https://ethect.dev/reference/tx/send/#under-the-hood) has every request of a send, with a key and
  with a wallet.
- [`Abi.parse`](https://ethect.dev/reference/abi/parse/#the-grammar) has the grammar of a signature.
