# Let the user pick a wallet

A wallet picker in React: the list of installed wallets, a click that connects, and a state
that follows the wallet. There is no React package: the hooks the picker uses are in
[one file](#the-setup), which you copy into your app. If you come from wagmi,
[this table](https://ethect.dev/getting-started/coming-from-viem/#wallets-and-connection) names each piece.

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

export function WalletPicker() {
  const wallets = useWallets(); // fills in as wallets announce themselves
  const connection = useConnection({ status: "disconnected" }); // follows the wallet

  if (connection.status === "connected") {
    return (
      <p>
        {Address.checksum(connection.accounts[0])} on chain {connection.chainId}{" "}
        <button onClick={() => void run(Connection.disconnect)}>Disconnect</button>
      </p>
    );
  }
  return (
    <ul>
      {wallets.map((wallet) => (
        <li key={wallet.id}>
          <button onClick={() => void run(Connection.connect(wallet))}>
            {wallet.icon && <img src={wallet.icon} alt="" width={20} height={20} />}
            {wallet.name}
            {connection.status === "connecting" && connection.wallet === wallet.id && "…"}
          </button>
        </li>
      ))}
    </ul>
  );
}
```
```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";

// The app, read from the bottom up.
const App = Signer.connected().pipe( // 4. signs with the connected wallet
  Layer.provideMerge(Connection.layer()), // 3. which wallet is connected
  Layer.provideMerge(Wallets.browser), // 2. which wallets are installed
  Layer.provideMerge(Transport.http("https://ethereum-rpc.publicnode.com")), // 1. the node it reads from
  Layer.provide(FetchHttpClient.layer), // how HTTP requests are made
);
type Services = Layer.Success<typeof App>;

// Built once, for the life of the page: the connection is the one of this runtime.
export const runtime = ManagedRuntime.make(App);

// Runs an effect from an event handler. A failure is in the Exit: nothing is thrown.
export const run = <A, E>(effect: Effect.Effect<A, E, Services>) => runtime.runPromiseExit(effect);

// The latest value of a stream, as React state.
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)); // stop when the component goes
  }, [stream]);
  return value;
}

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

## The setup

Three pieces, one after the other. The picker reads the first two and never names the third.

Three layers, each over the one before. Wallets is the list of what is installed. Connection is the one wallet the user clicked, with its accounts and its chain. Signer.connected sends every signature to that wallet.

Each piece is a layer, built once. A runtime holds them and runs what the components ask for.

`ethect.tsx`, the second tab above, is the whole of it. If you have never seen Effect, three
words are enough here:

| Word | Is | In this file |
| --- | --- | --- |
| effect | a description of work. Nothing happens until it is run | `Connection.connect(wallet)`, run by `run` |
| stream | values over time | `Wallets.changes` and `Connection.changes`, read by `useStream` |
| layer | a part of the app, built once and shared | the numbered lines of `App` |

## Listing wallets

`useWallets()` is a list of [`Wallets.Wallet`](https://ethect.dev/reference/wallets/#wallet): an `id` that is
the same on every visit, a `name`, an `icon` to use as the `src` of an image, and a `provider`
that nothing asks for until the user clicks.

- **Each installed wallet announces itself** to the page
  ([EIP-6963](https://eips.ethereum.org/EIPS/eip-6963)), so several are listed side by side.
- **The list starts empty and grows.** Installed wallets answer at once, and one that loads
  later is added when it does. A component that mounts late gets the whole list.
- **Listing asks the wallets nothing.** No request, no prompt, no permission.

## Connecting

A click runs `Connection.connect(wallet)`: that wallet opens its prompt, and no other wallet
is asked anything. The state says how it went, so the picker stores nothing.

| The user | The state becomes | `run` resolves with |
| --- | --- | --- |
| clicks a wallet | `connecting`, with the `id` of that wallet | nothing yet |
| approves | `connected`, with the accounts and the chain | a success: that state |
| refuses | what it was before the click | a failure: `SignerRejected` |
| clicks another wallet meanwhile | `connecting`, with the new wallet | an interruption, for the first click |

`run` never throws, and its promise never rejects: it resolves with an `Exit`, a success or a
failure. To show a refusal, turn each outcome into a sentence before you run it.

```tsx title="connect.tsx"
import { Effect, Exit } from "effect";
import { Address, Connection, type Wallets } from "@ethect/core";
import { run } from "./ethect";

const connect = (wallet: Wallets.Wallet) =>
  Connection.connect(wallet).pipe(
    Effect.map((state) => `Connected as ${Address.checksum(state.accounts[0])}`),
    Effect.catchTag("SignerRejected", () => Effect.succeed("You refused the connection")),
    Effect.catch((error) => Effect.succeed(error.message)), // every failure has a message
  );

// `show` is the `setState` of a line under the picker.
export const onPick = (wallet: Wallets.Wallet, show: (text: string) => void) =>
  run(connect(wallet)).then((exit) => {
    if (Exit.isSuccess(exit)) show(exit.value); // not a success: another click took over
  });
```

> **Caution: Run a click with `run`, not with `runtime.runPromise`**
>
> A second click interrupts the first `connect`. With `runPromise`, the promise of the first
> click rejects and nothing catches it. With `run` it resolves, with an `Exit` that says so.

## Staying in step

The user changes account or chain in the wallet, not in your page. The wallet tells the page,
the state changes, and every component that calls `useConnection` renders again.

| In the wallet, the user | The state becomes |
| --- | --- |
| picks another account | `connected`, with that account first in `accounts` |
| picks another chain | `connected`, with the new `chainId` |
| removes your site | `disconnected` |

- **`connection.accounts[0]` is the account to show.** A `connected` state always has one.
  It is lowercase, as every `Address` in memory: show
  [`Address.checksum`](https://ethect.dev/reference/primitives/address/#checksum) of it, its EIP-55 form.
- **`chainId` is where the wallet is.** Your reads still go to your node. A button brings
  the wallet back: [`Connection.switchChain(1)`](https://ethect.dev/reference/connection/switch-chain/).
- **A reload forgets the connection.** [A cookie keeps it](https://ethect.dev/guides/ssr/#the-setup), server or not.
- **Signing names no wallet.** `run(Tx.send(call))` goes to the connected one: see
  [A button with steps](https://ethect.dev/guides/transaction-button/).

## Under the hood

- **your program**: the page loads: listens to `"eip6963:announceProvider"`, dispatches `"eip6963:requestProvider"`
- **the wallet** `eth_requestAccounts`: a click on a wallet: the prompt, to that wallet alone
- **the wallet** `eth_chainId`: then
- **your program**: then listens to `accountsChanged`, `chainChanged` and `disconnect` on it
- **your program**: a change in a wallet: no request, the event carries the accounts or the chain
- **your program**: Disconnect: no request, the listeners are removed, and the wallet keeps its permission

Your node is never asked. See [`Wallets`](https://ethect.dev/reference/wallets/#under-the-hood),
[`Connection.connect`](https://ethect.dev/reference/connection/connect/#under-the-hood) and
[`Connection.State`](https://ethect.dev/reference/connection/state/#under-the-hood).

> **Note: The same without React**
>
> The hooks are two streams and one effect. Any framework can run them.
>
> ```ts
> import { Effect, Stream } from "effect";
> import { Connection, Wallets } from "@ethect/core";
>
> const list = (show: (wallets: ReadonlyArray<Wallets.Wallet>) => void) =>
>   Wallets.changes.pipe(Stream.runForEach((wallets) => Effect.sync(() => show(wallets))));
> const state = (render: (state: Connection.State) => void) =>
>   Connection.changes.pipe(Stream.runForEach((next) => Effect.sync(() => render(next))));
> const click = (wallet: Wallets.Wallet) => Connection.connect(wallet);
> ```
