@effect-blockchain/evm 0.2.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.
Files changed (44) hide show
  1. package/README.md +79 -1
  2. package/dist/EvmFeeHistory.d.ts +26 -0
  3. package/dist/EvmFeeHistory.d.ts.map +1 -0
  4. package/dist/EvmFeeHistory.js +25 -0
  5. package/dist/EvmFeeHistory.js.map +1 -0
  6. package/dist/EvmIndexer.d.ts +47 -9
  7. package/dist/EvmIndexer.d.ts.map +1 -1
  8. package/dist/EvmIndexer.js +95 -36
  9. package/dist/EvmIndexer.js.map +1 -1
  10. package/dist/EvmNetwork.d.ts.map +1 -1
  11. package/dist/EvmNetwork.js +8 -6
  12. package/dist/EvmNetwork.js.map +1 -1
  13. package/dist/EvmRelayer.d.ts +256 -0
  14. package/dist/EvmRelayer.d.ts.map +1 -0
  15. package/dist/EvmRelayer.js +330 -0
  16. package/dist/EvmRelayer.js.map +1 -0
  17. package/dist/EvmRpc.d.ts +88 -8
  18. package/dist/EvmRpc.d.ts.map +1 -1
  19. package/dist/EvmRpc.js +30 -9
  20. package/dist/EvmRpc.js.map +1 -1
  21. package/dist/EvmSigner.d.ts +78 -0
  22. package/dist/EvmSigner.d.ts.map +1 -0
  23. package/dist/EvmSigner.js +96 -0
  24. package/dist/EvmSigner.js.map +1 -0
  25. package/dist/EvmTransaction.d.ts +65 -0
  26. package/dist/EvmTransaction.d.ts.map +1 -0
  27. package/dist/EvmTransaction.js +60 -0
  28. package/dist/EvmTransaction.js.map +1 -0
  29. package/dist/index.d.ts +16 -0
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +16 -0
  32. package/dist/index.js.map +1 -1
  33. package/dist/internal/rpcMethods.js +57 -5
  34. package/dist/internal/rpcMethods.js.map +1 -1
  35. package/package.json +2 -2
  36. package/src/EvmFeeHistory.ts +28 -0
  37. package/src/EvmIndexer.ts +142 -49
  38. package/src/EvmNetwork.ts +8 -6
  39. package/src/EvmRelayer.ts +425 -0
  40. package/src/EvmRpc.ts +106 -9
  41. package/src/EvmSigner.ts +128 -0
  42. package/src/EvmTransaction.ts +64 -0
  43. package/src/index.ts +20 -0
  44. package/src/internal/rpcMethods.ts +67 -6
@@ -0,0 +1,425 @@
1
+ /**
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).
5
+ *
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.
9
+ *
10
+ * | status | meaning | final |
11
+ * |---|---|---|
12
+ * | `Pending` | known to the node, not in a block | no |
13
+ * | `Included` | in `block`, above the last confirmed block: a reorganisation can still move or drop it | no |
14
+ * | `Confirmed` | succeeded in `block`, at or below the last confirmed block | yes |
15
+ * | `Failed` | reverted in `block`, at or below the last confirmed block | yes |
16
+ * | `NotFound` | unknown to the node: dropped, not propagated yet, or never sent | no |
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * import type { EvmAddress } from "@effect-blockchain/evm/EvmAddress"
21
+ * import * as EvmRelayer from "@effect-blockchain/evm/EvmRelayer"
22
+ * import * as EvmRpc from "@effect-blockchain/evm/EvmRpc"
23
+ * import type { EvmSigner } from "@effect-blockchain/evm/EvmSigner"
24
+ * import type { EvmTransactionHash } from "@effect-blockchain/evm/EvmTransactionHash"
25
+ * import * as Config from "effect/Config"
26
+ * import * as Effect from "effect/Effect"
27
+ * import * as FetchHttpClient from "effect/http/FetchHttpClient"
28
+ * import * as Layer from "effect/Layer"
29
+ *
30
+ * declare const signer: EvmSigner
31
+ * declare const to: EvmAddress
32
+ * declare const store: (hash: EvmTransactionHash, nonce: bigint) => Effect.Effect<void>
33
+ *
34
+ * const program = Effect.gen(function*() {
35
+ * const relayer = yield* EvmRelayer.EvmRelayer
36
+ * const { hash, nonce, signed } = yield* relayer.sign({ signer, to, value: BigInt(1) })
37
+ * yield* store(hash, nonce)
38
+ * yield* relayer.broadcast({ signed })
39
+ * // `NotFound` keeps polling: the timeout bounds the wait
40
+ * return yield* relayer.awaitConfirmation({ hash }).pipe(Effect.timeout("10 minutes"))
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
+ * )
51
+ * ```
52
+ *
53
+ * @since 0.3.0
54
+ */
55
+ import * as Confirmations from "@effect-blockchain/core/Confirmations"
56
+ import * as JsonRpc from "@effect-blockchain/core/JsonRpc"
57
+ import * as Arr from "effect/Array"
58
+ import * as BigInt_ from "effect/BigInt"
59
+ import * as Config from "effect/Config"
60
+ import * as Context from "effect/Context"
61
+ import type * as Duration from "effect/Duration"
62
+ import * as Effect from "effect/Effect"
63
+ import * as Layer from "effect/Layer"
64
+ import * as Order from "effect/Order"
65
+ import type * as Schedule from "effect/Schedule"
66
+ import * as Schema from "effect/Schema"
67
+ import { keccak256 } from "viem"
68
+ import type { EvmAddress } from "./EvmAddress.ts"
69
+ import type { EvmHexData } from "./EvmHexData.ts"
70
+ import * as EvmNetwork from "./EvmNetwork.ts"
71
+ import * as EvmRpc from "./EvmRpc.ts"
72
+ import type { EvmSigner, EvmSignerError } from "./EvmSigner.ts"
73
+ import { EvmTransactionHash } from "./EvmTransactionHash.ts"
74
+
75
+ /**
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.
78
+ *
79
+ * @since 0.3.0
80
+ * @category models
81
+ */
82
+ export type EvmTransactionStatus =
83
+ | { readonly _tag: "Pending" }
84
+ | { readonly _tag: "Included"; readonly block: bigint }
85
+ | { readonly _tag: "Confirmed"; readonly block: bigint }
86
+ | { readonly _tag: "Failed"; readonly block: bigint; readonly reason: undefined }
87
+ | { readonly _tag: "NotFound" }
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
+
99
+ /**
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
101
+ * block producer above the base fee.
102
+ *
103
+ * @since 0.3.0
104
+ * @category models
105
+ */
106
+ export interface EvmFees {
107
+ readonly maxFeePerGas: bigint
108
+ readonly maxPriorityFeePerGas: bigint
109
+ }
110
+
111
+ /**
112
+ * What a fee strategy decides from, read with `eth_feeHistory` over the last 10 blocks: `baseFeePerGas` is the base
113
+ * fee of the next block and `rewards` holds, per block from the oldest, the priority fee paid at the 25th, 50th and
114
+ * 75th percentiles of its gas. A node may return fewer blocks or no `rewards`, and an empty block reports zeros.
115
+ *
116
+ * @since 0.3.0
117
+ * @category models
118
+ */
119
+ export interface EvmFeeEstimate {
120
+ readonly baseFeePerGas: bigint
121
+ readonly rewards: ReadonlyArray<ReadonlyArray<bigint>>
122
+ }
123
+
124
+ /**
125
+ * A transaction signed by {@link EvmRelayer.sign}: `signed` is what `broadcast` takes, `hash` its transaction hash
126
+ * and `nonce` the nonce it uses.
127
+ *
128
+ * @since 0.3.0
129
+ * @category models
130
+ */
131
+ export interface EvmSignedTransaction {
132
+ readonly hash: EvmTransactionHash
133
+ readonly signed: EvmHexData
134
+ readonly nonce: bigint
135
+ }
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
+
159
+ /**
160
+ * The sender's nonce is already used by a transaction in a block, and the node does not know this one: another
161
+ * transaction took its place.
162
+ *
163
+ * @since 0.4.0
164
+ * @category reasons
165
+ */
166
+ export class InvalidNonce extends Schema.TaggedError<InvalidNonce>()("InvalidNonce", {}) {}
167
+
168
+ /**
169
+ * The node's pool holds another transaction at this nonce and the fees do not exceed its fees enough to replace it.
170
+ *
171
+ * @since 0.3.0
172
+ * @category reasons
173
+ */
174
+ export class ReplacementUnderpriced
175
+ extends Schema.TaggedError<ReplacementUnderpriced>()("ReplacementUnderpriced", {})
176
+ {}
177
+
178
+ /**
179
+ * The fees are below what the node accepts: `maxFeePerGas` under the base fee, or a priority fee under its minimum.
180
+ *
181
+ * @since 0.3.0
182
+ * @category reasons
183
+ */
184
+ export class FeeTooLow extends Schema.TaggedError<FeeTooLow>()("FeeTooLow", {}) {}
185
+
186
+ /**
187
+ * The sender's balance does not cover `value` plus `gas` times `maxFeePerGas`.
188
+ *
189
+ * @since 0.3.0
190
+ * @category reasons
191
+ */
192
+ export class InsufficientFunds extends Schema.TaggedError<InsufficientFunds>()("InsufficientFunds", {}) {}
193
+
194
+ /**
195
+ * Why a node refused a transaction, the `reason` of an {@link EvmBroadcastError}, matched with `Effect.catchReason`.
196
+ *
197
+ * @since 0.3.0
198
+ * @category reasons
199
+ */
200
+ export const EvmBroadcastReason = Schema.Union([InvalidNonce, ReplacementUnderpriced, FeeTooLow, InsufficientFunds])
201
+
202
+ /**
203
+ * @since 0.3.0
204
+ * @category reasons
205
+ */
206
+ export type EvmBroadcastReason = typeof EvmBroadcastReason.Type
207
+
208
+ /**
209
+ * A node refused the transaction for a `reason` the sender can act on: `cause` is the {@link EvmRpc.EvmRpcError}
210
+ * holding the node's message. Any other refusal stays an `EvmRpcError`.
211
+ *
212
+ * @since 0.3.0
213
+ * @category errors
214
+ */
215
+ export class EvmBroadcastError extends Schema.TaggedError<EvmBroadcastError>()("EvmBroadcastError", {
216
+ reason: EvmBroadcastReason,
217
+ cause: Schema.Defect()
218
+ }) {}
219
+
220
+ /**
221
+ * @since 0.3.0
222
+ * @category services
223
+ */
224
+ export class EvmRelayer extends Context.Service<EvmRelayer, {
225
+ /**
226
+ * Signs an EIP-1559 call of `to` from `signer.address` without sending it. A missing `nonce` is the sender's pending
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.
230
+ */
231
+ readonly sign: (options: {
232
+ readonly signer: EvmSigner
233
+ readonly to: EvmAddress
234
+ readonly data?: EvmHexData | undefined
235
+ readonly value?: bigint | undefined
236
+ readonly nonce?: bigint | undefined
237
+ readonly gas?: bigint | undefined
238
+ readonly fees?: EvmFees | undefined
239
+ }) => Effect.Effect<EvmSignedTransaction, EvmRpc.EvmRpcError | EvmSignerError | EvmSimulationError>
240
+ /**
241
+ * Sends a signed transaction with `eth_sendRawTransaction` and returns its hash. Sending the same bytes again is
242
+ * safe: a node answering that it already has the transaction, or that the nonce is used while it knows this hash,
243
+ * is a success.
244
+ */
245
+ readonly broadcast: (options: {
246
+ readonly signed: EvmHexData
247
+ }) => Effect.Effect<EvmTransactionHash, EvmBroadcastError | EvmRpc.EvmRpcError>
248
+ /**
249
+ * The status of the transaction as the answering endpoint sees it. An endpoint behind the head, or one that never
250
+ * received the transaction, answers `Pending` or `NotFound` for a transaction another one has in a block.
251
+ */
252
+ readonly fetchTransactionStatus: (
253
+ options: EvmTransactionStatusOptions
254
+ ) => Effect.Effect<EvmTransactionStatus, EvmRpc.EvmRpcError>
255
+ /**
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}.
259
+ */
260
+ readonly awaitConfirmation: (
261
+ options: EvmTransactionStatusOptions & { readonly poll?: Schedule.Schedule<unknown> | undefined }
262
+ ) => Effect.Effect<EvmTransactionStatus, EvmRpc.EvmRpcError>
263
+ }>()("@effect-blockchain/evm/EvmRelayer") {}
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
+
273
+ // geth's default `miner.gasprice` (0.001 gwei): the lowest tip its block producers take
274
+ const PRIORITY_FEE_FLOOR = BigInt(1_000_000)
275
+
276
+ const FEE_HISTORY = { blockCount: 10, newestBlock: "latest", rewardPercentiles: [25, 50, 75] } as const
277
+
278
+ /**
279
+ * The library's fee strategy: the priority fee is the median over the blocks of their 50th percentile reward, at
280
+ * least 0.001 gwei, and `maxFeePerGas` is twice the next base fee plus that priority fee. Doubling the base fee keeps
281
+ * the transaction includable through 5 full blocks in a row, each raising the base fee by 12.5%.
282
+ *
283
+ * @since 0.3.0
284
+ * @category fees
285
+ */
286
+ export const defaultFees = (estimate: EvmFeeEstimate): EvmFees => {
287
+ const medians = Arr.sort(
288
+ Arr.filter(estimate.rewards.map((rewards) => rewards[1]), (reward) => reward !== undefined),
289
+ Order.BigInt
290
+ )
291
+ const maxPriorityFeePerGas = BigInt_.max(
292
+ medians[Math.floor(medians.length / 2)] ?? PRIORITY_FEE_FLOOR,
293
+ PRIORITY_FEE_FLOOR
294
+ )
295
+ return { maxFeePerGas: estimate.baseFeePerGas * BigInt(2) + maxPriorityFeePerGas, maxPriorityFeePerGas }
296
+ }
297
+
298
+ // the refusals of geth (`core/txpool/errors.go`, `core/error.go`), also used by erigon, reth and anvil, then those
299
+ // of Nethermind (`AcceptTxResult`), Besu and anvil that differ
300
+ const alreadyKnown = /already known|AlreadyKnown|known transaction|already imported/i
301
+ const refusals: ReadonlyArray<readonly [RegExp, () => EvmBroadcastReason]> = [
302
+ [/nonce too low|OldNonce/i, () => new InvalidNonce()],
303
+ [/replacement transaction underpriced|ReplacementNotAllowed/i, () => new ReplacementUnderpriced()],
304
+ [/insufficient funds|InsufficientFunds|exceeds transaction sender account balance/i, () => new InsufficientFunds()],
305
+ [/underpriced|less than block base fee|FeeTooLow|gas price below configured minimum/i, () => new FeeTooLow()]
306
+ ]
307
+
308
+ const messagesOf = (error: unknown) => JsonRpc.errorsOf(error).map(({ message }) => message).join("\n")
309
+
310
+ /**
311
+ * Builds an {@link EvmRelayer} over the provided {@link EvmRpc.EvmRpc}. `confirmations` overrides the network's
312
+ * default, as in `EvmIndexer.layer`: both agree on the last confirmed block. `fees` (default {@link defaultFees})
313
+ * prices the transactions signed without explicit fees, and `gasMultiplier` (default 1.2) is the margin applied to
314
+ * an estimated gas limit.
315
+ *
316
+ * @since 0.3.0
317
+ * @category layers
318
+ */
319
+ export const layer = (options: {
320
+ readonly confirmations?: number | undefined
321
+ readonly fees?: ((estimate: EvmFeeEstimate) => EvmFees) | undefined
322
+ readonly gasMultiplier?: number | undefined
323
+ } = {}): Layer.Layer<EvmRelayer, never, EvmRpc.EvmRpc> =>
324
+ Layer.effect(
325
+ EvmRelayer,
326
+ Effect.gen(function*() {
327
+ const rpc = yield* EvmRpc.EvmRpc
328
+ const chainId = EvmNetwork.toChainId(rpc.network)
329
+ const confirmations = options.confirmations ?? EvmNetwork.defaultConfirmations(rpc.network)
330
+ const gasPercent = BigInt(Math.round((options.gasMultiplier ?? 1.2) * 100))
331
+ const estimateFees = Effect.map(rpc.feeHistory(FEE_HISTORY), (history) =>
332
+ (options.fees ?? defaultFees)({
333
+ baseFeePerGas: Arr.lastNonEmpty(history.baseFeePerGas),
334
+ rewards: history.reward ?? []
335
+ }))
336
+ const sign = Effect.fn("EvmRelayer.sign")(
337
+ function*({ signer, to, data, value, ...given }: Parameters<EvmRelayer["Service"]["sign"]>[0]) {
338
+ const { fees, gas, nonce } = yield* Effect.all({
339
+ nonce: given.nonce === undefined
340
+ ? rpc.getTransactionCount({ address: signer.address, blockTag: "pending" })
341
+ : Effect.succeed(given.nonce),
342
+ gas: given.gas === undefined
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
+ )
355
+ )
356
+ : Effect.succeed(given.gas),
357
+ fees: given.fees === undefined ? estimateFees : Effect.succeed(given.fees)
358
+ }, { concurrency: "unbounded" })
359
+ const signed = yield* signer.signTransaction({ chainId, nonce, to, value, data, gas, ...fees })
360
+ return { hash: EvmTransactionHash.make(keccak256(signed)), signed, nonce }
361
+ }
362
+ )
363
+ const broadcast = Effect.fn("EvmRelayer.broadcast")(
364
+ function*({ signed }: { readonly signed: EvmHexData }) {
365
+ const sent = yield* Effect.result(rpc.sendRawTransaction({ signed }))
366
+ if (sent._tag === "Success") return sent.success
367
+ const cause = sent.failure
368
+ const hash = EvmTransactionHash.make(keccak256(signed))
369
+ const messages = messagesOf(cause)
370
+ if (alreadyKnown.test(messages)) return hash
371
+ const reason = refusals.find(([pattern]) => pattern.test(messages))?.[1]()
372
+ if (reason === undefined) return yield* cause
373
+ // a node that has this transaction in a block answers that its nonce is used
374
+ if (reason._tag === "InvalidNonce" && (yield* rpc.getTransactionByHash({ hash })) !== null) return hash
375
+ return yield* new EvmBroadcastError({ reason, cause })
376
+ }
377
+ )
378
+ const fetchTransactionStatus = Effect.fn("EvmRelayer.fetchTransactionStatus")(
379
+ function*({ hash }: EvmTransactionStatusOptions) {
380
+ const receipt = yield* rpc.getTransactionReceipt({ hash })
381
+ if (receipt === null) {
382
+ const transaction = yield* rpc.getTransactionByHash({ hash })
383
+ return transaction === null ? { _tag: "NotFound" } as const : { _tag: "Pending" } as const
384
+ }
385
+ // read after the receipt: a head older than the receipt's block could only delay `Confirmed`
386
+ const confirmed = Confirmations.lastConfirmedBlock(yield* rpc.blockNumber, confirmations)
387
+ const block = receipt.blockNumber
388
+ if (block > confirmed) return { _tag: "Included", block } as const
389
+ return receipt.status === 1
390
+ ? { _tag: "Confirmed", block } as const
391
+ : { _tag: "Failed", block, reason: undefined } as const
392
+ }
393
+ )
394
+ return EvmRelayer.of({
395
+ sign,
396
+ broadcast,
397
+ fetchTransactionStatus,
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"))
404
+ })
405
+ })
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,9 +1,8 @@
1
1
  /**
2
- * Typed, read-only 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 is a read, so retries and fallback
6
- * are safe. Methods are named after the JSON-RPC 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).
7
6
  *
8
7
  * @example
9
8
  * ```ts
@@ -42,9 +41,12 @@ import * as Ref from "effect/Ref"
42
41
  import * as Schema from "effect/Schema"
43
42
  import type { EvmAddress } from "./EvmAddress.ts"
44
43
  import type { EvmBlock } from "./EvmBlock.ts"
44
+ import type { EvmFeeHistory } from "./EvmFeeHistory.ts"
45
45
  import type { EvmHexData } from "./EvmHexData.ts"
46
46
  import type { EvmLog } from "./EvmLog.ts"
47
47
  import * as EvmNetwork from "./EvmNetwork.ts"
48
+ import type { EvmTransaction, EvmTransactionReceipt } from "./EvmTransaction.ts"
49
+ import type { EvmTransactionHash } from "./EvmTransactionHash.ts"
48
50
  import * as RpcMethods from "./internal/rpcMethods.ts"
49
51
 
50
52
  /**
@@ -59,9 +61,7 @@ export interface EvmRpcEndpoint {
59
61
  }
60
62
 
61
63
  /**
62
- * A failed call: its `reason` (a {@link JsonRpc.Reason}, matched with `Effect.catchReason`), the JSON-RPC error code or
63
- * HTTP status as `code`, and a `cause` without the endpoint URL. After several endpoints, the error is the last one
64
- * and `cause` is an `AggregateError` of each endpoint's error, in order.
64
+ * A failed call, with a {@link JsonRpc.Reason} as `reason`.
65
65
  *
66
66
  * On EVM, `Unavailable` includes the codes -32005, -32603, -32007, -1 and 429, `InvalidResponse` a log outside the
67
67
  * `getLogs` filter, and `Lagging` a head below the requested block.
@@ -100,6 +100,14 @@ export interface EvmLogsFilter {
100
100
  readonly topics?: ReadonlyArray<EvmHexData | ReadonlyArray<EvmHexData> | null> | undefined
101
101
  }
102
102
 
103
+ /**
104
+ * The block a state read is made at: `latest` is the head, `pending` adds the transactions of the node's pool.
105
+ *
106
+ * @since 0.3.0
107
+ * @category models
108
+ */
109
+ export type EvmBlockTag = "latest" | "pending"
110
+
103
111
  /**
104
112
  * @since 0.1.0
105
113
  * @category services
@@ -117,12 +125,85 @@ export class EvmRpc extends Context.Service<EvmRpc, {
117
125
  * requested one fails with `InvalidResponse`.
118
126
  */
119
127
  readonly getBlockByNumber: (options: { readonly blockNumber: bigint }) => Effect.Effect<EvmBlock, EvmRpcError>
128
+ /**
129
+ * `eth_getBalance`: the balance of `address` in wei at the end of `blockNumber`, only answered by an endpoint whose
130
+ * head has reached `blockNumber`. A block older than the endpoint's state history needs an archive endpoint: pruned
131
+ * nodes answer with provider-specific codes (-32000, -32602, -32603), which fall back but never map to `Pruned`.
132
+ *
133
+ * @since 0.3.0
134
+ */
135
+ readonly getBalance: (options: {
136
+ readonly address: EvmAddress
137
+ readonly blockNumber: bigint
138
+ }) => Effect.Effect<bigint, EvmRpcError>
120
139
  /**
121
140
  * `eth_getLogs`, only answered by an endpoint whose head has reached `toBlock`. Logs are returned in chain order:
122
141
  * sorted by block then log index. A removed, pending or out-of-filter log fails with `InvalidResponse`. An empty
123
142
  * range returns `[]`.
124
143
  */
125
144
  readonly getLogs: (filter: EvmLogsFilter) => Effect.Effect<ReadonlyArray<EvmLog>, EvmRpcError>
145
+ /**
146
+ * `eth_getTransactionByHash`: the transaction, pending or included, or `null` when the answering endpoint does not
147
+ * know it. `null` does not fall back: an endpoint behind the head or with another pool answers it too.
148
+ *
149
+ * @since 0.3.0
150
+ */
151
+ readonly getTransactionByHash: (options: {
152
+ readonly hash: EvmTransactionHash
153
+ }) => Effect.Effect<EvmTransaction | null, EvmRpcError>
154
+ /**
155
+ * `eth_getTransactionReceipt`: the receipt, or `null` until the answering endpoint has the transaction in a block.
156
+ * `null` does not fall back.
157
+ *
158
+ * @since 0.3.0
159
+ */
160
+ readonly getTransactionReceipt: (options: {
161
+ readonly hash: EvmTransactionHash
162
+ }) => Effect.Effect<EvmTransactionReceipt | null, EvmRpcError>
163
+ /**
164
+ * `eth_sendRawTransaction`: submits a signed transaction and returns its hash. A retry or a fallback sends the same
165
+ * bytes, so it never creates a second transaction, but a node that already has them refuses the second copy. A
166
+ * refusal (`already known`, `nonce too low`, `replacement transaction underpriced`, `insufficient funds`...) is
167
+ * `Rejected`, with the node's message in `cause`.
168
+ *
169
+ * @since 0.3.0
170
+ */
171
+ readonly sendRawTransaction: (options: {
172
+ readonly signed: EvmHexData
173
+ }) => Effect.Effect<EvmTransactionHash, EvmRpcError>
174
+ /**
175
+ * `eth_getTransactionCount`: the number of transactions sent by `address` at `blockTag`, which is the nonce of its
176
+ * next one. `pending` counts the transactions of the answering node's pool, which differs between nodes.
177
+ *
178
+ * @since 0.3.0
179
+ */
180
+ readonly getTransactionCount: (options: {
181
+ readonly address: EvmAddress
182
+ readonly blockTag: EvmBlockTag
183
+ }) => Effect.Effect<bigint, EvmRpcError>
184
+ /**
185
+ * `eth_estimateGas`: the gas a call from `from` to `to` needs at the head. A call that reverts is `Rejected`, with
186
+ * the node's message in `cause`.
187
+ *
188
+ * @since 0.3.0
189
+ */
190
+ readonly estimateGas: (options: {
191
+ readonly from: EvmAddress
192
+ readonly to: EvmAddress
193
+ readonly value?: bigint | undefined
194
+ readonly data?: EvmHexData | undefined
195
+ }) => Effect.Effect<bigint, EvmRpcError>
196
+ /**
197
+ * `eth_feeHistory`: the fees of the `blockCount` blocks ending at `newestBlock`, with the priority fees at
198
+ * `rewardPercentiles` (each between 0 and 100, in ascending order). A node may return fewer blocks.
199
+ *
200
+ * @since 0.3.0
201
+ */
202
+ readonly feeHistory: (options: {
203
+ readonly blockCount: number
204
+ readonly newestBlock: EvmBlockTag
205
+ readonly rewardPercentiles: ReadonlyArray<number>
206
+ }) => Effect.Effect<EvmFeeHistory, EvmRpcError>
126
207
  }>()("@effect-blockchain/evm/EvmRpc") {}
127
208
 
128
209
  // the JSON-RPC codes viem 2.57.11 retries (`utils/buildRequest.ts`, `shouldRetry`): limit exceeded, internal error,
@@ -235,16 +316,32 @@ export const layer = (options: {
235
316
  return Arr.sort(logs.map(({ removed: _removed, ...log }) => log), byBlockThenIndex)
236
317
  })
237
318
 
319
+ const callOn = <Params, A>(method: JsonRpc.Method<Params, A>, params: Params) =>
320
+ rpc.withFallback((endpoint) => rpc.call(endpoint, method, params))
321
+
238
322
  return EvmRpc.of({
239
323
  network,
240
324
  chainId: rpc.withFallback(rpc.checkNetwork),
241
325
  blockNumber: rpc.withFallback(blockNumberOn),
242
326
  getBlockByNumber: ({ blockNumber }) =>
243
327
  rpc.withFallback((endpoint) => getBlockByNumberOn(endpoint, blockNumber)),
328
+ getBalance: ({ address, blockNumber }) =>
329
+ rpc.withFallback((endpoint) =>
330
+ rpc.requireHead(endpoint, RpcMethods.getBalance.name, blockNumber, blockNumberOn(endpoint)).pipe(
331
+ Effect.andThen(rpc.call(endpoint, RpcMethods.getBalance, [address, blockNumber]))
332
+ )
333
+ ),
244
334
  getLogs: (filter) =>
245
335
  filter.fromBlock > filter.toBlock
246
336
  ? Effect.succeed([])
247
- : rpc.withFallback((endpoint) => getLogsOn(endpoint, filter))
337
+ : rpc.withFallback((endpoint) => getLogsOn(endpoint, filter)),
338
+ getTransactionByHash: ({ hash }) => callOn(RpcMethods.getTransactionByHash, [hash]),
339
+ getTransactionReceipt: ({ hash }) => callOn(RpcMethods.getTransactionReceipt, [hash]),
340
+ sendRawTransaction: ({ signed }) => callOn(RpcMethods.sendRawTransaction, [signed]),
341
+ getTransactionCount: ({ address, blockTag }) => callOn(RpcMethods.getTransactionCount, [address, blockTag]),
342
+ estimateGas: (call) => callOn(RpcMethods.estimateGas, [call]),
343
+ feeHistory: ({ blockCount, newestBlock, rewardPercentiles }) =>
344
+ callOn(RpcMethods.feeHistory, [blockCount, newestBlock, rewardPercentiles])
248
345
  })
249
346
  })
250
347
  )