# Coming from viem

Each viem and wagmi function you know and its counterpart in ethect, for contracts, transactions, events, wallets, units and names. What works differently, and what has no counterpart yet.

This page maps what you know to its counterpart. The names of viem were checked against viem
2.58. The names of wagmi are from memory: wagmi is not installed in the repository of ethect.

## A client becomes a program and its layers

In viem a client holds the transport and the account, and an action runs when you call it.

```ts
import { createPublicClient, createWalletClient, erc20Abi, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { mainnet } from "viem/chains";

declare const key: `0x${string}`;
declare const url: string;

const account = privateKeyToAccount(key);
const reader = createPublicClient({ chain: mainnet, transport: http(url) });
const wallet = createWalletClient({ account, chain: mainnet, transport: http(url) });

const usdc = { address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", abi: erc20Abi } as const;
const to = "0x70997970C51812dc3A010C7d01b50e0d17dc79C8";

const balance = await reader.readContract({
  ...usdc,
  functionName: "balanceOf",
  args: [account.address],
});
const hash = await wallet.writeContract({
  ...usdc,
  functionName: "transfer",
  args: [to, balance / 2n],
});
const receipt = await reader.waitForTransactionReceipt({ hash });
```

In ethect a program describes the calls. What it needs is provided where it runs: a node, and
a signer when it sends.

```ts
import { Config, Effect, Layer } from "effect";
import { FetchHttpClient } from "effect/http";
import { Address, Erc20, Signer, Transport, Tx } from "@ethect/core";

// `Erc20` is built in, as `erc20Abi` is. An ABI of your own goes through `Abi.fromJson`.
const usdc = Erc20.at(Address.makeUnsafe("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"));
const TO = Address.makeUnsafe("0x70997970C51812dc3A010C7d01b50e0d17dc79C8");

const program = Effect.gen(function* () {
  const me = yield* Signer.address;
  const balance = yield* usdc.balanceOf(me);
  return yield* Tx.send(usdc.transfer(TO, balance / 2n)); // the receipt
});

const Script = Layer.unwrap(
  Effect.gen(function* () {
    const url = yield* Config.Redacted("RPC_URL");
    const key = yield* Config.Redacted("PRIVATE_KEY");
    return Layer.merge(Signer.privateKey(key), Transport.http(url));
  }),
).pipe(Layer.provide(FetchHttpClient.layer));

const receipt = await program.pipe(Effect.provide(Script), Effect.runPromise);
```

| In viem | In ethect |
| --- | --- |
| `createPublicClient`, `createWalletClient` | no client: a [`Transport`](https://ethect.dev/reference/transport/) layer, and a [`Signer`](https://ethect.dev/reference/signer/) layer to send |
| an action runs when you call it | a function returns an `Effect`: a description, run where the program ends |
| `await` | `yield*` inside `Effect.gen`, and `Effect.runPromise` at the edge |
| `{ address, abi, functionName, args }` | `Erc20.at(address).balanceOf(owner)`: a [call](https://ethect.dev/reference/call/), which is a value |
| a failure is thrown | a failure is a value with a `_tag`, in the type of the program |
| `chain: mainnet` | the chain is the one of the node. There is no list of chains |
| an address is any `` `0x${string}` ``, and sent as given | an [`Address`](https://ethect.dev/reference/primitives/address/) is checked once, lowercase, and sent in its EIP-55 form |

[Effect essentials](https://ethect.dev/guides/effect-essentials/) covers `Effect.gen`, `yield*` and layers.

## Contracts

| viem | ethect | What differs |
| --- | --- | --- |
| `parseAbi([…])` | [`Abi.parse([…])`](https://ethect.dev/reference/abi/parse/) | It gives a contract: `fn`, `ev`, `err` and `at(address)` |
| a JSON ABI `as const` | [`Abi.fromJson(abi)`](https://ethect.dev/reference/abi/from-json/) | The same object works |
| `erc20Abi` | [`Erc20`](https://ethect.dev/reference/standards/erc20/) | A contract, not an ABI: `Erc20.at(token).balanceOf(owner)`. The same items |
| `erc721Abi` | [`Erc721`](https://ethect.dev/reference/standards/erc721/) | `safeTransferFrom` with `data` is payable, and `Approval` has `approved`: both as the EIP declares them |
| `erc1155Abi` | [`Erc1155`](https://ethect.dev/reference/standards/erc1155/) | No error, where viem's has seven: [`extend`](https://ethect.dev/reference/standards/erc1155/#extend) adds those of a token. `ApprovalForAll` has `owner` |
| `erc4626Abi` | [`Erc4626`](https://ethect.dev/reference/standards/erc4626/) | The same items. `Deposit` has `owner`, as the EIP names it |
| `getContract` | [`contract.at(address)`](https://ethect.dev/reference/contract/#at) | It holds no client: it builds calls |
| `readContract` | `yield* token.balanceOf(owner)` | Reads issued together [merge into one multicall](https://ethect.dev/guides/reading/). In viem that is `batch.multicall` on the client |
| `readContract` with `blockNumber`, `account`, `stateOverride` | [`Call.read(call, { block, from, stateOverride })`](https://ethect.dev/reference/call/read/) | |
| `multicall` | [`Call.all([…])`](https://ethect.dev/reference/call/all/) | The first failure fails the whole. `mode: "result"` is viem's default, `allowFailure: true` |
| `getBalance`, `getBlockNumber` beside reads | [`Call.balance`, `Call.blockNumber`](https://ethect.dev/reference/call/state/) | Read in the same request, at the same block |
| `writeContract` | [`Tx.send(token.transfer(to, amount))`](https://ethect.dev/reference/tx/send/) | It waits for the block and gives the receipt |
| `simulateContract` | [`Tx.simulate(calls, { from })`](https://ethect.dev/reference/tx/simulate/) | Several calls, each seeing the ones before it |
| `deployContract` | [`Call.make({ data })`](https://ethect.dev/reference/call/make/) without `to`, given to `Tx.send` | |
| `encodeFunctionData` | [`Call.encode(call)`](https://ethect.dev/reference/call/encode/), [`Fn.encodeInput`](https://ethect.dev/reference/fn/encode-input/) | |
| `decodeFunctionResult` | [`Fn.decodeOutput`](https://ethect.dev/reference/fn/decode-output/) | |
| `encodeAbiParameters`, `decodeAbiParameters` | [`Abi.encode`](https://ethect.dev/reference/abi/encode/), [`Abi.decode`](https://ethect.dev/reference/abi/decode/) | The types are values: `Abi.encode([Abi.address, Abi.uint256], [to, 1n])` |
| `decodeErrorResult` | [`Err.decode(errors, data)`](https://ethect.dev/reference/err/decode/) | It never fails: unknown data is a `RevertUnknown` |
| `ContractFunctionRevertedError` | the error of the contract, [caught by its tag](https://ethect.dev/guides/errors/) | |

See [Read and write a contract](https://ethect.dev/guides/contracts/).

## Transactions

| viem | ethect | What differs |
| --- | --- | --- |
| `privateKeyToAccount(key)` | [`Signer.privateKey(key)`](https://ethect.dev/reference/signer/private-key/) | A layer. The key is a `Redacted`, never a string |
| `toAccount({ … })`, a KMS | [`Signer.fromSign`](https://ethect.dev/reference/signer/from-sign/), [`Signer.make`](https://ethect.dev/reference/signer/make/) | |
| `sendTransaction({ to, value })` | `Tx.send(Call.make({ to, value }))` | |
| `sendTransaction`, then `waitForTransactionReceipt` | [`Tx.send`](https://ethect.dev/reference/tx/send/) | One step. [`Tx.submit`](https://ethect.dev/reference/tx/submit/) is the first half alone |
| `waitForTransactionReceipt({ hash })` | [`Tx.wait(hash)`](https://ethect.dev/reference/tx/wait/) | A reverted transaction is a failure, `TxReverted`. viem gives a receipt with `status: "reverted"` |
| `getTransactionReceipt({ hash })` | [`Tx.receipt(hash)`](https://ethect.dev/reference/tx/receipt/) | An `Option`: none when it is in no block, where viem throws. A reverted transaction is `TxReverted` |
| its `timeout`, 180 seconds by default | `Effect.timeout` on the wait | Nothing times out by itself |
| `prepareTransactionRequest` | nothing to call | `Tx.submit` estimates what you did not set in [`transaction`](https://ethect.dev/reference/tx/submit/#txfields) |
| `nonceManager` | [`Signer.Nonces`](https://ethect.dev/reference/signer/nonces/) | On by default for a key |
| `signTransaction` | [`Signer.signTransaction`](https://ethect.dev/reference/signer/sign-transaction/) | |
| `signMessage`, `signTypedData` | [`Signer.signMessage`](https://ethect.dev/reference/signer/sign-message/), [`Signer.signTypedData`](https://ethect.dev/reference/signer/sign-typed-data/) | |
| `client.verifyMessage`, `client.verifyTypedData`, `client.verifyHash` | [`Signature.verifyMessage`](https://ethect.dev/reference/signature/verify-message/), [`Signature.verifyTypedData`](https://ethect.dev/reference/signature/verify-typed-data/), [`Signature.verify`](https://ethect.dev/reference/signature/verify/) | A key's signature takes no request: viem asks the node first. A node that does not answer is a failure, never `false` |
| `recoverMessageAddress`, `recoverTypedDataAddress`, `recoverAddress` | [`Signature.recoverMessage`](https://ethect.dev/reference/signature/recover-message/), [`Signature.recoverTypedData`](https://ethect.dev/reference/signature/recover-typed-data/), [`Signature.recover`](https://ethect.dev/reference/signature/recover/) | The address is lowercase. A failure is a `Signature.Error`, not a throw |
| `verifyMessage`, `verifyTypedData`, `verifyHash` imported from `viem`, with no client | `Signature.recover*`, then [`Address.equals`](https://ethect.dev/reference/primitives/address/#equals) | Right for a key only, as in viem |
| `parseSignature`, `serializeSignature` | [`Signature.fromHex`](https://ethect.dev/reference/signature/from-hex/), [`Signature.toHex`](https://ethect.dev/reference/signature/from-hex/#tohex) | `r` and `s` are `bigint`. No compact form (EIP-2098) |
| `hashMessage`, `hashTypedData` | nothing to call | `Signature` hashes what it is given. A digest of your own goes to `Signature.verify` |
| `sendCalls`, `waitForCallsStatus` | `Tx.send([a, b])` | The same line with a key, a wallet that batches, and one that does not |
| `getCapabilities` | [`Tx.plan`](https://ethect.dev/reference/tx/plan/), [`Signer.capabilities`](https://ethect.dev/reference/signer/accounts/#capabilities) | |
| `simulateCalls` | [`Tx.simulate`](https://ethect.dev/reference/tx/simulate/) | |

See [Send transactions](https://ethect.dev/guides/transactions/).

## Events

| viem | ethect | What differs |
| --- | --- | --- |
| `parseEventLogs` | [`Ev.decode(events, logs)`](https://ethect.dev/reference/ev/decode/) | One event, an array, or a record that sorts them |
| `decodeEventLog` | `Ev.decode(event, [log])` | A log that does not match is left out, and nothing throws |
| `getLogs`, `getContractEvents` | [`Ev.logs`](https://ethect.dev/reference/ev/logs/) | A range the node refuses is read in pieces |
| `watchContractEvent`, `watchEvent` | [`Ev.watch`](https://ethect.dev/reference/ev/watch/) | A `Stream`. `fromBlock` gives the past first, `confirmations` waits for depth |
| `watchBlocks`, `watchBlockNumber` | [`Block.watch`](https://ethect.dev/reference/block/) | One per transport, shared by everyone who watches |
| the `unwatch` function | stop reading the stream | |

Like viem, `Ev.watch` and `Block.watch` poll over HTTP and are pushed over a WebSocket. See
[Decode and watch events](https://ethect.dev/guides/events/).

## Wallets and connection

The wagmi names are from memory. [Let the user pick a wallet](https://ethect.dev/guides/wallet-selection/) builds
a picker with the ethect side of this table.

| viem or wagmi | ethect |
| --- | --- |
| wagmi `createConfig({ chains, transports, connectors })` | four layers, built once: a transport, or [`Transport.chains`](https://ethect.dev/reference/transport/chains/) for several chains, [`Wallets.browser`](https://ethect.dev/reference/wallets/#browser), [`Connection.layer`](https://ethect.dev/reference/connection/layer/), [`Signer.connected`](https://ethect.dev/reference/signer/connected/). [The setup](https://ethect.dev/guides/wallet-selection/#the-setup) has them in one file |
| wagmi `useConnectors`, `injected()` | [`Wallets.changes`](https://ethect.dev/reference/wallets/#changes): the wallets that announce themselves (EIP-6963) |
| wagmi `useConnect`, viem `requestAddresses` | [`Connection.connect(wallet)`](https://ethect.dev/reference/connection/connect/) |
| wagmi `useAccount`, `watchAccount` | [`Connection.changes`](https://ethect.dev/reference/connection/state/#changes), `Connection.get` |
| wagmi `useDisconnect` | [`Connection.disconnect`](https://ethect.dev/reference/connection/connect/#disconnect) |
| wagmi `reconnect` | [`Connection.reconnect`](https://ethect.dev/reference/connection/connect/#reconnect) |
| wagmi `useSwitchChain`, viem `switchChain`, `addChain` | [`Connection.switchChain(chain)`](https://ethect.dev/reference/connection/switch-chain/) |
| wagmi `cookieStorage`, `cookieToInitialState` | [`Connection.toCookie(state)`](https://ethect.dev/reference/connection/cookie/) writes the cookie, and [`Connection.fromCookie(cookies)`](https://ethect.dev/reference/connection/cookie/#fromcookie) reads it for `Connection.layer({ initial })`: see [Render on the server](https://ethect.dev/guides/ssr/) |
| viem `getAddresses` | [`Signer.accounts`](https://ethect.dev/reference/signer/accounts/) |
| viem `custom(window.ethereum)` | [`Signer.wallet(provider)`](https://ethect.dev/reference/signer/wallet/) to sign, [`Transport.eip1193(provider)`](https://ethect.dev/reference/transport/eip1193/) to read through it: see [Talk to a wallet directly](https://ethect.dev/guides/wallets/) |
| wagmi `useWriteContract`, `useWaitForTransactionReceipt`, `useSendCalls` | `Tx.plan`, `Tx.submit` and `Tx.wait` behind one button: see [A button with steps](https://ethect.dev/guides/transaction-button/) |
| wagmi `useReadContract` and the other hooks | none: there is no React package. [A stream becomes state in a few lines](https://ethect.dev/guides/wallet-selection/#the-setup) |

## Units, names and values

| viem | ethect |
| --- | --- |
| `formatUnits(1500000n, 6)`, `formatEther` | `BigDecimal.format(BigDecimal.make(1_500_000n, 6))`, from `effect` |
| `parseUnits("1.5", 6)`, `parseEther` | `BigDecimal.scale(amount, 6).value`, after `BigDecimal.fromString("1.5")` |
| `getEnsAddress`, `getEnsName` | [`Ens.address`](https://ethect.dev/reference/ens/address/), [`Ens.name`](https://ethect.dev/reference/ens/name/), from `@ethect/core/ens` |
| `getEnsAvatar`, `getEnsText` | [`Ens.avatar`](https://ethect.dev/reference/ens/avatar/), [`Ens.text`](https://ethect.dev/reference/ens/text/) |
| `getAddress(text)`, which throws on what is no address | [`Address.makeUnsafe(text)`](https://ethect.dev/reference/primitives/address/#makeunsafe) for an address in your source: it throws too, when the file loads. [`Address.make(text)`](https://ethect.dev/reference/primitives/address/#make) for one you were given: a failure, and no throw. Both give the lowercase form, and refuse a wrong checksum, which `getAddress` corrects. [`Address.checksum`](https://ethect.dev/reference/primitives/address/#checksum) gives the EIP-55 form |
| `isAddress(text)` | [`Address.isAddress`](https://ethect.dev/reference/primitives/address/#isaddress). A mixed-case address with a wrong checksum is `false` in both |
| `keccak256` | [`Hash.keccak256`](https://ethect.dev/reference/primitives/hash/#keccak256) |

- **There are no unit helpers.** [Amounts and decimals](https://ethect.dev/guides/amounts/) shows both
  directions, and two traps.
- **A name with no address is not an error.** The four lookups of `Ens` give an `Option`.
- **The values are those of viem.** Wei, gas and block numbers are `bigint`. Chain ids and
  nonces are `number`. A receipt has `status: "success"`, a transaction `type: "eip1559"`.
- **An ethect address is accepted wherever viem wants a `` `0x${string}` ``.** The other way,
  pass a viem address through `Address.make`.

## Errors

viem throws, and you find the cause by walking the error.

```ts
import { BaseError, ContractFunctionRevertedError } from "viem";

const describe = (error: unknown) => {
  if (!(error instanceof BaseError)) return "unknown";
  const revert = error.walk((cause) => cause instanceof ContractFunctionRevertedError);
  if (revert instanceof ContractFunctionRevertedError) return revert.data?.errorName;
  return error.shortMessage;
};
```

ethect fails with a value, and you match its tag. The compiler knows which tags are possible.

```ts
import { Effect } from "effect";
import { Abi, Erc721, type Address } from "@ethect/core";

// The standard declares no error. This adds the one the collection reverts with.
const Nft = Erc721.extend(Abi.parse(["error ERC721NonexistentToken(uint256 tokenId)"]));

const owner = (nft: Address.Address, tokenId: bigint) =>
  Nft.at(nft)
    .ownerOf(tokenId)
    .pipe(
      Effect.catchTag("ERC721NonexistentToken", (error) =>
        Effect.succeed(`no token ${error.tokenId}`),
      ),
      Effect.catchTag("TransportError", () => Effect.succeed("no answer from the node")),
      Effect.catch((error) => Effect.succeed(error.message)),
    );
```

| viem | ethect |
| --- | --- |
| `ContractFunctionRevertedError`, with `data.errorName` | the error itself, with its fields. `TxReverted` with a `reason` in a send |
| `UserRejectedRequestError` | [`SignerRejected`](https://ethect.dev/reference/signer/) |
| `RpcRequestError`, and a class per code | [`RpcError`](https://ethect.dev/reference/errors/rpc-error/), with a `reason` per code |
| `HttpRequestError`, `SocketClosedError`, `TimeoutError` | [`TransportError`](https://ethect.dev/reference/errors/transport-error/), with a `reason` |
| `BlockNotFoundError`, `TransactionNotFoundError` | not an error: `null` |

[Errors](https://ethect.dev/guides/errors/) has every failure of the library in one table.

## Transports

| viem | ethect | What differs |
| --- | --- | --- |
| `http(url, { batch })` | [`Transport.http(url, { batch })`](https://ethect.dev/reference/transport/http/) | No timeout and no retry by default. viem times out after 10 seconds and retries |
| `webSocket(url)` | [`Transport.webSocket(url)`](https://ethect.dev/reference/transport/web-socket/) | It reconnects forever by default |
| `ipc(path)` | [`Transport.ipc()`](https://ethect.dev/reference/transport/ipc/) | The path goes to the `Socket` layer |
| `custom(provider)` | [`Transport.eip1193(provider)`](https://ethect.dev/reference/transport/eip1193/) | |
| a client per chain | [`Transport.chains({ 1: …, 8453: … })`](https://ethect.dev/reference/transport/chains/) | A part of the program says its chain with `Transport.on(8453)` |
| `fallback([…])` | none | [Write the wrapper](https://ethect.dev/guides/custom-transports/#fall-back-to-a-second-endpoint) |

## Plain JSON-RPC

An action of viem that is one request has a method in the [JSON-RPC layer](https://ethect.dev/rpc/), imported
from `@ethect/core/rpc`. A method takes the params of the request in order, and sends exactly
that request.

| viem action | ethect method |
| --- | --- |
| `getChainId`, `getBlockNumber` | [`Eth.chainId`](https://ethect.dev/rpc/eth/chain-id/), [`Eth.blockNumber`](https://ethect.dev/rpc/eth/block-number/) |
| `getBlock` | [`Eth.getBlockByNumber`](https://ethect.dev/rpc/eth/get-block-by-number/), [`Eth.getBlockByHash`](https://ethect.dev/rpc/eth/get-block-by-hash/) |
| `getBalance`, `getTransactionCount`, `getCode` | [`Eth.getBalance`](https://ethect.dev/rpc/eth/get-balance/), [`Eth.getTransactionCount`](https://ethect.dev/rpc/eth/get-transaction-count/), [`Eth.getCode`](https://ethect.dev/rpc/eth/get-code/) |
| `getStorageAt`, `getProof` | [`Eth.getStorageAt`](https://ethect.dev/rpc/eth/get-storage-at/), [`Eth.getProof`](https://ethect.dev/rpc/eth/get-proof/) |
| `getTransaction`, `getTransactionReceipt` | [`Eth.getTransactionByHash`](https://ethect.dev/rpc/eth/get-transaction-by-hash/), [`Eth.getTransactionReceipt`](https://ethect.dev/rpc/eth/get-transaction-receipt/) |
| `call`, `estimateGas`, `createAccessList` | [`Eth.call`](https://ethect.dev/rpc/eth/call/), [`Eth.estimateGas`](https://ethect.dev/rpc/eth/estimate-gas/), [`Eth.createAccessList`](https://ethect.dev/rpc/eth/create-access-list/) |
| `simulateBlocks` | [`Eth.simulateV1`](https://ethect.dev/rpc/eth/simulate-v1/) |
| `getGasPrice`, `getFeeHistory` | [`Eth.gasPrice`](https://ethect.dev/rpc/eth/fees/#gasprice), [`Eth.feeHistory`](https://ethect.dev/rpc/eth/fee-history/) |
| `getLogs`, `createEventFilter`, `getFilterChanges` | [`Eth.getLogs`](https://ethect.dev/rpc/eth/get-logs/), the [filter methods](https://ethect.dev/rpc/eth/filters/) |
| `sendRawTransaction` | [`Eth.sendRawTransaction`](https://ethect.dev/rpc/eth/send-raw-transaction/) |
| `watchPendingTransactions` | [`Eth.subscribe.newPendingTransactions`](https://ethect.dev/rpc/eth/subscribe/new-pending-transactions/) |
| `watchAsset`, `getPermissions`, `requestPermissions` | [`Wallet.watchAsset`](https://ethect.dev/rpc/wallet/watch-asset/), the [permission methods](https://ethect.dev/rpc/wallet/permissions/) |
| the test actions: `setBalance`, `mine`, `impersonateAccount`, `snapshot`… | the [`Anvil`](https://ethect.dev/rpc/anvil/) namespace |

- **Not found is `null`.** viem throws `BlockNotFoundError` or `TransactionNotFoundError`.
- **No prepared defaults.** `Eth.estimateGas` sends what you give it, and fills nothing in.
- **To start a node for a test**, see [`AnvilNode`](https://ethect.dev/guides/testing/).

## What has no counterpart yet

| viem or wagmi | Status in ethect |
| --- | --- |
| `fallback`, and the retries of a transport | none: `Effect.retry` on a call, or [a wrapper you write](https://ethect.dev/guides/custom-transports/) |
| `viem/chains` | none: a [`Chain`](https://ethect.dev/reference/chain/) is data you write, and you give the URL |
| `mnemonicToAccount`, HD accounts | none: [`Signer.privateKey`](https://ethect.dev/reference/signer/private-key/) takes one key |
| blob and EIP-7702 transactions signed with a key | none: `TxUnsupported`, with the reason `"signing"` |
| SIWE | none: [`Signature.verifyMessage`](https://ethect.dev/reference/signature/verify-message/) checks the signature, and the message is yours to write and to read |
| account abstraction, OP Stack and ZKsync extensions | none |
| wagmi's hooks, and its connectors for WalletConnect and others | none: [`Wallets.of`](https://ethect.dev/reference/wallets/#of) takes a provider you built |

## Next steps

- [Quick start](https://ethect.dev/getting-started/quick-start/): a first program.
- [Read and write a contract](https://ethect.dev/guides/contracts/): the first guide.
- [Effect essentials](https://ethect.dev/guides/effect-essentials/): the ideas behind `yield*` and `provide`.
- [How it works](https://ethect.dev/concepts/how-it-works/): the two services, and who is asked what.
