@effect-blockchain/starknet 0.1.0 → 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 (49) hide show
  1. package/dist/StarknetIndexer.d.ts +40 -2
  2. package/dist/StarknetIndexer.d.ts.map +1 -1
  3. package/dist/StarknetIndexer.js +89 -14
  4. package/dist/StarknetIndexer.js.map +1 -1
  5. package/dist/StarknetNetwork.d.ts +9 -0
  6. package/dist/StarknetNetwork.d.ts.map +1 -1
  7. package/dist/StarknetNetwork.js +9 -0
  8. package/dist/StarknetNetwork.js.map +1 -1
  9. package/dist/StarknetRelayer.d.ts +273 -0
  10. package/dist/StarknetRelayer.d.ts.map +1 -0
  11. package/dist/StarknetRelayer.js +352 -0
  12. package/dist/StarknetRelayer.js.map +1 -0
  13. package/dist/StarknetRpc.d.ts +107 -5
  14. package/dist/StarknetRpc.d.ts.map +1 -1
  15. package/dist/StarknetRpc.js +83 -5
  16. package/dist/StarknetRpc.js.map +1 -1
  17. package/dist/StarknetSigner.d.ts +75 -0
  18. package/dist/StarknetSigner.d.ts.map +1 -0
  19. package/dist/StarknetSigner.js +84 -0
  20. package/dist/StarknetSigner.js.map +1 -0
  21. package/dist/StarknetTransaction.d.ts +74 -0
  22. package/dist/StarknetTransaction.d.ts.map +1 -0
  23. package/dist/StarknetTransaction.js +2 -0
  24. package/dist/StarknetTransaction.js.map +1 -0
  25. package/dist/index.d.ts +12 -0
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +12 -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 +135 -0
  34. package/dist/internal/rpcMethods.js.map +1 -1
  35. package/dist/internal/transactionHash.d.ts +2 -0
  36. package/dist/internal/transactionHash.d.ts.map +1 -0
  37. package/dist/internal/transactionHash.js +60 -0
  38. package/dist/internal/transactionHash.js.map +1 -0
  39. package/package.json +1 -1
  40. package/src/StarknetIndexer.ts +141 -26
  41. package/src/StarknetNetwork.ts +12 -0
  42. package/src/StarknetRelayer.ts +437 -0
  43. package/src/StarknetRpc.ts +198 -6
  44. package/src/StarknetSigner.ts +115 -0
  45. package/src/StarknetTransaction.ts +68 -0
  46. package/src/index.ts +15 -0
  47. package/src/internal/confirmations.ts +17 -0
  48. package/src/internal/rpcMethods.ts +136 -0
  49. package/src/internal/transactionHash.ts +64 -0
@@ -29,6 +29,29 @@
29
29
  * })
30
30
  * ```
31
31
  *
32
+ * The STRK balance of an address, in fri, is read at one block or sampled every `step` blocks:
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * import type { StarknetAddress } from "@effect-blockchain/starknet/StarknetAddress"
37
+ * import { StarknetIndexer } from "@effect-blockchain/starknet/StarknetIndexer"
38
+ * import * as Effect from "effect/Effect"
39
+ * import * as Stream from "effect/Stream"
40
+ *
41
+ * declare const address: StarknetAddress
42
+ *
43
+ * // the balance every 1000 blocks from block 1000000 to 1010000
44
+ * const balances = Effect.gen(function*() {
45
+ * const indexer = yield* StarknetIndexer
46
+ * return yield* indexer.streamNativeBalance({
47
+ * address,
48
+ * fromBlock: BigInt(1_000_000),
49
+ * toBlock: BigInt(1_010_000),
50
+ * step: 1000
51
+ * }).pipe(Stream.runCollect)
52
+ * })
53
+ * ```
54
+ *
32
55
  * @since 0.1.0
33
56
  */
34
57
  import * as JsonRpc from "@effect-blockchain/core/JsonRpc"
@@ -42,10 +65,12 @@ import * as Layer from "effect/Layer"
42
65
  import * as Option from "effect/Option"
43
66
  import * as Schedule from "effect/Schedule"
44
67
  import * as Stream from "effect/Stream"
68
+ import * as Confirmations from "./internal/confirmations.ts"
69
+ import type { StarknetAddress } from "./StarknetAddress.ts"
45
70
  import type { StarknetEvent } from "./StarknetEvent.ts"
46
71
  import * as StarknetNetwork from "./StarknetNetwork.ts"
47
- import type { StarknetEventsCursor, StarknetEventsFilter, StarknetRpcError } from "./StarknetRpc.ts"
48
- import { StarknetRpc } from "./StarknetRpc.ts"
72
+ import type { StarknetEventsCursor, StarknetEventsFilter } from "./StarknetRpc.ts"
73
+ import { StarknetRpc, StarknetRpcError } from "./StarknetRpc.ts"
49
74
 
50
75
  /**
51
76
  * A {@link StarknetIndexer} `fetchEvents` filter: a `starknet_getEvents` filter without its paging fields, over the
@@ -101,6 +126,35 @@ export interface StarknetIndexerStreamOptions {
101
126
  readonly retry?: Schedule.Schedule<unknown, StarknetRpcError> | undefined
102
127
  }
103
128
 
129
+ /**
130
+ * The STRK balance of an address in fri at the end of `block`, emitted by
131
+ * {@link StarknetIndexer.Service.streamNativeBalance}.
132
+ *
133
+ * @since 0.2.0
134
+ * @category models
135
+ */
136
+ export interface StarknetNativeBalance {
137
+ readonly block: bigint
138
+ readonly balance: bigint
139
+ }
140
+
141
+ /**
142
+ * The {@link StarknetIndexer.Service.streamNativeBalance} options: one sample every `step` blocks from `fromBlock`.
143
+ * `step` is a positive integer, `poll` and `retry` behave as in {@link StarknetIndexerStreamOptions}.
144
+ *
145
+ * @since 0.2.0
146
+ * @category models
147
+ */
148
+ export interface StarknetIndexerNativeBalanceOptions {
149
+ readonly address: StarknetAddress
150
+ readonly fromBlock: bigint
151
+ /** The stream ends after the last sample at or below it, and is empty when `fromBlock > toBlock`. */
152
+ readonly toBlock?: bigint | undefined
153
+ readonly step: number
154
+ readonly poll?: Schedule.Schedule<unknown> | undefined
155
+ readonly retry?: Schedule.Schedule<unknown, StarknetRpcError> | undefined
156
+ }
157
+
104
158
  /**
105
159
  * @since 0.1.0
106
160
  * @category services
@@ -120,6 +174,17 @@ export class StarknetIndexer extends Context.Service<StarknetIndexer, {
120
174
  readonly streamEvents: (
121
175
  options: StarknetIndexerStreamOptions
122
176
  ) => Stream.Stream<StarknetIndexerBatch, StarknetRpcError>
177
+ /** The STRK balance of `address` in fri at the end of `block`. A `block` above `lastConfirmedBlock` is accepted. */
178
+ readonly fetchNativeBalance: (
179
+ options: { readonly address: StarknetAddress; readonly block: bigint }
180
+ ) => Effect.Effect<bigint, StarknetRpcError>
181
+ /**
182
+ * The STRK balance of `address` at `fromBlock`, `fromBlock + step`, `fromBlock + 2 * step`... one sample per step
183
+ * even when unchanged, following the confirmed head.
184
+ */
185
+ readonly streamNativeBalance: (
186
+ options: StarknetIndexerNativeBalanceOptions
187
+ ) => Stream.Stream<StarknetNativeBalance, StarknetRpcError>
123
188
  }>()("@effect-blockchain/starknet/StarknetIndexer") {}
124
189
 
125
190
  /**
@@ -130,6 +195,9 @@ export class StarknetIndexer extends Context.Service<StarknetIndexer, {
130
195
  */
131
196
  export const DEFAULT_POLL_INTERVAL: Duration.Duration = Duration.seconds(10)
132
197
 
198
+ // sn_keccak("balanceOf"), the ERC-20 entry point selector
199
+ const BALANCE_OF = "0x02e4263afad30923c891518314c3c95dbe830a16874e8abc5777a9a20b54c76e"
200
+
133
201
  // the confirmed blocks [next, head] not indexed yet, empty once the stream reaches the head it last read
134
202
  interface StreamPosition {
135
203
  readonly next: bigint
@@ -159,10 +227,8 @@ export const layer = (options: {
159
227
  if (!Number.isSafeInteger(maxBlockRange) || maxBlockRange < 1) {
160
228
  return yield* Effect.die(new RangeError(`maxBlockRange must be a positive integer, got ${maxBlockRange}`))
161
229
  }
162
- const confirmations = BigInt(options.confirmations ?? StarknetNetwork.defaultConfirmations(rpc.network))
163
230
  const size = BigInt(maxBlockRange)
164
- const lastConfirmedBlock = rpc.blockNumber.pipe(
165
- Effect.map((head) => BigInt_.max(head - confirmations, BigInt(0))),
231
+ const lastConfirmedBlock = Confirmations.lastConfirmedBlock(rpc, options.confirmations).pipe(
166
232
  Effect.withSpan("StarknetIndexer.lastConfirmedBlock")
167
233
  )
168
234
  const fetchEvents = Effect.fn("StarknetIndexer.fetchEvents")((filter: StarknetIndexerFilter) =>
@@ -191,38 +257,87 @@ export const layer = (options: {
191
257
  }
192
258
  ).pipe(Effect.map(Arr.flatten))
193
259
  )
260
+ // the head last read is reused while it covers `next` (the confirmed head only moves forward), else polled
261
+ const confirmedFor = (next: bigint, head: bigint, poll: Schedule.Schedule<unknown>) =>
262
+ next <= head
263
+ ? Effect.succeed(head)
264
+ : lastConfirmedBlock.pipe(Effect.repeat({ schedule: poll, until: (confirmed) => confirmed >= next }))
265
+ const retrying = <A, S>(
266
+ step: (state: S) => Effect.Effect<A, StarknetRpcError>,
267
+ retry: Schedule.Schedule<unknown, StarknetRpcError> | undefined
268
+ ) =>
269
+ retry === undefined
270
+ ? step
271
+ : (state: S) =>
272
+ Effect.retry(step(state), { schedule: retry, while: (error) => JsonRpc.isTransient(error.reason) })
273
+ const fetchNativeBalance = Effect.fn("StarknetIndexer.fetchNativeBalance")(
274
+ ({ address, block }: { readonly address: StarknetAddress; readonly block: bigint }) =>
275
+ rpc.call({
276
+ contractAddress: StarknetNetwork.STRK_TOKEN_ADDRESS,
277
+ entryPointSelector: BALANCE_OF,
278
+ calldata: [address],
279
+ blockNumber: block
280
+ }).pipe(Effect.flatMap((felts) =>
281
+ felts.length === 2
282
+ ? Effect.succeed(BigInt(felts[0]) + (BigInt(felts[1]) << BigInt(128)))
283
+ : Effect.fail(
284
+ new StarknetRpcError({
285
+ reason: new JsonRpc.InvalidResponse(),
286
+ method: "starknet_call",
287
+ endpoint: "StarknetIndexer",
288
+ cause: new Error(`balanceOf returned ${felts.length} felts, expected a u256 (low, high)`)
289
+ })
290
+ )
291
+ ))
292
+ )
194
293
  return StarknetIndexer.of({
195
294
  lastConfirmedBlock,
196
295
  fetchEvents,
296
+ fetchNativeBalance,
297
+ streamNativeBalance: (
298
+ { address, fromBlock, poll = Schedule.spaced(DEFAULT_POLL_INTERVAL), retry, step, toBlock }
299
+ ) => {
300
+ if (!Number.isSafeInteger(step) || step < 1) {
301
+ return Stream.die(new RangeError(`step must be a positive integer, got ${step}`))
302
+ }
303
+ if (toBlock !== undefined && fromBlock > toBlock) return Stream.empty
304
+ const size = BigInt(step)
305
+ const sample = (
306
+ { head, next }: StreamPosition
307
+ ): Effect.Effect<
308
+ readonly [ReadonlyArray<StarknetNativeBalance>, Option.Option<StreamPosition>],
309
+ StarknetRpcError
310
+ > =>
311
+ confirmedFor(next, head, poll).pipe(Effect.flatMap((confirmed) => {
312
+ if (next > confirmed) return Effect.succeed([[], Option.none()])
313
+ return fetchNativeBalance({ address, block: next }).pipe(Effect.map((balance) => [
314
+ [{ block: next, balance }],
315
+ toBlock !== undefined && next + size > toBlock
316
+ ? Option.none()
317
+ : Option.some({ next: next + size, head: confirmed })
318
+ ]))
319
+ }))
320
+ return Stream.paginate({ next: fromBlock, head: fromBlock - BigInt(1) }, retrying(sample, retry))
321
+ },
197
322
  streamEvents: ({ filter, fromBlock, poll = Schedule.spaced(DEFAULT_POLL_INTERVAL), retry, toBlock }) => {
198
323
  if (toBlock !== undefined && fromBlock > toBlock) return Stream.empty
199
- // the head last read is reused while it covers `next` (the confirmed head only moves forward), else polled
200
324
  const step = (
201
325
  { head, next }: StreamPosition
202
326
  ): Effect.Effect<
203
327
  readonly [ReadonlyArray<StarknetIndexerBatch>, Option.Option<StreamPosition>],
204
328
  StarknetRpcError
205
329
  > =>
206
- (next <= head
207
- ? Effect.succeed(head)
208
- : lastConfirmedBlock.pipe(Effect.repeat({ schedule: poll, until: (confirmed) => confirmed >= next })))
209
- .pipe(Effect.flatMap((confirmed) => {
210
- const cap = toBlock === undefined ? confirmed : BigInt_.min(confirmed, toBlock)
211
- if (next > cap) return Effect.succeed([[], Option.none()])
212
- const end = BigInt_.min(next + size - BigInt(1), cap)
213
- return fetchEvents({ ...filter, fromBlock: next, toBlock: end }).pipe(Effect.map((events) => [
214
- [{ fromBlock: next, toBlock: end, events }],
215
- end === toBlock ? Option.none() : Option.some({ next: end + BigInt(1), head: confirmed })
216
- ]))
217
- }))
218
- return Stream.paginate(
219
- // a head below `fromBlock`: the first step reads it
220
- { next: fromBlock, head: fromBlock - BigInt(1) },
221
- retry === undefined
222
- ? step
223
- : (remaining) =>
224
- Effect.retry(step(remaining), { schedule: retry, while: (error) => JsonRpc.isTransient(error.reason) })
225
- )
330
+ confirmedFor(next, head, poll).pipe(Effect.flatMap((confirmed) => {
331
+ const cap = toBlock === undefined ? confirmed : BigInt_.min(confirmed, toBlock)
332
+ if (next > cap) return Effect.succeed([[], Option.none()])
333
+ const end = BigInt_.min(next + size - BigInt(1), cap)
334
+ return fetchEvents({ ...filter, fromBlock: next, toBlock: end }).pipe(Effect.map((events) => [
335
+ [{ fromBlock: next, toBlock: end, events }],
336
+ end === toBlock ? Option.none() : Option.some({ next: end + BigInt(1), head: confirmed })
337
+ ]))
338
+ }))
339
+ // a head below `fromBlock`: the first step reads it
340
+ return Stream.paginate({ next: fromBlock, head: fromBlock - BigInt(1) }, retrying(step, retry))
226
341
  }
227
342
  })
228
343
  })
@@ -4,6 +4,7 @@
4
4
  * @since 0.1.0
5
5
  */
6
6
  import * as Schema from "effect/Schema"
7
+ import { StarknetAddress } from "./StarknetAddress.ts"
7
8
 
8
9
  /**
9
10
  * @since 0.1.0
@@ -87,6 +88,17 @@ export const defaultConfirmations = (network: StarknetNetwork): number => {
87
88
  }
88
89
  }
89
90
 
91
+ /**
92
+ * The STRK token contract, the token Starknet fees are paid in, counted in fri (10^-18 STRK). The same address on
93
+ * mainnet and Sepolia: https://docs.starknet.io/resources/chain-info
94
+ *
95
+ * @since 0.2.0
96
+ * @category constants
97
+ */
98
+ export const STRK_TOKEN_ADDRESS: StarknetAddress = StarknetAddress.make(
99
+ "0x04718f5a0fc34cc1af16a1cdee98ffb20c31f5cd61d6ab07201858f4287c938d"
100
+ )
101
+
90
102
  /**
91
103
  * @since 0.1.0
92
104
  * @category predicates