# Render on the server

A server has no wallet, and a page still has to show the account in its first HTML. The state
of the connection is plain data: store it in a cookie, render from it on the server, and let
the wallet confirm it in the browser.

```tsx title="page.tsx"
import { Address, Connection } from "@ethect/core";
import { useConnection } from "./ethect";

// Rendered on the server, then again in the browser. Both start from `initial`.
export function Account({ initial }: { initial: Connection.State }) {
  const connection = useConnection(initial);
  switch (connection.status) {
    case "connected": // the wallet says so. An address is shown in its EIP-55 form
      return <p>{Address.checksum(connection.accounts[0])}</p>;
    case "reconnecting": // the cookie says so, and the wallet has not answered yet
      return (
        <p className="unconfirmed">
          {connection.accounts[0] ? Address.checksum(connection.accounts[0]) : "…"}
        </p>
      );
    default:
      return <p>Not connected</p>;
  }
}

// On the server. `cookies` is the `Cookie` header of the request, or `null` when it has none.
export const Page = ({ cookies }: { cookies: string | null }) => (
  <Account initial={Connection.fromCookie(cookies)} />
);
```
```tsx title="ethect.tsx"
import { useEffect, useState } from "react";
import { Effect, Fiber, Layer, ManagedRuntime, Stream } from "effect";
import { FetchHttpClient } from "effect/http";
import { Connection, Signer, Transport, Wallets } from "@ethect/core";

// 1. The cookies of the page. A server has no `document`: it reads nothing.
const cookies = typeof document === "undefined" ? undefined : document.cookie;

const App = Signer.connected().pipe(
  Layer.provideMerge(Connection.layer({ initial: Connection.fromCookie(cookies) })),
  Layer.provideMerge(Wallets.browser), // an empty list on a server
  Layer.provideMerge(Transport.http("https://ethereum-rpc.publicnode.com")),
  Layer.provide(FetchHttpClient.layer),
);
type Services = Layer.Success<typeof App>;

export const runtime = ManagedRuntime.make(App);

export const run = <A, E>(effect: Effect.Effect<A, E, Services>) => runtime.runPromiseExit(effect);

export function useStream<A>(stream: Stream.Stream<A, never, Services>, initial: A): A {
  const [value, setValue] = useState(initial);
  useEffect(() => {
    const fiber = runtime.runFork(
      Stream.runForEach(stream, (next) => Effect.sync(() => setValue(next))),
    );
    return () => void runtime.runFork(Fiber.interrupt(fiber));
  }, [stream]);
  return value;
}

export const useWallets = () => useStream(Wallets.changes, []);
export const useConnection = (initial: Connection.State) => useStream(Connection.changes, initial);

// 2. Whatever changes (account, chain, wallet, disconnection), the cookie follows.
const persist = Connection.changes.pipe(
  Stream.runForEach((state) =>
    Effect.sync(() => {
      document.cookie = Connection.toCookie(state);
    }),
  ),
);

// 3. In the browser, once: the remembered wallet is asked for its accounts. No prompt.
if (typeof document !== "undefined") {
  runtime.runFork(persist);
  runtime.runFork(Connection.reconnect);
}
```

`Account` uses a hook: under React Server Components it is a client component, in a file of
its own that starts with `"use client"`.

## The setup

`ethect.tsx` is the file of [Let the user pick a wallet](https://ethect.dev/guides/wallet-selection/#the-setup),
with three additions: it starts from the cookie, it keeps the cookie in step, and it asks the
remembered wallet once.

Loading this file on a server touches no browser API, and builds nothing: the runtime is made
when something first runs on it, and on a server nothing does.

None of the three needs a server. In a page that only the browser renders, the cookie and
`Connection.reconnect` keep the connection across a reload: start `useConnection` from
`{ status: "disconnected" }`, as the picker does, and the state follows.

## What the cookie holds

| The state | The value of the `connection` cookie |
| --- | --- |
| `connected`, `reconnecting` | `{"v":1,"wallet":"io.metamask","accounts":["0x…"],"chainId":1}` |
| `disconnected`, `connecting` | `{"v":1}` |

The `id` of the wallet, its accounts and its chain. No provider, no permission, no key and no
signature. [`Connection.toCookie`](https://ethect.dev/reference/connection/cookie/) writes it percent-encoded,
for the whole site and for a year.
[`Connection.fromCookie`](https://ethect.dev/reference/connection/cookie/#fromcookie) finds it among the other
cookies and never fails: anything it does not know reads as `disconnected`.

> **Caution: A hint, never an identity**
>
> Anyone can write a cookie with any address in it. Render with it: a balance, a name, a
> portfolio are public anyway. Decide nothing from it. What an account may see or do is proved
> by a signature that your server checks, with
> [`Signature.verifyMessage`](https://ethect.dev/reference/signature/verify-message/), and the cookie is not one.

That is why a stored connection reads as `reconnecting`, and never as `connected`: only the
wallet can say that it is connected.

## From the request to the wallet

| When | Where | The state | `Account` shows |
| --- | --- | --- | --- |
| the request arrives | server | `reconnecting`, read from the cookie | the address of the cookie |
| the page hydrates | browser | the same: `initial` came with the HTML | the same HTML |
| the wallet answers | browser | `connected`, with what the wallet says now | the address, confirmed |
| the user changed account since | browser | `connected`, with the new account first | the new address |
| the wallet is gone, or gives no account | browser | `disconnected` | `Not connected` |

- **The first render is the same on both sides.** It comes from `initial`, which the server
  read and sent. The cookie the browser reads only tells the runtime which wallet to ask.
- **`reconnect` waits for the wallet, and gives up.** A wallet announces itself a moment after
  the page loads. It is waited for two seconds, and its answer for two more: see
  [`reconnectTimeout`](https://ethect.dev/reference/connection/layer/#optionsreconnecttimeout-optional).
- **A disconnection is stored too.** After `Connection.disconnect` the cookie is `{"v":1}`,
  so the next visit does not connect the user again behind their back.
- **Nothing signs on a server.** A send or a signature fails at once with `SignerError`
  `"Disconnected"`. Reads work: they go to your node.

## Reading on the server

To render more than the address, read for it on the server. Build the layers for each request:
the runtime of `ethect.tsx` is one connection, and on a server it would be every visitor's.

```ts title="server.ts"
import { Effect, Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { Call, Connection, Transport, Wallets } from "@ethect/core";

// The layers of one request: the cookie is the state, and there is no wallet.
const Server = (cookies: string | null) =>
  Connection.layer({ initial: Connection.fromCookie(cookies) }).pipe(
    Layer.provideMerge(Wallets.of([])),
    Layer.provideMerge(Transport.http("https://ethereum-rpc.publicnode.com")),
    Layer.provide(FetchHttpClient.layer),
  );

// The account of the cookie and its balance, or nothing.
const header = Effect.gen(function* () {
  const state = yield* Connection.get;
  const account = state.status === "reconnecting" ? state.accounts[0] : undefined;
  return account && { account, balance: yield* Call.balance(account) };
});

export const load = (request: Request) =>
  header.pipe(
    Effect.provide(Server(request.headers.get("cookie"))),
    Effect.orElseSucceed(() => undefined), // the node did not answer: render without it
    Effect.runPromise,
  );
```

## Under the hood

**the server**

- **your node**: no wallet is asked: there is none. Your node is asked what you read

**the browser**

- **your program**: waits for the remembered wallet to announce itself, up to 2 s
- **the wallet** `eth_accounts`: no prompt
- **the wallet** `eth_chainId`: then: no prompt
- **your program**: then listens to `accountsChanged`, `chainChanged` and `disconnect`

**each change**

- **your program**: the cookie is written again. No request

`eth_requestAccounts`, the request that prompts, is never sent here: only a click on a wallet
sends it. See [`Connection.reconnect`](https://ethect.dev/reference/connection/connect/#reconnect),
[`Connection.toCookie`](https://ethect.dev/reference/connection/cookie/) and
[`Signer.connected`](https://ethect.dev/reference/signer/connected/#on-a-server).
