@effect-blockchain/starknet 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 (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/StarknetAddress.d.ts +29 -0
  4. package/dist/StarknetAddress.d.ts.map +1 -0
  5. package/dist/StarknetAddress.js +29 -0
  6. package/dist/StarknetAddress.js.map +1 -0
  7. package/dist/StarknetBlock.d.ts +49 -0
  8. package/dist/StarknetBlock.d.ts.map +1 -0
  9. package/dist/StarknetBlock.js +52 -0
  10. package/dist/StarknetBlock.js.map +1 -0
  11. package/dist/StarknetEvent.d.ts +34 -0
  12. package/dist/StarknetEvent.d.ts.map +1 -0
  13. package/dist/StarknetEvent.js +39 -0
  14. package/dist/StarknetEvent.js.map +1 -0
  15. package/dist/StarknetIndexer.d.ts +157 -0
  16. package/dist/StarknetIndexer.d.ts.map +1 -0
  17. package/dist/StarknetIndexer.js +245 -0
  18. package/dist/StarknetIndexer.js.map +1 -0
  19. package/dist/StarknetNetwork.d.ts +72 -0
  20. package/dist/StarknetNetwork.d.ts.map +1 -0
  21. package/dist/StarknetNetwork.js +83 -0
  22. package/dist/StarknetNetwork.js.map +1 -0
  23. package/dist/StarknetRelayer.d.ts +273 -0
  24. package/dist/StarknetRelayer.d.ts.map +1 -0
  25. package/dist/StarknetRelayer.js +352 -0
  26. package/dist/StarknetRelayer.js.map +1 -0
  27. package/dist/StarknetRpc.d.ts +306 -0
  28. package/dist/StarknetRpc.d.ts.map +1 -0
  29. package/dist/StarknetRpc.js +281 -0
  30. package/dist/StarknetRpc.js.map +1 -0
  31. package/dist/StarknetSigner.d.ts +75 -0
  32. package/dist/StarknetSigner.d.ts.map +1 -0
  33. package/dist/StarknetSigner.js +84 -0
  34. package/dist/StarknetSigner.js.map +1 -0
  35. package/dist/StarknetTransaction.d.ts +74 -0
  36. package/dist/StarknetTransaction.d.ts.map +1 -0
  37. package/dist/StarknetTransaction.js +2 -0
  38. package/dist/StarknetTransaction.js.map +1 -0
  39. package/dist/StarknetTransactionHash.d.ts +22 -0
  40. package/dist/StarknetTransactionHash.d.ts.map +1 -0
  41. package/dist/StarknetTransactionHash.js +22 -0
  42. package/dist/StarknetTransactionHash.js.map +1 -0
  43. package/dist/index.d.ts +44 -0
  44. package/dist/index.d.ts.map +1 -0
  45. package/dist/index.js +45 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/internal/PaddedFelt.d.ts +2 -0
  48. package/dist/internal/PaddedFelt.d.ts.map +1 -0
  49. package/dist/internal/PaddedFelt.js +15 -0
  50. package/dist/internal/PaddedFelt.js.map +1 -0
  51. package/dist/internal/confirmations.d.ts +2 -0
  52. package/dist/internal/confirmations.d.ts.map +1 -0
  53. package/dist/internal/confirmations.js +13 -0
  54. package/dist/internal/confirmations.js.map +1 -0
  55. package/dist/internal/rpcMethods.d.ts +2 -0
  56. package/dist/internal/rpcMethods.d.ts.map +1 -0
  57. package/dist/internal/rpcMethods.js +225 -0
  58. package/dist/internal/rpcMethods.js.map +1 -0
  59. package/dist/internal/transactionHash.d.ts +2 -0
  60. package/dist/internal/transactionHash.d.ts.map +1 -0
  61. package/dist/internal/transactionHash.js +60 -0
  62. package/dist/internal/transactionHash.js.map +1 -0
  63. package/package.json +66 -3
  64. package/src/StarknetAddress.ts +42 -0
  65. package/src/StarknetBlock.ts +54 -0
  66. package/src/StarknetEvent.ts +45 -0
  67. package/src/StarknetIndexer.ts +363 -0
  68. package/src/StarknetNetwork.ts +107 -0
  69. package/src/StarknetRelayer.ts +437 -0
  70. package/src/StarknetRpc.ts +524 -0
  71. package/src/StarknetSigner.ts +115 -0
  72. package/src/StarknetTransaction.ts +68 -0
  73. package/src/StarknetTransactionHash.ts +31 -0
  74. package/src/index.ts +55 -0
  75. package/src/internal/PaddedFelt.ts +18 -0
  76. package/src/internal/confirmations.ts +17 -0
  77. package/src/internal/rpcMethods.ts +224 -0
  78. package/src/internal/transactionHash.ts +64 -0
@@ -0,0 +1,524 @@
1
+ /**
2
+ * Typed Starknet 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 (`starknet_chainId`). Every method but `addInvokeTransaction`
6
+ * and `addDeployAccountTransaction` is a read, so retries and fallback are safe; these two document their own case.
7
+ * Methods are named after the JSON-RPC method without its namespace (`starknet_getEvents` is `getEvents`). A
8
+ * `getEvents` page cursor is only sent to the endpoint that issued it, with no fallback.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import type { StarknetAddress } from "@effect-blockchain/starknet/StarknetAddress"
13
+ * import type { StarknetEvent } from "@effect-blockchain/starknet/StarknetEvent"
14
+ * import * as StarknetRpc from "@effect-blockchain/starknet/StarknetRpc"
15
+ * import * as Effect from "effect/Effect"
16
+ *
17
+ * declare const address: StarknetAddress
18
+ *
19
+ * // every event of `address` in blocks 100 to 200, page by page
20
+ * const events = Effect.gen(function*() {
21
+ * const rpc = yield* StarknetRpc.StarknetRpc
22
+ * const all: Array<StarknetEvent> = []
23
+ * let cursor: StarknetRpc.StarknetEventsCursor | undefined
24
+ * do {
25
+ * const page = yield* rpc.getEvents({ address, fromBlock: BigInt(100), toBlock: BigInt(200), cursor })
26
+ * all.push(...page.events)
27
+ * cursor = page.cursor
28
+ * } while (cursor !== undefined)
29
+ * return all
30
+ * })
31
+ * ```
32
+ *
33
+ * @since 0.1.0
34
+ */
35
+ import * as JsonRpc from "@effect-blockchain/core/JsonRpc"
36
+ import * as Arr from "effect/Array"
37
+ import * as Config from "effect/Config"
38
+ import * as Context from "effect/Context"
39
+ import type * as Duration from "effect/Duration"
40
+ import * as Effect from "effect/Effect"
41
+ import type * as HttpClient from "effect/http/HttpClient"
42
+ import * as Layer from "effect/Layer"
43
+ import type * as Redacted from "effect/Redacted"
44
+ import * as Ref from "effect/Ref"
45
+ import * as Schema from "effect/Schema"
46
+ import * as RpcMethods from "./internal/rpcMethods.ts"
47
+ import type { StarknetAddress } from "./StarknetAddress.ts"
48
+ import type { StarknetBlock } from "./StarknetBlock.ts"
49
+ import type { StarknetEvent } from "./StarknetEvent.ts"
50
+ import * as StarknetNetwork from "./StarknetNetwork.ts"
51
+ import type {
52
+ StarknetDeployAccountTransaction,
53
+ StarknetInvokeTransaction,
54
+ StarknetResourceBounds,
55
+ StarknetTransaction
56
+ } from "./StarknetTransaction.ts"
57
+ import type { StarknetTransactionHash } from "./StarknetTransactionHash.ts"
58
+
59
+ /**
60
+ * A JSON-RPC endpoint. The `name` is shown in errors and spans, the `url` is never logged.
61
+ *
62
+ * @since 0.1.0
63
+ * @category models
64
+ */
65
+ export interface StarknetRpcEndpoint {
66
+ readonly name: string
67
+ readonly url: Redacted.Redacted<string>
68
+ }
69
+
70
+ /**
71
+ * A failed call: its `reason` (a {@link JsonRpc.Reason}, matched with `Effect.catchReason`), the JSON-RPC error code or
72
+ * HTTP status as `code`, and a `cause` without the endpoint URL. After several endpoints, the error is the last one
73
+ * and `cause` is an `AggregateError` of each endpoint's error, in order.
74
+ *
75
+ * On Starknet, `Unavailable` includes the codes 63 (`UNEXPECTED_ERROR`), -32603, -32005 and 429, `InvalidResponse` an
76
+ * event outside the `getEvents` filter, and `Lagging` a head below the requested block, `BLOCK_NOT_FOUND` (24) and
77
+ * `TXN_HASH_NOT_FOUND` (29).
78
+ *
79
+ * @since 0.1.0
80
+ * @category errors
81
+ */
82
+ export class StarknetRpcError extends Schema.TaggedError<StarknetRpcError>()("StarknetRpcError", {
83
+ reason: JsonRpc.Reason,
84
+ method: Schema.String,
85
+ endpoint: Schema.String,
86
+ code: Schema.optional(Schema.Number),
87
+ cause: Schema.Defect()
88
+ }) {
89
+ /**
90
+ * @since 0.1.0
91
+ */
92
+ override get message(): string {
93
+ return `${this.method} failed on ${this.endpoint}: ${this.reason._tag}${
94
+ this.code === undefined ? "" : ` (${this.code})`
95
+ }`
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Where to continue a `starknet_getEvents` range: the provider's continuation token and the endpoint that issued it.
101
+ * Opaque: only pass it back to {@link StarknetRpc} `getEvents` with the same filter.
102
+ *
103
+ * @since 0.1.0
104
+ * @category schemas
105
+ */
106
+ export const StarknetEventsCursor = Schema.Struct({
107
+ endpoint: Schema.String,
108
+ cursor: Schema.String
109
+ }).pipe(Schema.brand("StarknetEventsCursor"))
110
+
111
+ /**
112
+ * @since 0.1.0
113
+ * @category models
114
+ */
115
+ export type StarknetEventsCursor = typeof StarknetEventsCursor.Type
116
+
117
+ /**
118
+ * A `starknet_getEvents` filter over the inclusive block range `[fromBlock, toBlock]`.
119
+ *
120
+ * - `keys` filters by position, an empty position matches any key.
121
+ * - `chunkSize` is the page size, default 1000 (providers commonly cap it at 1024).
122
+ * - `cursor` continues the range from a previous page.
123
+ *
124
+ * @since 0.1.0
125
+ * @category models
126
+ */
127
+ export interface StarknetEventsFilter {
128
+ readonly address: StarknetAddress
129
+ readonly fromBlock: bigint
130
+ readonly toBlock: bigint
131
+ readonly keys?: ReadonlyArray<ReadonlyArray<string>> | undefined
132
+ readonly chunkSize?: number | undefined
133
+ readonly cursor?: StarknetEventsCursor | undefined
134
+ }
135
+
136
+ /**
137
+ * One page of events. `cursor` is `undefined` when the range is done.
138
+ *
139
+ * @since 0.1.0
140
+ * @category models
141
+ */
142
+ export interface StarknetEventsPage {
143
+ readonly events: ReadonlyArray<StarknetEvent>
144
+ readonly cursor: StarknetEventsCursor | undefined
145
+ }
146
+
147
+ /**
148
+ * The part of a confirmed transaction receipt an indexer needs. `events` are in emission order.
149
+ *
150
+ * @since 0.1.0
151
+ * @category models
152
+ */
153
+ export interface StarknetTransactionReceipt {
154
+ readonly transactionHash: StarknetTransactionHash
155
+ readonly blockNumber: bigint
156
+ readonly blockHash: string
157
+ readonly events: ReadonlyArray<Pick<StarknetEvent, "fromAddress" | "keys" | "data">>
158
+ }
159
+
160
+ /**
161
+ * The `starknet_getTransactionStatus` result of the JSON-RPC spec v0.9. `executionStatus` is absent until the
162
+ * transaction is executed (`RECEIVED`, `CANDIDATE`), and `failureReason` is the node's revert message of a `REVERTED`
163
+ * transaction.
164
+ *
165
+ * @since 0.2.0
166
+ * @category models
167
+ */
168
+ export interface StarknetTransactionStatusResult {
169
+ readonly finalityStatus: "RECEIVED" | "CANDIDATE" | "PRE_CONFIRMED" | "ACCEPTED_ON_L2" | "ACCEPTED_ON_L1"
170
+ readonly executionStatus?: "SUCCEEDED" | "REVERTED" | undefined
171
+ readonly failureReason?: string | undefined
172
+ }
173
+
174
+ /**
175
+ * The block a state read is made at: the latest accepted block, or the pre-confirmed block being built on top of it.
176
+ *
177
+ * @since 0.2.0
178
+ * @category models
179
+ */
180
+ export type StarknetBlockTag = "latest" | "pre_confirmed"
181
+
182
+ /**
183
+ * One `starknet_estimateFee` result: the amount of each resource a transaction consumes and its price, in FRI (10^-18
184
+ * STRK) per unit. `overallFee` is their total.
185
+ *
186
+ * @since 0.2.0
187
+ * @category models
188
+ */
189
+ export interface StarknetFeeEstimate {
190
+ readonly l1GasConsumed: bigint
191
+ readonly l1GasPrice: bigint
192
+ readonly l1DataGasConsumed: bigint
193
+ readonly l1DataGasPrice: bigint
194
+ readonly l2GasConsumed: bigint
195
+ readonly l2GasPrice: bigint
196
+ readonly overallFee: bigint
197
+ }
198
+
199
+ /**
200
+ * @since 0.1.0
201
+ * @category services
202
+ */
203
+ export class StarknetRpc extends Context.Service<StarknetRpc, {
204
+ readonly network: StarknetNetwork.StarknetNetwork
205
+ /** `starknet_chainId`, verified against `network` once per endpoint then served from that check. */
206
+ readonly chainId: Effect.Effect<StarknetNetwork.StarknetChainId, StarknetRpcError>
207
+ /** `starknet_blockNumber` */
208
+ readonly blockNumber: Effect.Effect<bigint, StarknetRpcError>
209
+ /**
210
+ * `starknet_getBlockWithTxHashes`, only answered by an endpoint whose head has reached `blockNumber`. A pre-confirmed
211
+ * block fails with `InvalidResponse`.
212
+ */
213
+ readonly getBlockWithTxHashes: (
214
+ options: { readonly blockNumber: bigint }
215
+ ) => Effect.Effect<StarknetBlock, StarknetRpcError>
216
+ /**
217
+ * `starknet_getEvents`, one page, only answered by an endpoint whose head has reached `toBlock`. Events keep the
218
+ * provider's order, which is chain order (`event_index` is not always returned to sort them). A pre-confirmed or
219
+ * out-of-filter event fails with `InvalidResponse`, and an empty range returns no events.
220
+ */
221
+ readonly getEvents: (filter: StarknetEventsFilter) => Effect.Effect<StarknetEventsPage, StarknetRpcError>
222
+ /**
223
+ * `starknet_call`, the raw felts a view function returns at the end of `blockNumber`, only answered by an endpoint
224
+ * whose head has reached `blockNumber`.
225
+ */
226
+ readonly call: (options: {
227
+ readonly contractAddress: StarknetAddress
228
+ readonly entryPointSelector: string
229
+ readonly calldata: ReadonlyArray<string>
230
+ readonly blockNumber: bigint
231
+ }) => Effect.Effect<ReadonlyArray<string>, StarknetRpcError>
232
+ /** `starknet_getTransactionReceipt`. A pre-confirmed receipt fails with `InvalidResponse`. */
233
+ readonly getTransactionReceipt: (
234
+ options: { readonly transactionHash: StarknetTransactionHash }
235
+ ) => Effect.Effect<StarknetTransactionReceipt, StarknetRpcError>
236
+ /**
237
+ * `starknet_getTransactionStatus`, `null` when the last endpoint tried answers `TXN_HASH_NOT_FOUND` (29): an endpoint
238
+ * that does not know the transaction falls back to the next one first.
239
+ */
240
+ readonly getTransactionStatus: (
241
+ options: { readonly transactionHash: StarknetTransactionHash }
242
+ ) => Effect.Effect<StarknetTransactionStatusResult | null, StarknetRpcError>
243
+ /**
244
+ * `starknet_getNonce`: the nonce of the next transaction of the account at `address`. `pre_confirmed` counts the
245
+ * transactions of the block being built, not the ones still waiting in the mempool. An address without a contract
246
+ * is `Rejected` with the code 20 (`CONTRACT_NOT_FOUND`).
247
+ *
248
+ * @since 0.2.0
249
+ */
250
+ readonly getNonce: (options: {
251
+ readonly address: StarknetAddress
252
+ readonly blockTag: StarknetBlockTag
253
+ }) => Effect.Effect<bigint, StarknetRpcError>
254
+ /**
255
+ * `starknet_estimateFee`: one estimate per transaction, each executed on top of the previous ones at `blockTag`
256
+ * (a reply without an estimate is an `InvalidResponse`).
257
+ * `skipValidate` sends the `SKIP_VALIDATE` flag, which accepts unsigned transactions. A transaction that fails is
258
+ * `Rejected` with the code 41 (`TRANSACTION_EXECUTION_ERROR`) and the node's message in `cause`.
259
+ *
260
+ * @since 0.2.0
261
+ */
262
+ readonly estimateFee: (options: {
263
+ readonly transactions: Arr.NonEmptyReadonlyArray<StarknetTransaction>
264
+ readonly skipValidate?: boolean | undefined
265
+ readonly blockTag: StarknetBlockTag
266
+ }) => Effect.Effect<Arr.NonEmptyReadonlyArray<StarknetFeeEstimate>, StarknetRpcError>
267
+ /**
268
+ * `starknet_addInvokeTransaction`: submits a signed `INVOKE` transaction and returns its hash. A retry or a fallback
269
+ * sends the same transaction, so it never creates a second one, but a node that already has it refuses the second
270
+ * copy. A refusal (`DUPLICATE_TX`, `INVALID_TRANSACTION_NONCE`, `INSUFFICIENT_ACCOUNT_BALANCE`...) is `Rejected`,
271
+ * with the spec's error code as `code`.
272
+ *
273
+ * @since 0.2.0
274
+ */
275
+ readonly addInvokeTransaction: (options: {
276
+ readonly transaction: StarknetInvokeTransaction
277
+ }) => Effect.Effect<StarknetTransactionHash, StarknetRpcError>
278
+ /**
279
+ * `starknet_addDeployAccountTransaction`: submits a signed `DEPLOY_ACCOUNT` transaction and returns its hash and
280
+ * the address of the account. Retries, fallback and refusals are those of `addInvokeTransaction`.
281
+ *
282
+ * @since 0.2.0
283
+ */
284
+ readonly addDeployAccountTransaction: (options: {
285
+ readonly transaction: StarknetDeployAccountTransaction
286
+ }) => Effect.Effect<
287
+ { readonly transactionHash: StarknetTransactionHash; readonly contractAddress: StarknetAddress },
288
+ StarknetRpcError
289
+ >
290
+ }>()("@effect-blockchain/starknet/StarknetRpc") {}
291
+
292
+ const TXN_HASH_NOT_FOUND = 29
293
+
294
+ // error codes from the Starknet JSON-RPC spec v0.9 (starknet_api_openrpc.json), plus the common provider ones
295
+ const codes: ReadonlyMap<number, JsonRpc.CodeReason> = new Map([
296
+ // UNEXPECTED_ERROR, JSON-RPC internal error and provider rate limits: the endpoint is struggling, retry then fall back
297
+ [63, "Unavailable"],
298
+ [-32603, "Unavailable"],
299
+ [-32005, "Unavailable"],
300
+ [429, "Unavailable"],
301
+ // BLOCK_NOT_FOUND, TXN_HASH_NOT_FOUND: another endpoint may be further ahead
302
+ [24, "Lagging"],
303
+ [TXN_HASH_NOT_FOUND, "Lagging"]
304
+ ])
305
+
306
+ const bound = (bound: StarknetResourceBounds["l1Gas"]) => ({
307
+ max_amount: bound.maxAmount,
308
+ max_price_per_unit: bound.maxPricePerUnit
309
+ })
310
+
311
+ const v3 = (transaction: StarknetTransaction) => ({
312
+ version: "0x3" as const,
313
+ signature: transaction.signature,
314
+ nonce: transaction.nonce,
315
+ resource_bounds: {
316
+ l1_gas: bound(transaction.resourceBounds.l1Gas),
317
+ l2_gas: bound(transaction.resourceBounds.l2Gas),
318
+ l1_data_gas: bound(transaction.resourceBounds.l1DataGas)
319
+ },
320
+ tip: transaction.tip,
321
+ paymaster_data: [] as const,
322
+ nonce_data_availability_mode: "L1" as const,
323
+ fee_data_availability_mode: "L1" as const
324
+ })
325
+
326
+ const invoke = (transaction: StarknetInvokeTransaction) => ({
327
+ type: transaction.type,
328
+ sender_address: transaction.senderAddress,
329
+ calldata: transaction.calldata,
330
+ account_deployment_data: [] as const,
331
+ ...v3(transaction)
332
+ })
333
+
334
+ const deployAccount = (transaction: StarknetDeployAccountTransaction) => ({
335
+ type: transaction.type,
336
+ class_hash: transaction.classHash,
337
+ contract_address_salt: transaction.contractAddressSalt,
338
+ constructor_calldata: transaction.constructorCalldata,
339
+ ...v3(transaction)
340
+ })
341
+
342
+ /**
343
+ * Builds a {@link StarknetRpc} over `endpoints`, tried in order, sending requests with the provided `HttpClient`
344
+ * (e.g. `FetchHttpClient.layer`). `timeout` (default 30 seconds) bounds each attempt, `retries` (default 3) and
345
+ * `retryDelay` (default 500 millis) set the backoff before falling back: see {@link JsonRpc.Unavailable}.
346
+ *
347
+ * @since 0.1.0
348
+ * @category layers
349
+ */
350
+ export const layer = (options: {
351
+ readonly network: StarknetNetwork.StarknetNetwork
352
+ readonly endpoints: Arr.NonEmptyReadonlyArray<StarknetRpcEndpoint>
353
+ readonly timeout?: Duration.Input | undefined
354
+ readonly retries?: number | undefined
355
+ readonly retryDelay?: Duration.Input | undefined
356
+ }): Layer.Layer<StarknetRpc, never, HttpClient.HttpClient> =>
357
+ Layer.effect(
358
+ StarknetRpc,
359
+ Effect.gen(function*() {
360
+ const { network } = options
361
+ const expectedChainId = StarknetNetwork.toChainId(network)
362
+
363
+ const rpc = yield* JsonRpc.make({
364
+ spanPrefix: "StarknetRpc",
365
+ network,
366
+ endpoints: options.endpoints,
367
+ timeout: options.timeout,
368
+ retries: options.retries,
369
+ retryDelay: options.retryDelay,
370
+ codes,
371
+ checkNetwork: (send, endpoint) =>
372
+ send(RpcMethods.chainId, {}).pipe(
373
+ Effect.flatMap((chainId) =>
374
+ chainId === expectedChainId
375
+ ? Effect.succeed(expectedChainId)
376
+ : Effect.fail(
377
+ new StarknetRpcError({
378
+ reason: new JsonRpc.WrongNetwork({ expected: expectedChainId, actual: chainId }),
379
+ method: RpcMethods.chainId.name,
380
+ endpoint,
381
+ cause: new Error(`expected chain ID ${expectedChainId} for ${network}, got ${chainId}`)
382
+ })
383
+ )
384
+ )
385
+ ),
386
+ makeError: (fields: JsonRpc.ErrorFields) => new StarknetRpcError(fields)
387
+ })
388
+ type Endpoint = JsonRpc.Endpoint<StarknetNetwork.StarknetChainId, StarknetRpcError>
389
+
390
+ const blockNumberOn = (endpoint: Endpoint) =>
391
+ rpc.call(endpoint, RpcMethods.blockNumber, {}).pipe(
392
+ Effect.tap((head) => Ref.update(endpoint.head, (known) => head > known ? head : known))
393
+ )
394
+
395
+ const getEventsOn = (endpoint: Endpoint, filter: StarknetEventsFilter) =>
396
+ Effect.gen(function*() {
397
+ const method = RpcMethods.getEvents.name
398
+ yield* rpc.requireHead(endpoint, method, filter.toBlock, blockNumberOn(endpoint))
399
+ const page = yield* rpc.call(endpoint, RpcMethods.getEvents, {
400
+ filter: {
401
+ address: filter.address,
402
+ from_block: { block_number: filter.fromBlock },
403
+ to_block: { block_number: filter.toBlock },
404
+ ...(filter.keys !== undefined && { keys: filter.keys }),
405
+ chunk_size: filter.chunkSize ?? 1000,
406
+ ...(filter.cursor !== undefined && { continuation_token: filter.cursor.cursor })
407
+ }
408
+ })
409
+ const invalid = page.events.find((event) =>
410
+ event.blockNumber < filter.fromBlock || event.blockNumber > filter.toBlock ||
411
+ event.fromAddress !== filter.address
412
+ )
413
+ if (invalid !== undefined) {
414
+ return yield* rpc.fail(
415
+ endpoint,
416
+ method,
417
+ new JsonRpc.InvalidResponse(),
418
+ new Error(`event of ${invalid.transactionHash} in block ${invalid.blockNumber} is outside the filter`)
419
+ )
420
+ }
421
+ return {
422
+ events: page.events,
423
+ cursor: page.continuation_token === undefined ? undefined : StarknetEventsCursor.make({
424
+ endpoint: endpoint.name,
425
+ cursor: page.continuation_token
426
+ })
427
+ }
428
+ })
429
+
430
+ const getEvents = (filter: StarknetEventsFilter): Effect.Effect<StarknetEventsPage, StarknetRpcError> => {
431
+ if (filter.fromBlock > filter.toBlock) return Effect.succeed({ events: [], cursor: undefined })
432
+ if (filter.cursor === undefined) return rpc.withFallback((endpoint) => getEventsOn(endpoint, filter))
433
+ // a cursor only means something to the endpoint that issued it
434
+ return rpc.endpointOf(RpcMethods.getEvents.name, filter.cursor).pipe(
435
+ Effect.flatMap((endpoint) => getEventsOn(endpoint, filter))
436
+ )
437
+ }
438
+
439
+ return StarknetRpc.of({
440
+ network,
441
+ chainId: rpc.withFallback(rpc.checkNetwork),
442
+ blockNumber: rpc.withFallback(blockNumberOn),
443
+ getBlockWithTxHashes: ({ blockNumber }) =>
444
+ rpc.withFallback((endpoint) =>
445
+ rpc.requireHead(endpoint, RpcMethods.getBlockWithTxHashes.name, blockNumber, blockNumberOn(endpoint)).pipe(
446
+ Effect.andThen(
447
+ rpc.call(endpoint, RpcMethods.getBlockWithTxHashes, { block_id: { block_number: blockNumber } })
448
+ )
449
+ )
450
+ ),
451
+ getEvents,
452
+ call: (options) =>
453
+ rpc.withFallback((endpoint) =>
454
+ rpc.requireHead(endpoint, RpcMethods.call.name, options.blockNumber, blockNumberOn(endpoint)).pipe(
455
+ Effect.andThen(rpc.call(endpoint, RpcMethods.call, {
456
+ request: {
457
+ contract_address: options.contractAddress,
458
+ entry_point_selector: options.entryPointSelector,
459
+ calldata: options.calldata
460
+ },
461
+ block_id: { block_number: options.blockNumber }
462
+ }))
463
+ )
464
+ ),
465
+ getTransactionReceipt: ({ transactionHash }) =>
466
+ rpc.withFallback((endpoint) =>
467
+ rpc.call(endpoint, RpcMethods.getTransactionReceipt, { transaction_hash: transactionHash })
468
+ ),
469
+ getTransactionStatus: ({ transactionHash }) =>
470
+ rpc.withFallback((endpoint) =>
471
+ rpc.call(endpoint, RpcMethods.getTransactionStatus, { transaction_hash: transactionHash })
472
+ ).pipe(
473
+ Effect.catchIf((error) => error.code === TXN_HASH_NOT_FOUND, () => Effect.succeed(null))
474
+ ),
475
+ getNonce: ({ address, blockTag }) =>
476
+ rpc.withFallback((endpoint) =>
477
+ rpc.call(endpoint, RpcMethods.getNonce, { block_id: blockTag, contract_address: address })
478
+ ),
479
+ estimateFee: ({ blockTag, skipValidate, transactions }) =>
480
+ rpc.withFallback((endpoint) =>
481
+ rpc.call(endpoint, RpcMethods.estimateFee, {
482
+ request: Arr.map(
483
+ transactions,
484
+ (transaction) => transaction.type === "INVOKE" ? invoke(transaction) : deployAccount(transaction)
485
+ ),
486
+ simulation_flags: skipValidate === true ? ["SKIP_VALIDATE"] : [],
487
+ block_id: blockTag
488
+ })
489
+ ),
490
+ addInvokeTransaction: ({ transaction }) =>
491
+ rpc.withFallback((endpoint) =>
492
+ rpc.call(endpoint, RpcMethods.addInvokeTransaction, { invoke_transaction: invoke(transaction) })
493
+ ).pipe(Effect.map(({ transactionHash }) => transactionHash)),
494
+ addDeployAccountTransaction: ({ transaction }) =>
495
+ rpc.withFallback((endpoint) =>
496
+ rpc.call(endpoint, RpcMethods.addDeployAccountTransaction, {
497
+ deploy_account_transaction: deployAccount(transaction)
498
+ })
499
+ )
500
+ })
501
+ })
502
+ )
503
+
504
+ /**
505
+ * Builds an {@link StarknetRpc} like {@link layer}, reading the options from `Config`. Endpoint URLs stay `Redacted`.
506
+ *
507
+ * @example
508
+ * ```ts
509
+ * import * as StarknetRpc from "@effect-blockchain/starknet/StarknetRpc"
510
+ * import * as Config from "effect/Config"
511
+ *
512
+ * const RpcLive = StarknetRpc.layerConfig({
513
+ * network: Config.succeed("Starknet"),
514
+ * endpoints: Config.all([Config.all({ name: Config.succeed("main"), url: Config.Redacted("STARKNET_RPC_URL") })])
515
+ * })
516
+ * ```
517
+ *
518
+ * @since 0.1.0
519
+ * @category layers
520
+ */
521
+ export const layerConfig = (
522
+ options: Config.Wrap<Parameters<typeof layer>[0]>
523
+ ): Layer.Layer<StarknetRpc, Config.ConfigError, HttpClient.HttpClient> =>
524
+ Layer.unwrap(Effect.map(Config.unwrap(options), layer))
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Signers of Starknet 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 V3 `INVOKE` and
6
+ * `DEPLOY_ACCOUNT` transactions are signed.
7
+ *
8
+ * A Starknet signature is whatever the account contract at `address` validates, so a signer returns felts and the
9
+ * address is given, not derived from the key: `[r, s]` on the Stark curve for OpenZeppelin and Argent accounts.
10
+ *
11
+ * @since 0.2.0
12
+ */
13
+ import * as Effect from "effect/Effect"
14
+ import * as Redacted from "effect/Redacted"
15
+ import * as Schema from "effect/Schema"
16
+ import { ec, num } from "starknet"
17
+ import { transactionHash } from "./internal/transactionHash.ts"
18
+ import type { StarknetAddress } from "./StarknetAddress.ts"
19
+ import type { StarknetDeployAccountTransaction, StarknetInvokeTransaction } from "./StarknetTransaction.ts"
20
+ import type { StarknetTransactionHash } from "./StarknetTransactionHash.ts"
21
+
22
+ /**
23
+ * A signature could not be produced: `cause` is the signer's own failure, or why its signature was refused. It never
24
+ * holds a private key.
25
+ *
26
+ * @since 0.2.0
27
+ * @category errors
28
+ */
29
+ export class StarknetSignerError extends Schema.TaggedError<StarknetSignerError>()("StarknetSignerError", {
30
+ cause: Schema.Defect()
31
+ }) {}
32
+
33
+ /**
34
+ * A V3 transaction before its signature.
35
+ *
36
+ * @since 0.2.0
37
+ * @category models
38
+ */
39
+ export type StarknetUnsignedTransaction =
40
+ | Omit<StarknetInvokeTransaction, "signature">
41
+ | Omit<StarknetDeployAccountTransaction, "signature">
42
+
43
+ /**
44
+ * Signs transactions sent from the account contract at `address`. `signTransaction` returns the signature felts, in
45
+ * the format that account contract validates.
46
+ *
47
+ * @since 0.2.0
48
+ * @category models
49
+ */
50
+ export interface StarknetSigner {
51
+ readonly address: StarknetAddress
52
+ readonly signTransaction: (
53
+ transaction: StarknetUnsignedTransaction
54
+ ) => Effect.Effect<ReadonlyArray<string>, StarknetSignerError>
55
+ }
56
+
57
+ const toError = (cause: unknown) => cause instanceof StarknetSignerError ? cause : new StarknetSignerError({ cause })
58
+
59
+ const isFelts = Schema.is(Schema.Array(Schema.String.check(Schema.isPattern(/^0x[0-9a-fA-F]{1,64}$/))))
60
+
61
+ /**
62
+ * A signer for a key held elsewhere (a custody API, an HSM) that only signs a hash. `signHash` receives the V3
63
+ * transaction hash and returns the signature felts of the account at `address`, `[r, s]` for OpenZeppelin and Argent
64
+ * accounts. A failure of `signHash` or a signature that is not 0x-prefixed felts fails with a
65
+ * {@link StarknetSignerError}; the signature itself is only checked by the account contract.
66
+ *
67
+ * @since 0.2.0
68
+ * @category constructors
69
+ */
70
+ export const fromHashSigner = <E>(options: {
71
+ readonly address: StarknetAddress
72
+ readonly signHash: (hash: StarknetTransactionHash) => Effect.Effect<ReadonlyArray<string>, E>
73
+ }): StarknetSigner => ({
74
+ address: options.address,
75
+ signTransaction: Effect.fnUntraced(function*(transaction) {
76
+ const hash = yield* Effect.try({ try: () => transactionHash(transaction), catch: toError })
77
+ const signature = yield* Effect.mapError(options.signHash(hash), toError)
78
+ if (!isFelts(signature)) return yield* toError(new Error("the signature is not an array of 0x-prefixed felts"))
79
+ return signature
80
+ })
81
+ })
82
+
83
+ /**
84
+ * A signer holding the Stark curve private key (hex) of the account at `address` in memory, signing
85
+ * `[r, s]` as OpenZeppelin and Argent accounts validate. An invalid key fails with a {@link StarknetSignerError} that
86
+ * does not repeat it.
87
+ *
88
+ * @since 0.2.0
89
+ * @category constructors
90
+ */
91
+ export const fromPrivateKey = (options: {
92
+ readonly address: StarknetAddress
93
+ readonly key: Redacted.Redacted<string>
94
+ }): Effect.Effect<StarknetSigner, StarknetSignerError> =>
95
+ Effect.try({
96
+ try: () => {
97
+ const key = Redacted.value(options.key)
98
+ ec.starkCurve.getStarkKey(key)
99
+ return key
100
+ },
101
+ // the thrown error can quote the key
102
+ catch: () => new StarknetSignerError({ cause: new Error("invalid private key") })
103
+ }).pipe(Effect.map((key) =>
104
+ fromHashSigner({
105
+ address: options.address,
106
+ signHash: (hash) =>
107
+ Effect.try({
108
+ try: () => {
109
+ const { r, s } = ec.starkCurve.sign(hash, key)
110
+ return [num.toHex(r), num.toHex(s)]
111
+ },
112
+ catch: toError
113
+ })
114
+ })
115
+ ))