# Abi.parse

Builds a [contract](https://ethect.dev/reference/contract/) from human-readable signatures. Its functions,
events and errors are the definitions you would write by hand.

## Usage

```ts
import { Effect } from "effect";
import { FetchHttpClient } from "effect/http";
import { Abi, Address, Transport } from "@ethect/core";

const Erc20 = Abi.parse([
  "function balanceOf(address owner) view returns (uint256)",
  "function transfer(address to, uint256 amount) returns (bool)",
  "event Transfer(address indexed from, address indexed to, uint256 value)",
  "error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed)",
]);

const usdc = Erc20.at(Address.makeUnsafe("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"));
const USER = Address.makeUnsafe("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266");

const program = Effect.gen(function* () {
  const balance = yield* usdc.balanceOf(USER); // a view: reading it is one `eth_call`
  const call = usdc.transfer(USER, balance); // a write: plain data, to send
  return { balance, call };
});

const result = await program.pipe(
  Effect.provide(Transport.http("https://ethereum-rpc.publicnode.com")),
  Effect.provide(FetchHttpClient.layer),
  Effect.runPromise,
);
```

Arguments are positional and have no names: `balanceOf(args_0: Address)`. For named
arguments, define the function with [`Fn.view`](https://ethect.dev/reference/fn/view/).

### Structs

A struct declared in the list is used by its name in the other signatures. It can be declared
before or after them, and hold other structs.

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

const Exchange = Abi.parse([
  "struct Leg { uint8 kind; bytes data; }",
  "struct Order { address maker; uint256 amount; Leg[] legs; }",
  "function fill(Order order) payable returns (bool)",
]);

const fill = (exchange: Address.Address, maker: Address.Address) =>
  // a struct is an object of its members, and a payable function takes a value
  Exchange.at(exchange).fill({ maker, amount: 100n, legs: [] }, { value: 10n ** 18n });
```

Parameters in parentheses are a type written in place. With a name on each, the value is an
object. With one name missing, it is a tuple.

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

const { fn } = Abi.parse([
  "function open((address owner, uint256 amount) position)",
  "function batch((address, uint256)[] positions)",
]);

const calls = (pool: Address.Address, owner: Address.Address) => [
  fn.open.at(pool)({ owner, amount: 1n }),
  fn.batch.at(pool)([[owner, 1n]]),
];
```

### Events and errors

An event and an error are the classes [`Ev.make`](https://ethect.dev/reference/ev/make/) and
[`Err.make`](https://ethect.dev/reference/err/make/) give, under `ev` and `err`. Every error of the list is a
typed failure of every function.

```ts
import { Effect, Option } from "effect";
import { Abi, type Address, Ev } from "@ethect/core";
import type { Log } from "@ethect/core/rpc";

const Nft = Abi.parse([
  "function ownerOf(uint256 tokenId) view returns (address)",
  "event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)",
  "error ERC721NonexistentToken(uint256 tokenId)",
]);

const transfers = (logs: ReadonlyArray<Log.Log>) => Ev.decode(Nft.ev.Transfer, logs);

const ownerOf = (nft: Address.Address, tokenId: bigint) =>
  Nft.at(nft)
    .ownerOf(tokenId)
    .pipe(
      Effect.map(Option.some),
      Effect.catchTag("ERC721NonexistentToken", () => Effect.succeed(Option.none())),
    );
```

A parameter of an event or of an error that has no name is named by its place: `arg0`,
`arg1`.

### A signature that does not parse

It does not compile. The message is the type the signature should have been.

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

const Broken = Abi.parse([
  "function decimals() view returns (uint8)",
  // @ts-expect-error adress is not a type: it is no Solidity type, and no struct of that name is declared
  "function transfer(adress to, uint256 amount)",
  // @ts-expect-error A parenthesis is not closed
  "function approve(address spender, uint256 amount",
  // @ts-expect-error vew is not expected after the parameters of a function
  "function totalSupply() vew returns (uint256)",
]);
```

## The grammar

It is the one of abitype's human-readable ABI.

| Signature | Declares |
| --- | --- |
| `function name(type [location] [name], …) [visibility] [mutability] [returns (type [name], …)]` | a function |
| `event Name(type [indexed] [name], …)` | an event |
| `error Name(type [name], …)` | an error |
| `struct Name { type name; … }` | a struct, for the other signatures to use by name |
| `constructor(…)`, `fallback()`, `receive()` | nothing: they are read and ignored |

| A type is written | It is |
| --- | --- |
| `address`, `bool`, `string`, `bytes`, `bytes1` to `bytes32`, `uint8` to `uint256`, `int8` to `int256` | the [type of `Abi`](https://ethect.dev/reference/abi/types/) of that name |
| `uint`, `int` | `uint256`, `int256` |
| `address payable` | `address` |
| `T[]`, `T[3]` | an [array](https://ethect.dev/reference/abi/array/) of `T`, of any length or of three |
| `Name` | the struct declared under that name |
| `(type name, …)` | a [struct](https://ethect.dev/reference/abi/struct/) when each parameter has a name, a [tuple](https://ethect.dev/reference/abi/tuple/) otherwise |

| A word | Where | Says |
| --- | --- | --- |
| `calldata`, `memory`, `storage` | after the type of a parameter of a function that is a `string`, `bytes`, an array or a struct | where the value is kept. It is read and not kept |
| `indexed` | after the type of a field of an event | that the field is stored in a topic: see [`Abi.indexed`](https://ethect.dev/reference/abi/indexed/) |
| `external`, `public` | after the parameters of a function | its visibility. It is read and not kept |
| `pure`, `view`, `nonpayable`, `payable` | after the visibility | what the function does to the chain. Without one, it is `nonpayable` |

What each signature becomes is the table of
[`Abi.fromJson`](https://ethect.dev/reference/abi/from-json/#what-each-item-becomes): a signature is read as the
item a JSON ABI has for it.

## Returns

[`Contract.Contract<Fns, Evs, Errs>`](https://ethect.dev/reference/contract/)

A contract, as [`Contract.make`](https://ethect.dev/reference/contract/#make) gives:

| Member | Holds |
| --- | --- |
| `fn` | the functions, by name: each a [`Fn.Fn`](https://ethect.dev/reference/fn/#what-a-function-holds) |
| `ev` | the events, by name: each the class [`Ev.make`](https://ethect.dev/reference/ev/make/) gives |
| `err` | the errors, by name: each the class [`Err.make`](https://ethect.dev/reference/err/make/) gives |
| `at(address)` | the functions [at an address](https://ethect.dev/reference/contract/#at): each one builds calls |

Signatures that are not literals, such as a `string[]` read from a file, give functions that
take any arguments and return `unknown`: see
[an ABI that is not `as const`](https://ethect.dev/reference/abi/from-json/#an-abi-that-is-not-as-const).

## Parameters

### signatures

- **Type:** `ReadonlyArray<string>`

The signatures, one definition each. Write them in the call, or declare the list `as const`:
their text is what types the contract.

## Behavior

- **A signature that does not parse does not compile**, and the message says why. When the
  program runs it gives a definition under its name whose every use fails with an
  [`AbiError`](https://ethect.dev/reference/errors/abi-error/). The message quotes the signature and says where
  it stops: `transfer: Cannot parse "function transfer(adress to, uint256 amount)": adress is
  not a type: it is no Solidity type, and no struct of that name is declared, at character 18:
  "adress to, uint256 amount)"`.
- **Nothing throws.** A function that does not parse is a view, so a call of it is an effect
  that fails. An event or an error that does not parse decodes nothing. A signature whose kind
  or name cannot be read declares nothing.
- **The types read less than the program does.** These compile, and are refused when the
  program runs: a name that is not a Solidity identifier, `indexed` outside an event, a
  location on a type that has none (`uint256 memory`), an array of no item (`uint256[0]`).
- **An overloaded name** is one function that takes each of its argument lists, and each of
  its functions is also under its signature. See
  [overloads](https://ethect.dev/reference/abi/from-json/#overloads).
- **A signature that is there twice declares one definition.**
- **A type nests 32 arrays and tuples at most**, structs included.
- **Spaces between words do not count**, and a signature can run over several lines. The
  types ask one thing more: the `[]` of an array is written against its type, `uint256[]`.
- **Names are read and not kept**, except those of the fields of an event, of an error, of a
  struct, and of several returned values.

## Errors

`Abi.parse` returns a contract and has no failure of its own.

| Error | When |
| --- | --- |
| [`AbiError`](https://ethect.dev/reference/errors/abi-error/) | encoding a call of, or decoding what came back from, a function whose signature does not parse |
| `AbiError` | the same for a function that uses a struct whose signature does not parse |
