# Abi.Class

A struct as a class. Its values are instances, so they can have methods.

## Usage

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

class Position extends Abi.Class<Position>("Position")({
  supplyShares: Abi.uint256,
  collateral: Abi.uint128,
}) {
  get isEmpty() {
    return this.supplyShares === 0n && this.collateral === 0n;
  }
}

const program = Effect.gen(function* () {
  const position = new Position({ supplyShares: 5n, collateral: 0n });
  const data = yield* Abi.encode(Position, position);
  const decoded = yield* Abi.decode(Position, data);
  return decoded.isEmpty; // false: what is decoded is a Position
});
```

The class is the type. Use it where a type goes.

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

class Position extends Abi.Class<Position>("Position")({
  supplyShares: Abi.uint256,
  collateral: Abi.uint128,
}) {}

const Positions = Abi.array(Position); // (uint256,uint128)[]
const Account = Abi.struct({ owner: Abi.address, position: Position });
```

## Returns

A class to extend. It is an [`Abi.Reference<Self>`](https://ethect.dev/reference/abi/#reference-types), an
`Abi.Type` that says it is a reference type, and its constructor takes the fields as an object.

## Parameters

`Abi.Class` is called twice. The type argument comes first, on its own, so that the fields are
still inferred.

### name

- **Type:** `string`

A name for the class. It tells its instances apart from those of another class.

### fields

- **Type:** `Abi.Fields`

The types of the fields, by name and in order: what [`Abi.struct`](https://ethect.dev/reference/abi/struct/)
takes, with the same [key order](https://ethect.dev/reference/abi/struct/#key-order).

## Behavior

- **Encoded as its fields.** A class and a struct of the same fields are the same bytes.
- **Decoding gives instances.** Also inside an array or a struct.
- **Encoding takes an instance.** A plain object with the same fields is not a `Position`:
  build one with `new`.
- **`new` checks no range.** `new Position({ supplyShares: -1n, collateral: 0n })` is built,
  and fails when it is encoded, as a plain struct does.
- **`new` throws on a field that is missing, or of the wrong JavaScript type.** The types
  refuse both, so it takes a cast or plain JavaScript to get there. The constructor is the one
  of Effect's `Schema.Class`, which reads the shape of what it is given.
- **Encoding an instance and decoding to one do not throw.** They fail with an `AbiError`,
  as everything else here.
- **One class per definition.** Extend what `Abi.Class` returns once. To get a second class
  with the same fields, call `Abi.Class` again.

## Errors

| Error | When |
| --- | --- |
| [`AbiError`](https://ethect.dev/reference/errors/abi-error/) | encoding what is not an instance of the class |
| `AbiError` | encoding an instance with a field its type refuses |
| `AbiError` | any use of a class whose field names are not Solidity identifiers |
