# ERC-20 token (Erc20)

The ERC-20 token, built in. Its functions and its events at any address, with no ABI to write, and what a token adds to them.

The ERC-20 token, built in: the functions and the events of
[EIP-20](https://eips.ethereum.org/EIPS/eip-20), with no ABI to write. It is a
[contract](https://ethect.dev/reference/contract/): at an address it gives its functions, and each one builds
[calls](https://ethect.dev/reference/call/).

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

const USDC = Address.makeUnsafe("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");
const TO = Address.makeUnsafe("0x70997970C51812dc3A010C7d01b50e0d17dc79C8");

const usdc = Erc20.at(USDC);

const program = Effect.gen(function* () {
  const me = yield* Signer.address;
  // three reads, one `eth_call`
  const { symbol, decimals, balance } = yield* Call.all({
    symbol: usdc.symbol(),
    decimals: usdc.decimals(),
    balance: usdc.balanceOf(me),
  });
  // a write is plain data: `Tx.send` signs it, sends it and waits for its block
  const receipt = yield* Tx.send(usdc.transfer(TO, balance / 2n));
  const [transfer] = Ev.decode(Erc20.ev.Transfer, receipt.logs);
  return { symbol, decimals, sent: transfer?.value };
});

// 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);
```

| Export | Kind | Description |
| --- | --- | --- |
| [`Erc20.at(address)`](#at) | function | The functions at a token: each one builds calls. |
| [`Erc20.fn`](#fn-ev-and-err) | record | The functions, unbound: `Erc20.fn.balanceOf`. |
| [`Erc20.ev`](#fn-ev-and-err) | record | The events: `Erc20.ev.Transfer`, `Erc20.ev.Approval`. |
| [`Erc20.err`](#fn-ev-and-err) | record | The errors: none. |
| [`Erc20.extend(more)`](#extend) | function | ERC-20 and what a token adds to it, in one contract. |

[`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.

## What it declares

The nine functions and the two events of the EIP, with the names it gives their arguments.

```solidity
function name() view returns (string)
function symbol() view returns (string)
function decimals() view returns (uint8)
function totalSupply() view returns (uint256)
function balanceOf(address owner) view returns (uint256)
function allowance(address owner, address spender) view returns (uint256)
function transfer(address to, uint256 value) returns (bool)
function approve(address spender, uint256 value) returns (bool)
function transferFrom(address from, address to, uint256 value) returns (bool)

event Transfer(address indexed from, address indexed to, uint256 value)
event Approval(address indexed owner, address indexed spender, uint256 value)
```

- **`name`, `symbol` and `decimals` are optional in the EIP.** On a token without one of
  them, reading it fails.
- **It declares no error.** The EIP has none: each token reverts with its own, and
  [`extend`](#extend) adds them.

## at

Gives the functions at a token. Each takes the arguments of the function, by the names the
EIP gives them: `transferFrom(from, to, value)`.

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

const USDC = Address.makeUnsafe("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");
const SPENDER = Address.makeUnsafe("0x70997970C51812dc3A010C7d01b50e0d17dc79C8");

const usdc = Erc20.at(USDC);
// a view: Call.View<bigint>, also the effect of reading it
const allowance = (owner: Address.Address) => usdc.allowance(owner, SPENDER);
// a write: Call.Call<boolean>, to give to `Tx.send`
const approval = usdc.approve(SPENDER, 1_000_000n);
```

### Returns

[`Contract.Bound<Fns>`](https://ethect.dev/reference/contract/#at): an object with one key per function.

### Parameters

#### to

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

The address of the token.

## fn, ev and err

The definitions themselves, as a [contract](https://ethect.dev/reference/contract/) holds them.

```ts
import { Erc20, Ev } from "@ethect/core";
import type { Log } from "@ethect/core/rpc";

Erc20.fn.transfer.selector; // "0xa9059cbb"
// the transfers among the logs of any token
const moved = (logs: ReadonlyArray<Log.Log>) => Ev.decode(Erc20.ev.Transfer, logs);
// the first topic of an approval
Erc20.ev.Approval.topic;
```

`Erc20.err` is an empty record.

## extend

Gives ERC-20 and what a token adds to it, in one contract. It is the
[`extend` of any contract](https://ethect.dev/reference/contract/#extend), and takes a contract.

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

// What USDC adds to the standard, and an error it reverts with.
const Usdc = Erc20.extend(
  Abi.parse([
    "function nonces(address owner) view returns (uint256)",
    "function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)",
    "error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed)",
  ]),
);

const usdc = Usdc.at(Address.makeUnsafe("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"));

const read = (owner: Address.Address) =>
  Effect.gen(function* () {
    const nonce = yield* usdc.nonces(owner);
    // the error is a failure of every function, those of the standard too
    const balance = yield* usdc
      .balanceOf(owner)
      .pipe(Effect.catchTag("ERC20InsufficientBalance", (failure) => Effect.succeed(failure.balance)));
    return { nonce, balance };
  });
```

### With a JSON ABI, or definitions made by hand

Any contract extends it: the one of a JSON ABI, or one made by hand.

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

const abi = [
  { type: "function", name: "pause", stateMutability: "nonpayable", inputs: [], outputs: [] },
  { type: "error", name: "EnforcedPause", inputs: [] },
] as const;

class Frozen extends Err.make("Frozen", { account: Abi.address }) {}

// from the JSON ABI of the token
const Pausable = Erc20.extend(Abi.fromJson(abi));
// from definitions written by hand, and from what was just built
const Token = Pausable.extend(Contract.make({ Frozen }));
```

What `extend` returns is a contract, extended again the same way.

### A function the token declares another way

A function of the same name takes the place of the standard's. That is how a token that
does not follow the EIP is described, such as one whose `transfer` returns nothing.

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

const Token = Erc20.extend(
  Abi.parse([
    "function transfer(address to, uint256 value)",
    "function approve(address spender, uint256 value)",
    "function transferFrom(address from, address to, uint256 value)",
  ]),
);
```

[`contract.extend`](https://ethect.dev/reference/contract/#extend) has every case: a function of the same name,
an event or an error of the same name, and how a name is overloaded.

### Returns

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

The contract of both: the functions and the events of ERC-20, those of the contract you gave,
and its errors as failures of every function.

### Parameters

#### more

- **Type:** [`Contract.Contract`](https://ethect.dev/reference/contract/)

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

## Compared with viem's `erc20Abi`

The same eleven items, by signature and by mutability. The names of the arguments are the
EIP's: `transfer(to, value)`, where viem's ABI says `recipient` and `amount`.

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

// the ABI you gave viem builds the same calls
const FromViem = Abi.fromJson(erc20Abi);
Erc20.fn.transfer.selector === FromViem.fn.transfer.selector; // true
```

## Behavior

- **Nothing is encoded or sent.** `Erc20` is definitions. A call is built when you call a
  function, and reaches a node when it is read or sent.
- **The arguments have names.** A contract parsed from signatures or from a JSON ABI takes
  them by position. This one is defined by hand: an editor shows `balanceOf(owner)`.
- **A call is typed as the one a parsed contract builds.**
  `Abi.parse(["function balanceOf(address owner) view returns (uint256)"])` gives the same
  `Call.View<bigint>`.
- **`extend` changes nothing of `Erc20`.** It gives a new contract.
- **A program ships what it uses.** One that does not import `Erc20` holds nothing of it. One
  that reads a token, or extends `Erc20` with a contract made by hand, holds no reader of
  signatures: that comes with `Abi.parse`, in the program that calls it.

## Errors

`Erc20` declares no error, and none of its exports fails.

| Error | When |
| --- | --- |
| [`Call.Error`](https://ethect.dev/reference/call/#what-a-read-fails-with) | reading a call: the node cannot be reached, the call reverts, or what came back is not what the function returns |
| [`AbiError`](https://ethect.dev/reference/errors/abi-error/) | using a function of a contract given to `extend`, when its signature did not parse |

A revert of a token is a [`Revert`](https://ethect.dev/reference/revert/): `Revert.Reason` for a
`require(…, "message")`, `Revert.Unknown` for a custom error that the contract does not
declare. Give the errors of the token to [`extend`](#extend) to have them typed.

## Under the hood

`Erc20` asks no node. Its definitions are built once, when its module is loaded, with the
[definers](https://ethect.dev/reference/fn/view/) a contract made by hand uses. A request is sent when a call
is read or sent.

**`Erc20.at(USDC).balanceOf(owner)`**

- **your program**: no request: the call is plain data, `{ to: USDC, fn: balanceOf, args: [owner] }`

**`yield*` that call**

- **your node** `eth_call({ to: USDC, data: 0x70a08231 + owner })`: the read, merged with the reads issued beside it

**`Erc20.extend(more)`**

- **your program**: no request: the definitions of both, in a new contract

A read goes through [`Call.Reader`](https://ethect.dev/reference/call/reader/), and a call that is sent through
[`Tx.send`](https://ethect.dev/reference/tx/send/#under-the-hood).
