# ERC-4626 vault (Erc4626)

The ERC-4626 tokenized vault, built in. Its functions and its events at any address, those of the ERC-20 of its shares included, and what a vault adds to them.

The ERC-4626 tokenized vault, built in: the functions and the events of
[EIP-4626](https://eips.ethereum.org/EIPS/eip-4626), with no ABI to write. A vault is the
token of its shares, so `Erc4626` has the functions and the events of
[`Erc20`](https://ethect.dev/reference/standards/erc20/) too. 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, Erc4626, Ev, Signer, Transport, Tx } from "@ethect/core";

const USDC = Address.makeUnsafe("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");
const VAULT = Address.makeUnsafe("0xBEEF01735c132Ada46AA9aA4c54623cAA92A64CB");

const usdc = Erc20.at(USDC);
const vault = Erc4626.at(VAULT);

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),
  });
  // approve the vault, then deposit: each is signed, sent and waited for
  const receipts = yield* Tx.send([usdc.approve(VAULT, balance), vault.deposit(balance, me)]);
  // the transfers of both, the shares the vault minted among them
  const transfers = Ev.decode(Erc20.ev.Transfer, receipts.flatMap((receipt) => receipt.logs));
  return { symbol, decimals, transfers };
});

// 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 |
| --- | --- | --- |
| [`Erc4626.at(address)`](#at) | function | The functions at a vault: each one builds calls. |
| [`Erc4626.fn`](#fn-ev-and-err) | record | The functions, unbound: `Erc4626.fn.deposit`, and those of ERC-20. |
| [`Erc4626.ev`](#fn-ev-and-err) | record | The events: `Deposit`, `Withdraw`, and those of ERC-20. |
| [`Erc4626.err`](#fn-ev-and-err) | record | The errors: none. |
| [`Erc4626.extend(more)`](#extend) | function | ERC-4626 and what a vault adds to it, in one contract. |

## What it declares

The sixteen functions and the two events of the EIP, and
[those of ERC-20](https://ethect.dev/reference/standards/erc20/#what-it-declares): the EIP requires EIP-20, with
its optional `name`, `symbol` and `decimals`.

```solidity
function asset() view returns (address)
function totalAssets() view returns (uint256)
function convertToShares(uint256 assets) view returns (uint256)
function convertToAssets(uint256 shares) view returns (uint256)
function maxDeposit(address receiver) view returns (uint256)
function previewDeposit(uint256 assets) view returns (uint256)
function deposit(uint256 assets, address receiver) returns (uint256)
function maxMint(address receiver) view returns (uint256)
function previewMint(uint256 shares) view returns (uint256)
function mint(uint256 shares, address receiver) returns (uint256)
function maxWithdraw(address owner) view returns (uint256)
function previewWithdraw(uint256 assets) view returns (uint256)
function withdraw(uint256 assets, address receiver, address owner) returns (uint256)
function maxRedeem(address owner) view returns (uint256)
function previewRedeem(uint256 shares) view returns (uint256)
function redeem(uint256 shares, address receiver, address owner) returns (uint256)

event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares)
event Withdraw(address indexed sender, address indexed receiver, address indexed owner, uint256 assets, uint256 shares)

// and ERC-20, for the shares
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)
```

- **It declares no error.** The EIP has none: each vault reverts with its own, and
  [`extend`](#extend) adds them.
- **The EIP lets a vault have the permit of EIP-2612.** It is not here: add it with `extend`.

## at

Gives the functions at a vault. Each takes the arguments of the function, by the names the
EIP gives them: `withdraw(assets, receiver, owner)`.

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

const vault = Erc4626.at(Address.makeUnsafe("0xBEEF01735c132Ada46AA9aA4c54623cAA92A64CB"));

const position = (owner: Address.Address) =>
  Effect.gen(function* () {
    const shares = yield* vault.balanceOf(owner); // of ERC-20: the shares
    // a view: Call.View<bigint>, also the effect of reading it
    const assets = yield* vault.convertToAssets(shares);
    // a write: Call.Call<bigint>, to give to `Tx.send`
    return { assets, exit: vault.redeem(shares, owner, owner) };
  });
```

### 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 vault.

## fn, ev and err

The definitions themselves, as a [contract](https://ethect.dev/reference/contract/) holds them. Those of ERC-20
are the ones `Erc20` holds: a transfer of shares decodes as an `Erc20.ev.Transfer`.

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

Erc4626.fn.deposit.selector; // "0x6e553f65"
// what went in and what came out, in the order of the logs
const flows = (logs: ReadonlyArray<Log.Log>) =>
  Ev.decode([Erc4626.ev.Deposit, Erc4626.ev.Withdraw], logs);
// the same class, not a copy
Erc4626.ev.Transfer === Erc20.ev.Transfer; // true
```

`Erc4626.err` is an empty record.

## extend

Gives ERC-4626 and what a vault 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, Erc4626, type Address } from "@ethect/core";

// from signatures
const Vault = Erc4626.extend(
  Abi.parse([
    "function fee() view returns (uint96)",
    "error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max)",
  ]),
);

// or from the JSON ABI of the vault, which declares the standard again: one item each
declare const vaultAbi: readonly [
  { type: "function"; name: "skim"; stateMutability: "nonpayable"; inputs: []; outputs: [] },
];
const MyVault = Erc4626.extend(Abi.fromJson(vaultAbi));

const room = (vault: Address.Address, user: Address.Address) =>
  Vault.at(vault).maxDeposit(user).pipe(
    Effect.catchTag("ERC4626ExceededMaxDeposit", (failure) => Effect.succeed(failure.max)),
  );
```

The error is a failure of every function, those of the shares too. A function, an event or
an error of a name the standard has takes its place: see
[`contract.extend`](https://ethect.dev/reference/contract/#extend) for every case.

### Returns

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

### 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 `erc4626Abi`

The same twenty-nine items, by signature and by mutability. One field has the name the EIP
gives it:

| Item | Here, as the EIP declares it | viem's `erc4626Abi` |
| --- | --- | --- |
| the second field of `Deposit` | `owner`: who owns the shares | `receiver` |

The field is the key a decoded event holds: `deposit.owner`. The argument of `maxDeposit` and
of `maxMint` is `receiver` here, and `caller` in viem's ABI.

## Behavior

- **Nothing is encoded or sent.** `Erc4626` 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.** An editor shows `deposit(assets, receiver)`.
- **`asset()` is not read for you.** The token a vault holds is another contract:
  `Erc20.at(yield* vault.asset())`.
- **`extend` changes nothing of `Erc4626`.** It gives a new contract.
- **A program ships what it uses.** One that imports `Erc4626` holds it and `Erc20`, and
  nothing of the two other standards.

## Errors

`Erc4626` 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 |

## Under the hood

`Erc4626` 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, beside those of `Erc20`. A
request is sent when a call is read or sent.

**`Call.all({ symbol, decimals, balance })`**

- **your node** `eth_call({ to: Multicall3, data: aggregate3([symbol(), decimals(), balanceOf(me)]) })`: the three reads, in one request

**`Tx.send([usdc.approve(VAULT, balance), vault.deposit(balance, me)])`**

- **your node** `eth_sendRawTransaction`: with a key: once per call
- **the wallet** `wallet_sendCalls`: with a wallet that batches: the two calls, in one prompt

**`Ev.decode(Erc20.ev.Transfer, logs)`**

- **your program**: no request: the logs are those of the receipts

[`Call.all`](https://ethect.dev/reference/call/all/#under-the-hood) and
[`Tx.send`](https://ethect.dev/reference/tx/send/#under-the-hood) have every request of a read and of a send.
