@effect-blockchain/evm 0.2.0 → 0.3.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/dist/EvmFeeHistory.d.ts +26 -0
  2. package/dist/EvmFeeHistory.d.ts.map +1 -0
  3. package/dist/EvmFeeHistory.js +25 -0
  4. package/dist/EvmFeeHistory.js.map +1 -0
  5. package/dist/EvmIndexer.d.ts +45 -1
  6. package/dist/EvmIndexer.d.ts.map +1 -1
  7. package/dist/EvmIndexer.js +91 -26
  8. package/dist/EvmIndexer.js.map +1 -1
  9. package/dist/EvmRelayer.d.ts +200 -0
  10. package/dist/EvmRelayer.d.ts.map +1 -0
  11. package/dist/EvmRelayer.js +281 -0
  12. package/dist/EvmRelayer.js.map +1 -0
  13. package/dist/EvmRpc.d.ts +87 -3
  14. package/dist/EvmRpc.d.ts.map +1 -1
  15. package/dist/EvmRpc.js +29 -4
  16. package/dist/EvmRpc.js.map +1 -1
  17. package/dist/EvmSigner.d.ts +78 -0
  18. package/dist/EvmSigner.d.ts.map +1 -0
  19. package/dist/EvmSigner.js +98 -0
  20. package/dist/EvmSigner.js.map +1 -0
  21. package/dist/EvmTransaction.d.ts +65 -0
  22. package/dist/EvmTransaction.d.ts.map +1 -0
  23. package/dist/EvmTransaction.js +60 -0
  24. package/dist/EvmTransaction.js.map +1 -0
  25. package/dist/index.d.ts +16 -0
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +16 -0
  28. package/dist/index.js.map +1 -1
  29. package/dist/internal/confirmations.d.ts +2 -0
  30. package/dist/internal/confirmations.d.ts.map +1 -0
  31. package/dist/internal/confirmations.js +13 -0
  32. package/dist/internal/confirmations.js.map +1 -0
  33. package/dist/internal/rpcMethods.js +53 -0
  34. package/dist/internal/rpcMethods.js.map +1 -1
  35. package/package.json +1 -1
  36. package/src/EvmFeeHistory.ts +28 -0
  37. package/src/EvmIndexer.ts +136 -33
  38. package/src/EvmRelayer.ts +361 -0
  39. package/src/EvmRpc.ts +105 -4
  40. package/src/EvmSigner.ts +128 -0
  41. package/src/EvmTransaction.ts +64 -0
  42. package/src/index.ts +20 -0
  43. package/src/internal/confirmations.ts +17 -0
  44. package/src/internal/rpcMethods.ts +63 -0
package/src/EvmIndexer.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  /**
2
- * EVM log indexing on top of {@link EvmRpc.EvmRpc}: the last confirmed block, the logs of a set of contracts over a
3
- * block range, and a stream of them following the confirmed head.
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.
4
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.
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.
7
8
  *
8
9
  * @example
9
10
  * ```ts
@@ -27,6 +28,24 @@
27
28
  * })
28
29
  * ```
29
30
  *
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
+ * )
46
+ * })
47
+ * ```
48
+ *
30
49
  * @since 0.1.0
31
50
  */
32
51
  import * as JsonRpc from "@effect-blockchain/core/JsonRpc"
@@ -40,9 +59,10 @@ import * as Layer from "effect/Layer"
40
59
  import * as Option from "effect/Option"
41
60
  import * as Schedule from "effect/Schedule"
42
61
  import * as Stream from "effect/Stream"
62
+ import type { EvmAddress } from "./EvmAddress.ts"
43
63
  import type { EvmLog } from "./EvmLog.ts"
44
- import * as EvmNetwork from "./EvmNetwork.ts"
45
64
  import * as EvmRpc from "./EvmRpc.ts"
65
+ import * as Confirmations from "./internal/confirmations.ts"
46
66
 
47
67
  /**
48
68
  * A {@link EvmIndexer} `fetchLogs` filter: an `eth_getLogs` filter over the inclusive block range
@@ -89,6 +109,35 @@ export interface EvmIndexerStreamOptions {
89
109
  readonly retry?: Schedule.Schedule<unknown, EvmRpc.EvmRpcError> | undefined
90
110
  }
91
111
 
112
+ /**
113
+ * The native balance of an address in wei at the end of `block`, emitted by
114
+ * {@link EvmIndexer.Service.streamNativeBalance}.
115
+ *
116
+ * @since 0.3.0
117
+ * @category models
118
+ */
119
+ export interface EvmNativeBalance {
120
+ readonly block: bigint
121
+ readonly balance: bigint
122
+ }
123
+
124
+ /**
125
+ * The {@link EvmIndexer.Service.streamNativeBalance} options: one sample at `fromBlock`, then every `step` blocks.
126
+ * `step` is a positive safe integer, `poll` and `retry` work as in {@link EvmIndexerStreamOptions}.
127
+ *
128
+ * @since 0.3.0
129
+ * @category models
130
+ */
131
+ export interface EvmIndexerNativeBalanceOptions {
132
+ readonly address: EvmAddress
133
+ readonly fromBlock: bigint
134
+ /** The stream ends after the last sample not above it, and is empty when `fromBlock > toBlock`. */
135
+ readonly toBlock?: bigint | undefined
136
+ readonly step: number
137
+ readonly poll?: Schedule.Schedule<unknown> | undefined
138
+ readonly retry?: Schedule.Schedule<unknown, EvmRpc.EvmRpcError> | undefined
139
+ }
140
+
92
141
  /**
93
142
  * @since 0.1.0
94
143
  * @category services
@@ -106,6 +155,24 @@ export class EvmIndexer extends Context.Service<EvmIndexer, {
106
155
  * the confirmed head.
107
156
  */
108
157
  readonly streamLogs: (options: EvmIndexerStreamOptions) => Stream.Stream<EvmIndexerBatch, EvmRpc.EvmRpcError>
158
+ /**
159
+ * The native balance of `address` in wei at the end of `block`, which needs an archive endpoint for an old block.
160
+ *
161
+ * @since 0.3.0
162
+ */
163
+ readonly fetchNativeBalance: (options: {
164
+ readonly address: EvmAddress
165
+ readonly block: bigint
166
+ }) => Effect.Effect<bigint, EvmRpc.EvmRpcError>
167
+ /**
168
+ * The native balance of `address` at `fromBlock`, `fromBlock + step`, ... (a sample at every step, changed or not),
169
+ * each read once its block is confirmed, following the confirmed head.
170
+ *
171
+ * @since 0.3.0
172
+ */
173
+ readonly streamNativeBalance: (
174
+ options: EvmIndexerNativeBalanceOptions
175
+ ) => Stream.Stream<EvmNativeBalance, EvmRpc.EvmRpcError>
109
176
  }>()("@effect-blockchain/evm/EvmIndexer") {}
110
177
 
111
178
  /**
@@ -130,10 +197,12 @@ interface StreamPosition {
130
197
  readonly head: bigint
131
198
  }
132
199
 
200
+ type Page<A> = readonly [ReadonlyArray<A>, Option.Option<StreamPosition>]
201
+
133
202
  /**
134
203
  * Builds an {@link EvmIndexer} reading through the provided {@link EvmRpc.EvmRpc}.
135
204
  *
136
- * - `confirmations` overrides {@link EvmNetwork.defaultConfirmations} for the RPC's network.
205
+ * - `confirmations` overrides `EvmNetwork.defaultConfirmations` for the RPC's network.
137
206
  * - `maxBlockRange`, a positive integer, defaults to {@link DEFAULT_MAX_BLOCK_RANGE}.
138
207
  *
139
208
  * @since 0.1.0
@@ -151,12 +220,28 @@ export const layer = (options: {
151
220
  if (!Number.isSafeInteger(maxBlockRange) || maxBlockRange < 1) {
152
221
  return yield* Effect.die(new RangeError(`maxBlockRange must be a positive integer, got ${maxBlockRange}`))
153
222
  }
154
- const confirmations = BigInt(options.confirmations ?? EvmNetwork.defaultConfirmations(rpc.network))
155
223
  const size = BigInt(maxBlockRange)
156
- const lastConfirmedBlock = rpc.blockNumber.pipe(
157
- Effect.map((head) => BigInt_.max(head - confirmations, BigInt(0))),
224
+ const lastConfirmedBlock = Confirmations.lastConfirmedBlock(rpc, options.confirmations).pipe(
158
225
  Effect.withSpan("EvmIndexer.lastConfirmedBlock")
159
226
  )
227
+ // the head last read is reused while it covers `next` (the confirmed head only moves forward), else polled
228
+ const confirmedHead = (poll: Schedule.Schedule<unknown>, { head, next }: StreamPosition) =>
229
+ next <= head
230
+ ? Effect.succeed(head)
231
+ : lastConfirmedBlock.pipe(Effect.repeat({ schedule: poll, until: (confirmed) => confirmed >= next }))
232
+ const paginate = <A>(
233
+ start: bigint,
234
+ retry: Schedule.Schedule<unknown, EvmRpc.EvmRpcError> | undefined,
235
+ step: (position: StreamPosition) => Effect.Effect<Page<A>, EvmRpc.EvmRpcError>
236
+ ) =>
237
+ Stream.paginate(
238
+ // a head below `start`: the first step reads it
239
+ { next: start, head: start - BigInt(1) },
240
+ retry === undefined
241
+ ? step
242
+ : (position) =>
243
+ Effect.retry(step(position), { schedule: retry, while: (error) => JsonRpc.isTransient(error.reason) })
244
+ )
160
245
  const fetchLogs = Effect.fn("EvmIndexer.fetchLogs")((filter: EvmIndexerFilter) => {
161
246
  if (filter.fromBlock > filter.toBlock) return Effect.succeed([])
162
247
  const count = Number((filter.toBlock - filter.fromBlock) / size) + 1
@@ -166,38 +251,56 @@ export const layer = (options: {
166
251
  rpc.getLogs({ ...filter, fromBlock, toBlock: BigInt_.min(fromBlock + size - BigInt(1), filter.toBlock) })
167
252
  ).pipe(Effect.map(Arr.flatten))
168
253
  })
254
+ const fetchNativeBalance = Effect.fn("EvmIndexer.fetchNativeBalance")(
255
+ ({ address, block }: { readonly address: EvmAddress; readonly block: bigint }) =>
256
+ rpc.getBalance({ address, blockNumber: block })
257
+ )
169
258
  return EvmIndexer.of({
170
259
  lastConfirmedBlock,
171
260
  fetchLogs,
172
261
  streamLogs: ({ filter, fromBlock, poll = Schedule.spaced(DEFAULT_POLL_INTERVAL), retry, toBlock }) => {
173
262
  if (toBlock !== undefined && fromBlock > toBlock) return Stream.empty
174
- // the head last read is reused while it covers `next` (the confirmed head only moves forward), else polled
175
- const step = (
176
- { head, next }: StreamPosition
177
- ): Effect.Effect<
178
- readonly [ReadonlyArray<EvmIndexerBatch>, Option.Option<StreamPosition>],
179
- EvmRpc.EvmRpcError
180
- > =>
181
- (next <= head
182
- ? Effect.succeed(head)
183
- : lastConfirmedBlock.pipe(Effect.repeat({ schedule: poll, until: (confirmed) => confirmed >= next })))
184
- .pipe(Effect.flatMap((confirmed) => {
185
- const cap = toBlock === undefined ? confirmed : BigInt_.min(confirmed, toBlock)
186
- if (next > cap) return Effect.succeed([[], Option.none()])
187
- const end = BigInt_.min(next + size - BigInt(1), cap)
188
- return fetchLogs({ ...filter, fromBlock: next, toBlock: end }).pipe(Effect.map((logs) => [
263
+ return paginate(fromBlock, retry, (position) =>
264
+ confirmedHead(poll, position).pipe(Effect.flatMap((confirmed) => {
265
+ const { next } = position
266
+ const cap = toBlock === undefined ? confirmed : BigInt_.min(confirmed, toBlock)
267
+ if (next > cap) {
268
+ return Effect.succeed<Page<EvmIndexerBatch>>([[], Option.none()])
269
+ }
270
+ const end = BigInt_.min(next + size - BigInt(1), cap)
271
+ return fetchLogs({ ...filter, fromBlock: next, toBlock: end }).pipe(Effect.map((logs) =>
272
+ [
189
273
  [{ fromBlock: next, toBlock: end, logs }],
190
274
  end === toBlock ? Option.none() : Option.some({ next: end + BigInt(1), head: confirmed })
191
- ]))
192
- }))
193
- return Stream.paginate(
194
- // a head below `fromBlock`: the first step reads it
195
- { next: fromBlock, head: fromBlock - BigInt(1) },
196
- retry === undefined
197
- ? step
198
- : (remaining) =>
199
- Effect.retry(step(remaining), { schedule: retry, while: (error) => JsonRpc.isTransient(error.reason) })
200
- )
275
+ ] as const
276
+ ))
277
+ })))
278
+ },
279
+ fetchNativeBalance,
280
+ streamNativeBalance: (
281
+ { address, fromBlock, poll = Schedule.spaced(DEFAULT_POLL_INTERVAL), retry, step, toBlock }
282
+ ) => {
283
+ if (!Number.isSafeInteger(step) || step < 1) {
284
+ return Stream.die(new RangeError(`step must be a positive safe integer, got ${step}`))
285
+ }
286
+ if (toBlock !== undefined && fromBlock > toBlock) {
287
+ return Stream.empty
288
+ }
289
+ const stride = BigInt(step)
290
+ return paginate(fromBlock, retry, (position) =>
291
+ confirmedHead(poll, position).pipe(Effect.flatMap((confirmed) => {
292
+ const block = position.next
293
+ if (block > confirmed) {
294
+ return Effect.succeed<Page<EvmNativeBalance>>([[], Option.none()])
295
+ }
296
+ const next = block + stride
297
+ return fetchNativeBalance({ address, block }).pipe(Effect.map((balance) =>
298
+ [
299
+ [{ block, balance }],
300
+ toBlock !== undefined && next > toBlock ? Option.none() : Option.some({ next, head: confirmed })
301
+ ] as const
302
+ ))
303
+ })))
201
304
  }
202
305
  })
203
306
  })
@@ -0,0 +1,361 @@
1
+ /**
2
+ * EVM transaction relaying on top of {@link EvmRpc.EvmRpc}: signing a transaction, broadcasting it and following it
3
+ * until it is final.
4
+ *
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}:
21
+ *
22
+ * | status | meaning | final |
23
+ * |---|---|---|
24
+ * | `Pending` | known to the node, not in a block | no |
25
+ * | `Included` | in `block`, above the last confirmed block: a reorganisation can still move or drop it | no |
26
+ * | `Confirmed` | succeeded in `block`, at or below the last confirmed block | yes |
27
+ * | `Failed` | reverted in `block`, at or below the last confirmed block | yes |
28
+ * | `NotFound` | unknown to the node: dropped, not propagated yet, or never sent | no |
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * import type { EvmAddress } from "@effect-blockchain/evm/EvmAddress"
33
+ * import { EvmRelayer } from "@effect-blockchain/evm/EvmRelayer"
34
+ * import type { EvmSigner } from "@effect-blockchain/evm/EvmSigner"
35
+ * import type { EvmTransactionHash } from "@effect-blockchain/evm/EvmTransactionHash"
36
+ * import * as Effect from "effect/Effect"
37
+ *
38
+ * declare const signer: EvmSigner
39
+ * declare const to: EvmAddress
40
+ * declare const store: (hash: EvmTransactionHash, nonce: bigint) => Effect.Effect<void>
41
+ *
42
+ * const program = Effect.gen(function*() {
43
+ * const relayer = yield* EvmRelayer
44
+ * 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
+ * yield* store(hash, nonce)
47
+ * 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
+ * }
53
+ * })
54
+ * ```
55
+ *
56
+ * @since 0.3.0
57
+ */
58
+ import * as Arr from "effect/Array"
59
+ import * as BigInt_ from "effect/BigInt"
60
+ import * as Context from "effect/Context"
61
+ import * as Effect from "effect/Effect"
62
+ import * as Layer from "effect/Layer"
63
+ import * as Order from "effect/Order"
64
+ import * as Schedule from "effect/Schedule"
65
+ import * as Schema from "effect/Schema"
66
+ import { keccak256 } from "viem"
67
+ import type { EvmAddress } from "./EvmAddress.ts"
68
+ import type { EvmHexData } from "./EvmHexData.ts"
69
+ import { DEFAULT_POLL_INTERVAL } from "./EvmIndexer.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
+ import * as Confirmations from "./internal/confirmations.ts"
75
+
76
+ /**
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.
79
+ *
80
+ * @since 0.3.0
81
+ * @category models
82
+ */
83
+ export type EvmTransactionStatus =
84
+ | { readonly _tag: "Pending" }
85
+ | { readonly _tag: "Included"; readonly block: bigint }
86
+ | { readonly _tag: "Confirmed"; readonly block: bigint }
87
+ | { readonly _tag: "Failed"; readonly block: bigint; readonly reason: EvmHexData | undefined }
88
+ | { readonly _tag: "NotFound" }
89
+
90
+ /**
91
+ * 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
+ * block producer above the base fee.
93
+ *
94
+ * @since 0.3.0
95
+ * @category models
96
+ */
97
+ export interface EvmFees {
98
+ readonly maxFeePerGas: bigint
99
+ readonly maxPriorityFeePerGas: bigint
100
+ }
101
+
102
+ /**
103
+ * What a fee strategy decides from, read with `eth_feeHistory` over the last 10 blocks: `baseFeePerGas` is the base
104
+ * fee of the next block and `rewards` holds, per block from the oldest, the priority fee paid at the 25th, 50th and
105
+ * 75th percentiles of its gas. A node may return fewer blocks or no `rewards`, and an empty block reports zeros.
106
+ *
107
+ * @since 0.3.0
108
+ * @category models
109
+ */
110
+ export interface EvmFeeEstimate {
111
+ readonly baseFeePerGas: bigint
112
+ readonly rewards: ReadonlyArray<ReadonlyArray<bigint>>
113
+ }
114
+
115
+ /**
116
+ * A transaction signed by {@link EvmRelayer.sign}: `signed` is what `broadcast` takes, `hash` its transaction hash
117
+ * and `nonce` the nonce it uses.
118
+ *
119
+ * @since 0.3.0
120
+ * @category models
121
+ */
122
+ export interface EvmSignedTransaction {
123
+ readonly hash: EvmTransactionHash
124
+ readonly signed: EvmHexData
125
+ readonly nonce: bigint
126
+ }
127
+
128
+ /**
129
+ * The sender's nonce is already used by a transaction in a block, and the node does not know this one: another
130
+ * transaction took its place.
131
+ *
132
+ * @since 0.3.0
133
+ * @category reasons
134
+ */
135
+ export class NonceTooLow extends Schema.TaggedError<NonceTooLow>()("NonceTooLow", {}) {}
136
+
137
+ /**
138
+ * The node's pool holds another transaction at this nonce and the fees do not exceed its fees enough to replace it.
139
+ *
140
+ * @since 0.3.0
141
+ * @category reasons
142
+ */
143
+ export class ReplacementUnderpriced
144
+ extends Schema.TaggedError<ReplacementUnderpriced>()("ReplacementUnderpriced", {})
145
+ {}
146
+
147
+ /**
148
+ * The fees are below what the node accepts: `maxFeePerGas` under the base fee, or a priority fee under its minimum.
149
+ *
150
+ * @since 0.3.0
151
+ * @category reasons
152
+ */
153
+ export class FeeTooLow extends Schema.TaggedError<FeeTooLow>()("FeeTooLow", {}) {}
154
+
155
+ /**
156
+ * The sender's balance does not cover `value` plus `gas` times `maxFeePerGas`.
157
+ *
158
+ * @since 0.3.0
159
+ * @category reasons
160
+ */
161
+ export class InsufficientFunds extends Schema.TaggedError<InsufficientFunds>()("InsufficientFunds", {}) {}
162
+
163
+ /**
164
+ * Why a node refused a transaction, the `reason` of an {@link EvmBroadcastError}, matched with `Effect.catchReason`.
165
+ *
166
+ * @since 0.3.0
167
+ * @category reasons
168
+ */
169
+ export const EvmBroadcastReason = Schema.Union([NonceTooLow, ReplacementUnderpriced, FeeTooLow, InsufficientFunds])
170
+
171
+ /**
172
+ * @since 0.3.0
173
+ * @category reasons
174
+ */
175
+ export type EvmBroadcastReason = typeof EvmBroadcastReason.Type
176
+
177
+ /**
178
+ * A node refused the transaction for a `reason` the sender can act on: `cause` is the {@link EvmRpc.EvmRpcError}
179
+ * holding the node's message. Any other refusal stays an `EvmRpcError`.
180
+ *
181
+ * @since 0.3.0
182
+ * @category errors
183
+ */
184
+ export class EvmBroadcastError extends Schema.TaggedError<EvmBroadcastError>()("EvmBroadcastError", {
185
+ reason: EvmBroadcastReason,
186
+ cause: Schema.Defect()
187
+ }) {}
188
+
189
+ /**
190
+ * @since 0.3.0
191
+ * @category services
192
+ */
193
+ export class EvmRelayer extends Context.Service<EvmRelayer, {
194
+ /**
195
+ * 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.
198
+ */
199
+ readonly sign: (options: {
200
+ readonly signer: EvmSigner
201
+ readonly to: EvmAddress
202
+ readonly data?: EvmHexData | undefined
203
+ readonly value?: bigint | undefined
204
+ readonly nonce?: bigint | undefined
205
+ readonly gas?: bigint | undefined
206
+ readonly fees?: EvmFees | undefined
207
+ }) => Effect.Effect<EvmSignedTransaction, EvmRpc.EvmRpcError | EvmSignerError>
208
+ /**
209
+ * Sends a signed transaction with `eth_sendRawTransaction` and returns its hash. Sending the same bytes again is
210
+ * safe: a node answering that it already has the transaction, or that the nonce is used while it knows this hash,
211
+ * is a success.
212
+ */
213
+ readonly broadcast: (options: {
214
+ readonly signed: EvmHexData
215
+ }) => Effect.Effect<EvmTransactionHash, EvmBroadcastError | EvmRpc.EvmRpcError>
216
+ /**
217
+ * The status of the transaction as the answering endpoint sees it. An endpoint behind the head, or one that never
218
+ * received the transaction, answers `Pending` or `NotFound` for a transaction another one has in a block.
219
+ */
220
+ readonly fetchTransactionStatus: (options: {
221
+ readonly hash: EvmTransactionHash
222
+ }) => Effect.Effect<EvmTransactionStatus, EvmRpc.EvmRpcError>
223
+ /**
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.
227
+ */
228
+ readonly awaitConfirmation: (options: {
229
+ readonly hash: EvmTransactionHash
230
+ readonly poll?: Schedule.Schedule<unknown> | undefined
231
+ }) => Effect.Effect<EvmTransactionStatus, EvmRpc.EvmRpcError>
232
+ }>()("@effect-blockchain/evm/EvmRelayer") {}
233
+
234
+ // geth's default `miner.gasprice` (0.001 gwei): the lowest tip its block producers take
235
+ const PRIORITY_FEE_FLOOR = BigInt(1_000_000)
236
+
237
+ const FEE_HISTORY = { blockCount: 10, newestBlock: "latest", rewardPercentiles: [25, 50, 75] } as const
238
+
239
+ /**
240
+ * The library's fee strategy: the priority fee is the median over the blocks of their 50th percentile reward, at
241
+ * least 0.001 gwei, and `maxFeePerGas` is twice the next base fee plus that priority fee. Doubling the base fee keeps
242
+ * the transaction includable through 5 full blocks in a row, each raising the base fee by 12.5%.
243
+ *
244
+ * @since 0.3.0
245
+ * @category fees
246
+ */
247
+ export const defaultFees = (estimate: EvmFeeEstimate): EvmFees => {
248
+ const medians = Arr.sort(
249
+ Arr.filter(estimate.rewards.map((rewards) => rewards[1]), (reward) => reward !== undefined),
250
+ Order.BigInt
251
+ )
252
+ const maxPriorityFeePerGas = BigInt_.max(
253
+ medians[Math.floor(medians.length / 2)] ?? PRIORITY_FEE_FLOOR,
254
+ PRIORITY_FEE_FLOOR
255
+ )
256
+ return { maxFeePerGas: estimate.baseFeePerGas * BigInt(2) + maxPriorityFeePerGas, maxPriorityFeePerGas }
257
+ }
258
+
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
+ // the refusals of geth (`core/txpool/errors.go`, `core/error.go`), also used by erigon, reth and anvil, then those
267
+ // of Nethermind (`AcceptTxResult`), Besu and anvil that differ
268
+ const alreadyKnown = /already known|AlreadyKnown|known transaction|already imported/i
269
+ const refusals: ReadonlyArray<readonly [RegExp, () => EvmBroadcastReason]> = [
270
+ [/nonce too low|OldNonce/i, () => new NonceTooLow()],
271
+ [/replacement transaction underpriced|ReplacementNotAllowed/i, () => new ReplacementUnderpriced()],
272
+ [/insufficient funds|InsufficientFunds|exceeds transaction sender account balance/i, () => new InsufficientFunds()],
273
+ [/underpriced|less than block base fee|FeeTooLow|gas price below configured minimum/i, () => new FeeTooLow()]
274
+ ]
275
+
276
+ /**
277
+ * Builds an {@link EvmRelayer} over the provided {@link EvmRpc.EvmRpc}. `confirmations` overrides the network's
278
+ * default, as in `EvmIndexer.layer`: both agree on the last confirmed block. `fees` (default {@link defaultFees})
279
+ * prices the transactions signed without explicit fees, and `gasMultiplier` (default 1.2) is the margin applied to
280
+ * an estimated gas limit.
281
+ *
282
+ * @since 0.3.0
283
+ * @category layers
284
+ */
285
+ export const layer = (options: {
286
+ readonly confirmations?: number | undefined
287
+ readonly fees?: ((estimate: EvmFeeEstimate) => EvmFees) | undefined
288
+ readonly gasMultiplier?: number | undefined
289
+ } = {}): Layer.Layer<EvmRelayer, never, EvmRpc.EvmRpc> =>
290
+ Layer.effect(
291
+ EvmRelayer,
292
+ Effect.gen(function*() {
293
+ const rpc = yield* EvmRpc.EvmRpc
294
+ const chainId = EvmNetwork.toChainId(rpc.network)
295
+ const gasPercent = BigInt(Math.round((options.gasMultiplier ?? 1.2) * 100))
296
+ const estimateFees = Effect.map(rpc.feeHistory(FEE_HISTORY), (history) =>
297
+ (options.fees ?? defaultFees)({
298
+ baseFeePerGas: Arr.lastNonEmpty(history.baseFeePerGas),
299
+ rewards: history.reward ?? []
300
+ }))
301
+ const sign = Effect.fn("EvmRelayer.sign")(
302
+ function*({ signer, to, data, value, ...given }: Parameters<EvmRelayer["Service"]["sign"]>[0]) {
303
+ const { fees, gas, nonce } = yield* Effect.all({
304
+ nonce: given.nonce === undefined
305
+ ? rpc.getTransactionCount({ address: signer.address, blockTag: "pending" })
306
+ : Effect.succeed(given.nonce),
307
+ gas: given.gas === undefined
308
+ ? Effect.map(
309
+ rpc.estimateGas({ from: signer.address, to, value, data }),
310
+ (estimate) => estimate * gasPercent / BigInt(100)
311
+ )
312
+ : Effect.succeed(given.gas),
313
+ fees: given.fees === undefined ? estimateFees : Effect.succeed(given.fees)
314
+ }, { concurrency: "unbounded" })
315
+ const signed = yield* signer.signTransaction({ chainId, nonce, to, value, data, gas, ...fees })
316
+ return { hash: EvmTransactionHash.make(keccak256(signed)), signed, nonce }
317
+ }
318
+ )
319
+ const broadcast = Effect.fn("EvmRelayer.broadcast")(
320
+ function*({ signed }: { readonly signed: EvmHexData }) {
321
+ const sent = yield* Effect.result(rpc.sendRawTransaction({ signed }))
322
+ if (sent._tag === "Success") return sent.success
323
+ const cause = sent.failure
324
+ const hash = EvmTransactionHash.make(keccak256(signed))
325
+ const messages = messagesOf(cause).join("\n")
326
+ if (alreadyKnown.test(messages)) return hash
327
+ const reason = refusals.find(([pattern]) => pattern.test(messages))?.[1]()
328
+ if (reason === undefined) return yield* cause
329
+ // 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
331
+ return yield* new EvmBroadcastError({ reason, cause })
332
+ }
333
+ )
334
+ const fetchTransactionStatus = Effect.fn("EvmRelayer.fetchTransactionStatus")(
335
+ function*({ hash }: { readonly hash: EvmTransactionHash }) {
336
+ const receipt = yield* rpc.getTransactionReceipt({ hash })
337
+ if (receipt === null) {
338
+ const transaction = yield* rpc.getTransactionByHash({ hash })
339
+ return transaction === null ? { _tag: "NotFound" } as const : { _tag: "Pending" } as const
340
+ }
341
+ // 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)
343
+ const block = receipt.blockNumber
344
+ if (block > confirmed) return { _tag: "Included", block } as const
345
+ return receipt.status === 1
346
+ ? { _tag: "Confirmed", block } as const
347
+ : { _tag: "Failed", block, reason: undefined } as const
348
+ }
349
+ )
350
+ return EvmRelayer.of({
351
+ sign,
352
+ broadcast,
353
+ 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
+ )
359
+ })
360
+ })
361
+ )