# Amounts and decimals

A token amount is a bigint of its smallest units. Effect's BigDecimal shows 1500000 units of USDC as 1.5, and turns the 1.5 a user typed back into units. Two traps to know.

On chain, an amount is a `bigint` of the token's smallest units: 1.5 USDC is `1500000n`,
since USDC has 6 decimals. ethect has no unit helpers, because Effect's `BigDecimal` already
does both conversions. The example shows a balance as text, and sends what a user typed.

```ts title="pay.ts"
import { BigDecimal, Effect, Option } from "effect";
import { Call, Erc20, Signer, Tx, type Address } from "@ethect/core";

// Units to text: 1500000n at 6 decimals is "1.5". Four digits at most, never rounded up.
export const show = (units: bigint, decimals: number) =>
  BigDecimal.format(
    BigDecimal.round(BigDecimal.make(units, decimals), { scale: 4, mode: "floor" }),
  );

// Text to units: "1.5" at 6 decimals is 1500000n. Nothing when it is no amount of the token.
export const parse = (text: string, decimals: number) => {
  const amount = Option.getOrUndefined(BigDecimal.fromString(text.trim()));
  if (amount === undefined || text.trim() === "") return undefined; // not a number
  if (BigDecimal.isNegative(amount)) return undefined;
  if (BigDecimal.normalize(amount).scale > decimals) return undefined; // too many decimals
  return BigDecimal.scale(amount, decimals).value;
};

export const pay = (token: Address.Address, to: Address.Address, typed: string) =>
  Effect.gen(function* () {
    const usdc = Erc20.at(token);
    const me = yield* Signer.address;
    // One request: how many decimals the token has, and what you hold.
    const { decimals, balance } = yield* Call.all({
      decimals: usdc.decimals(),
      balance: usdc.balanceOf(me),
    });
    const amount = parse(typed, decimals);
    if (amount === undefined) return `"${typed}" is not an amount of this token`;
    if (amount > balance) return `You hold ${show(balance, decimals)} only`;
    const { blockNumber } = yield* Tx.send(usdc.transfer(to, amount));
    return `Sent ${show(amount, decimals)} of ${show(balance, decimals)} in block ${blockNumber}`;
  });
```

`pay(usdc, to, "1.5")` gives `Sent 1.5 of 1.5 in block 21000000` for someone who holds 1.5
USDC. It needs a signer and a node: [Send transactions](https://ethect.dev/guides/transactions/) has the layer
that gives both. Read the decimals from the token, as here, or write them as a constant: never
guess them.

## Units to text

A `BigDecimal` is a `bigint` and a scale: the number of digits after the point.
`BigDecimal.make(1_500_000n, 6)` is 1.5, exactly. No `number` is involved, so no precision is
lost on the way.

```ts
import { BigDecimal } from "effect";

// what the chain holds, and the decimals of the token
BigDecimal.format(BigDecimal.make(1_500_000n, 6)); // "1.5"
// ether has 18 decimals
BigDecimal.format(BigDecimal.make(10n ** 18n, 18)); // "1"
// floor to two digits: 1.239 is shown as 1.23, never as 1.24
BigDecimal.format(BigDecimal.round(BigDecimal.make(1_239_000n, 6), { scale: 2, mode: "floor" }));
```

Round down what you show of a balance: a user who reads `1.24` and holds `1.239` cannot send
what the screen says.

## Text to units

`BigDecimal.fromString` reads text and gives an `Option`: the number, or nothing when the text
is not one. `BigDecimal.scale(amount, 6)` moves it to the scale of the token, and `.value` is
the `bigint` to send.

```ts
import { BigDecimal, Option } from "effect";

// "1.5" is 15 at scale 1. At scale 6 it is 1500000.
const amount = Option.getOrUndefined(BigDecimal.fromString("1.5"));
// 1500000n, or undefined when the text was no number
const units = amount === undefined ? undefined : BigDecimal.scale(amount, 6).value;
```

A form sends more than numbers. This is what `parse` above makes of each:

| The user typed | `BigDecimal.fromString` gives | `parse` gives |
| --- | --- | --- |
| `1.5` | 1.5 | `1500000n` |
| ` 1.5 `, with spaces | nothing | `1500000n`: it trims first |
| `abc`, `1,5` | nothing | `undefined` |
| nothing at all | 0 | `undefined` |
| `-1` | -1 | `undefined` |
| `1.123456789` | 1.123456789 | `undefined`: USDC has 6 decimals |

## The two traps

Both were checked with `effect` 4.1.7.

**A long fraction is written with an exponent.** `BigDecimal.format` switches to scientific
notation at sixteen digits after the point. A token with 18 decimals gets there.

```ts
import { BigDecimal } from "effect";

const one = BigDecimal.make(10n ** 18n + 1n, 18); // one ether and one wei
BigDecimal.format(one); // "1.000000000000000001e+0"
BigDecimal.format(BigDecimal.make(1n, 18)); // "1e-18"
// Round first, to the digits you show.
BigDecimal.format(BigDecimal.round(one, { scale: 4, mode: "floor" })); // "1"
```

**Decimals the token does not have are dropped in silence.** Moving a number to a smaller
scale cuts what does not fit. The user typed more than they send, and nothing says so.

```ts
import { BigDecimal } from "effect";

const typed = BigDecimal.fromStringUnsafe("1.123456789");
BigDecimal.scale(typed, 6).value; // 1123456n: the last three digits are gone
// Check the scale of what was typed, and refuse it.
BigDecimal.normalize(typed).scale > 6; // true: not an amount of USDC
```

`normalize` drops the zeros at the end first, so `1.5000000` is still an amount of USDC.

## Under the hood

`BigDecimal` is arithmetic on a `bigint`: it sends nothing. The requests of `pay` are those of
its two lines that reach a node.

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

- **your node** `eth_call`: one, to Multicall3: both reads, at one block

**`Tx.send(usdc.transfer(to, amount))`**

- **your node**: the fees, the gas
- **your node** `eth_sendRawTransaction`
- **your node**: the receipt

- A `uint256` of a contract is a `bigint` in both directions: an argument, and a result.
- [`Call.all`](https://ethect.dev/reference/call/all/) and [`Tx.send`](https://ethect.dev/reference/tx/send/) have the requests.
- `BigDecimal` and `Option` are modules of `effect`, the package ethect is built on.
