@effect-blockchain/evm 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/EvmIndexer.ts CHANGED
@@ -1,59 +1,53 @@
1
1
  /**
2
- * EVM indexing on top of {@link EvmRpc.EvmRpc}: the last confirmed block, the logs of a set of contracts over a block
3
- * range, the native balance of an address at a block, and streams of both following the confirmed head.
2
+ * Reads the logs of a set of contracts and the native balance of an address over confirmed blocks, on top of
3
+ * {@link EvmRpc.EvmRpc}, once or as a stream following the confirmed head. The stream options are described in
4
+ * [Concepts](https://github.com/spiko-tech/effect-blockchain/blob/main/docs/concepts.md#indexer-streams).
4
5
  *
5
- * A range is split into ranges of at most `maxBlockRange` blocks, one `eth_getLogs` after another. A failing range
6
- * fails the whole call and drops the logs already read: the caller retries the same range. A balance is one
7
- * `eth_getBalance` per sample.
6
+ * A log range is split into ranges of at most `maxBlockRange` blocks, with one `eth_getLogs` each. A failing range
7
+ * fails the whole call, and the caller retries the same range.
8
8
  *
9
9
  * @example
10
10
  * ```ts
11
- * import type { EvmIndexerFilter } from "@effect-blockchain/evm/EvmIndexer"
12
- * import { EvmIndexer } from "@effect-blockchain/evm/EvmIndexer"
11
+ * import * as EvmIndexer from "@effect-blockchain/evm/EvmIndexer"
12
+ * import * as EvmRpc from "@effect-blockchain/evm/EvmRpc"
13
+ * import * as Config from "effect/Config"
13
14
  * import * as Effect from "effect/Effect"
14
- * import * as Schedule from "effect/Schedule"
15
+ * import * as FetchHttpClient from "effect/http/FetchHttpClient"
16
+ * import * as Layer from "effect/Layer"
15
17
  * import * as Stream from "effect/Stream"
16
18
  *
17
- * declare const filter: Omit<EvmIndexerFilter, "fromBlock" | "toBlock">
19
+ * declare const filter: Omit<EvmIndexer.EvmIndexerFilter, "fromBlock" | "toBlock">
18
20
  * declare const cursor: bigint
19
21
  * declare const save: (block: bigint) => Effect.Effect<void>
20
22
  *
21
23
  * const program = Effect.gen(function*() {
22
- * const indexer = yield* EvmIndexer
23
- * // once caught up, read the head after 1 s, 2 s, 4 s... at most every minute
24
- * const poll = Schedule.min([Schedule.exponential("1 second"), Schedule.spaced("1 minute")])
25
- * yield* indexer.streamLogs({ filter, fromBlock: cursor + BigInt(1), poll }).pipe(
24
+ * const rpc = yield* EvmRpc.EvmRpc
25
+ * const indexer = yield* EvmIndexer.EvmIndexer
26
+ * yield* Effect.log(`head: ${yield* rpc.blockNumber}`)
27
+ * yield* indexer.streamLogs({ filter, fromBlock: cursor + BigInt(1) }).pipe(
26
28
  * Stream.runForEach((batch) => save(batch.toBlock))
27
29
  * )
28
30
  * })
29
- * ```
30
31
  *
31
- * @example
32
- * ```ts
33
- * import type { EvmAddress } from "@effect-blockchain/evm/EvmAddress"
34
- * import { EvmIndexer } from "@effect-blockchain/evm/EvmIndexer"
35
- * import * as Effect from "effect/Effect"
36
- * import * as Stream from "effect/Stream"
37
- *
38
- * declare const address: EvmAddress
39
- *
40
- * // the balance in wei every 7200 blocks (about a day on Ethereum) up to the head, then every new 7200 blocks
41
- * const daily = Effect.gen(function*() {
42
- * const indexer = yield* EvmIndexer
43
- * return indexer.streamNativeBalance({ address, fromBlock: BigInt(21_000_000), step: 7200 }).pipe(
44
- * Stream.tap(({ balance, block }) => Effect.log(`${block}: ${balance} wei`))
45
- * )
32
+ * const RpcLive = EvmRpc.layerConfig({
33
+ * network: Config.succeed("Ethereum"),
34
+ * endpoints: Config.all([Config.all({ name: Config.succeed("main"), url: Config.Redacted("ETHEREUM_RPC_URL") })])
46
35
  * })
36
+ *
37
+ * const main = program.pipe(
38
+ * Effect.provide(EvmIndexer.layer().pipe(Layer.provideMerge(RpcLive), Layer.provide(FetchHttpClient.layer)))
39
+ * )
47
40
  * ```
48
41
  *
49
42
  * @since 0.1.0
50
43
  */
44
+ import * as Confirmations from "@effect-blockchain/core/Confirmations"
51
45
  import * as JsonRpc from "@effect-blockchain/core/JsonRpc"
52
46
  import * as Arr from "effect/Array"
53
47
  import * as BigInt_ from "effect/BigInt"
54
48
  import * as Config from "effect/Config"
55
49
  import * as Context from "effect/Context"
56
- import * as Duration from "effect/Duration"
50
+ import type * as Duration from "effect/Duration"
57
51
  import * as Effect from "effect/Effect"
58
52
  import * as Layer from "effect/Layer"
59
53
  import * as Option from "effect/Option"
@@ -61,8 +55,8 @@ import * as Schedule from "effect/Schedule"
61
55
  import * as Stream from "effect/Stream"
62
56
  import type { EvmAddress } from "./EvmAddress.ts"
63
57
  import type { EvmLog } from "./EvmLog.ts"
58
+ import * as EvmNetwork from "./EvmNetwork.ts"
64
59
  import * as EvmRpc from "./EvmRpc.ts"
65
- import * as Confirmations from "./internal/confirmations.ts"
66
60
 
67
61
  /**
68
62
  * A {@link EvmIndexer} `fetchLogs` filter: an `eth_getLogs` filter over the inclusive block range
@@ -90,7 +84,8 @@ export interface EvmIndexerBatch {
90
84
  }
91
85
 
92
86
  /**
93
- * The {@link EvmIndexer.Service.streamLogs} options.
87
+ * The {@link EvmIndexer.Service.streamLogs} options. `toBlock`, `poll` and `retry` are described in
88
+ * [Concepts](https://github.com/spiko-tech/effect-blockchain/blob/main/docs/concepts.md#indexer-streams).
94
89
  *
95
90
  * @since 0.1.0
96
91
  * @category models
@@ -98,14 +93,8 @@ export interface EvmIndexerBatch {
98
93
  export interface EvmIndexerStreamOptions {
99
94
  readonly filter: Omit<EvmIndexerFilter, "fromBlock" | "toBlock">
100
95
  readonly fromBlock: bigint
101
- /** The stream ends after the batch reaching it, and is empty when `fromBlock > toBlock`. */
102
96
  readonly toBlock?: bigint | undefined
103
- /**
104
- * When to read the head again once caught up, `Schedule.spaced(DEFAULT_POLL_INTERVAL)` by default. It restarts after
105
- * each batch, and its end ends the stream: `Schedule.recurs(0)` drains to the head and stops.
106
- */
107
97
  readonly poll?: Schedule.Schedule<unknown> | undefined
108
- /** Retries a step failing with a transient reason ({@link JsonRpc.isTransient}) at the same block. Off by default. */
109
98
  readonly retry?: Schedule.Schedule<unknown, EvmRpc.EvmRpcError> | undefined
110
99
  }
111
100
 
@@ -131,7 +120,6 @@ export interface EvmNativeBalance {
131
120
  export interface EvmIndexerNativeBalanceOptions {
132
121
  readonly address: EvmAddress
133
122
  readonly fromBlock: bigint
134
- /** The stream ends after the last sample not above it, and is empty when `fromBlock > toBlock`. */
135
123
  readonly toBlock?: bigint | undefined
136
124
  readonly step: number
137
125
  readonly poll?: Schedule.Schedule<unknown> | undefined
@@ -189,7 +177,7 @@ export const DEFAULT_MAX_BLOCK_RANGE = 1000
189
177
  * @since 0.1.0
190
178
  * @category constants
191
179
  */
192
- export const DEFAULT_POLL_INTERVAL: Duration.Duration = Duration.seconds(10)
180
+ export const DEFAULT_POLL_INTERVAL: Duration.Duration = Confirmations.DEFAULT_POLL_INTERVAL
193
181
 
194
182
  // the confirmed blocks [next, head] not indexed yet, empty once the stream reaches the head it last read
195
183
  interface StreamPosition {
@@ -221,7 +209,9 @@ export const layer = (options: {
221
209
  return yield* Effect.die(new RangeError(`maxBlockRange must be a positive integer, got ${maxBlockRange}`))
222
210
  }
223
211
  const size = BigInt(maxBlockRange)
224
- const lastConfirmedBlock = Confirmations.lastConfirmedBlock(rpc, options.confirmations).pipe(
212
+ const confirmations = options.confirmations ?? EvmNetwork.defaultConfirmations(rpc.network)
213
+ const lastConfirmedBlock = rpc.blockNumber.pipe(
214
+ Effect.map((head) => Confirmations.lastConfirmedBlock(head, confirmations)),
225
215
  Effect.withSpan("EvmIndexer.lastConfirmedBlock")
226
216
  )
227
217
  // the head last read is reused while it covers `next` (the confirmed head only moves forward), else polled
package/src/EvmNetwork.ts CHANGED
@@ -134,10 +134,11 @@ export const isTestnet = (network: EvmNetwork): boolean => (testnets as Readonly
134
134
 
135
135
  // testnets reuse their mainnet value: same consensus and block time
136
136
  const confirmations: Record<EvmNetwork, number> = {
137
- // 2 epochs, Kraken credits at finalization "typically after 64-96": https://support.kraken.com/articles/203325283
137
+ // finalized after 2 epochs of 32 slots: https://ethereum.org/en/developers/docs/consensus-mechanisms/pos/#finality
138
138
  Ethereum: 64,
139
139
  Sepolia: 64,
140
- // milestones finalize in 2-5s since Heimdall v2: https://docs.polygon.technology/pos/concepts/finality/finality/
140
+ // milestones finalize a block within 2 to 5 s, 1 to 3 blocks of 2 s. 32 blocks keep a margin for a late milestone,
141
+ // when a block only has probabilistic finality: https://docs.polygon.technology/pos/concepts/finality/finality/
141
142
  Polygon: 32,
142
143
  PolygonAmoy: 32,
143
144
  // ~1 min of 2s blocks against sequencer reorgs: https://docs.optimism.io/stack/transactions/transaction-finality
@@ -149,18 +150,19 @@ const confirmations: Record<EvmNetwork, number> = {
149
150
  // confirmed on Tezos L1 in ~6s: https://docs.etherlink.com
150
151
  Etherlink: 20,
151
152
  EtherlinkTestnet: 20,
152
- // Pionex uses 27 for Optimism: https://intercom.help/pionex/en/articles/14700793-what-is-block-confirmation
153
+ // OP Stack, as Base: https://docs.optimism.io/stack/transactions/transaction-finality
153
154
  Optimism: 30,
154
155
  OptimismSepolia: 30,
155
- // Snowman finality is irreversible, Circle uses 1: https://developers.circle.com/circle-mint/blockchain-confirmations
156
+ // Snowman acceptance is final: https://build.avax.network/docs/primary-network/avalanche-consensus
156
157
  Avalanche: 1,
157
158
  AvalancheFuji: 1,
158
- // Kraken uses 50 (fast finality in 2 blocks): https://support.kraken.com/articles/203325283
159
+ // fast finality finalizes a block once its child is justified. 50 blocks keep a margin for when no block is
160
+ // justified and finality is probabilistic again: https://github.com/bnb-chain/BEPs/blob/master/BEPs/BEP126.md
159
161
  BnbSmartChain: 50,
160
162
  BnbSmartChainTestnet: 50,
161
163
  // 2 epochs of 16 slots: https://docs.gnosischain.com/about/specs/consensus/
162
164
  Gnosis: 32,
163
- // ~1 min of 2s blocks, Circle Fast Transfer uses 1: https://developers.circle.com/cctp/required-block-confirmations
165
+ // ~1 min of 2s blocks against sequencer reorgs: https://docs.linea.build/protocol/transaction-lifecycle
164
166
  Linea: 30,
165
167
  LineaSepolia: 30,
166
168
  // local node mines instantly and never reorgs: https://getfoundry.sh/anvil/overview
package/src/EvmRelayer.ts CHANGED
@@ -1,23 +1,11 @@
1
1
  /**
2
- * EVM transaction relaying on top of {@link EvmRpc.EvmRpc}: signing a transaction, broadcasting it and following it
3
- * until it is final.
2
+ * Signs EIP-1559 transactions, broadcasts them and follows them until they are final, on top of
3
+ * {@link EvmRpc.EvmRpc}. The relayer keeps no state and `broadcast` is idempotent, as described in
4
+ * [Concepts](https://github.com/spiko-tech/effect-blockchain/blob/main/docs/concepts.md#stateless-relayer).
4
5
  *
5
- * A relayer here sends an account's own transactions and manages their nonces and fees, as OpenZeppelin Relayer does.
6
- * It is not a meta-transaction relayer (Gelato, ERC-2771) paying for someone else's transaction. It keeps no state:
7
- * storing hashes and nonces, deciding when to resend and holding keys belong to the application. Senders sharing an
8
- * address must each pass their own nonce, as the node's pending count does not see a transaction that is signed and
9
- * not yet broadcast, and two concurrent `sign` calls read the same count.
10
- *
11
- * Only EIP-1559 (type 2) transactions calling an address are sent: legacy transactions and contract creations are
12
- * not. `sign` returns the transaction hash before anything is broadcast, so it can be stored first, and `broadcast`
13
- * can be repeated with the same bytes.
14
- *
15
- * Fees come from `eth_feeHistory` (see {@link EvmFeeEstimate} and {@link defaultFees}) unless `sign` receives them.
16
- * The estimate covers the execution fee only: on a rollup, the L1 data fee is not in `eth_feeHistory` and is charged
17
- * on top, and where blocks are ordered first-come first-served (Arbitrum) the priority fee buys nothing. Replacing a
18
- * stuck transaction is `sign` with the same nonce and higher explicit `fees`: nodes ask for at least 10% more on both.
19
- *
20
- * A transaction is in one {@link EvmTransactionStatus}:
6
+ * Fees come from `eth_feeHistory` and cover execution only: a rollup charges its L1 data fee on top. To replace a
7
+ * pending transaction, call `sign` with the same nonce and with both fees at least 10% higher, the smallest bump
8
+ * nodes accept.
21
9
  *
22
10
  * | status | meaning | final |
23
11
  * |---|---|---|
@@ -30,52 +18,63 @@
30
18
  * @example
31
19
  * ```ts
32
20
  * import type { EvmAddress } from "@effect-blockchain/evm/EvmAddress"
33
- * import { EvmRelayer } from "@effect-blockchain/evm/EvmRelayer"
21
+ * import * as EvmRelayer from "@effect-blockchain/evm/EvmRelayer"
22
+ * import * as EvmRpc from "@effect-blockchain/evm/EvmRpc"
34
23
  * import type { EvmSigner } from "@effect-blockchain/evm/EvmSigner"
35
24
  * import type { EvmTransactionHash } from "@effect-blockchain/evm/EvmTransactionHash"
25
+ * import * as Config from "effect/Config"
36
26
  * import * as Effect from "effect/Effect"
27
+ * import * as FetchHttpClient from "effect/http/FetchHttpClient"
28
+ * import * as Layer from "effect/Layer"
37
29
  *
38
30
  * declare const signer: EvmSigner
39
31
  * declare const to: EvmAddress
40
32
  * declare const store: (hash: EvmTransactionHash, nonce: bigint) => Effect.Effect<void>
41
33
  *
42
34
  * const program = Effect.gen(function*() {
43
- * const relayer = yield* EvmRelayer
35
+ * const relayer = yield* EvmRelayer.EvmRelayer
44
36
  * const { hash, nonce, signed } = yield* relayer.sign({ signer, to, value: BigInt(1) })
45
- * // stored before the broadcast: a crash in between leaves a hash to look up, never an unknown transaction
46
37
  * yield* store(hash, nonce)
47
38
  * yield* relayer.broadcast({ signed })
48
- * // a transaction the node never sees stays `NotFound`: the timeout bounds the wait
49
- * const status = yield* relayer.awaitConfirmation({ hash }).pipe(Effect.timeout("10 minutes"))
50
- * if (status._tag === "Failed") {
51
- * yield* Effect.logError(`reverted in block ${status.block}`)
52
- * }
39
+ * // `NotFound` keeps polling: the timeout bounds the wait
40
+ * return yield* relayer.awaitConfirmation({ hash }).pipe(Effect.timeout("10 minutes"))
53
41
  * })
42
+ *
43
+ * const RpcLive = EvmRpc.layerConfig({
44
+ * network: Config.succeed("Ethereum"),
45
+ * endpoints: Config.all([Config.all({ name: Config.succeed("main"), url: Config.Redacted("ETHEREUM_RPC_URL") })])
46
+ * })
47
+ *
48
+ * const main = program.pipe(
49
+ * Effect.provide(EvmRelayer.layer().pipe(Layer.provide(RpcLive), Layer.provide(FetchHttpClient.layer)))
50
+ * )
54
51
  * ```
55
52
  *
56
53
  * @since 0.3.0
57
54
  */
55
+ import * as Confirmations from "@effect-blockchain/core/Confirmations"
56
+ import * as JsonRpc from "@effect-blockchain/core/JsonRpc"
58
57
  import * as Arr from "effect/Array"
59
58
  import * as BigInt_ from "effect/BigInt"
59
+ import * as Config from "effect/Config"
60
60
  import * as Context from "effect/Context"
61
+ import type * as Duration from "effect/Duration"
61
62
  import * as Effect from "effect/Effect"
62
63
  import * as Layer from "effect/Layer"
63
64
  import * as Order from "effect/Order"
64
- import * as Schedule from "effect/Schedule"
65
+ import type * as Schedule from "effect/Schedule"
65
66
  import * as Schema from "effect/Schema"
66
67
  import { keccak256 } from "viem"
67
68
  import type { EvmAddress } from "./EvmAddress.ts"
68
69
  import type { EvmHexData } from "./EvmHexData.ts"
69
- import { DEFAULT_POLL_INTERVAL } from "./EvmIndexer.ts"
70
70
  import * as EvmNetwork from "./EvmNetwork.ts"
71
71
  import * as EvmRpc from "./EvmRpc.ts"
72
72
  import type { EvmSigner, EvmSignerError } from "./EvmSigner.ts"
73
73
  import { EvmTransactionHash } from "./EvmTransactionHash.ts"
74
- import * as Confirmations from "./internal/confirmations.ts"
75
74
 
76
75
  /**
77
- * Where a transaction stands, by `_tag`: see the module's table. `block` is the block holding it, and `reason` the
78
- * revert data, `undefined` when it is not available: a receipt does not carry it.
76
+ * Where a transaction stands, by `_tag`: see the module's table. `block` is the block holding it. `reason` is always
77
+ * `undefined`: a receipt does not carry the revert data.
79
78
  *
80
79
  * @since 0.3.0
81
80
  * @category models
@@ -84,9 +83,19 @@ export type EvmTransactionStatus =
84
83
  | { readonly _tag: "Pending" }
85
84
  | { readonly _tag: "Included"; readonly block: bigint }
86
85
  | { readonly _tag: "Confirmed"; readonly block: bigint }
87
- | { readonly _tag: "Failed"; readonly block: bigint; readonly reason: EvmHexData | undefined }
86
+ | { readonly _tag: "Failed"; readonly block: bigint; readonly reason: undefined }
88
87
  | { readonly _tag: "NotFound" }
89
88
 
89
+ /**
90
+ * The transaction to look up: its `hash`.
91
+ *
92
+ * @since 0.4.0
93
+ * @category models
94
+ */
95
+ export interface EvmTransactionStatusOptions {
96
+ readonly hash: EvmTransactionHash
97
+ }
98
+
90
99
  /**
91
100
  * The fees of an EIP-1559 transaction, in wei per gas: the most it pays in total, and the part of it offered to the
92
101
  * block producer above the base fee.
@@ -125,14 +134,36 @@ export interface EvmSignedTransaction {
125
134
  readonly nonce: bigint
126
135
  }
127
136
 
137
+ /**
138
+ * The simulation of the call failed: `error` is the node's message, with the revert reason when the node gives it.
139
+ *
140
+ * @since 0.4.0
141
+ * @category reasons
142
+ */
143
+ export class SimulationFailed extends Schema.TaggedError<SimulationFailed>()("SimulationFailed", {
144
+ error: Schema.String
145
+ }) {}
146
+
147
+ /**
148
+ * A transaction could not be prepared for signing, for a `reason` matched with `Effect.catchReason`: `cause` is the
149
+ * {@link EvmRpc.EvmRpcError} of the refused `eth_estimateGas`.
150
+ *
151
+ * @since 0.4.0
152
+ * @category errors
153
+ */
154
+ export class EvmSimulationError extends Schema.TaggedError<EvmSimulationError>()("EvmSimulationError", {
155
+ reason: Schema.Union([SimulationFailed]),
156
+ cause: Schema.Defect()
157
+ }) {}
158
+
128
159
  /**
129
160
  * The sender's nonce is already used by a transaction in a block, and the node does not know this one: another
130
161
  * transaction took its place.
131
162
  *
132
- * @since 0.3.0
163
+ * @since 0.4.0
133
164
  * @category reasons
134
165
  */
135
- export class NonceTooLow extends Schema.TaggedError<NonceTooLow>()("NonceTooLow", {}) {}
166
+ export class InvalidNonce extends Schema.TaggedError<InvalidNonce>()("InvalidNonce", {}) {}
136
167
 
137
168
  /**
138
169
  * The node's pool holds another transaction at this nonce and the fees do not exceed its fees enough to replace it.
@@ -166,7 +197,7 @@ export class InsufficientFunds extends Schema.TaggedError<InsufficientFunds>()("
166
197
  * @since 0.3.0
167
198
  * @category reasons
168
199
  */
169
- export const EvmBroadcastReason = Schema.Union([NonceTooLow, ReplacementUnderpriced, FeeTooLow, InsufficientFunds])
200
+ export const EvmBroadcastReason = Schema.Union([InvalidNonce, ReplacementUnderpriced, FeeTooLow, InsufficientFunds])
170
201
 
171
202
  /**
172
203
  * @since 0.3.0
@@ -193,8 +224,9 @@ export class EvmBroadcastError extends Schema.TaggedError<EvmBroadcastError>()("
193
224
  export class EvmRelayer extends Context.Service<EvmRelayer, {
194
225
  /**
195
226
  * Signs an EIP-1559 call of `to` from `signer.address` without sending it. A missing `nonce` is the sender's pending
196
- * transaction count, a missing `gas` is `eth_estimateGas` times the layer's `gasMultiplier` (a call that reverts
197
- * fails with `Rejected`), and missing `fees` come from the layer's fee strategy.
227
+ * transaction count, a missing `gas` is `eth_estimateGas` times the layer's `gasMultiplier` (a call the node
228
+ * refuses to estimate, as one that reverts, fails with an {@link EvmSimulationError}), and missing `fees` come from
229
+ * the layer's fee strategy.
198
230
  */
199
231
  readonly sign: (options: {
200
232
  readonly signer: EvmSigner
@@ -204,7 +236,7 @@ export class EvmRelayer extends Context.Service<EvmRelayer, {
204
236
  readonly nonce?: bigint | undefined
205
237
  readonly gas?: bigint | undefined
206
238
  readonly fees?: EvmFees | undefined
207
- }) => Effect.Effect<EvmSignedTransaction, EvmRpc.EvmRpcError | EvmSignerError>
239
+ }) => Effect.Effect<EvmSignedTransaction, EvmRpc.EvmRpcError | EvmSignerError | EvmSimulationError>
208
240
  /**
209
241
  * Sends a signed transaction with `eth_sendRawTransaction` and returns its hash. Sending the same bytes again is
210
242
  * safe: a node answering that it already has the transaction, or that the nonce is used while it knows this hash,
@@ -217,20 +249,27 @@ export class EvmRelayer extends Context.Service<EvmRelayer, {
217
249
  * The status of the transaction as the answering endpoint sees it. An endpoint behind the head, or one that never
218
250
  * received the transaction, answers `Pending` or `NotFound` for a transaction another one has in a block.
219
251
  */
220
- readonly fetchTransactionStatus: (options: {
221
- readonly hash: EvmTransactionHash
222
- }) => Effect.Effect<EvmTransactionStatus, EvmRpc.EvmRpcError>
252
+ readonly fetchTransactionStatus: (
253
+ options: EvmTransactionStatusOptions
254
+ ) => Effect.Effect<EvmTransactionStatus, EvmRpc.EvmRpcError>
223
255
  /**
224
- * Reads {@link fetchTransactionStatus} on `poll` (`Schedule.spaced(EvmIndexer.DEFAULT_POLL_INTERVAL)` by default) until it is
225
- * `Confirmed` or `Failed`, and returns it. `NotFound` keeps polling, so bound the wait with a timeout. A `poll` that
226
- * ends first returns the last status read.
256
+ * Reads {@link fetchTransactionStatus} on `poll` until it is `Confirmed` or `Failed`, and returns it. `NotFound`
257
+ * keeps polling, so bound the wait with a timeout. `poll` and errors work as in
258
+ * {@link Confirmations.awaitConfirmation}.
227
259
  */
228
- readonly awaitConfirmation: (options: {
229
- readonly hash: EvmTransactionHash
230
- readonly poll?: Schedule.Schedule<unknown> | undefined
231
- }) => Effect.Effect<EvmTransactionStatus, EvmRpc.EvmRpcError>
260
+ readonly awaitConfirmation: (
261
+ options: EvmTransactionStatusOptions & { readonly poll?: Schedule.Schedule<unknown> | undefined }
262
+ ) => Effect.Effect<EvmTransactionStatus, EvmRpc.EvmRpcError>
232
263
  }>()("@effect-blockchain/evm/EvmRelayer") {}
233
264
 
265
+ /**
266
+ * The default `poll` spacing of {@link EvmRelayer.Service.awaitConfirmation}: 10 seconds.
267
+ *
268
+ * @since 0.4.0
269
+ * @category constants
270
+ */
271
+ export const DEFAULT_POLL_INTERVAL: Duration.Duration = Confirmations.DEFAULT_POLL_INTERVAL
272
+
234
273
  // geth's default `miner.gasprice` (0.001 gwei): the lowest tip its block producers take
235
274
  const PRIORITY_FEE_FLOOR = BigInt(1_000_000)
236
275
 
@@ -256,23 +295,18 @@ export const defaultFees = (estimate: EvmFeeEstimate): EvmFees => {
256
295
  return { maxFeePerGas: estimate.baseFeePerGas * BigInt(2) + maxPriorityFeePerGas, maxPriorityFeePerGas }
257
296
  }
258
297
 
259
- const messagesOf = (cause: unknown): ReadonlyArray<string> =>
260
- cause instanceof AggregateError
261
- ? cause.errors.flatMap(messagesOf)
262
- : cause instanceof Error
263
- ? [cause.message, ...messagesOf(cause.cause)]
264
- : []
265
-
266
298
  // the refusals of geth (`core/txpool/errors.go`, `core/error.go`), also used by erigon, reth and anvil, then those
267
299
  // of Nethermind (`AcceptTxResult`), Besu and anvil that differ
268
300
  const alreadyKnown = /already known|AlreadyKnown|known transaction|already imported/i
269
301
  const refusals: ReadonlyArray<readonly [RegExp, () => EvmBroadcastReason]> = [
270
- [/nonce too low|OldNonce/i, () => new NonceTooLow()],
302
+ [/nonce too low|OldNonce/i, () => new InvalidNonce()],
271
303
  [/replacement transaction underpriced|ReplacementNotAllowed/i, () => new ReplacementUnderpriced()],
272
304
  [/insufficient funds|InsufficientFunds|exceeds transaction sender account balance/i, () => new InsufficientFunds()],
273
305
  [/underpriced|less than block base fee|FeeTooLow|gas price below configured minimum/i, () => new FeeTooLow()]
274
306
  ]
275
307
 
308
+ const messagesOf = (error: unknown) => JsonRpc.errorsOf(error).map(({ message }) => message).join("\n")
309
+
276
310
  /**
277
311
  * Builds an {@link EvmRelayer} over the provided {@link EvmRpc.EvmRpc}. `confirmations` overrides the network's
278
312
  * default, as in `EvmIndexer.layer`: both agree on the last confirmed block. `fees` (default {@link defaultFees})
@@ -292,6 +326,7 @@ export const layer = (options: {
292
326
  Effect.gen(function*() {
293
327
  const rpc = yield* EvmRpc.EvmRpc
294
328
  const chainId = EvmNetwork.toChainId(rpc.network)
329
+ const confirmations = options.confirmations ?? EvmNetwork.defaultConfirmations(rpc.network)
295
330
  const gasPercent = BigInt(Math.round((options.gasMultiplier ?? 1.2) * 100))
296
331
  const estimateFees = Effect.map(rpc.feeHistory(FEE_HISTORY), (history) =>
297
332
  (options.fees ?? defaultFees)({
@@ -305,9 +340,18 @@ export const layer = (options: {
305
340
  ? rpc.getTransactionCount({ address: signer.address, blockTag: "pending" })
306
341
  : Effect.succeed(given.nonce),
307
342
  gas: given.gas === undefined
308
- ? Effect.map(
309
- rpc.estimateGas({ from: signer.address, to, value, data }),
310
- (estimate) => estimate * gasPercent / BigInt(100)
343
+ ? rpc.estimateGas({ from: signer.address, to, value, data }).pipe(
344
+ Effect.map((estimate) => estimate * gasPercent / BigInt(100)),
345
+ Effect.catchIf(
346
+ (cause) => cause.reason._tag === "Rejected",
347
+ (cause) =>
348
+ Effect.fail(
349
+ new EvmSimulationError({
350
+ reason: new SimulationFailed({ error: messagesOf(cause.cause) }),
351
+ cause
352
+ })
353
+ )
354
+ )
311
355
  )
312
356
  : Effect.succeed(given.gas),
313
357
  fees: given.fees === undefined ? estimateFees : Effect.succeed(given.fees)
@@ -322,24 +366,24 @@ export const layer = (options: {
322
366
  if (sent._tag === "Success") return sent.success
323
367
  const cause = sent.failure
324
368
  const hash = EvmTransactionHash.make(keccak256(signed))
325
- const messages = messagesOf(cause).join("\n")
369
+ const messages = messagesOf(cause)
326
370
  if (alreadyKnown.test(messages)) return hash
327
371
  const reason = refusals.find(([pattern]) => pattern.test(messages))?.[1]()
328
372
  if (reason === undefined) return yield* cause
329
373
  // a node that has this transaction in a block answers that its nonce is used
330
- if (reason._tag === "NonceTooLow" && (yield* rpc.getTransactionByHash({ hash })) !== null) return hash
374
+ if (reason._tag === "InvalidNonce" && (yield* rpc.getTransactionByHash({ hash })) !== null) return hash
331
375
  return yield* new EvmBroadcastError({ reason, cause })
332
376
  }
333
377
  )
334
378
  const fetchTransactionStatus = Effect.fn("EvmRelayer.fetchTransactionStatus")(
335
- function*({ hash }: { readonly hash: EvmTransactionHash }) {
379
+ function*({ hash }: EvmTransactionStatusOptions) {
336
380
  const receipt = yield* rpc.getTransactionReceipt({ hash })
337
381
  if (receipt === null) {
338
382
  const transaction = yield* rpc.getTransactionByHash({ hash })
339
383
  return transaction === null ? { _tag: "NotFound" } as const : { _tag: "Pending" } as const
340
384
  }
341
385
  // read after the receipt: a head older than the receipt's block could only delay `Confirmed`
342
- const confirmed = yield* Confirmations.lastConfirmedBlock(rpc, options.confirmations)
386
+ const confirmed = Confirmations.lastConfirmedBlock(yield* rpc.blockNumber, confirmations)
343
387
  const block = receipt.blockNumber
344
388
  if (block > confirmed) return { _tag: "Included", block } as const
345
389
  return receipt.status === 1
@@ -351,11 +395,31 @@ export const layer = (options: {
351
395
  sign,
352
396
  broadcast,
353
397
  fetchTransactionStatus,
354
- awaitConfirmation: ({ hash, poll = Schedule.spaced(DEFAULT_POLL_INTERVAL) }) =>
355
- fetchTransactionStatus({ hash }).pipe(
356
- Effect.repeat({ schedule: poll, until: ({ _tag }) => _tag === "Confirmed" || _tag === "Failed" }),
357
- Effect.withSpan("EvmRelayer.awaitConfirmation")
358
- )
398
+ awaitConfirmation: ({ hash, poll }) =>
399
+ Confirmations.awaitConfirmation({
400
+ fetch: fetchTransactionStatus({ hash }),
401
+ isFinal: ({ _tag }) => _tag === "Confirmed" || _tag === "Failed",
402
+ poll
403
+ }).pipe(Effect.withSpan("EvmRelayer.awaitConfirmation"))
359
404
  })
360
405
  })
361
406
  )
407
+
408
+ /**
409
+ * Builds an {@link EvmRelayer} like {@link layer}, reading `confirmations` and `gasMultiplier` from `Config`. The fee
410
+ * strategy is {@link defaultFees}.
411
+ *
412
+ * @example
413
+ * ```ts
414
+ * import * as EvmRelayer from "@effect-blockchain/evm/EvmRelayer"
415
+ * import * as Config from "effect/Config"
416
+ *
417
+ * const RelayerLive = EvmRelayer.layerConfig({ confirmations: Config.Int("ETHEREUM_CONFIRMATIONS") })
418
+ * ```
419
+ *
420
+ * @since 0.4.0
421
+ * @category layers
422
+ */
423
+ export const layerConfig = (
424
+ options: Config.Wrap<Omit<NonNullable<Parameters<typeof layer>[0]>, "fees">>
425
+ ): Layer.Layer<EvmRelayer, Config.ConfigError, EvmRpc.EvmRpc> => Layer.unwrap(Effect.map(Config.unwrap(options), layer))
package/src/EvmRpc.ts CHANGED
@@ -1,10 +1,8 @@
1
1
  /**
2
- * Typed EVM JSON-RPC methods over an ordered list of endpoints with fallback.
3
- *
4
- * A call starts at the first endpoint and moves to the next one on failure, except on `WrongNetwork`. Each endpoint
5
- * is checked once to serve the configured network (`eth_chainId`). Every method but `sendRawTransaction` is a read,
6
- * so retries and fallback are safe; `sendRawTransaction` documents its own case. Methods are named after the JSON-RPC
7
- * method without its namespace (`eth_getLogs` is `getLogs`).
2
+ * The EVM JSON-RPC methods over an ordered list of endpoints with fallback, one request per call. Methods are named
3
+ * after the JSON-RPC method without its namespace (`eth_getLogs` is `getLogs`). The fallback rules and the error
4
+ * reasons are described in
5
+ * [Concepts](https://github.com/spiko-tech/effect-blockchain/blob/main/docs/concepts.md#endpoint-fallback).
8
6
  *
9
7
  * @example
10
8
  * ```ts
@@ -63,9 +61,7 @@ export interface EvmRpcEndpoint {
63
61
  }
64
62
 
65
63
  /**
66
- * A failed call: its `reason` (a {@link JsonRpc.Reason}, matched with `Effect.catchReason`), the JSON-RPC error code or
67
- * HTTP status as `code`, and a `cause` without the endpoint URL. After several endpoints, the error is the last one
68
- * and `cause` is an `AggregateError` of each endpoint's error, in order.
64
+ * A failed call, with a {@link JsonRpc.Reason} as `reason`.
69
65
  *
70
66
  * On EVM, `Unavailable` includes the codes -32005, -32603, -32007, -1 and 429, `InvalidResponse` a log outside the
71
67
  * `getLogs` filter, and `Lagging` a head below the requested block.
package/src/EvmSigner.ts CHANGED
@@ -1,9 +1,7 @@
1
1
  /**
2
- * Signers of EVM transactions: a local private key, or a custody API that only signs a hash.
3
- *
4
- * A signer is a value and receives the whole transaction, never a hash chosen by its caller: signing an opaque hash
5
- * hides what is being authorised, and custody policy engines and hardware wallets refuse it. Only EIP-1559
6
- * transactions calling an address are signed.
2
+ * Signers of EIP-1559 transactions: a private key held in memory, or a custody API that only signs a hash. The
3
+ * reason a signer receives the whole transaction is described in
4
+ * [Concepts](https://github.com/spiko-tech/effect-blockchain/blob/main/docs/concepts.md#signers).
7
5
  *
8
6
  * @since 0.3.0
9
7
  */
@@ -78,10 +76,12 @@ const serializable = (transaction: EvmUnsignedTransaction) => ({
78
76
  * @since 0.3.0
79
77
  * @category constructors
80
78
  */
81
- export const fromPrivateKey = (key: Redacted.Redacted<string>): Effect.Effect<EvmSigner, EvmSignerError> =>
79
+ export const fromPrivateKey = (options: {
80
+ readonly key: Redacted.Redacted<string>
81
+ }): Effect.Effect<EvmSigner, EvmSignerError> =>
82
82
  Effect.try({
83
83
  try: () => {
84
- const value = Redacted.value(key)
84
+ const value = Redacted.value(options.key)
85
85
  if (!isHex(value)) throw new Error("not hex")
86
86
  return privateKeyToAccount(value)
87
87
  },