Send transactions
Send one transaction or several, and wait for them. The example is a script that approves a token, then deposits it in a vault.
import { Config, Effect, Layer } from "effect";import { FetchHttpClient } from "effect/http";import { Abi, Erc20, Erc4626, Signer, Transport, Tx, type Address } from "@ethect/core";
// The standard, and the error this vault reverts with.const Vault = Erc4626.extend( Abi.parse(["error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max)"]),);
export const deposit = (usdc: Address.Address, vault: Address.Address, amount: bigint) => Effect.gen(function* () { const me = yield* Signer.address; // Two calls. Each is signed, sent, and waited for until it is in a block. const receipts = yield* Tx.send([ Erc20.at(usdc).approve(vault, amount), Vault.at(vault).deposit(amount, me), ]); return receipts.map((receipt) => receipt.transactionHash); });
// A key and a node, both read from the environment as secrets.export 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));import { Effect } from "effect";import { Address } from "@ethect/core";import { deposit, Script } from "./deposit";
const USDC = Address.makeUnsafe("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48");const VAULT = Address.makeUnsafe("0xBEEF01735c132Ada46AA9aA4c54623cAA92A64CB");
// 100 USDCconst program = deposit(USDC, VAULT, 100_000_000n);
const hashes = await program.pipe(Effect.provide(Script), Effect.runPromise);Erc20.at(usdc).approve(vault, amount) builds a call, which is plain data.
Tx.send is what sends. It needs two things, both given by Script: a
Signer that signs, and a Transport that
reaches a node. The key and the URL are read as Redacted values, so neither can end up in a
log or in an error. Effect.gen and yield* are the async and await of
Effect.
What comes back
Section titled “What comes back”Tx.send(call) gives one receipt. Tx.send([a, b]) gives a list of
receipts, in the order of the calls.
- A receipt is always a success. A transaction that reverts is a failure, not a receipt with a bad status.
- By default the send returns when each transaction is in a block. Ask for more with
{ confirmations: 3 }or{ confirmations: "finalized" }. - Several calls are not always several transactions. It depends on who signs, and your code does not change:
| The signer | The calls go | You get |
|---|---|---|
| a key, as here | as two transactions with nonces in a row | one receipt per call |
| a wallet that batches | as one batch, all or nothing, in one prompt | one receipt for all |
| a wallet that does not | one prompt per call, each mined before the next | one receipt per call |
With a key the two transactions are sent together, and they are not atomic: the approval can be mined and the deposit fail.
When it fails
Section titled “When it fails”Nothing throws. Every failure is a value with a _tag to match on and a message to show.
import { Effect } from "effect";import type { Address } from "@ethect/core";import { deposit } from "./deposit";
const outcome = (usdc: Address.Address, vault: Address.Address, amount: bigint) => deposit(usdc, vault, amount).pipe( Effect.map((hashes) => `Deposited in ${hashes.length} transactions`), // The user said no in the wallet. Nothing was sent. Effect.catchTag("SignerRejected", () => Effect.succeed("You refused to sign")), // The vault reverted with its own error: typed, with its fields. Effect.catchReason("TxReverted", "ERC4626ExceededMaxDeposit", (reason) => Effect.succeed(`The vault takes ${reason.max} more`), ), // Whatever is left: every failure has a message. Effect.catch((error) => Effect.succeed(error.message)), );| Failure | What happened | What to do |
|---|---|---|
SignerRejected |
The user refused in the wallet. Nothing was sent | Nothing. Let them click again |
TxReverted |
A call reverted. With a key it is found before anything is sent | Catch its reason, or read error.reason: the error of the contract, typed. error.call says which call |
TxDropped |
The transaction left the mempool, or another one took its nonce | Look at error.replacedBy, then send again if nothing took its place |
TxUnsupported |
The signer cannot do what you asked. Nothing was sent | Read error.reason: the list says what to change |
TxPartial |
With a key: a first transaction went out, then one was refused | Tx.wait(error.sent), then send the calls from error.failedAt on |
SignerError |
The key or the wallet cannot sign: wrong chain, unknown account, no wallet | Show error.message. error.reason says which |
AbiError |
An argument is not a value of its type. Nothing was signed | Fix the argument |
RpcError, TransportError |
The node refused, or did not answer | The transaction may be out: wait for it again before you send it again |
A call often reverts with the error of another contract: a vault fails with the token’s
ERC20InsufficientAllowance. Give it to extend with the vault’s own, or the reason is a
RevertUnknown that holds raw data. Failures has every field.
One step at a time
Section titled “One step at a time”Tx.send is three functions in a loop. Call them yourself when you need what is between them.
import { Effect } from "effect";import { type Call, Tx } from "@ethect/core";
const steps = (calls: ReadonlyArray<Call.Call<unknown, unknown>>) => Effect.gen(function* () { // How many signatures the calls take. Nothing is signed. const plan = yield* Tx.plan(calls); for (const step of plan) { // One signature. It returns as soon as the transactions are sent. const pending = yield* Tx.submit(step); yield* Effect.log(`Sent: ${Tx.toJson(pending)}`); // plain data: it can be stored // In a block, three deep. yield* Tx.wait(pending, { confirmations: 3 }); } return plan.length; });| You want | Use |
|---|---|
| the receipts, and nothing else | Tx.send |
| to show the steps before the user signs anything | Tx.plan |
| to sign, and return before the block: a queue, an HTTP handler | Tx.submit. What it gives is plain JSON: store it |
| to wait for something sent earlier, or by another process | Tx.wait, with what submit gave |
| the receipt of a hash you got from anywhere | Tx.wait(hash). It needs no signer |
| to set the nonce, the gas or the fees yourself | the transaction option of submit and send |
Under the hood
Section titled “Under the hood”With a key, the script above signs in the process and sends nine requests to the node, when both transactions are in a block by the time it asks for their receipts.
- your node
eth_chainIdonce per node - your node
eth_getBlockByNumber("latest")the base fee - your node
eth_simulateV1the gas of both calls. A revert here fails the send - your node
eth_maxPriorityFeePerGasthe tip - your node
eth_getTransactionCount(me, "pending")the nonce, once: then the signer counts - your node
eth_sendRawTransactionthe approval - your node
eth_sendRawTransactionthe deposit - your node
eth_getTransactionReceipt × 2asked first. Both in a block: the send is over one is in no block yet: the blocks are watched
- your node
eth_getBlockByNumber("latest")each new block - your node
eth_getTransactionCount(me, "latest")was its nonce taken by another transaction? - your node
eth_getTransactionReceipt × 2at each new block, until both are in one
- your node
- One call uses
eth_estimateGas. Several useeth_simulateV1, since the deposit only works after the approval. - A wallet is asked instead of signing here:
eth_sendTransactionfor one call,wallet_sendCallsfor a batch.
Each step has its requests on its page: Tx.plan,
Tx.submit, Tx.wait.
Signer.privateKey has how fees and gas are
chosen.