Skip to content

Coming from viem

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.

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

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.

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 layer, and a 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, 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 is checked once, lowercase, and sent in its EIP-55 form

Effect essentials covers Effect.gen, yield* and layers.

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

See Read and write a contract.

viem ethect What differs
privateKeyToAccount(key) Signer.privateKey(key) A layer. The key is a Redacted, never a string
toAccount({ … }), a KMS Signer.fromSign, Signer.make
sendTransaction({ to, value }) Tx.send(Call.make({ to, value }))
sendTransaction, then waitForTransactionReceipt Tx.send One step. Tx.submit is the first half alone
waitForTransactionReceipt({ hash }) Tx.wait(hash) A reverted transaction is a failure, TxReverted. viem gives a receipt with status: "reverted"
getTransactionReceipt({ hash }) Tx.receipt(hash) 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
nonceManager Signer.Nonces On by default for a key
signTransaction Signer.signTransaction
signMessage, signTypedData Signer.signMessage, Signer.signTypedData
client.verifyMessage, client.verifyTypedData, client.verifyHash Signature.verifyMessage, Signature.verifyTypedData, 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, Signature.recoverTypedData, 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 Right for a key only, as in viem
parseSignature, serializeSignature Signature.fromHex, Signature.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, Signer.capabilities
simulateCalls Tx.simulate

See Send transactions.

viem ethect What differs
parseEventLogs Ev.decode(events, logs) 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 A range the node refuses is read in pieces
watchContractEvent, watchEvent Ev.watch A Stream. fromBlock gives the past first, confirmations waits for depth
watchBlocks, watchBlockNumber Block.watch 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.

The wagmi names are from memory. Let the user pick a wallet 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 for several chains, Wallets.browser, Connection.layer, Signer.connected. The setup has them in one file
wagmi useConnectors, injected() Wallets.changes: the wallets that announce themselves (EIP-6963)
wagmi useConnect, viem requestAddresses Connection.connect(wallet)
wagmi useAccount, watchAccount Connection.changes, Connection.get
wagmi useDisconnect Connection.disconnect
wagmi reconnect Connection.reconnect
wagmi useSwitchChain, viem switchChain, addChain Connection.switchChain(chain)
wagmi cookieStorage, cookieToInitialState Connection.toCookie(state) writes the cookie, and Connection.fromCookie(cookies) reads it for Connection.layer({ initial }): see Render on the server
viem getAddresses Signer.accounts
viem custom(window.ethereum) Signer.wallet(provider) to sign, Transport.eip1193(provider) to read through it: see Talk to a wallet directly
wagmi useWriteContract, useWaitForTransactionReceipt, useSendCalls Tx.plan, Tx.submit and Tx.wait behind one button: see A button with steps
wagmi useReadContract and the other hooks none: there is no React package. A stream becomes state in a few lines
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, Ens.name, from @ethect/core/ens
getEnsAvatar, getEnsText Ens.avatar, Ens.text
getAddress(text), which throws on what is no address Address.makeUnsafe(text) for an address in your source: it throws too, when the file loads. Address.make(text) 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 gives the EIP-55 form
isAddress(text) Address.isAddress. A mixed-case address with a wrong checksum is false in both
keccak256 Hash.keccak256
  • There are no unit helpers. Amounts and decimals 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.

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

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.

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 Rejected
RpcRequestError, and a class per code RpcError, with a reason per code
HttpRequestError, SocketClosedError, TimeoutError TransportError, with a reason
BlockNotFoundError, TransactionNotFoundError not an error: null

Errors has every failure of the library in one table.

viem ethect What differs
http(url, { batch }) Transport.http(url, { batch }) No timeout and no retry by default. viem times out after 10 seconds and retries
webSocket(url) Transport.webSocket(url) It reconnects forever by default
ipc(path) Transport.ipc() The path goes to the Socket layer
custom(provider) Transport.eip1193(provider)
a client per chain Transport.chains({ 1: …, 8453: … }) A part of the program says its chain with Transport.on(8453)
fallback([…]) none Write the wrapper

An action of viem that is one request has a method in the JSON-RPC layer, 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, Eth.blockNumber
getBlock Eth.getBlockByNumber, Eth.getBlockByHash
getBalance, getTransactionCount, getCode Eth.getBalance, Eth.getTransactionCount, Eth.getCode
getStorageAt, getProof Eth.getStorageAt, Eth.getProof
getTransaction, getTransactionReceipt Eth.getTransactionByHash, Eth.getTransactionReceipt
call, estimateGas, createAccessList Eth.call, Eth.estimateGas, Eth.createAccessList
simulateBlocks Eth.simulateV1
getGasPrice, getFeeHistory Eth.gasPrice, Eth.feeHistory
getLogs, createEventFilter, getFilterChanges Eth.getLogs, the filter methods
sendRawTransaction Eth.sendRawTransaction
watchPendingTransactions Eth.subscribe.newPendingTransactions
watchAsset, getPermissions, requestPermissions Wallet.watchAsset, the permission methods
the test actions: setBalance, mine, impersonateAccount, snapshot… the 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.
viem or wagmi Status in ethect
fallback, and the retries of a transport none: Effect.retry on a call, or a wrapper you write
viem/chains none: a Chain is data you write, and you give the URL
mnemonicToAccount, HD accounts none: Signer.privateKey takes one key
blob and EIP-7702 transactions signed with a key none: TxUnsupported, with the reason "signing"
SIWE none: Signature.verifyMessage 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 takes a provider you built