@effect-blockchain/evm 0.0.0-stage → 0.2.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 (58) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/EvmAddress.d.ts +33 -0
  4. package/dist/EvmAddress.d.ts.map +1 -0
  5. package/dist/EvmAddress.js +43 -0
  6. package/dist/EvmAddress.js.map +1 -0
  7. package/dist/EvmBlock.d.ts +25 -0
  8. package/dist/EvmBlock.d.ts.map +1 -0
  9. package/dist/EvmBlock.js +25 -0
  10. package/dist/EvmBlock.js.map +1 -0
  11. package/dist/EvmHexData.d.ts +19 -0
  12. package/dist/EvmHexData.d.ts.map +1 -0
  13. package/dist/EvmHexData.js +31 -0
  14. package/dist/EvmHexData.js.map +1 -0
  15. package/dist/EvmIndexer.d.ts +115 -0
  16. package/dist/EvmIndexer.d.ts.map +1 -0
  17. package/dist/EvmIndexer.js +153 -0
  18. package/dist/EvmIndexer.js.map +1 -0
  19. package/dist/EvmLog.d.ts +32 -0
  20. package/dist/EvmLog.d.ts.map +1 -0
  21. package/dist/EvmLog.js +34 -0
  22. package/dist/EvmLog.js.map +1 -0
  23. package/dist/EvmNetwork.d.ts +74 -0
  24. package/dist/EvmNetwork.d.ts.map +1 -0
  25. package/dist/EvmNetwork.js +128 -0
  26. package/dist/EvmNetwork.js.map +1 -0
  27. package/dist/EvmRpc.d.ts +154 -0
  28. package/dist/EvmRpc.d.ts.map +1 -0
  29. package/dist/EvmRpc.js +174 -0
  30. package/dist/EvmRpc.js.map +1 -0
  31. package/dist/EvmTransactionHash.d.ts +19 -0
  32. package/dist/EvmTransactionHash.d.ts.map +1 -0
  33. package/dist/EvmTransactionHash.js +29 -0
  34. package/dist/EvmTransactionHash.js.map +1 -0
  35. package/dist/index.d.ts +36 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +37 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/internal/QuantityFromHex.d.ts +2 -0
  40. package/dist/internal/QuantityFromHex.d.ts.map +1 -0
  41. package/dist/internal/QuantityFromHex.js +23 -0
  42. package/dist/internal/QuantityFromHex.js.map +1 -0
  43. package/dist/internal/rpcMethods.d.ts +2 -0
  44. package/dist/internal/rpcMethods.d.ts.map +1 -0
  45. package/dist/internal/rpcMethods.js +46 -0
  46. package/dist/internal/rpcMethods.js.map +1 -0
  47. package/package.json +70 -3
  48. package/src/EvmAddress.ts +53 -0
  49. package/src/EvmBlock.ts +28 -0
  50. package/src/EvmHexData.ts +39 -0
  51. package/src/EvmIndexer.ts +222 -0
  52. package/src/EvmLog.ts +37 -0
  53. package/src/EvmNetwork.ts +176 -0
  54. package/src/EvmRpc.ts +272 -0
  55. package/src/EvmTransactionHash.ts +36 -0
  56. package/src/index.ts +45 -0
  57. package/src/internal/QuantityFromHex.ts +24 -0
  58. package/src/internal/rpcMethods.ts +43 -0
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Named EVM networks and their chain IDs.
3
+ *
4
+ * @since 0.1.0
5
+ */
6
+ import * as Option from "effect/Option"
7
+ import * as Schema from "effect/Schema"
8
+
9
+ /**
10
+ * @since 0.1.0
11
+ * @category constants
12
+ */
13
+ export const mainnets = [
14
+ "Ethereum",
15
+ "Polygon",
16
+ "Base",
17
+ "Arbitrum",
18
+ "Etherlink",
19
+ "Optimism",
20
+ "Avalanche",
21
+ "BnbSmartChain",
22
+ "Gnosis",
23
+ "Linea"
24
+ ] as const
25
+
26
+ /**
27
+ * `Anvil` is the local Foundry node with its default chain ID 31337: a node started with another `--chain-id` must use
28
+ * the network matching that ID, since the network check compares chain IDs.
29
+ *
30
+ * @since 0.1.0
31
+ * @category constants
32
+ */
33
+ export const testnets = [
34
+ "Sepolia",
35
+ "PolygonAmoy",
36
+ "BaseSepolia",
37
+ "ArbitrumSepolia",
38
+ "EtherlinkTestnet",
39
+ "OptimismSepolia",
40
+ "AvalancheFuji",
41
+ "BnbSmartChainTestnet",
42
+ "LineaSepolia",
43
+ "Anvil"
44
+ ] as const
45
+
46
+ /**
47
+ * Every supported network, mainnets first.
48
+ *
49
+ * @since 0.1.0
50
+ * @category constants
51
+ */
52
+ export const networks = [...mainnets, ...testnets] as const
53
+
54
+ /**
55
+ * @since 0.1.0
56
+ * @category schemas
57
+ */
58
+ export const EvmNetwork = Schema.Literals(networks).annotate({
59
+ identifier: "EvmNetwork",
60
+ title: "EVM network",
61
+ description: "a named EVM network e.g. \"Ethereum\", \"Polygon\", \"Arbitrum\""
62
+ })
63
+
64
+ /**
65
+ * @since 0.1.0
66
+ * @category models
67
+ */
68
+ export type EvmNetwork = typeof EvmNetwork.Type
69
+
70
+ /**
71
+ * An EIP-155 chain ID: a positive integer.
72
+ *
73
+ * @since 0.1.0
74
+ * @category schemas
75
+ */
76
+ export const EvmChainId = Schema.Int.check(Schema.isGreaterThan(0)).pipe(
77
+ Schema.brand("EvmChainId"),
78
+ Schema.annotate({
79
+ identifier: "EvmChainId",
80
+ title: "EVM chain ID",
81
+ description: "an EIP-155 chain ID, a positive integer e.g. 1 for Ethereum"
82
+ })
83
+ )
84
+
85
+ /**
86
+ * @since 0.1.0
87
+ * @category models
88
+ */
89
+ export type EvmChainId = typeof EvmChainId.Type
90
+
91
+ const chainIds: Record<EvmNetwork, number> = {
92
+ Ethereum: 1,
93
+ Sepolia: 11155111,
94
+ Polygon: 137,
95
+ PolygonAmoy: 80002,
96
+ Base: 8453,
97
+ BaseSepolia: 84532,
98
+ Arbitrum: 42161,
99
+ ArbitrumSepolia: 421614,
100
+ Etherlink: 42793,
101
+ EtherlinkTestnet: 128123,
102
+ Optimism: 10,
103
+ OptimismSepolia: 11155420,
104
+ Avalanche: 43114,
105
+ AvalancheFuji: 43113,
106
+ BnbSmartChain: 56,
107
+ BnbSmartChainTestnet: 97,
108
+ Gnosis: 100,
109
+ Linea: 59144,
110
+ LineaSepolia: 59141,
111
+ Anvil: 31337
112
+ }
113
+
114
+ /**
115
+ * @since 0.1.0
116
+ * @category conversions
117
+ */
118
+ export const toChainId = (network: EvmNetwork): EvmChainId => EvmChainId.make(chainIds[network])
119
+
120
+ /**
121
+ * Returns the named network for a chain ID, or `None` when the chain is not in {@link networks}.
122
+ *
123
+ * @since 0.1.0
124
+ * @category conversions
125
+ */
126
+ export const fromChainId = (chainId: number): Option.Option<EvmNetwork> =>
127
+ Option.fromNullishOr(networks.find((network) => chainIds[network] === chainId))
128
+
129
+ /**
130
+ * @since 0.1.0
131
+ * @category predicates
132
+ */
133
+ export const isTestnet = (network: EvmNetwork): boolean => (testnets as ReadonlyArray<EvmNetwork>).includes(network)
134
+
135
+ // testnets reuse their mainnet value: same consensus and block time
136
+ const confirmations: Record<EvmNetwork, number> = {
137
+ // 2 epochs, Kraken credits at finalization "typically after 64-96": https://support.kraken.com/articles/203325283
138
+ Ethereum: 64,
139
+ Sepolia: 64,
140
+ // milestones finalize in 2-5s since Heimdall v2: https://docs.polygon.technology/pos/concepts/finality/finality/
141
+ Polygon: 32,
142
+ PolygonAmoy: 32,
143
+ // ~1 min of 2s blocks against sequencer reorgs: https://docs.optimism.io/stack/transactions/transaction-finality
144
+ Base: 30,
145
+ BaseSepolia: 30,
146
+ // ~1 min of 0.25s blocks: https://docs.arbitrum.io/how-arbitrum-works/reference/finality-and-reorgs
147
+ Arbitrum: 240,
148
+ ArbitrumSepolia: 240,
149
+ // confirmed on Tezos L1 in ~6s: https://docs.etherlink.com
150
+ Etherlink: 20,
151
+ EtherlinkTestnet: 20,
152
+ // Pionex uses 27 for Optimism: https://intercom.help/pionex/en/articles/14700793-what-is-block-confirmation
153
+ Optimism: 30,
154
+ OptimismSepolia: 30,
155
+ // Snowman finality is irreversible, Circle uses 1: https://developers.circle.com/circle-mint/blockchain-confirmations
156
+ Avalanche: 1,
157
+ AvalancheFuji: 1,
158
+ // Kraken uses 50 (fast finality in 2 blocks): https://support.kraken.com/articles/203325283
159
+ BnbSmartChain: 50,
160
+ BnbSmartChainTestnet: 50,
161
+ // 2 epochs of 16 slots: https://docs.gnosischain.com/about/specs/consensus/
162
+ Gnosis: 32,
163
+ // ~1 min of 2s blocks, Circle Fast Transfer uses 1: https://developers.circle.com/cctp/required-block-confirmations
164
+ Linea: 30,
165
+ LineaSepolia: 30,
166
+ // local node mines instantly and never reorgs: https://getfoundry.sh/anvil/overview
167
+ Anvil: 0
168
+ }
169
+
170
+ /**
171
+ * The number of blocks behind the head after which a block is treated as final by default.
172
+ *
173
+ * @since 0.1.0
174
+ * @category getters
175
+ */
176
+ export const defaultConfirmations = (network: EvmNetwork): number => confirmations[network]
package/src/EvmRpc.ts ADDED
@@ -0,0 +1,272 @@
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`).
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import type { EvmLog } from "@effect-blockchain/evm/EvmLog"
11
+ * import * as EvmRpc from "@effect-blockchain/evm/EvmRpc"
12
+ * import * as Effect from "effect/Effect"
13
+ *
14
+ * // dates logs with one `eth_getBlockByNumber` per distinct block
15
+ * const withTimestamps = (logs: ReadonlyArray<EvmLog>) =>
16
+ * Effect.gen(function*() {
17
+ * const rpc = yield* EvmRpc.EvmRpc
18
+ * const blocks = yield* Effect.forEach(
19
+ * new Set(logs.map((log) => log.blockNumber)),
20
+ * (blockNumber) => rpc.getBlockByNumber({ blockNumber }),
21
+ * { concurrency: 4 }
22
+ * )
23
+ * const timestamps = new Map(blocks.map((block) => [block.number, block.timestamp]))
24
+ * return logs.map((log) => ({ ...log, timestamp: timestamps.get(log.blockNumber) }))
25
+ * })
26
+ * ```
27
+ *
28
+ * @since 0.1.0
29
+ */
30
+ import * as JsonRpc from "@effect-blockchain/core/JsonRpc"
31
+ import * as Arr from "effect/Array"
32
+ import * as BigInt_ from "effect/BigInt"
33
+ import * as Config from "effect/Config"
34
+ import * as Context from "effect/Context"
35
+ import type * as Duration from "effect/Duration"
36
+ import * as Effect from "effect/Effect"
37
+ import type * as HttpClient from "effect/http/HttpClient"
38
+ import * as Layer from "effect/Layer"
39
+ import * as Order from "effect/Order"
40
+ import type * as Redacted from "effect/Redacted"
41
+ import * as Ref from "effect/Ref"
42
+ import * as Schema from "effect/Schema"
43
+ import type { EvmAddress } from "./EvmAddress.ts"
44
+ import type { EvmBlock } from "./EvmBlock.ts"
45
+ import type { EvmHexData } from "./EvmHexData.ts"
46
+ import type { EvmLog } from "./EvmLog.ts"
47
+ import * as EvmNetwork from "./EvmNetwork.ts"
48
+ import * as RpcMethods from "./internal/rpcMethods.ts"
49
+
50
+ /**
51
+ * A JSON-RPC endpoint. The `name` is shown in errors and spans, the `url` is never logged.
52
+ *
53
+ * @since 0.1.0
54
+ * @category models
55
+ */
56
+ export interface EvmRpcEndpoint {
57
+ readonly name: string
58
+ readonly url: Redacted.Redacted<string>
59
+ }
60
+
61
+ /**
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.
65
+ *
66
+ * On EVM, `Unavailable` includes the codes -32005, -32603, -32007, -1 and 429, `InvalidResponse` a log outside the
67
+ * `getLogs` filter, and `Lagging` a head below the requested block.
68
+ *
69
+ * @since 0.1.0
70
+ * @category errors
71
+ */
72
+ export class EvmRpcError extends Schema.TaggedError<EvmRpcError>()("EvmRpcError", {
73
+ reason: JsonRpc.Reason,
74
+ method: Schema.String,
75
+ endpoint: Schema.String,
76
+ code: Schema.optional(Schema.Number),
77
+ cause: Schema.Defect()
78
+ }) {
79
+ /**
80
+ * @since 0.1.0
81
+ */
82
+ override get message(): string {
83
+ return `${this.method} failed on ${this.endpoint}: ${this.reason._tag}${
84
+ this.code === undefined ? "" : ` (${this.code})`
85
+ }`
86
+ }
87
+ }
88
+
89
+ /**
90
+ * An `eth_getLogs` filter over the inclusive block range `[fromBlock, toBlock]`, matching the logs of any of
91
+ * `addresses`. The addresses are always sent as the JSON-RPC `address` array.
92
+ *
93
+ * @since 0.1.0
94
+ * @category models
95
+ */
96
+ export interface EvmLogsFilter {
97
+ readonly addresses: Arr.NonEmptyReadonlyArray<EvmAddress>
98
+ readonly fromBlock: bigint
99
+ readonly toBlock: bigint
100
+ readonly topics?: ReadonlyArray<EvmHexData | ReadonlyArray<EvmHexData> | null> | undefined
101
+ }
102
+
103
+ /**
104
+ * @since 0.1.0
105
+ * @category services
106
+ */
107
+ export class EvmRpc extends Context.Service<EvmRpc, {
108
+ readonly network: EvmNetwork.EvmNetwork
109
+ /** `eth_chainId`, verified against `network` once per endpoint then served from that check. */
110
+ readonly chainId: Effect.Effect<EvmNetwork.EvmChainId, EvmRpcError>
111
+ /** `eth_blockNumber` */
112
+ readonly blockNumber: Effect.Effect<bigint, EvmRpcError>
113
+ /**
114
+ * `eth_getBlockByNumber` without the transactions, only answered by an endpoint whose head has reached
115
+ * `blockNumber`. A block unknown to an endpoint past it (`null`) fails with `Lagging`: every node keeps the headers
116
+ * of its chain, so the reply came from a backend node behind the provider's head. A block whose `number` is not the
117
+ * requested one fails with `InvalidResponse`.
118
+ */
119
+ readonly getBlockByNumber: (options: { readonly blockNumber: bigint }) => Effect.Effect<EvmBlock, EvmRpcError>
120
+ /**
121
+ * `eth_getLogs`, only answered by an endpoint whose head has reached `toBlock`. Logs are returned in chain order:
122
+ * sorted by block then log index. A removed, pending or out-of-filter log fails with `InvalidResponse`. An empty
123
+ * range returns `[]`.
124
+ */
125
+ readonly getLogs: (filter: EvmLogsFilter) => Effect.Effect<ReadonlyArray<EvmLog>, EvmRpcError>
126
+ }>()("@effect-blockchain/evm/EvmRpc") {}
127
+
128
+ // the JSON-RPC codes viem 2.57.11 retries (`utils/buildRequest.ts`, `shouldRetry`): limit exceeded, internal error,
129
+ // QuickNode rate limit, unknown error and Alchemy's batch rate limit. The endpoint is struggling: retry then fall back
130
+ const codes: ReadonlyMap<number, JsonRpc.CodeReason> = new Map(
131
+ [-32005, -32603, -32007, -1, 429].map((code) => [code, "Unavailable"])
132
+ )
133
+
134
+ const byBlockThenIndex = Order.combine(
135
+ Order.mapInput(Order.BigInt, (log: EvmLog) => log.blockNumber),
136
+ Order.mapInput(Order.Number, (log: EvmLog) => log.logIndex)
137
+ )
138
+
139
+ /**
140
+ * Builds an {@link EvmRpc} over `endpoints`, tried in order, sending requests with the provided `HttpClient`
141
+ * (e.g. `FetchHttpClient.layer`). `timeout` (default 30 seconds) bounds each attempt, `retries` (default 3) and
142
+ * `retryDelay` (default 500 millis) set the backoff before falling back: see {@link JsonRpc.Unavailable}.
143
+ *
144
+ * @since 0.1.0
145
+ * @category layers
146
+ */
147
+ export const layer = (options: {
148
+ readonly network: EvmNetwork.EvmNetwork
149
+ readonly endpoints: Arr.NonEmptyReadonlyArray<EvmRpcEndpoint>
150
+ readonly timeout?: Duration.Input | undefined
151
+ readonly retries?: number | undefined
152
+ readonly retryDelay?: Duration.Input | undefined
153
+ }): Layer.Layer<EvmRpc, never, HttpClient.HttpClient> =>
154
+ Layer.effect(
155
+ EvmRpc,
156
+ Effect.gen(function*() {
157
+ const { network } = options
158
+ const expectedChainId = EvmNetwork.toChainId(network)
159
+ const rpc = yield* JsonRpc.make({
160
+ spanPrefix: "EvmRpc",
161
+ network,
162
+ endpoints: options.endpoints,
163
+ timeout: options.timeout,
164
+ retries: options.retries,
165
+ retryDelay: options.retryDelay,
166
+ codes,
167
+ checkNetwork: (send, endpoint) =>
168
+ send(RpcMethods.chainId, []).pipe(
169
+ Effect.flatMap((chainId) =>
170
+ chainId === expectedChainId ?
171
+ Effect.succeed(expectedChainId) :
172
+ Effect.fail(
173
+ new EvmRpcError({
174
+ reason: new JsonRpc.WrongNetwork({ expected: String(expectedChainId), actual: String(chainId) }),
175
+ method: RpcMethods.chainId.name,
176
+ endpoint,
177
+ cause: new Error(`expected chain ID ${expectedChainId} for ${network}, got ${chainId}`)
178
+ })
179
+ )
180
+ )
181
+ ),
182
+ makeError: (fields: JsonRpc.ErrorFields) => new EvmRpcError(fields)
183
+ })
184
+ type Endpoint = JsonRpc.Endpoint<EvmNetwork.EvmChainId, EvmRpcError>
185
+
186
+ const blockNumberOn = (endpoint: Endpoint) =>
187
+ rpc.call(endpoint, RpcMethods.blockNumber, []).pipe(
188
+ Effect.tap((head) => Ref.update(endpoint.head, BigInt_.max(head)))
189
+ )
190
+
191
+ const getBlockByNumberOn = (endpoint: Endpoint, blockNumber: bigint) =>
192
+ Effect.gen(function*() {
193
+ const method = RpcMethods.getBlockByNumber.name
194
+ yield* rpc.requireHead(endpoint, method, blockNumber, blockNumberOn(endpoint))
195
+ const block = yield* rpc.call(endpoint, RpcMethods.getBlockByNumber, [blockNumber, false])
196
+ if (block === null) {
197
+ const head = yield* Ref.get(endpoint.head)
198
+ return yield* rpc.fail(
199
+ endpoint,
200
+ method,
201
+ new JsonRpc.Lagging({ head, toBlock: blockNumber }),
202
+ new Error(`block ${blockNumber} is unknown below head ${head}`)
203
+ )
204
+ }
205
+ if (block.number !== blockNumber) {
206
+ return yield* rpc.fail(
207
+ endpoint,
208
+ method,
209
+ new JsonRpc.InvalidResponse(),
210
+ new Error(`block ${block.number} answered for block ${blockNumber}`)
211
+ )
212
+ }
213
+ return block
214
+ })
215
+
216
+ const getLogsOn = (endpoint: Endpoint, filter: EvmLogsFilter) =>
217
+ Effect.gen(function*() {
218
+ const method = RpcMethods.getLogs.name
219
+ yield* rpc.requireHead(endpoint, method, filter.toBlock, blockNumberOn(endpoint))
220
+ const { addresses, ...range } = filter
221
+ const logs = yield* rpc.call(endpoint, RpcMethods.getLogs, [{ ...range, address: addresses }])
222
+ const allowed = new Set<string>(addresses)
223
+ const invalid = logs.find((log) =>
224
+ log.blockNumber < filter.fromBlock || log.blockNumber > filter.toBlock ||
225
+ !allowed.has(log.address)
226
+ )
227
+ if (invalid !== undefined) {
228
+ return yield* rpc.fail(
229
+ endpoint,
230
+ method,
231
+ new JsonRpc.InvalidResponse(),
232
+ new Error(`log ${invalid.transactionHash}#${invalid.logIndex} is outside the filter`)
233
+ )
234
+ }
235
+ return Arr.sort(logs.map(({ removed: _removed, ...log }) => log), byBlockThenIndex)
236
+ })
237
+
238
+ return EvmRpc.of({
239
+ network,
240
+ chainId: rpc.withFallback(rpc.checkNetwork),
241
+ blockNumber: rpc.withFallback(blockNumberOn),
242
+ getBlockByNumber: ({ blockNumber }) =>
243
+ rpc.withFallback((endpoint) => getBlockByNumberOn(endpoint, blockNumber)),
244
+ getLogs: (filter) =>
245
+ filter.fromBlock > filter.toBlock
246
+ ? Effect.succeed([])
247
+ : rpc.withFallback((endpoint) => getLogsOn(endpoint, filter))
248
+ })
249
+ })
250
+ )
251
+
252
+ /**
253
+ * Builds an {@link EvmRpc} like {@link layer}, reading the options from `Config`. Endpoint URLs stay `Redacted`.
254
+ *
255
+ * @example
256
+ * ```ts
257
+ * import * as EvmRpc from "@effect-blockchain/evm/EvmRpc"
258
+ * import * as Config from "effect/Config"
259
+ *
260
+ * const RpcLive = EvmRpc.layerConfig({
261
+ * network: Config.succeed("Ethereum"),
262
+ * endpoints: Config.all([Config.all({ name: Config.succeed("main"), url: Config.Redacted("ETHEREUM_RPC_URL") })])
263
+ * })
264
+ * ```
265
+ *
266
+ * @since 0.1.0
267
+ * @category layers
268
+ */
269
+ export const layerConfig = (
270
+ options: Config.Wrap<Parameters<typeof layer>[0]>
271
+ ): Layer.Layer<EvmRpc, Config.ConfigError, HttpClient.HttpClient> =>
272
+ Layer.unwrap(Effect.map(Config.unwrap(options), layer))
@@ -0,0 +1,36 @@
1
+ /**
2
+ * EVM transaction hashes.
3
+ *
4
+ * @since 0.1.0
5
+ */
6
+ import * as Schema from "effect/Schema"
7
+ import * as SchemaTransformation from "effect/SchemaTransformation"
8
+ import { isHash } from "viem"
9
+
10
+ const evmTransactionHashRegex = /^0x[a-f0-9]{64}$/
11
+
12
+ /**
13
+ * An EVM transaction hash (0x followed by 64 hexadecimal characters), stored lowercase.
14
+ *
15
+ * @since 0.1.0
16
+ * @category schemas
17
+ */
18
+ export const EvmTransactionHash = Schema.String.pipe(
19
+ Schema.decodeTo(Schema.String.check(Schema.isLowercased()), SchemaTransformation.toLowerCase()),
20
+ Schema.refine((hash: string): hash is `0x${string}` => isHash(hash), {
21
+ expected: "a valid EVM transaction hash",
22
+ arbitraryConstraint: { patterns: [{ source: evmTransactionHashRegex.source, flags: "" }] }
23
+ }),
24
+ Schema.brand("EvmTransactionHash"),
25
+ Schema.annotate({
26
+ identifier: "EvmTransactionHash",
27
+ title: "EVM transaction hash",
28
+ description: "a valid EVM transaction hash, starting with 0x and followed by 64 hexadecimal characters"
29
+ })
30
+ )
31
+
32
+ /**
33
+ * @since 0.1.0
34
+ * @category models
35
+ */
36
+ export type EvmTransactionHash = typeof EvmTransactionHash.Type
package/src/index.ts ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * @since 0.1.0
3
+ */
4
+
5
+ // @barrel: Auto-generated exports. Do not edit manually.
6
+
7
+ /**
8
+ * @since 0.1.0
9
+ */
10
+ export * as EvmAddress from "./EvmAddress.ts"
11
+
12
+ /**
13
+ * @since 0.1.0
14
+ */
15
+ export * as EvmBlock from "./EvmBlock.ts"
16
+
17
+ /**
18
+ * @since 0.1.0
19
+ */
20
+ export * as EvmHexData from "./EvmHexData.ts"
21
+
22
+ /**
23
+ * @since 0.1.0
24
+ */
25
+ export * as EvmIndexer from "./EvmIndexer.ts"
26
+
27
+ /**
28
+ * @since 0.1.0
29
+ */
30
+ export * as EvmLog from "./EvmLog.ts"
31
+
32
+ /**
33
+ * @since 0.1.0
34
+ */
35
+ export * as EvmNetwork from "./EvmNetwork.ts"
36
+
37
+ /**
38
+ * @since 0.1.0
39
+ */
40
+ export * as EvmRpc from "./EvmRpc.ts"
41
+
42
+ /**
43
+ * @since 0.1.0
44
+ */
45
+ export * as EvmTransactionHash from "./EvmTransactionHash.ts"
@@ -0,0 +1,24 @@
1
+ import * as Schema from "effect/Schema"
2
+ import * as SchemaTransformation from "effect/SchemaTransformation"
3
+
4
+ const HexQuantity = Schema.String.check(Schema.isPattern(/^0x[0-9a-fA-F]+$/))
5
+
6
+ const toHex = (value: bigint | number) => `0x${value.toString(16)}`
7
+
8
+ /**
9
+ * A JSON-RPC hex quantity (`"0x10"`) decoded to a `bigint`, e.g. a block number.
10
+ *
11
+ * @internal
12
+ */
13
+ export const QuantityFromHex = HexQuantity.pipe(
14
+ Schema.decodeTo(Schema.BigInt, SchemaTransformation.transform({ decode: BigInt, encode: toHex }))
15
+ )
16
+
17
+ /**
18
+ * A JSON-RPC hex quantity decoded to a safe integer `number`, e.g. a chain ID or a log index.
19
+ *
20
+ * @internal
21
+ */
22
+ export const IntFromHex = HexQuantity.pipe(
23
+ Schema.decodeTo(Schema.Int, SchemaTransformation.transform({ decode: Number, encode: toHex }))
24
+ )
@@ -0,0 +1,43 @@
1
+ import * as JsonRpc from "@effect-blockchain/core/JsonRpc"
2
+ import * as Schema from "effect/Schema"
3
+ import { EvmAddress } from "../EvmAddress.ts"
4
+ import { EvmBlock } from "../EvmBlock.ts"
5
+ import { EvmHexData } from "../EvmHexData.ts"
6
+ import { EvmLog } from "../EvmLog.ts"
7
+ import { IntFromHex, QuantityFromHex } from "./QuantityFromHex.ts"
8
+
9
+ const make = <Params, Result>(method: JsonRpc.Method<Params, Result>): JsonRpc.Method<Params, Result> => method
10
+
11
+ const NoParams = Schema.Tuple([])
12
+
13
+ const Topics = Schema.Array(Schema.NullOr(Schema.Union([EvmHexData, Schema.Array(EvmHexData)])))
14
+
15
+ /** @internal */
16
+ export const chainId = make({ name: "eth_chainId", params: NoParams, result: IntFromHex })
17
+
18
+ /** @internal */
19
+ export const blockNumber = make({ name: "eth_blockNumber", params: NoParams, result: QuantityFromHex })
20
+
21
+ /** @internal */
22
+ export const getBlockByNumber = make({
23
+ name: "eth_getBlockByNumber",
24
+ // `false`: transaction hashes only, never the full transactions
25
+ params: Schema.Tuple([QuantityFromHex, Schema.Literal(false)]),
26
+ // `null` when the node does not know the block
27
+ result: Schema.NullOr(EvmBlock)
28
+ })
29
+
30
+ /** @internal */
31
+ export const getLogs = make({
32
+ name: "eth_getLogs",
33
+ params: Schema.Tuple([
34
+ Schema.Struct({
35
+ address: Schema.Array(EvmAddress),
36
+ fromBlock: QuantityFromHex,
37
+ toBlock: QuantityFromHex,
38
+ topics: JsonRpc.optionalOmitted(Topics)
39
+ })
40
+ ]),
41
+ // a log dropped by a reorg comes back with `removed: true` and must not be returned
42
+ result: Schema.Array(Schema.Struct({ ...EvmLog.fields, removed: Schema.optionalKey(Schema.Literal(false)) }))
43
+ })