# Hex

A `0x`-prefixed hexadecimal string, the wire format of every byte value in Ethereum JSON-RPC.
The module has the type, its schemas, and the conversions to and from bytes.

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

const program = Effect.gen(function* () {
  const message = Hex.fromUtf8("hello"); // "0x68656c6c6f"
  const bytes = yield* Hex.toBytes(message); // Uint8Array [104, 101, 108, 108, 111]
  return Hex.size(message); // 5
});
```

Calldata, bytecode, signatures and storage values are all `Hex.Hex`. The type is a template
literal, so a string literal that starts with `0x` is one without a conversion.

| Export | Kind | Description |
| --- | --- | --- |
| [`Hex`](#hex) | type | A `0x`-prefixed hexadecimal string. |
| [`isHex`](#ishex) | function | Whether a value is a `0x`-prefixed hexadecimal string. |
| [`schema`](#schema) | schema | Any `0x`-prefixed hexadecimal string. |
| [`sized`](#sized) | function | A schema for exactly a number of bytes. |
| [`matching`](#matching) | function | A schema for the hex strings a pattern matches. |
| [`fromBytes`](#frombytes) | function | Encodes bytes as hex. |
| [`toBytes`](#tobytes) | function | Decodes hex into bytes, as an `Effect`. |
| [`toBytesResult`](#tobytesresult) | function | The same, as a `Result`. |
| [`fromUtf8`](#fromutf8) | function | Encodes a string as UTF-8, in hex. |
| [`size`](#size) | function | The number of bytes a hex string represents. |
| [`concat`](#concat) | function | Joins hex strings into one. |
| [`InvalidHexError`](#invalidhexerror) | error | What `toBytes` fails with. |

## Hex

The type: `` `0x${string}` ``.

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

// transfer(address,uint256)
const selector: Hex.Hex = "0xa9059cbb";
```

The type only says that the string starts with `0x`. It does not check the characters or the
length: [`isHex`](#ishex) and the schemas do.

## isHex

Tells whether a value is a `0x`-prefixed hexadecimal string.

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

const yes = Hex.isHex("0xAbC"); // true
const empty = Hex.isHex("0x"); // true
const no = Hex.isHex("abc"); // false
```

- **Parameters:** `u` (`unknown`).
- **Returns:** `boolean`, as a type guard to `Hex.Hex`. Both letter cases and odd lengths are
  hex. An uppercase `0X` prefix is not.

## schema

The schema of any `0x`-prefixed hexadecimal string. Methods use it for calldata, code and other
byte values.

```ts
import { Schema } from "effect";
import { Hex } from "@ethect/core";

const decode = Schema.decodeUnknownEffect(Hex.schema);

const data = decode("0xa9059cbb"); // succeeds with "0xa9059cbb"
const bad = decode("0xzz"); // fails: Expected a 0x-prefixed hex string
```

- **Type:** `Hex.Hex`. **Encoded:** a `string`.
- It accepts the empty `"0x"`, odd lengths such as `"0x123"`, and both letter cases.
- **Decoding lowercases.** `"0xA9059CBB"` decodes to `"0xa9059cbb"`, so two values read from a
  node compare with `===`. Encoding sends a value in the case it was written.

## sized

Makes a schema for exactly `size` bytes of hex, such as a 32-byte hash or a 4-byte selector.

```ts
import { Schema } from "effect";
import { Hex } from "@ethect/core";

const Selector = Hex.sized(4);

const ok = Schema.decodeUnknownEffect(Selector)("0xa9059cbb");
// "0x123456" fails: Expected 4 bytes of 0x-prefixed hex
const short = Schema.decodeUnknownEffect(Selector)("0x123456");
```

- **Parameters:** `size` (`number`), in bytes.
- **Returns:** a schema of `Hex.Hex`. [`Hash.schema`](https://ethect.dev/reference/primitives/hash/) is
  `Hex.sized(32)`.

## matching

Makes a schema for the hex strings a regular expression matches. `schema` and `sized` are built
with it.

```ts
import { Schema } from "effect";
import { Hex } from "@ethect/core";

const Bytes = Hex.matching(/^0x([0-9a-f]{2})*$/, "whole bytes of 0x-prefixed hex");

const ok = Schema.decodeUnknownEffect(Bytes)("0xA9059CBB"); // "0xa9059cbb"
// fails: Expected whole bytes of 0x-prefixed hex
const odd = Schema.decodeUnknownEffect(Bytes)("0x123");
```

- **Parameters:** `pattern` (`RegExp`), then `expected` (`string`), the words a decoding error
  uses for what was expected.
- **Returns:** a schema of `Hex.Hex`. The pattern must only match strings that start with
  `0x`.
- **Write the pattern for lowercase digits.** Decoding lowercases the string, then matches.
  Encoding takes either case.

## fromBytes

Encodes bytes as a lowercase hex string.

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

const hex = Hex.fromBytes(new Uint8Array([0, 255, 16, 171])); // "0x00ff10ab"
```

- **Parameters:** `bytes` (`Uint8Array`).
- **Returns:** `Hex.Hex`. No bytes give `"0x"`.

## toBytes

Decodes a hex string into bytes.

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

const program = Effect.gen(function* () {
  const bytes = yield* Hex.toBytes("0x00ff10Ab"); // Uint8Array [0, 255, 16, 171]
  return bytes.length; // 4
});
```

- **Parameters:** `hex` (`string`).
- **Returns:** `Effect<Uint8Array, Hex.InvalidHexError>`.

An odd number of digits is read with a zero in front, as a number is: `"0x123"` is the two
bytes `01 23`, which is also what [`size`](#size) counts.

It fails as a value when the string has no `0x` prefix or a character that is not hex.

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

const length = Hex.toBytes("0xzz").pipe(
  Effect.map((bytes) => bytes.length),
  Effect.catchTag("InvalidHexError", () => Effect.succeed(0)),
);
```

## toBytesResult

The same parser as a `Result`, for code that is not inside an `Effect`.

```ts
import { Result } from "effect";
import { Hex } from "@ethect/core";

const result = Hex.toBytesResult("0x6869");
const bytes = Result.isSuccess(result) ? result.success : new Uint8Array();
// Uint8Array [104, 105]
```

- **Parameters:** `hex` (`string`).
- **Returns:** `Result<Uint8Array, Hex.InvalidHexError>`. `toBytes` is this function lifted
  into an `Effect`.

## fromUtf8

Encodes a string as UTF-8 and returns the bytes as hex.

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

const message = Hex.fromUtf8("hello"); // "0x68656c6c6f"
```

- **Parameters:** `value` (`string`).
- **Returns:** `Hex.Hex`. It is the form
  [`Wallet.personalSign`](https://ethect.dev/rpc/wallet/personal-sign/) takes a text message in.

## size

Returns the number of bytes a hex string represents.

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

const bytes = Hex.size("0x00ff10ab"); // 4
```

- **Parameters:** `hex` (`Hex.Hex`).
- **Returns:** `number`. `"0x"` is `0`, and an odd length rounds up: `"0x123"` is `2`.

## concat

Joins hex strings into one.

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

// a selector followed by one 32-byte argument
const data = Hex.concat("0xa9059cbb", `0x${"00".repeat(32)}`);
```

- **Parameters:** any number of `Hex.Hex` values.
- **Returns:** `Hex.Hex`. No value gives `"0x"`. The letters keep the case they came in.

## InvalidHexError

The error `toBytes` and `toBytesResult` fail with.

| Field | Type | Notes |
| --- | --- | --- |
| `_tag` | `"InvalidHexError"` | the tag `Effect.catchTag` matches |
| `value` | `string` | the input |
| `message` | `string` | what is wrong with it |

The message, for `0xzz`:

```txt
Expected a 0x-prefixed hex string, got 0xzz
```

## Behavior

- **Lowercase out.** `fromBytes` and `fromUtf8` return lowercase hex.
- **Lowercase from a node.** The schemas decode to lowercase, so every hex value a method
  returns is lowercase.
- **Your case is kept.** A value you write is sent as you wrote it, and `concat` joins its
  arguments in the case each came in.
- **Two kinds of failure.** `toBytes` fails with an `InvalidHexError`. A schema fails with a
  `SchemaError`, which a method reports as a `CodecError`.
