# ERC-721 token (Erc721)

The ERC-721 non-fungible token, built in: the functions and the events of
[EIP-721](https://eips.ethereum.org/EIPS/eip-721), 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 { Effect } from "effect";
import { Address, Erc721, Signer, Tx } from "@ethect/core";

const NFT = Address.makeUnsafe("0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D");
const TO = Address.makeUnsafe("0x70997970C51812dc3A010C7d01b50e0d17dc79C8");

const nft = Erc721.at(NFT);

const give = (tokenId: bigint) =>
  Effect.gen(function* () {
    const me = yield* Signer.address;
    const owner = yield* nft.ownerOf(tokenId);
    // one name for two functions: three arguments, or four with `data`
    const receipt = yield* Tx.send(nft.safeTransferFrom(me, TO, tokenId));
    // the events of the standard decode the logs
    return { owner, block: receipt.blockNumber, topic: Erc721.ev.Transfer.topic };
  });
```

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

## What it declares

The nine functions and the three events of the EIP, the `supportsInterface` of the
[ERC-165](https://eips.ethereum.org/EIPS/eip-165) it requires, and its two optional
extensions: metadata and enumeration.

```solidity
function balanceOf(address owner) view returns (uint256)
function ownerOf(uint256 tokenId) view returns (address)
function safeTransferFrom(address from, address to, uint256 tokenId, bytes data) payable
function safeTransferFrom(address from, address to, uint256 tokenId) payable
function transferFrom(address from, address to, uint256 tokenId) payable
function approve(address approved, uint256 tokenId) payable
function setApprovalForAll(address operator, bool approved)
function getApproved(uint256 tokenId) view returns (address)
function isApprovedForAll(address owner, address operator) view returns (bool)

// ERC-165
function supportsInterface(bytes4 interfaceId) view returns (bool)

// optional: metadata
function name() view returns (string)
function symbol() view returns (string)
function tokenURI(uint256 tokenId) view returns (string)

// optional: enumeration
function totalSupply() view returns (uint256)
function tokenByIndex(uint256 index) view returns (uint256)
function tokenOfOwnerByIndex(address owner, uint256 index) view returns (uint256)

event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId)
event ApprovalForAll(address indexed owner, address indexed operator, bool approved)
```

- **Four functions are payable**, as the EIP declares them: the two `safeTransferFrom`,
  `transferFrom` and `approve`. Each takes `{ value }` after its arguments. The EIP lets a
  token implement them as non-payable: such a token reverts when it is sent a value.
- **The two extensions are optional.** On a token without one, reading its functions 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.

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

const NFT = Address.makeUnsafe("0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D");
const nft = Erc721.at(NFT);

const calls = (from: Address.Address, to: Address.Address) => [
  // the arguments say which of the two functions is called
  nft.safeTransferFrom(from, to, 1n),
  // with `data`
  nft.safeTransferFrom(from, to, 1n, "0x1234"),
  // payable: a value after the arguments
  nft.safeTransferFrom(from, to, 1n, { value: 1n }),
  // one of the two, by its signature
  nft["safeTransferFrom(address,address,uint256,bytes)"](from, to, 1n, "0x"),
];
```

### Returns

[`Contract.Bound<Fns>`](https://ethect.dev/reference/contract/#at): an object with one key per function. The
name `safeTransferFrom` is [one key for its two functions](https://ethect.dev/reference/abi/from-json/#overloads),
and each is also there under its signature.

### 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 { Erc721, Ev } from "@ethect/core";
import type { Log } from "@ethect/core/rpc";

Erc721.fn.ownerOf.selector; // "0x6352211e"
// one of the two `safeTransferFrom`
Erc721.fn["safeTransferFrom(address,address,uint256)"].signature;
// the transfers among logs: `tokenId` is indexed, which the `Transfer` of ERC-20 is not
const moved = (logs: ReadonlyArray<Log.Log>) => Ev.decode(Erc721.ev.Transfer, logs);
```

`Erc721.err` is an empty record.

## extend

Gives ERC-721 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, Erc721, type Address } from "@ethect/core";

const Collection = Erc721.extend(
  Abi.parse([
    "function mint(address to) payable returns (uint256)",
    "function royaltyInfo(uint256 tokenId, uint256 salePrice) view returns (address receiver, uint256 amount)",
    "error ERC721NonexistentToken(uint256 tokenId)",
  ]),
);

const ownerOf = (collection: Address.Address, tokenId: bigint) =>
  Collection.at(collection).ownerOf(tokenId).pipe(
    Effect.catchTag("ERC721NonexistentToken", () => Effect.succeed(undefined)),
  );
```

The error is a failure of every function, the two `safeTransferFrom` included. 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, and
[`Erc20.extend`](https://ethect.dev/reference/standards/erc20/#extend) for a JSON ABI and a contract made by hand.

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

The same nineteen items by signature. Two things follow the EIP where viem's ABI does not:

| Item | Here, as the EIP declares it | viem's `erc721Abi` |
| --- | --- | --- |
| `safeTransferFrom(address,address,uint256,bytes)` | `payable` | `nonpayable` |
| the second field of `Approval` | `approved` | `spender` |

The field is the key a decoded event holds: `approval.approved`.

## Behavior

- **Nothing is encoded or sent.** `Erc721` is definitions. A call is built when you call a
  function, and reaches a node when it is read or sent.
- **`safeTransferFrom` picks its function by the arguments**: by how many there are, then by
  their types. A fourth argument that is bytes is `data`, and one that is an object is the
  value sent.
- **`Transfer` and `Approval` are not those of ERC-20.** Their third field is indexed: a log
  of one standard is no log of the other, though the two have one signature.
- **`extend` changes nothing of `Erc721`.** It gives a new contract.
- **A program ships what it uses.** One that does not import `Erc721` holds nothing of it.

## Errors

`Erc721` 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/) | encoding a `safeTransferFrom` whose arguments are those of neither function |
| `AbiError` | using a function of a contract given to `extend`, when its signature did not parse |

## Under the hood

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

**`Erc721.at(NFT).safeTransferFrom(from, to, 1n, data)`**

- **your program**: no request: four arguments, the fourth is bytes, so the function is `safeTransferFrom(address,address,uint256,bytes)`

**`Tx.send` of that call**

- **your node** `eth_sendRawTransaction`: with a key
- **the wallet** `eth_sendTransaction`: with a wallet

**`yield* Erc721.at(NFT).ownerOf(1n)`**

- **your node** `eth_call({ to: NFT, data: 0x6352211e + tokenId })`: the read

A read goes through [`Call.Reader`](https://ethect.dev/reference/call/reader/).
[`Tx.send`](https://ethect.dev/reference/tx/send/#under-the-hood) has every request of a send.
