@effect-blockchain/starknet 0.0.0-stage → 0.1.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 (53) 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 +119 -0
  16. package/dist/StarknetIndexer.d.ts.map +1 -0
  17. package/dist/StarknetIndexer.js +170 -0
  18. package/dist/StarknetIndexer.js.map +1 -0
  19. package/dist/StarknetNetwork.d.ts +63 -0
  20. package/dist/StarknetNetwork.d.ts.map +1 -0
  21. package/dist/StarknetNetwork.js +74 -0
  22. package/dist/StarknetNetwork.js.map +1 -0
  23. package/dist/StarknetRpc.d.ts +204 -0
  24. package/dist/StarknetRpc.d.ts.map +1 -0
  25. package/dist/StarknetRpc.js +203 -0
  26. package/dist/StarknetRpc.js.map +1 -0
  27. package/dist/StarknetTransactionHash.d.ts +22 -0
  28. package/dist/StarknetTransactionHash.d.ts.map +1 -0
  29. package/dist/StarknetTransactionHash.js +22 -0
  30. package/dist/StarknetTransactionHash.js.map +1 -0
  31. package/dist/index.d.ts +32 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +33 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/internal/PaddedFelt.d.ts +2 -0
  36. package/dist/internal/PaddedFelt.d.ts.map +1 -0
  37. package/dist/internal/PaddedFelt.js +15 -0
  38. package/dist/internal/PaddedFelt.js.map +1 -0
  39. package/dist/internal/rpcMethods.d.ts +2 -0
  40. package/dist/internal/rpcMethods.d.ts.map +1 -0
  41. package/dist/internal/rpcMethods.js +90 -0
  42. package/dist/internal/rpcMethods.js.map +1 -0
  43. package/package.json +66 -3
  44. package/src/StarknetAddress.ts +42 -0
  45. package/src/StarknetBlock.ts +54 -0
  46. package/src/StarknetEvent.ts +45 -0
  47. package/src/StarknetIndexer.ts +248 -0
  48. package/src/StarknetNetwork.ts +95 -0
  49. package/src/StarknetRpc.ts +332 -0
  50. package/src/StarknetTransactionHash.ts +31 -0
  51. package/src/index.ts +40 -0
  52. package/src/internal/PaddedFelt.ts +18 -0
  53. package/src/internal/rpcMethods.ts +88 -0
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Named Starknet networks and their chain IDs.
3
+ *
4
+ * @since 0.1.0
5
+ */
6
+ import * as Schema from "effect/Schema"
7
+
8
+ /**
9
+ * @since 0.1.0
10
+ * @category constants
11
+ */
12
+ export const mainnets = ["Starknet"] as const
13
+
14
+ /**
15
+ * @since 0.1.0
16
+ * @category constants
17
+ */
18
+ export const testnets = ["StarknetSepolia"] as const
19
+
20
+ /**
21
+ * Every supported network, mainnets first.
22
+ *
23
+ * @since 0.1.0
24
+ * @category constants
25
+ */
26
+ export const networks = [...mainnets, ...testnets] as const
27
+
28
+ /**
29
+ * @since 0.1.0
30
+ * @category schemas
31
+ */
32
+ export const StarknetNetwork = Schema.Literals(networks).annotate({
33
+ identifier: "StarknetNetwork",
34
+ title: "Starknet network",
35
+ description: "a Starknet network name: \"Starknet\" (mainnet) or \"StarknetSepolia\" (testnet)"
36
+ })
37
+
38
+ /**
39
+ * @since 0.1.0
40
+ * @category models
41
+ */
42
+ export type StarknetNetwork = typeof StarknetNetwork.Type
43
+
44
+ /**
45
+ * A Starknet chain ID, the short string `starknet_chainId` returns.
46
+ *
47
+ * @since 0.1.0
48
+ * @category schemas
49
+ */
50
+ export const StarknetChainId = Schema.Literals(["SN_MAIN", "SN_SEPOLIA"]).annotate({
51
+ identifier: "StarknetChainId",
52
+ title: "Starknet chain ID",
53
+ description: "a Starknet chain ID as a short string: \"SN_MAIN\" or \"SN_SEPOLIA\""
54
+ })
55
+
56
+ /**
57
+ * @since 0.1.0
58
+ * @category models
59
+ */
60
+ export type StarknetChainId = typeof StarknetChainId.Type
61
+
62
+ const chainIds: Record<StarknetNetwork, StarknetChainId> = {
63
+ Starknet: "SN_MAIN",
64
+ StarknetSepolia: "SN_SEPOLIA"
65
+ }
66
+
67
+ /**
68
+ * @since 0.1.0
69
+ * @category conversions
70
+ */
71
+ export const toChainId = (network: StarknetNetwork): StarknetChainId => chainIds[network]
72
+
73
+ /**
74
+ * Default number of confirmations an indexer waits for on each network, on top of the latest accepted block.
75
+ *
76
+ * @since 0.1.0
77
+ * @category getters
78
+ */
79
+ export const defaultConfirmations = (network: StarknetNetwork): number => {
80
+ switch (network) {
81
+ // ACCEPTED_ON_L2 blocks are "finalized by the consensus protocol": https://docs.starknet.io/learn/protocol/transactions
82
+ case "Starknet":
83
+ return 0
84
+ // same protocol and finality rules as mainnet: https://docs.starknet.io/learn/protocol/transactions
85
+ case "StarknetSepolia":
86
+ return 0
87
+ }
88
+ }
89
+
90
+ /**
91
+ * @since 0.1.0
92
+ * @category predicates
93
+ */
94
+ export const isTestnet = (network: StarknetNetwork): boolean =>
95
+ (testnets as ReadonlyArray<StarknetNetwork>).includes(network)
@@ -0,0 +1,332 @@
1
+ /**
2
+ * Typed, read-only 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 is a read, so retries and
6
+ * fallback are safe. Methods are named after the JSON-RPC method without its namespace (`starknet_getEvents` is
7
+ * `getEvents`). A `getEvents` page cursor is only sent to the endpoint that issued it, with no fallback.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import type { StarknetAddress } from "@effect-blockchain/starknet/StarknetAddress"
12
+ * import type { StarknetEvent } from "@effect-blockchain/starknet/StarknetEvent"
13
+ * import * as StarknetRpc from "@effect-blockchain/starknet/StarknetRpc"
14
+ * import * as Effect from "effect/Effect"
15
+ *
16
+ * declare const address: StarknetAddress
17
+ *
18
+ * // every event of `address` in blocks 100 to 200, page by page
19
+ * const events = Effect.gen(function*() {
20
+ * const rpc = yield* StarknetRpc.StarknetRpc
21
+ * const all: Array<StarknetEvent> = []
22
+ * let cursor: StarknetRpc.StarknetEventsCursor | undefined
23
+ * do {
24
+ * const page = yield* rpc.getEvents({ address, fromBlock: BigInt(100), toBlock: BigInt(200), cursor })
25
+ * all.push(...page.events)
26
+ * cursor = page.cursor
27
+ * } while (cursor !== undefined)
28
+ * return all
29
+ * })
30
+ * ```
31
+ *
32
+ * @since 0.1.0
33
+ */
34
+ import * as JsonRpc from "@effect-blockchain/core/JsonRpc"
35
+ import type * as Arr from "effect/Array"
36
+ import * as Config from "effect/Config"
37
+ import * as Context from "effect/Context"
38
+ import type * as Duration from "effect/Duration"
39
+ import * as Effect from "effect/Effect"
40
+ import type * as HttpClient from "effect/http/HttpClient"
41
+ import * as Layer from "effect/Layer"
42
+ import type * as Redacted from "effect/Redacted"
43
+ import * as Ref from "effect/Ref"
44
+ import * as Schema from "effect/Schema"
45
+ import * as RpcMethods from "./internal/rpcMethods.ts"
46
+ import type { StarknetAddress } from "./StarknetAddress.ts"
47
+ import type { StarknetBlock } from "./StarknetBlock.ts"
48
+ import type { StarknetEvent } from "./StarknetEvent.ts"
49
+ import * as StarknetNetwork from "./StarknetNetwork.ts"
50
+ import type { StarknetTransactionHash } from "./StarknetTransactionHash.ts"
51
+
52
+ /**
53
+ * A JSON-RPC endpoint. The `name` is shown in errors and spans, the `url` is never logged.
54
+ *
55
+ * @since 0.1.0
56
+ * @category models
57
+ */
58
+ export interface StarknetRpcEndpoint {
59
+ readonly name: string
60
+ readonly url: Redacted.Redacted<string>
61
+ }
62
+
63
+ /**
64
+ * A failed call: its `reason` (a {@link JsonRpc.Reason}, matched with `Effect.catchReason`), the JSON-RPC error code or
65
+ * HTTP status as `code`, and a `cause` without the endpoint URL. After several endpoints, the error is the last one
66
+ * and `cause` is an `AggregateError` of each endpoint's error, in order.
67
+ *
68
+ * On Starknet, `Unavailable` includes the codes 63 (`UNEXPECTED_ERROR`), -32603, -32005 and 429, `InvalidResponse` an
69
+ * event outside the `getEvents` filter, and `Lagging` a head below the requested block, `BLOCK_NOT_FOUND` (24) and
70
+ * `TXN_HASH_NOT_FOUND` (29).
71
+ *
72
+ * @since 0.1.0
73
+ * @category errors
74
+ */
75
+ export class StarknetRpcError extends Schema.TaggedError<StarknetRpcError>()("StarknetRpcError", {
76
+ reason: JsonRpc.Reason,
77
+ method: Schema.String,
78
+ endpoint: Schema.String,
79
+ code: Schema.optional(Schema.Number),
80
+ cause: Schema.Defect()
81
+ }) {
82
+ /**
83
+ * @since 0.1.0
84
+ */
85
+ override get message(): string {
86
+ return `${this.method} failed on ${this.endpoint}: ${this.reason._tag}${
87
+ this.code === undefined ? "" : ` (${this.code})`
88
+ }`
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Where to continue a `starknet_getEvents` range: the provider's continuation token and the endpoint that issued it.
94
+ * Opaque: only pass it back to {@link StarknetRpc} `getEvents` with the same filter.
95
+ *
96
+ * @since 0.1.0
97
+ * @category schemas
98
+ */
99
+ export const StarknetEventsCursor = Schema.Struct({
100
+ endpoint: Schema.String,
101
+ cursor: Schema.String
102
+ }).pipe(Schema.brand("StarknetEventsCursor"))
103
+
104
+ /**
105
+ * @since 0.1.0
106
+ * @category models
107
+ */
108
+ export type StarknetEventsCursor = typeof StarknetEventsCursor.Type
109
+
110
+ /**
111
+ * A `starknet_getEvents` filter over the inclusive block range `[fromBlock, toBlock]`.
112
+ *
113
+ * - `keys` filters by position, an empty position matches any key.
114
+ * - `chunkSize` is the page size, default 1000 (providers commonly cap it at 1024).
115
+ * - `cursor` continues the range from a previous page.
116
+ *
117
+ * @since 0.1.0
118
+ * @category models
119
+ */
120
+ export interface StarknetEventsFilter {
121
+ readonly address: StarknetAddress
122
+ readonly fromBlock: bigint
123
+ readonly toBlock: bigint
124
+ readonly keys?: ReadonlyArray<ReadonlyArray<string>> | undefined
125
+ readonly chunkSize?: number | undefined
126
+ readonly cursor?: StarknetEventsCursor | undefined
127
+ }
128
+
129
+ /**
130
+ * One page of events. `cursor` is `undefined` when the range is done.
131
+ *
132
+ * @since 0.1.0
133
+ * @category models
134
+ */
135
+ export interface StarknetEventsPage {
136
+ readonly events: ReadonlyArray<StarknetEvent>
137
+ readonly cursor: StarknetEventsCursor | undefined
138
+ }
139
+
140
+ /**
141
+ * The part of a confirmed transaction receipt an indexer needs. `events` are in emission order.
142
+ *
143
+ * @since 0.1.0
144
+ * @category models
145
+ */
146
+ export interface StarknetTransactionReceipt {
147
+ readonly transactionHash: StarknetTransactionHash
148
+ readonly blockNumber: bigint
149
+ readonly blockHash: string
150
+ readonly events: ReadonlyArray<Pick<StarknetEvent, "fromAddress" | "keys" | "data">>
151
+ }
152
+
153
+ /**
154
+ * @since 0.1.0
155
+ * @category services
156
+ */
157
+ export class StarknetRpc extends Context.Service<StarknetRpc, {
158
+ readonly network: StarknetNetwork.StarknetNetwork
159
+ /** `starknet_chainId`, verified against `network` once per endpoint then served from that check. */
160
+ readonly chainId: Effect.Effect<StarknetNetwork.StarknetChainId, StarknetRpcError>
161
+ /** `starknet_blockNumber` */
162
+ readonly blockNumber: Effect.Effect<bigint, StarknetRpcError>
163
+ /**
164
+ * `starknet_getBlockWithTxHashes`, only answered by an endpoint whose head has reached `blockNumber`. A pre-confirmed
165
+ * block fails with `InvalidResponse`.
166
+ */
167
+ readonly getBlockWithTxHashes: (
168
+ options: { readonly blockNumber: bigint }
169
+ ) => Effect.Effect<StarknetBlock, StarknetRpcError>
170
+ /**
171
+ * `starknet_getEvents`, one page, only answered by an endpoint whose head has reached `toBlock`. Events keep the
172
+ * provider's order, which is chain order (`event_index` is not always returned to sort them). A pre-confirmed or
173
+ * out-of-filter event fails with `InvalidResponse`, and an empty range returns no events.
174
+ */
175
+ readonly getEvents: (filter: StarknetEventsFilter) => Effect.Effect<StarknetEventsPage, StarknetRpcError>
176
+ /** `starknet_getTransactionReceipt`. A pre-confirmed receipt fails with `InvalidResponse`. */
177
+ readonly getTransactionReceipt: (
178
+ options: { readonly transactionHash: StarknetTransactionHash }
179
+ ) => Effect.Effect<StarknetTransactionReceipt, StarknetRpcError>
180
+ }>()("@effect-blockchain/starknet/StarknetRpc") {}
181
+
182
+ // error codes from the Starknet JSON-RPC spec v0.9 (starknet_api_openrpc.json), plus the common provider ones
183
+ const codes: ReadonlyMap<number, JsonRpc.CodeReason> = new Map([
184
+ // UNEXPECTED_ERROR, JSON-RPC internal error and provider rate limits: the endpoint is struggling, retry then fall back
185
+ [63, "Unavailable"],
186
+ [-32603, "Unavailable"],
187
+ [-32005, "Unavailable"],
188
+ [429, "Unavailable"],
189
+ // BLOCK_NOT_FOUND, TXN_HASH_NOT_FOUND: another endpoint may be further ahead
190
+ [24, "Lagging"],
191
+ [29, "Lagging"]
192
+ ])
193
+
194
+ /**
195
+ * Builds a {@link StarknetRpc} over `endpoints`, tried in order, sending requests with the provided `HttpClient`
196
+ * (e.g. `FetchHttpClient.layer`). `timeout` (default 30 seconds) bounds each attempt, `retries` (default 3) and
197
+ * `retryDelay` (default 500 millis) set the backoff before falling back: see {@link JsonRpc.Unavailable}.
198
+ *
199
+ * @since 0.1.0
200
+ * @category layers
201
+ */
202
+ export const layer = (options: {
203
+ readonly network: StarknetNetwork.StarknetNetwork
204
+ readonly endpoints: Arr.NonEmptyReadonlyArray<StarknetRpcEndpoint>
205
+ readonly timeout?: Duration.Input | undefined
206
+ readonly retries?: number | undefined
207
+ readonly retryDelay?: Duration.Input | undefined
208
+ }): Layer.Layer<StarknetRpc, never, HttpClient.HttpClient> =>
209
+ Layer.effect(
210
+ StarknetRpc,
211
+ Effect.gen(function*() {
212
+ const { network } = options
213
+ const expectedChainId = StarknetNetwork.toChainId(network)
214
+
215
+ const rpc = yield* JsonRpc.make({
216
+ spanPrefix: "StarknetRpc",
217
+ network,
218
+ endpoints: options.endpoints,
219
+ timeout: options.timeout,
220
+ retries: options.retries,
221
+ retryDelay: options.retryDelay,
222
+ codes,
223
+ checkNetwork: (send, endpoint) =>
224
+ send(RpcMethods.chainId, {}).pipe(
225
+ Effect.flatMap((chainId) =>
226
+ chainId === expectedChainId
227
+ ? Effect.succeed(expectedChainId)
228
+ : Effect.fail(
229
+ new StarknetRpcError({
230
+ reason: new JsonRpc.WrongNetwork({ expected: expectedChainId, actual: chainId }),
231
+ method: RpcMethods.chainId.name,
232
+ endpoint,
233
+ cause: new Error(`expected chain ID ${expectedChainId} for ${network}, got ${chainId}`)
234
+ })
235
+ )
236
+ )
237
+ ),
238
+ makeError: (fields: JsonRpc.ErrorFields) => new StarknetRpcError(fields)
239
+ })
240
+ type Endpoint = JsonRpc.Endpoint<StarknetNetwork.StarknetChainId, StarknetRpcError>
241
+
242
+ const blockNumberOn = (endpoint: Endpoint) =>
243
+ rpc.call(endpoint, RpcMethods.blockNumber, {}).pipe(
244
+ Effect.tap((head) => Ref.update(endpoint.head, (known) => head > known ? head : known))
245
+ )
246
+
247
+ const getEventsOn = (endpoint: Endpoint, filter: StarknetEventsFilter) =>
248
+ Effect.gen(function*() {
249
+ const method = RpcMethods.getEvents.name
250
+ yield* rpc.requireHead(endpoint, method, filter.toBlock, blockNumberOn(endpoint))
251
+ const page = yield* rpc.call(endpoint, RpcMethods.getEvents, {
252
+ filter: {
253
+ address: filter.address,
254
+ from_block: { block_number: filter.fromBlock },
255
+ to_block: { block_number: filter.toBlock },
256
+ ...(filter.keys !== undefined && { keys: filter.keys }),
257
+ chunk_size: filter.chunkSize ?? 1000,
258
+ ...(filter.cursor !== undefined && { continuation_token: filter.cursor.cursor })
259
+ }
260
+ })
261
+ const invalid = page.events.find((event) =>
262
+ event.blockNumber < filter.fromBlock || event.blockNumber > filter.toBlock ||
263
+ event.fromAddress !== filter.address
264
+ )
265
+ if (invalid !== undefined) {
266
+ return yield* rpc.fail(
267
+ endpoint,
268
+ method,
269
+ new JsonRpc.InvalidResponse(),
270
+ new Error(`event of ${invalid.transactionHash} in block ${invalid.blockNumber} is outside the filter`)
271
+ )
272
+ }
273
+ return {
274
+ events: page.events,
275
+ cursor: page.continuation_token === undefined ? undefined : StarknetEventsCursor.make({
276
+ endpoint: endpoint.name,
277
+ cursor: page.continuation_token
278
+ })
279
+ }
280
+ })
281
+
282
+ const getEvents = (filter: StarknetEventsFilter): Effect.Effect<StarknetEventsPage, StarknetRpcError> => {
283
+ if (filter.fromBlock > filter.toBlock) return Effect.succeed({ events: [], cursor: undefined })
284
+ if (filter.cursor === undefined) return rpc.withFallback((endpoint) => getEventsOn(endpoint, filter))
285
+ // a cursor only means something to the endpoint that issued it
286
+ return rpc.endpointOf(RpcMethods.getEvents.name, filter.cursor).pipe(
287
+ Effect.flatMap((endpoint) => getEventsOn(endpoint, filter))
288
+ )
289
+ }
290
+
291
+ return StarknetRpc.of({
292
+ network,
293
+ chainId: rpc.withFallback(rpc.checkNetwork),
294
+ blockNumber: rpc.withFallback(blockNumberOn),
295
+ getBlockWithTxHashes: ({ blockNumber }) =>
296
+ rpc.withFallback((endpoint) =>
297
+ rpc.requireHead(endpoint, RpcMethods.getBlockWithTxHashes.name, blockNumber, blockNumberOn(endpoint)).pipe(
298
+ Effect.andThen(
299
+ rpc.call(endpoint, RpcMethods.getBlockWithTxHashes, { block_id: { block_number: blockNumber } })
300
+ )
301
+ )
302
+ ),
303
+ getEvents,
304
+ getTransactionReceipt: ({ transactionHash }) =>
305
+ rpc.withFallback((endpoint) =>
306
+ rpc.call(endpoint, RpcMethods.getTransactionReceipt, { transaction_hash: transactionHash })
307
+ )
308
+ })
309
+ })
310
+ )
311
+
312
+ /**
313
+ * Builds an {@link StarknetRpc} like {@link layer}, reading the options from `Config`. Endpoint URLs stay `Redacted`.
314
+ *
315
+ * @example
316
+ * ```ts
317
+ * import * as StarknetRpc from "@effect-blockchain/starknet/StarknetRpc"
318
+ * import * as Config from "effect/Config"
319
+ *
320
+ * const RpcLive = StarknetRpc.layerConfig({
321
+ * network: Config.succeed("Starknet"),
322
+ * endpoints: Config.all([Config.all({ name: Config.succeed("main"), url: Config.Redacted("STARKNET_RPC_URL") })])
323
+ * })
324
+ * ```
325
+ *
326
+ * @since 0.1.0
327
+ * @category layers
328
+ */
329
+ export const layerConfig = (
330
+ options: Config.Wrap<Parameters<typeof layer>[0]>
331
+ ): Layer.Layer<StarknetRpc, Config.ConfigError, HttpClient.HttpClient> =>
332
+ Layer.unwrap(Effect.map(Config.unwrap(options), layer))
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Starknet transaction hashes.
3
+ *
4
+ * @since 0.1.0
5
+ */
6
+ import * as Schema from "effect/Schema"
7
+ import { PaddedFelt } from "./internal/PaddedFelt.ts"
8
+
9
+ /**
10
+ * A Starknet transaction hash: `0x` followed by 64 lowercase hex digits.
11
+ *
12
+ * Decoding lowercases the input and left-pads it with zeros, so `"0xc9"` decodes
13
+ * to `"0x00…00c9"`.
14
+ *
15
+ * @since 0.1.0
16
+ * @category schemas
17
+ */
18
+ export const StarknetTransactionHash = PaddedFelt.pipe(
19
+ Schema.brand("StarknetTransactionHash"),
20
+ Schema.annotate({
21
+ identifier: "StarknetTransactionHash",
22
+ title: "Starknet transaction hash",
23
+ description: "a valid Starknet transaction hash, starting with 0x and followed by 64 hexadecimal characters"
24
+ })
25
+ )
26
+
27
+ /**
28
+ * @since 0.1.0
29
+ * @category models
30
+ */
31
+ export type StarknetTransactionHash = typeof StarknetTransactionHash.Type
package/src/index.ts ADDED
@@ -0,0 +1,40 @@
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 StarknetAddress from "./StarknetAddress.ts"
11
+
12
+ /**
13
+ * @since 0.1.0
14
+ */
15
+ export * as StarknetBlock from "./StarknetBlock.ts"
16
+
17
+ /**
18
+ * @since 0.1.0
19
+ */
20
+ export * as StarknetEvent from "./StarknetEvent.ts"
21
+
22
+ /**
23
+ * @since 0.1.0
24
+ */
25
+ export * as StarknetIndexer from "./StarknetIndexer.ts"
26
+
27
+ /**
28
+ * @since 0.1.0
29
+ */
30
+ export * as StarknetNetwork from "./StarknetNetwork.ts"
31
+
32
+ /**
33
+ * @since 0.1.0
34
+ */
35
+ export * as StarknetRpc from "./StarknetRpc.ts"
36
+
37
+ /**
38
+ * @since 0.1.0
39
+ */
40
+ export * as StarknetTransactionHash from "./StarknetTransactionHash.ts"
@@ -0,0 +1,18 @@
1
+ import { identity } from "effect/Function"
2
+ import * as Schema from "effect/Schema"
3
+ import * as SchemaTransformation from "effect/SchemaTransformation"
4
+
5
+ const padFelt = (hex: string): string => `0x${(hex.startsWith("0x") ? hex.slice(2) : hex).padStart(64, "0")}`
6
+
7
+ /**
8
+ * A field element as a hex string: accepts 1 to 64 hex digits with an optional
9
+ * `0x` prefix in any case, decodes to `0x` + 64 lowercase hex digits.
10
+ *
11
+ * @internal
12
+ */
13
+ export const PaddedFelt = Schema.String.pipe(
14
+ Schema.check(Schema.isPattern(/^(0x)?[0-9a-fA-F]{1,64}$/u)),
15
+ Schema.decodeTo(Schema.String, SchemaTransformation.toLowerCase()),
16
+ Schema.decodeTo(Schema.String, SchemaTransformation.transform({ decode: padFelt, encode: identity })),
17
+ Schema.check(Schema.isPattern(/^0x[0-9a-f]{64}$/u))
18
+ )
@@ -0,0 +1,88 @@
1
+ import * as JsonRpc from "@effect-blockchain/core/JsonRpc"
2
+ import * as Schema from "effect/Schema"
3
+ import * as SchemaTransformation from "effect/SchemaTransformation"
4
+ import { StarknetAddress } from "../StarknetAddress.ts"
5
+ import { StarknetBlock } from "../StarknetBlock.ts"
6
+ import { StarknetEvent } from "../StarknetEvent.ts"
7
+ import { StarknetTransactionHash } from "../StarknetTransactionHash.ts"
8
+ import { PaddedFelt } from "./PaddedFelt.ts"
9
+
10
+ // by-name params: every method sends an object, `{}` when it takes none
11
+ const make = <Params, Result>(method: JsonRpc.Method<Params, Result>): JsonRpc.Method<Params, Result> => method
12
+
13
+ const NoParams = Schema.Struct({})
14
+
15
+ const decodeShortString = (felt: string) => {
16
+ const hex = BigInt(felt).toString(16)
17
+ return hex.padStart(hex.length + hex.length % 2, "0").replace(
18
+ /../g,
19
+ (byte) => String.fromCharCode(parseInt(byte, 16))
20
+ )
21
+ }
22
+
23
+ const encodeShortString = (text: string) =>
24
+ `0x${Array.from(text, (char) => char.charCodeAt(0).toString(16).padStart(2, "0")).join("")}`
25
+
26
+ // a chain ID is a short string encoded as a felt: "0x534e5f4d41494e" is "SN_MAIN"
27
+ const ShortStringFromFelt = Schema.String.check(Schema.isPattern(/^0x[0-9a-fA-F]{1,64}$/)).pipe(
28
+ Schema.decodeTo(
29
+ Schema.String,
30
+ SchemaTransformation.transform({ decode: decodeShortString, encode: encodeShortString })
31
+ )
32
+ )
33
+
34
+ // params accept any felt (`0x1`), results are normalized to 64 digits
35
+ const Felt = Schema.toEncoded(PaddedFelt)
36
+
37
+ const BlockId = Schema.Struct({ block_number: JsonRpc.BigIntFromInt })
38
+
39
+ /** @internal */
40
+ export const chainId = make({ name: "starknet_chainId", params: NoParams, result: ShortStringFromFelt })
41
+
42
+ /** @internal */
43
+ export const blockNumber = make({ name: "starknet_blockNumber", params: NoParams, result: JsonRpc.BigIntFromInt })
44
+
45
+ /** @internal */
46
+ export const getBlockWithTxHashes = make({
47
+ name: "starknet_getBlockWithTxHashes",
48
+ params: Schema.Struct({ block_id: BlockId }),
49
+ // a pre-confirmed block has no block hash and does not decode
50
+ result: StarknetBlock
51
+ })
52
+
53
+ /** @internal */
54
+ export const getEvents = make({
55
+ name: "starknet_getEvents",
56
+ params: Schema.Struct({
57
+ filter: Schema.Struct({
58
+ address: StarknetAddress,
59
+ from_block: BlockId,
60
+ to_block: BlockId,
61
+ keys: Schema.optionalKey(Schema.Array(Schema.Array(Felt))),
62
+ chunk_size: Schema.Int,
63
+ continuation_token: Schema.optionalKey(Schema.String)
64
+ })
65
+ }),
66
+ result: Schema.Struct({
67
+ events: Schema.Array(StarknetEvent),
68
+ continuation_token: Schema.optionalKey(Schema.String)
69
+ })
70
+ })
71
+
72
+ /** @internal */
73
+ export const getTransactionReceipt = make({
74
+ name: "starknet_getTransactionReceipt",
75
+ params: Schema.Struct({ transaction_hash: StarknetTransactionHash }),
76
+ // a pre-confirmed receipt has no block hash and does not decode
77
+ result: Schema.Struct({
78
+ transactionHash: StarknetTransactionHash,
79
+ blockNumber: JsonRpc.BigIntFromInt,
80
+ blockHash: PaddedFelt,
81
+ events: Schema.Array(
82
+ Schema.Struct({ fromAddress: StarknetAddress, keys: Schema.Array(PaddedFelt), data: Schema.Array(PaddedFelt) })
83
+ .pipe(Schema.encodeKeys({ fromAddress: "from_address" }))
84
+ )
85
+ }).pipe(
86
+ Schema.encodeKeys({ transactionHash: "transaction_hash", blockNumber: "block_number", blockHash: "block_hash" })
87
+ )
88
+ })