# Connection.toJson

The [state](https://ethect.dev/reference/connection/state/) of a connection as text, for local storage or any
other place that holds text. [`Connection.fromJson`](#fromjson) reads it back, and never
fails. For a cookie, [`Connection.toCookie`](https://ethect.dev/reference/connection/cookie/) writes this text
with what a cookie needs.

## Usage

```ts
import { Effect, Layer, Stream } from "effect";
import { Connection, Wallets } from "@ethect/core";

// Whatever changes (account, chain, wallet, disconnection), what is stored follows.
const persist = Connection.changes.pipe(
  Stream.map(Connection.toJson),
  Stream.runForEach((text) => Effect.sync(() => localStorage.setItem("connection", text))),
);

// On the next visit, the app starts from it.
const App = (stored: string | null) =>
  Connection.layer({ initial: Connection.fromJson(stored ?? undefined) }).pipe(
    Layer.provideMerge(Wallets.browser),
  );

const app = App(localStorage.getItem("connection"));
```

### In a cookie

[`Connection.toCookie`](https://ethect.dev/reference/connection/cookie/) and
[`Connection.fromCookie`](https://ethect.dev/reference/connection/cookie/#fromcookie) are these two functions
for a cookie: the text is percent-encoded and gets its attributes, and it is read back from
`document.cookie` or from a `Cookie` header.

`fromJson` is for a framework that hands you the value of one cookie, already decoded.

```ts
import { Layer } from "effect";
import { Connection, Wallets } from "@ethect/core";

// `cookie` is the value of the `connection` cookie, as your framework gives it: decoded.
const Server = (cookie: string | undefined) =>
  Connection.layer({ initial: Connection.fromJson(cookie) }).pipe(
    Layer.provideMerge(Wallets.of([])),
  );
```

`fromJson` reads JSON. A value that is still percent-encoded reads as `disconnected`: that
one is for `fromCookie`.

### fromJson

Reads what `toJson` wrote. The result is a state to start from: pass it to
[`Connection.layer`](https://ethect.dev/reference/connection/layer/) as `initial`.

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

Connection.fromJson('{"v":1,"wallet":"io.metamask","accounts":["0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"],"chainId":1}');
// { status: "reconnecting", wallet: "io.metamask", accounts: ["0xf39fd6e5…fffb92266"], chainId: 1 }

Connection.fromJson('{"v":1}'); // { status: "disconnected" }
Connection.fromJson(undefined); // { status: "disconnected" }: no cookie
Connection.fromJson("not json"); // { status: "disconnected" }
```

## What is stored

| The state | `toJson` gives |
| --- | --- |
| `connected`, `reconnecting` | `{"v":1,"wallet":"io.metamask","accounts":["0xf39Fd6e5…cffFb92266"],"chainId":1}`, each account in its EIP-55 form |
| `disconnected`, `connecting` | `{"v":1}` |

| What is read | `fromJson` gives |
| --- | --- |
| a stored connection | `reconnecting`, with its wallet, accounts and chain |
| `{"v":1}` | `disconnected` |
| anything else: no text, text that is not JSON, another version, a field that is missing or of another type, an account that is not an address | `disconnected` |

- **Storing `disconnected` matters.** After the user disconnects, what is stored says so. The
  next visit starts `disconnected`, and
  [`reconnect`](https://ethect.dev/reference/connection/connect/#reconnect) does nothing: the user is not
  connected again behind their back.
- **The id of the wallet is what is remembered.** `reconnect` looks for a wallet with that id
  among the [`Wallets`](https://ethect.dev/reference/wallets/). No provider, no permission and no key is stored.

## Returns

| Function | Type |
| --- | --- |
| `toJson(state)` | `string` |
| `fromJson(text)` | `Connection.Disconnected \| Connection.Reconnecting` |

## Parameters

### state

- **Type:** [`Connection.State`](https://ethect.dev/reference/connection/state/)

The state to store: usually each one that [`Connection.changes`](https://ethect.dev/reference/connection/state/#changes)
gives.

### text

- **Type:** `string | undefined`

What storage holds, or `undefined` when it holds nothing.

## Behavior

- **`fromJson` never fails and never throws**, whatever it is given.
- **A stored connection reads as `reconnecting`, never as `connected`.** Only the wallet can
  say that it is connected: [`reconnect`](https://ethect.dev/reference/connection/connect/#reconnect) asks it.
- **A cookie is a hint, never an identity.** Anyone can write a cookie with any address in
  it. Render with it, and decide nothing from it: what an account may see or do is proved by
  a signature, on the server.
- **Accounts are written in EIP-55,** as every address ethect writes.
- **Addresses are read as addresses.** An account in any case is read as the lowercase
  address, so what was stored in lowercase before reads as it did. One that is not 20 bytes of
  hex makes the whole text read as `disconnected`.
- **The version is checked.** Text with another `v` than `1` reads as `disconnected`.
- **What it does not know is left out.** Other fields in the text are ignored.

## Under the hood

Nothing is sent, and nothing is asked of a wallet: these are two pure functions.

```text
toJson(state)
  connected, reconnecting   → {"v":1,"wallet":…,"accounts":[…in EIP-55],"chainId":…}
  anything else             → {"v":1}

fromJson(text)
  JSON with v 1, a wallet, accounts that are addresses and a chain id
                            → { status: "reconnecting", wallet, accounts, chainId }
  anything else             → { status: "disconnected" }
```
