# Talk to a wallet directly

The low-level way to a wallet. One EIP-1193 provider as a transport, and each wallet method as a typed function, for what Connection and Tx do not cover.

Most apps do not need this page. To list the installed wallets, connect to one and send
through it, read [Let the user pick a wallet](https://ethect.dev/guides/wallet-selection/): `Connection` and `Tx`
do what follows for you, and keep a state. This page is the layer underneath: one provider
you already hold, and each wallet method as a function.

```ts title="sign-in.ts"
import { Effect } from "effect";
import { type Eip1193, Hex, Transport } from "@ethect/core";
import { Eth, Wallet } from "@ethect/core/rpc";

// The wallet's EIP-1193 provider: `window.ethereum`, or the one a wallet SDK returns.
declare const provider: Eip1193.Provider;

const optimism = {
  chainId: 10,
  chainName: "OP Mainnet",
  nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
  rpcUrls: ["https://mainnet.optimism.io"],
};

const signIn = Effect.gen(function* () {
  const [account] = yield* Wallet.requestAccounts(); // the wallet prompts
  if (account === undefined) return undefined;
  if ((yield* Eth.chainId()) !== optimism.chainId) {
    yield* Wallet.switchEthereumChain({ chainId: optimism.chainId }).pipe(
      // the wallet does not know the chain: offer it, then switch
      Effect.catchReason("RpcError", "UnrecognizedChain", () =>
        Effect.andThen(
          Wallet.addEthereumChain(optimism),
          Wallet.switchEthereumChain({ chainId: optimism.chainId }),
        ),
      ),
    );
  }
  // the message as bytes, then the account
  const signature = yield* Wallet.personalSign(Hex.fromUtf8("Sign in to Example"), account);
  return { account, signature };
}).pipe(
  // the user closed a prompt: that is an answer, not a failure of the program
  Effect.catchReason("RpcError", "UserRejectedRequest", () => Effect.succeed(undefined)),
  Effect.provide(Transport.eip1193(provider)),
);
```

[`Transport.eip1193`](https://ethect.dev/reference/transport/eip1193/) turns the provider into a transport, and
every function of [`Wallet`](https://ethect.dev/rpc/wallet/) and [`Eth`](https://ethect.dev/rpc/eth/) then goes to the wallet.
Nothing is kept between two calls: no state, no listener, no account.

## Getting the provider

An injected wallet is at `window.ethereum`. TypeScript's DOM types do not declare it, so
declare it once in your project.

```ts title="provider.ts"
import type { Eip1193 } from "@ethect/core";

declare global {
  interface Window {
    ethereum?: Eip1193.Provider;
  }
}

/** The injected provider, or `undefined` when no wallet is installed. */
export const injected = (): Eip1193.Provider | undefined => window.ethereum;
```

Any object with `request`, `on` and `removeListener` is a
[provider](https://ethect.dev/reference/eip1193/#provider): the one a wallet SDK returns works the same way.
Several installed wallets compete for that one name. To list them all, each with its own
provider, use [`Wallets`](https://ethect.dev/reference/wallets/).

## What the layers above do for you

Each line of `sign-in.ts` has a function above it that does more. Use this page for the last
row, and when you hold one provider and want no state.

| You want | Here, one request | Above |
| --- | --- | --- |
| to connect | [`Wallet.requestAccounts()`](https://ethect.dev/rpc/wallet/request-accounts/) | [`Connection.connect(wallet)`](https://ethect.dev/reference/connection/connect/), which keeps a state and listens to the wallet |
| the accounts, without a prompt | [`Eth.accounts()`](https://ethect.dev/rpc/eth/accounts/) | [`Connection.get`](https://ethect.dev/reference/connection/state/#get), with no request |
| another chain | [`Wallet.switchEthereumChain`](https://ethect.dev/rpc/wallet/switch-ethereum-chain/), then [`addEthereumChain`](https://ethect.dev/rpc/wallet/add-ethereum-chain/) on `UnrecognizedChain` | [`Connection.switchChain(chain)`](https://ethect.dev/reference/connection/switch-chain/), which does both and checks the result |
| to send | [`Eth.sendTransaction`](https://ethect.dev/rpc/eth/send-transaction/): a hash, as soon as the wallet sent it | [`Tx.send`](https://ethect.dev/reference/tx/send/): the receipt, once it is in a block |
| several calls in one prompt | [`Wallet.sendCalls`](https://ethect.dev/rpc/wallet/send-calls/), then [`getCallsStatus`](https://ethect.dev/rpc/wallet/calls-status/#getcallsstatus) until it is included | `Tx.send([a, b])`, on any wallet |
| a signature | [`Wallet.personalSign`](https://ethect.dev/rpc/wallet/personal-sign/), [`Eth.signTypedDataV4`](https://ethect.dev/rpc/eth/sign-typed-data-v4/) | [`Signer.signMessage`](https://ethect.dev/reference/signer/sign-message/), [`Signer.signTypedData`](https://ethect.dev/reference/signer/sign-typed-data/) |
| to follow the user | the streams of [`Eip1193`](https://ethect.dev/reference/eip1193/) | [`Connection.changes`](https://ethect.dev/reference/connection/state/#changes) |
| a token in the wallet's list, permissions, the wallet's assets | [`Wallet.watchAsset`](https://ethect.dev/rpc/wallet/watch-asset/), [`getPermissions`](https://ethect.dev/rpc/wallet/permissions/), [`getAssets`](https://ethect.dev/rpc/wallet/get-assets/) | nothing: only here |

The two layers work on the same wallet. An app that connects with `Connection` asks for the
provider of the connected wallet, and uses it for the last row.

```ts
import { Effect } from "effect";
import { type Address, Connection, Transport } from "@ethect/core";
import { Wallet } from "@ethect/core/rpc";

const watch = (address: Address.Address) =>
  Effect.gen(function* () {
    const { provider } = yield* Connection.session;
    const asset = { type: "ERC20", options: { address, symbol: "USDC", decimals: 6 } } as const;
    return yield* Wallet.watchAsset(asset).pipe(Effect.provide(Transport.eip1193(provider)));
  });
```

## Following the wallet

The user changes account or chain in the wallet at any time. The provider's events are
streams, and each one registers its listener when it starts to run.

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

// The wallet's EIP-1193 provider: `window.ethereum`, or the one a wallet SDK returns.
declare const provider: Eip1193.Provider;

const followWallet = Stream.merge(
  Stream.map(Eip1193.accountsChanged(provider), ([account]) => ({ account })),
  Stream.map(Eip1193.chainChanged(provider), (chainId) => ({ chainId })),
).pipe(Stream.runForEach((change) => Effect.log(change)));
```

| Stream | Emits | When |
| --- | --- | --- |
| `Eip1193.accountsChanged(provider)` | the accounts, an empty list when none | the user switches account, locks the wallet or removes the app |
| `Eip1193.chainChanged(provider)` | the chain id, a `number` | the wallet changes chain |
| `Eip1193.connect(provider)` | the chain id | the provider becomes able to reach a chain |
| `Eip1193.disconnect(provider)` | an `RpcError` | the provider loses every chain |

The streams emit changes only. Read the starting state with `Eth.accounts` and `Eth.chainId`.

## What a wallet refuses

A wallet answers with an error code, which is the `reason` of an
[`RpcError`](https://ethect.dev/reference/errors/rpc-error/). `Effect.catchReason` handles one and lets the
others through.

| Reason | Code | Means |
| --- | --- | --- |
| `UserRejectedRequest` | `4001` | the user closed or refused the prompt |
| `Unauthorized` | `4100` | the app is not connected, or not allowed the method or the account |
| `UnsupportedMethod` | `4200` | the wallet does not serve the method |
| `Disconnected` | `4900` | the wallet reaches no chain |
| `ChainDisconnected` | `4901` | the wallet does not reach the requested chain |
| `UnrecognizedChain` | `4902` | the wallet does not know the chain |
| `MethodNotFound` | `-32601` | the wallet, or the node behind it, does not know the method |

A wallet forwards most `Eth` calls to its node, so the node's own errors reach you too. To
test a refusal without a browser, see [`TestWallet`](https://ethect.dev/reference/testing/test-wallet/).

## Seeing what a wallet answers

Wallets do not all answer as their standard writes it. ethect reads what a wallet means
whenever it is unambiguous, and an answer it cannot read fails with a
[`CodecError`](https://ethect.dev/reference/errors/codec-error/) whose `value` is the answer as it came.

A wallet's requests never show in the Network tab of a browser. Each one is logged at the
Debug level, with its params and the raw answer:

```ts
import { Effect, References } from "effect";
import { type Eip1193, Transport } from "@ethect/core";
import { Wallet } from "@ethect/core/rpc";

// The wallet's EIP-1193 provider: `window.ethereum`, or the one a wallet SDK returns.
declare const provider: Eip1193.Provider;

const accounts = Wallet.requestAccounts().pipe(
  Effect.provide(Transport.eip1193(provider)),
  // message=eth_requestAccounts ms=840 params=[] answer=["0x…"]
  Effect.provideService(References.MinimumLogLevel, "Debug"),
);
```

See [`Transport.eip1193`](https://ethect.dev/reference/transport/eip1193/#seeing-what-the-wallet-answers) for
every annotation.

## Under the hood

One function is one request to the provider, and nothing else.

- **the wallet** `request({ method: "eth_requestAccounts" })`: `Wallet.requestAccounts()`
- **the wallet** `request({ method: "wallet_switchEthereumChain", params: [{ chainId: "0xa" }] })`: `Wallet.switchEthereumChain(…)`
- **the wallet** `request({ method: "personal_sign", params: [bytes, account] })`: `Wallet.personalSign(…)`
- **the wallet** `on(event, listener)`: a stream of `Eip1193`, and `removeListener` when it ends

Chain ids are numbers in your code and hex on the wire. Accounts are lowercase in your code,
and sent in their EIP-55 form: Ambire looks an account up by its checksum, and answers that
one in lowercase does not exist. The accounts a wallet answers are read in any case. Your node
is never asked: a program
that also reads from a node gives that transport to its reads, as
[`Signer.wallet`](https://ethect.dev/reference/signer/wallet/) does.
