# Contracts (Contract)

The functions, events and errors of a contract under one name. A contract at an address gives
its functions bound to it, each one building [calls](https://ethect.dev/reference/call/). The errors of a
contract are typed failures of all its functions.

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

export class ExceededMaxDeposit extends Err.make("ERC4626ExceededMaxDeposit", {
  receiver: Abi.address,
  assets: Abi.uint256,
  max: Abi.uint256,
}) {}

export class Deposit extends Ev.make("Deposit", {
  sender: Abi.indexed(Abi.address),
  owner: Abi.indexed(Abi.address),
  assets: Abi.uint256,
  shares: Abi.uint256,
}) {}

export const Vault = Contract.make({
  totalAssets: Fn.view()("totalAssets", { inputs: [], output: Abi.uint256 }),
  maxDeposit: Fn.view<[receiver: _]>()("maxDeposit", {
    inputs: [Abi.address],
    output: Abi.uint256,
  }),
  deposit: Fn.nonpayable<[assets: _, receiver: _]>()("deposit", {
    inputs: [Abi.uint256, Abi.address],
    output: Abi.uint256,
  }),
  Deposit, // an event
  ExceededMaxDeposit, // an error
});
```

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

const room = (address: Address.Address, user: Address.Address) => {
  const vault = Vault.at(address);
  return Effect.all([vault.totalAssets(), vault.maxDeposit(user)]);
};
```

| Export | Kind | Description |
| --- | --- | --- |
| [`Contract.make(definitions)`](#make) | function | A contract from one record of functions, events and errors. |
| [`contract.at(address)`](#at) | member | The functions of a contract at an address. |
| [`contract.extend(more)`](#extend) | member | The contract and another, in one. |
| `Contract.Contract<Fns, Evs, Errs>` | type | A contract: `fn`, `ev`, `err`, `at(address)` and `extend(more)`. |
| [`Contract.Extended<Base, More>`](#extend) | type | The contract that `base.extend(more)` gives. |
| `Contract.Bound<Fns>` | type | The functions at an address. |
| `Contract.Functions<D>` | type | The functions among definitions. |
| `Contract.Events<D>` | type | The events among definitions. |
| `Contract.Errors<D>` | type | The errors among definitions. |

[`Abi.parse`](https://ethect.dev/reference/abi/parse/) and [`Abi.fromJson`](https://ethect.dev/reference/abi/from-json/) build the same contract
from signatures and from a JSON ABI. [`Erc20`](https://ethect.dev/reference/standards/erc20/),
[`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.

## make

Gathers the definitions of a contract. It takes one record, and sorts each entry by what it
is: a function, an event or an error.

```ts
import { Vault } from "./vault";

Vault.fn.deposit; // the function, unbound: Vault.fn.deposit.at(address)(100n, user)
Vault.ev.Deposit; // the event class
Vault.err.ExceededMaxDeposit; // the error class
```

### Returns

`Contract.Contract<Fns, Evs, Errs>`

| Member | Holds |
| --- | --- |
| `fn` | the functions, by the key you gave each |
| `ev` | the event classes |
| `err` | the error classes |
| `at(address)` | the functions bound to an address |
| `extend(more)` | the contract and another, in one |

### Parameters

#### definitions

- **Type:** `Readonly<Record<string, Fn.Any | Ev.Any | Err.Any>>`

The definitions, each under a key of your choice. A [function](https://ethect.dev/reference/fn/view/) is used by
its key, so the key is most often its name. An [event](https://ethect.dev/reference/ev/make/) and an
[error](https://ethect.dev/reference/err/make/) are classes: a key is how you reach them, and their `_tag` stays
the name the contract gives them.

### Errors of a contract

An error given to a contract is a failure of every function reached through it, beside the
errors each function declares itself.

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

// `maxDeposit` declares no error. Through the contract, it fails with the contract's.
const room = (address: Address.Address, user: Address.Address) =>
  Vault.at(address).maxDeposit(user).pipe(
    Effect.catchTag("ERC4626ExceededMaxDeposit", (error) => Effect.succeed(error.max)),
  );
```

- A contract usually declares its errors once, and any of its functions may revert with one,
  through a modifier or an internal call. Giving them to the contract says so for all of them.
- The functions you gave are not changed. `Vault.fn.deposit` is a new function that knows the
  errors of the contract. The one you defined knows only its own.

## at

Gives the functions of a contract at an address. Each one is called with the arguments of the
function and builds a [call](https://ethect.dev/reference/call/).

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

const program = (address: Address.Address, user: Address.Address) =>
  Effect.gen(function* () {
    const vault = Vault.at(address);
    // a view: reading it is an effect
    const assets = yield* vault.totalAssets();
    // a write: plain data, to send as a transaction
    const call = vault.deposit(assets, user);
    return call;
  });
```

### Returns

`Contract.Bound<Fns>`

An object with the keys of `fn`. Each value is what
[`fn.at(address)`](https://ethect.dev/reference/fn/at/) gives: a function from the arguments to a call.

### Parameters

#### to

- **Type:** [`Address.Address`](https://ethect.dev/reference/primitives/address/)

The address of the contract.

### The chain

A contract carries no chain: `at` takes an address, and nothing else. A call is read or sent
on the node the program is given.

- **Under [`Transport.on(chainId)`](https://ethect.dev/reference/transport/chains/)** the node is on that chain.
  It was asked once, and one that is on another chain fails with `UnknownChain`.
- **With one `Transport`** nothing checks which chain the node is on. A program that must be
  on one chain checks it first, and fails with an error of its own:

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

class WrongChain extends Data.TaggedError("WrongChain")<{ expected: number; actual: number }> {}

/** Fails unless the node this runs on is on `expected`. */
const onlyOn = (expected: number) =>
  Effect.flatMap(Call.chainId, (actual) =>
    actual === expected ? Effect.void : Effect.fail(new WrongChain({ expected, actual })),
  );

// A vault of mainnet: on another chain the address is another contract, or none.
const vault = Vault.at(Address.makeUnsafe("0xBEEF01735c132Ada46AA9aA4c54623cAA92A64CB"));
const assets = onlyOn(1).pipe(Effect.andThen(vault.totalAssets()));
```

[`Call.chainId`](https://ethect.dev/reference/call/state/) asks the node once, `eth_chainId`, and keeps the
answer. Under `Transport.on` it asks nothing. [Several chains](https://ethect.dev/guides/multi-chain/#say-the-chain)
has the same lines in an app on two chains.

## extend

Gives the contract and another, in one: the functions, the events and the errors of both. The
errors of both are failures of every function.

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

const Fees = Abi.parse([
  "function fee() view returns (uint96)",
  "event FeeSet(uint96 fee)",
  "error NotCurator(address caller)",
]);

// the vault, and what this one adds to it
const FeeVault = Vault.extend(Fees);

const read = (address: Address.Address, user: Address.Address) => {
  const vault = FeeVault.at(address);
  return Effect.all([
    // a function of `Fees`, which also fails with the error of `Vault`
    vault.fee(),
    // a function of `Vault`, which also fails with the error of `Fees`
    vault.maxDeposit(user),
  ]).pipe(Effect.catchTag("NotCurator", (failure) => Effect.succeed(failure.caller)));
};
```

`extend` takes a contract, and nothing else. Signatures go through
[`Abi.parse`](https://ethect.dev/reference/abi/parse/) first, as above, and a JSON ABI through
[`Abi.fromJson`](https://ethect.dev/reference/abi/from-json/). A [built-in contract](https://ethect.dev/reference/standards/erc20/#extend)
has the same `extend`: `Erc20.extend(Abi.parse(["error …"]))`.

### A name both declare

The two contracts are merged by name. What `more` declares under a name takes the place of
what the contract had under it.

| Both declare | The result holds |
| --- | --- |
| a function, with the same signature | one function: the one of `more` |
| a function of the same name, with other inputs | the one of `more`. The name is not overloaded |
| an event of the same name | the one of `more`, whatever its fields |
| an error of the same name | the one of `more`. A revert no longer decodes as the other |

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

const Token = Abi.parse(["function transfer(address to, uint256 value) returns (bool)"]);

// the same name, another function: `transfer` takes three arguments, and only three
const WithData = Token.extend(
  Abi.parse(["function transfer(address to, uint256 value, bytes data)"]),
);

// to have both, declare both in one list: the name is then overloaded
const Both = Token.extend(
  Abi.parse([
    "function transfer(address to, uint256 value) returns (bool)",
    "function transfer(address to, uint256 value, bytes data)",
  ]),
);

const calls = (token: Address.Address, to: Address.Address) => [
  WithData.at(token).transfer(to, 1n, "0x"),
  // @ts-expect-error the `transfer` of two arguments is not there any more
  WithData.at(token).transfer(to, 1n),
  Both.at(token).transfer(to, 1n),
  Both.at(token).transfer(to, 1n, "0x"),
  Both.at(token)["transfer(address,uint256,bytes)"](to, 1n, "0x"),
];
```

- **Two functions of one name are an [overloaded name](https://ethect.dev/reference/abi/from-json/#overloads)
  when one list declares both**, as `Abi.parse` and `Abi.fromJson` give it. `extend` does not
  overload a name across the two contracts: a function does not say its signature in its
  type, so the types could not tell the same function declared twice from two functions.
- **A JSON ABI that declares a standard again extends it without doubles.**
  `Erc4626.extend(Abi.fromJson(vaultAbi))` holds each function once: the one of the ABI.
- **That is also how a function is corrected.** A token whose `transfer` returns nothing is
  `Erc20.extend(Abi.parse(["function transfer(address to, uint256 value)"]))`.

### Returns

`Contract.Extended<Base, More>`

A `Contract.Contract` of the functions, the events and the errors of both, with their literal
types. `Contract.Extended<typeof Vault, typeof Fees>` names it. A module that exports `fn`,
`ev` and `err` is a contract here: `Contract.Extended<typeof Erc20, typeof Fees>`.

### Parameters

#### more

- **Type:** `Contract.Contract<Fns, Evs, Errs>`

The contract to add: one that [`Contract.make`](#make), [`Abi.parse`](https://ethect.dev/reference/abi/parse/),
[`Abi.fromJson`](https://ethect.dev/reference/abi/from-json/) or another `extend` gave, or a built-in one, such
as `Erc20`.

## Behavior

- **Nothing is encoded or sent.** A contract is definitions under a name. A call is built when
  you call a function, and reaches a node when it is read or sent.
- **An entry is sorted by what it is, not by its key.** A class that `Ev.make` built is an
  event, any other class is an error, and an object is a function.
- **Two functions of one name need two keys.** An overloaded name is one key for each
  definition.
- **`extend` changes neither contract.** It gives a new one. A function that gains no error
  is the same function: `Erc4626.fn.transfer` is `Erc20.fn.transfer`.
- **`extend` never throws.** What is no contract adds nothing. The types refuse it.
- **A parsed contract is a contract.** What [`Abi.parse`](https://ethect.dev/reference/abi/parse/) and
  [`Abi.fromJson`](https://ethect.dev/reference/abi/from-json/) return is a `Contract.Contract`: a function that
  takes a contract takes it. A name that several of its functions share is
  [one key](https://ethect.dev/reference/abi/from-json/#overloads), and `at` binds it as it binds a function.
