ERC-20 token (Erc20)
The ERC-20 token, built in: the functions and the events of EIP-20, with no ABI to write. It is a contract: at an address it gives its functions, and each one builds calls.
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) |
function | The functions at a token: each one builds calls. |
Erc20.fn |
record | The functions, unbound: Erc20.fn.balanceOf. |
Erc20.ev |
record | The events: Erc20.ev.Transfer, Erc20.ev.Approval. |
Erc20.err |
record | The errors: none. |
Erc20.extend(more) |
function | ERC-20 and what a token adds to it, in one contract. |
Erc721, Erc1155 and
Erc4626 are built in the same way.
What it declares
Section titled “What it declares”The nine functions and the two events of the EIP, with the names it gives their arguments.
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,symbolanddecimalsare 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
extendadds them.
Gives the functions at a token. Each takes the arguments of the function, by the names the
EIP gives them: transferFrom(from, to, value).
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 itconst 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
Section titled “Returns”Contract.Bound<Fns>: an object with one key per function.
Parameters
Section titled “Parameters”- Type:
Address.Address
The address of the token.
fn, ev and err
Section titled “fn, ev and err”The definitions themselves, as a contract holds them.
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 tokenconst moved = (logs: ReadonlyArray<Log.Log>) => Ev.decode(Erc20.ev.Transfer, logs);// the first topic of an approvalErc20.ev.Approval.topic;Erc20.err is an empty record.
extend
Section titled “extend”Gives ERC-20 and what a token adds to it, in one contract. It is the
extend of any contract, and takes a contract.
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
Section titled “With a JSON ABI, or definitions made by hand”Any contract extends it: the one of a JSON ABI, or one made by hand.
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 tokenconst Pausable = Erc20.extend(Abi.fromJson(abi));// from definitions written by hand, and from what was just builtconst Token = Pausable.extend(Contract.make({ Frozen }));What extend returns is a contract, extended again the same way.
A function the token declares another way
Section titled “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.
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 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
Section titled “Returns”Contract.Contract<Fns, Evs, Errs>
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
Section titled “Parameters”- Type:
Contract.Contract
The contract to add: one that Abi.parse,
Abi.fromJson or Contract.make
gave, or another built-in one.
Compared with viem’s erc20Abi
Section titled “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.
import { erc20Abi } from "viem";import { Abi, Erc20 } from "@ethect/core";
// the ABI you gave viem builds the same callsconst FromViem = Abi.fromJson(erc20Abi);Erc20.fn.transfer.selector === FromViem.fn.transfer.selector; // trueBehavior
Section titled “Behavior”- Nothing is encoded or sent.
Erc20is 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 sameCall.View<bigint>. extendchanges nothing ofErc20. It gives a new contract.- A program ships what it uses. One that does not import
Erc20holds nothing of it. One that reads a token, or extendsErc20with a contract made by hand, holds no reader of signatures: that comes withAbi.parse, in the program that calls it.
Errors
Section titled “Errors”Erc20 declares no error, and none of its exports fails.
| Error | When |
|---|---|
Call.Error |
reading a call: the node cannot be reached, the call reverts, or what came back is not what the function returns |
AbiError |
using a function of a contract given to extend, when its signature did not parse |
A revert of a token is a 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 to have them typed.
Under the hood
Section titled “Under the hood”Erc20 asks no node. Its definitions are built once, when its module is loaded, with the
definers a contract made by hand uses. A request is sent when a call
is read or sent.
Erc20.at(USDC).balanceOf(owner)- your programno request: the call is plain data,
{ to: USDC, fn: balanceOf, args: [owner] }
- your programno request: the call is plain data,
yield*that call- your node
eth_call({ to: USDC, data: 0x70a08231 + owner })the read, merged with the reads issued beside it
- your node
Erc20.extend(more)- your programno request: the definitions of both, in a new contract
A read goes through Call.Reader, and a call that is sent through
Tx.send.