@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
package/dist/index.js ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @since 0.1.0
3
+ */
4
+ // @barrel: Auto-generated exports. Do not edit manually.
5
+ /**
6
+ * @since 0.1.0
7
+ */
8
+ export * as StarknetAddress from "./StarknetAddress.js";
9
+ /**
10
+ * @since 0.1.0
11
+ */
12
+ export * as StarknetBlock from "./StarknetBlock.js";
13
+ /**
14
+ * @since 0.1.0
15
+ */
16
+ export * as StarknetEvent from "./StarknetEvent.js";
17
+ /**
18
+ * @since 0.1.0
19
+ */
20
+ export * as StarknetIndexer from "./StarknetIndexer.js";
21
+ /**
22
+ * @since 0.1.0
23
+ */
24
+ export * as StarknetNetwork from "./StarknetNetwork.js";
25
+ /**
26
+ * @since 0.1.0
27
+ */
28
+ export * as StarknetRpc from "./StarknetRpc.js";
29
+ /**
30
+ * @since 0.1.0
31
+ */
32
+ export * as StarknetTransactionHash from "./StarknetTransactionHash.js";
33
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":[null],"mappings":"AAAA;;;AAIA;AAEA;;;AAGA,OAAO,KAAK,eAAe,MAAM,sBAAsB;AAEvD;;;AAGA,OAAO,KAAK,aAAa,MAAM,oBAAoB;AAEnD;;;AAGA,OAAO,KAAK,aAAa,MAAM,oBAAoB;AAEnD;;;AAGA,OAAO,KAAK,eAAe,MAAM,sBAAsB;AAEvD;;;AAGA,OAAO,KAAK,eAAe,MAAM,sBAAsB;AAEvD;;;AAGA,OAAO,KAAK,WAAW,MAAM,kBAAkB;AAE/C;;;AAGA,OAAO,KAAK,uBAAuB,MAAM,8BAA8B","ignoreList":[]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=PaddedFelt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PaddedFelt.d.ts","sourceRoot":"","sources":["../../src/internal/PaddedFelt.ts"],"names":[],"mappings":""}
@@ -0,0 +1,15 @@
1
+ import { identity } from "effect/Function";
2
+ import * as Schema from "effect/Schema";
3
+ import * as SchemaTransformation from "effect/SchemaTransformation";
4
+ const padFelt = hex => `0x${(hex.startsWith("0x") ? hex.slice(2) : hex).padStart(64, "0")}`;
5
+ /**
6
+ * A field element as a hex string: accepts 1 to 64 hex digits with an optional
7
+ * `0x` prefix in any case, decodes to `0x` + 64 lowercase hex digits.
8
+ *
9
+ * @internal
10
+ */
11
+ export const PaddedFelt = /*#__PURE__*/Schema.String.pipe(/*#__PURE__*/Schema.check(/*#__PURE__*/Schema.isPattern(/^(0x)?[0-9a-fA-F]{1,64}$/u)), /*#__PURE__*/Schema.decodeTo(Schema.String, /*#__PURE__*/SchemaTransformation.toLowerCase()), /*#__PURE__*/Schema.decodeTo(Schema.String, /*#__PURE__*/SchemaTransformation.transform({
12
+ decode: padFelt,
13
+ encode: identity
14
+ })), /*#__PURE__*/Schema.check(/*#__PURE__*/Schema.isPattern(/^0x[0-9a-f]{64}$/u)));
15
+ //# sourceMappingURL=PaddedFelt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PaddedFelt.js","names":[],"sources":["../../src/internal/PaddedFelt.ts"],"sourcesContent":[null],"mappings":"AAAA,SAAS,QAAQ,QAAQ,iBAAiB;AAC1C,OAAO,KAAK,MAAM,MAAM,eAAe;AACvC,OAAO,KAAK,oBAAoB,MAAM,6BAA6B;AAEnE,MAAM,OAAO,GAAI,GAAW,IAAa,KAAK,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,GAAG,EAAE,QAAQ,CAAC,EAAE,EAAE,GAAG,CAAC,EAAE;AAE7G;;;;;;AAMA,OAAO,MAAM,UAAU,gBAAG,MAAM,CAAC,MAAM,CAAC,IAAI,cAC1C,MAAM,CAAC,KAAK,cAAC,MAAM,CAAC,SAAS,CAAC,2BAA2B,CAAC,CAAC,eAC3D,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,eAAE,oBAAoB,CAAC,WAAW,EAAE,CAAC,eAClE,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,eAAE,oBAAoB,CAAC,SAAS,CAAC;EAAE,MAAM,EAAE,OAAO;EAAE,MAAM,EAAE;AAAQ,CAAE,CAAC,CAAC,eACrG,MAAM,CAAC,KAAK,cAAC,MAAM,CAAC,SAAS,CAAC,mBAAmB,CAAC,CAAC,CACpD","ignoreList":[]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=rpcMethods.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpcMethods.d.ts","sourceRoot":"","sources":["../../src/internal/rpcMethods.ts"],"names":[],"mappings":""}
@@ -0,0 +1,90 @@
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.js";
5
+ import { StarknetBlock } from "../StarknetBlock.js";
6
+ import { StarknetEvent } from "../StarknetEvent.js";
7
+ import { StarknetTransactionHash } from "../StarknetTransactionHash.js";
8
+ import { PaddedFelt } from "./PaddedFelt.js";
9
+ // by-name params: every method sends an object, `{}` when it takes none
10
+ const make = method => method;
11
+ const NoParams = /*#__PURE__*/Schema.Struct({});
12
+ const decodeShortString = felt => {
13
+ const hex = BigInt(felt).toString(16);
14
+ return hex.padStart(hex.length + hex.length % 2, "0").replace(/../g, byte => String.fromCharCode(parseInt(byte, 16)));
15
+ };
16
+ const encodeShortString = text => `0x${Array.from(text, char => char.charCodeAt(0).toString(16).padStart(2, "0")).join("")}`;
17
+ // a chain ID is a short string encoded as a felt: "0x534e5f4d41494e" is "SN_MAIN"
18
+ const ShortStringFromFelt = /*#__PURE__*/Schema.String.check(Schema.isPattern(/^0x[0-9a-fA-F]{1,64}$/)).pipe(/*#__PURE__*/Schema.decodeTo(Schema.String, /*#__PURE__*/SchemaTransformation.transform({
19
+ decode: decodeShortString,
20
+ encode: encodeShortString
21
+ })));
22
+ // params accept any felt (`0x1`), results are normalized to 64 digits
23
+ const Felt = /*#__PURE__*/Schema.toEncoded(PaddedFelt);
24
+ const BlockId = /*#__PURE__*/Schema.Struct({
25
+ block_number: JsonRpc.BigIntFromInt
26
+ });
27
+ /** @internal */
28
+ export const chainId = /*#__PURE__*/make({
29
+ name: "starknet_chainId",
30
+ params: NoParams,
31
+ result: ShortStringFromFelt
32
+ });
33
+ /** @internal */
34
+ export const blockNumber = /*#__PURE__*/make({
35
+ name: "starknet_blockNumber",
36
+ params: NoParams,
37
+ result: JsonRpc.BigIntFromInt
38
+ });
39
+ /** @internal */
40
+ export const getBlockWithTxHashes = /*#__PURE__*/make({
41
+ name: "starknet_getBlockWithTxHashes",
42
+ params: /*#__PURE__*/Schema.Struct({
43
+ block_id: BlockId
44
+ }),
45
+ // a pre-confirmed block has no block hash and does not decode
46
+ result: StarknetBlock
47
+ });
48
+ /** @internal */
49
+ export const getEvents = /*#__PURE__*/make({
50
+ name: "starknet_getEvents",
51
+ params: /*#__PURE__*/Schema.Struct({
52
+ filter: /*#__PURE__*/Schema.Struct({
53
+ address: StarknetAddress,
54
+ from_block: BlockId,
55
+ to_block: BlockId,
56
+ keys: /*#__PURE__*/Schema.optionalKey(/*#__PURE__*/Schema.Array(/*#__PURE__*/Schema.Array(Felt))),
57
+ chunk_size: Schema.Int,
58
+ continuation_token: /*#__PURE__*/Schema.optionalKey(Schema.String)
59
+ })
60
+ }),
61
+ result: /*#__PURE__*/Schema.Struct({
62
+ events: /*#__PURE__*/Schema.Array(StarknetEvent),
63
+ continuation_token: /*#__PURE__*/Schema.optionalKey(Schema.String)
64
+ })
65
+ });
66
+ /** @internal */
67
+ export const getTransactionReceipt = /*#__PURE__*/make({
68
+ name: "starknet_getTransactionReceipt",
69
+ params: /*#__PURE__*/Schema.Struct({
70
+ transaction_hash: StarknetTransactionHash
71
+ }),
72
+ // a pre-confirmed receipt has no block hash and does not decode
73
+ result: /*#__PURE__*/Schema.Struct({
74
+ transactionHash: StarknetTransactionHash,
75
+ blockNumber: JsonRpc.BigIntFromInt,
76
+ blockHash: PaddedFelt,
77
+ events: Schema.Array(Schema.Struct({
78
+ fromAddress: StarknetAddress,
79
+ keys: Schema.Array(PaddedFelt),
80
+ data: Schema.Array(PaddedFelt)
81
+ }).pipe(Schema.encodeKeys({
82
+ fromAddress: "from_address"
83
+ })))
84
+ }).pipe(/*#__PURE__*/Schema.encodeKeys({
85
+ transactionHash: "transaction_hash",
86
+ blockNumber: "block_number",
87
+ blockHash: "block_hash"
88
+ }))
89
+ });
90
+ //# sourceMappingURL=rpcMethods.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpcMethods.js","names":[],"sources":["../../src/internal/rpcMethods.ts"],"sourcesContent":[null],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,iCAAiC;AAC1D,OAAO,KAAK,MAAM,MAAM,eAAe;AACvC,OAAO,KAAK,oBAAoB,MAAM,6BAA6B;AACnE,SAAS,eAAe,QAAQ,uBAAuB;AACvD,SAAS,aAAa,QAAQ,qBAAqB;AACnD,SAAS,aAAa,QAAQ,qBAAqB;AACnD,SAAS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AAgB,EAAE;EAAuB,CAAE,CAAC;EACpE;EACA,MAAM,eAAE,MAAM,CAAC,MAAM,CAAC;IACpB,eAAe,EAAE,uBAAuB;IACxC,WAAW,EAAE,OAAO,CAAC,aAAa;IAClC,SAAS,EAAE,UAAU;IACrB,MAAM,EAAE,MAAM,CAAC,KAAK,CAClB,MAAM,CAAC,MAAM,CAAC;MAAE,WAAW,EAAE,eAAe;MAAE,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC;MAAE,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,UAAU;IAAC,CAAE,CAAC,CAC5G,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC;MAAE,WAAW,EAAE;IAAc,CAAE,CAAC,CAAC;GAE9D,CAAC,CAAC,IAAI,cACL,MAAM,CAAC,UAAU,CAAC;IAAE,eAAe,EAAE,kBAAkB;IAAE,WAAW,EAAE,cAAc;IAAE,SAAS,EAAE;EAAY,CAAE,CAAC;CAEnH,CAAC","ignoreList":[]}
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
2
  "name": "@effect-blockchain/starknet",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Starknet blockchain toolkit for Effect",
5
+ "keywords": [
6
+ "typescript",
7
+ "effect",
8
+ "blockchain",
9
+ "starknet"
10
+ ],
11
+ "homepage": "https://github.com/spiko-tech/effect-blockchain",
12
+ "bugs": {
13
+ "url": "https://github.com/spiko-tech/effect-blockchain/issues"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/spiko-tech/effect-blockchain.git",
18
+ "directory": "packages/starknet"
19
+ },
20
+ "license": "MIT",
21
+ "sideEffects": [],
22
+ "type": "module",
23
+ "exports": {
24
+ "./package.json": "./package.json",
25
+ ".": "./dist/index.js",
26
+ "./*": "./dist/*.js",
27
+ "./internal/*": null,
28
+ "./index": null,
29
+ "./*/index": null
30
+ },
31
+ "files": [
32
+ "src/**/*.ts",
33
+ "dist/**/*.js",
34
+ "dist/**/*.js.map",
35
+ "dist/**/*.d.ts",
36
+ "dist/**/*.d.ts.map"
37
+ ],
38
+ "dependencies": {
39
+ "@effect-blockchain/core": "^0.1.0"
40
+ },
41
+ "devDependencies": {
42
+ "@effect/vitest": "4.1.0",
43
+ "effect": "4.1.0",
44
+ "starknet": "^8.9.2"
45
+ },
46
+ "peerDependencies": {
47
+ "effect": "^4.0.0",
48
+ "starknet": "^8.9.2"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public",
52
+ "provenance": true
53
+ },
54
+ "tags": [
55
+ "typescript",
56
+ "effect",
57
+ "blockchain",
58
+ "starknet"
59
+ ],
60
+ "scripts": {
61
+ "codegen": "node ../../scripts/codegen.mjs . 'src/**/index.ts'",
62
+ "build": "tsc -b tsconfig.json tsconfig.release.json && pnpm babel",
63
+ "babel": "babel dist --plugins annotate-pure-calls --out-dir dist --source-maps",
64
+ "check": "tsc -b tsconfig.json",
65
+ "test": "vitest",
66
+ "coverage": "vitest --coverage",
67
+ "record-fixtures": "node --env-file-if-exists=../../.env scripts/record-fixtures.ts"
68
+ }
6
69
  }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Starknet contract and account addresses.
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 address: `0x` followed by 64 lowercase hex digits.
11
+ *
12
+ * Decoding lowercases the input and left-pads it with zeros, so `"0x32"` decodes
13
+ * to `"0x00…0032"`.
14
+ *
15
+ * @since 0.1.0
16
+ * @category schemas
17
+ */
18
+ export const StarknetAddress = PaddedFelt.pipe(
19
+ Schema.brand("StarknetAddress"),
20
+ Schema.annotate({
21
+ identifier: "StarknetAddress",
22
+ title: "Starknet address",
23
+ description:
24
+ "a valid Starknet address, starting with 0x and followed by 64 hexadecimal characters e.g. \"0x0000000000000000000000000000000000000000000000000000000000000000\""
25
+ })
26
+ )
27
+
28
+ /**
29
+ * @since 0.1.0
30
+ * @category models
31
+ */
32
+ export type StarknetAddress = typeof StarknetAddress.Type
33
+
34
+ /**
35
+ * The Starknet zero address.
36
+ *
37
+ * @since 0.1.0
38
+ * @category constants
39
+ */
40
+ export const NULL_ADDRESS: StarknetAddress = StarknetAddress.make(
41
+ "0x0000000000000000000000000000000000000000000000000000000000000000"
42
+ )
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Starknet blocks, as returned by `starknet_getBlockWithTxHashes`.
3
+ *
4
+ * @since 0.1.0
5
+ */
6
+ import { BigIntFromInt } from "@effect-blockchain/core/JsonRpc"
7
+ import * as Schema from "effect/Schema"
8
+ import { PaddedFelt } from "./internal/PaddedFelt.ts"
9
+ import { StarknetTransactionHash } from "./StarknetTransactionHash.ts"
10
+
11
+ /**
12
+ * A confirmed block header with its transaction hashes in block order, decoded from the raw JSON-RPC block (snake case
13
+ * keys, integers as `bigint`). `timestamp` is in Unix seconds. A pre-confirmed block (no block hash, no
14
+ * `ACCEPTED_ON_L2` or `ACCEPTED_ON_L1` status) does not decode.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * import type { StarknetEvent } from "@effect-blockchain/starknet/StarknetEvent"
19
+ * import * as StarknetRpc from "@effect-blockchain/starknet/StarknetRpc"
20
+ * import * as Effect from "effect/Effect"
21
+ *
22
+ * // the timestamp of each event, reading each block once
23
+ * const withTimestamps = (events: ReadonlyArray<StarknetEvent>) =>
24
+ * Effect.gen(function*() {
25
+ * const rpc = yield* StarknetRpc.StarknetRpc
26
+ * const blockNumbers = [...new Set(events.map((event) => event.blockNumber))]
27
+ * const blocks = yield* Effect.forEach(blockNumbers, (blockNumber) => rpc.getBlockWithTxHashes({ blockNumber }), {
28
+ * concurrency: 5
29
+ * })
30
+ * const timestamps = new Map(blocks.map((block) => [block.blockNumber, block.timestamp]))
31
+ * return events.map((event) => ({ event, timestamp: timestamps.get(event.blockNumber) }))
32
+ * })
33
+ * ```
34
+ *
35
+ * @since 0.1.0
36
+ * @category schemas
37
+ */
38
+ export const StarknetBlock = Schema.Struct({
39
+ blockNumber: BigIntFromInt,
40
+ blockHash: PaddedFelt,
41
+ parentHash: PaddedFelt,
42
+ timestamp: BigIntFromInt,
43
+ status: Schema.Literals(["ACCEPTED_ON_L2", "ACCEPTED_ON_L1"]),
44
+ transactions: Schema.Array(StarknetTransactionHash)
45
+ }).pipe(
46
+ Schema.encodeKeys({ blockNumber: "block_number", blockHash: "block_hash", parentHash: "parent_hash" }),
47
+ Schema.annotate({ identifier: "StarknetBlock", title: "Starknet block" })
48
+ )
49
+
50
+ /**
51
+ * @since 0.1.0
52
+ * @category models
53
+ */
54
+ export type StarknetBlock = typeof StarknetBlock.Type
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Starknet events, as returned by `starknet_getEvents`.
3
+ *
4
+ * @since 0.1.0
5
+ */
6
+ import { BigIntFromInt } from "@effect-blockchain/core/JsonRpc"
7
+ import * as Schema from "effect/Schema"
8
+ import { PaddedFelt } from "./internal/PaddedFelt.ts"
9
+ import { StarknetAddress } from "./StarknetAddress.ts"
10
+ import { StarknetTransactionHash } from "./StarknetTransactionHash.ts"
11
+
12
+ /**
13
+ * An event emitted by a contract in a block, decoded from the raw JSON-RPC event (snake case keys, felts as `0x` + 64
14
+ * lowercase hex digits). A pre-confirmed event (no block hash or block number) does not decode. `transactionIndex` and
15
+ * `eventIndex` (the event's position in its transaction) are only returned by RPC 0.10 and later.
16
+ *
17
+ * @since 0.1.0
18
+ * @category schemas
19
+ */
20
+ export const StarknetEvent = Schema.Struct({
21
+ fromAddress: StarknetAddress,
22
+ keys: Schema.Array(PaddedFelt),
23
+ data: Schema.Array(PaddedFelt),
24
+ blockNumber: BigIntFromInt,
25
+ blockHash: PaddedFelt,
26
+ transactionHash: StarknetTransactionHash,
27
+ transactionIndex: Schema.optionalKey(Schema.Int),
28
+ eventIndex: Schema.optionalKey(Schema.Int)
29
+ }).pipe(
30
+ Schema.encodeKeys({
31
+ fromAddress: "from_address",
32
+ blockNumber: "block_number",
33
+ blockHash: "block_hash",
34
+ transactionHash: "transaction_hash",
35
+ transactionIndex: "transaction_index",
36
+ eventIndex: "event_index"
37
+ }),
38
+ Schema.annotate({ identifier: "StarknetEvent", title: "Starknet event" })
39
+ )
40
+
41
+ /**
42
+ * @since 0.1.0
43
+ * @category models
44
+ */
45
+ export type StarknetEvent = typeof StarknetEvent.Type
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Starknet event indexing on top of {@link StarknetRpc}: the last confirmed block, the events of a contract over a
3
+ * block range, and a stream of them following the confirmed head.
4
+ *
5
+ * A range is split into ranges of at most `maxBlockRange` blocks, each paged with `starknet_getEvents` (`chunkSize`
6
+ * events per page) until its continuation token is absent. A cursor page is pinned to the endpoint that issued it, so
7
+ * when it fails the range restarts once from its first page, through the fallback again. Any other failure fails the whole call and drops the
8
+ * events already read: the caller retries the same range.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import type { StarknetIndexerFilter } from "@effect-blockchain/starknet/StarknetIndexer"
13
+ * import { StarknetIndexer } from "@effect-blockchain/starknet/StarknetIndexer"
14
+ * import * as Effect from "effect/Effect"
15
+ * import * as Schedule from "effect/Schedule"
16
+ * import * as Stream from "effect/Stream"
17
+ *
18
+ * declare const filter: Omit<StarknetIndexerFilter, "fromBlock" | "toBlock">
19
+ * declare const cursor: bigint
20
+ * declare const save: (block: bigint) => Effect.Effect<void>
21
+ *
22
+ * const program = Effect.gen(function*() {
23
+ * const indexer = yield* StarknetIndexer
24
+ * // once caught up, read the head after 1 s, 2 s, 4 s... at most every minute
25
+ * const poll = Schedule.min([Schedule.exponential("1 second"), Schedule.spaced("1 minute")])
26
+ * yield* indexer.streamEvents({ filter, fromBlock: cursor + BigInt(1), poll }).pipe(
27
+ * Stream.runForEach((batch) => save(batch.toBlock))
28
+ * )
29
+ * })
30
+ * ```
31
+ *
32
+ * @since 0.1.0
33
+ */
34
+ import * as JsonRpc from "@effect-blockchain/core/JsonRpc"
35
+ import * as Arr from "effect/Array"
36
+ import * as BigInt_ from "effect/BigInt"
37
+ import * as Config from "effect/Config"
38
+ import * as Context from "effect/Context"
39
+ import * as Duration from "effect/Duration"
40
+ import * as Effect from "effect/Effect"
41
+ import * as Layer from "effect/Layer"
42
+ import * as Option from "effect/Option"
43
+ import * as Schedule from "effect/Schedule"
44
+ import * as Stream from "effect/Stream"
45
+ import type { StarknetEvent } from "./StarknetEvent.ts"
46
+ import * as StarknetNetwork from "./StarknetNetwork.ts"
47
+ import type { StarknetEventsCursor, StarknetEventsFilter, StarknetRpcError } from "./StarknetRpc.ts"
48
+ import { StarknetRpc } from "./StarknetRpc.ts"
49
+
50
+ /**
51
+ * A {@link StarknetIndexer} `fetchEvents` filter: a `starknet_getEvents` filter without its paging fields, over the
52
+ * inclusive block range `[fromBlock, toBlock]`.
53
+ *
54
+ * @since 0.1.0
55
+ * @category models
56
+ */
57
+ export type StarknetIndexerFilter = Omit<StarknetEventsFilter, "chunkSize" | "cursor">
58
+
59
+ /**
60
+ * The events of `[fromBlock, toBlock]` (both inclusive), in chain order, emitted by
61
+ * {@link StarknetIndexer.Service.streamEvents}.
62
+ *
63
+ * A batch is emitted for every range, even without events. Delivery is at-least-once: save `batch.toBlock` once the
64
+ * batch is handled and resume from `toBlock + 1`.
65
+ *
66
+ * @since 0.1.0
67
+ * @category models
68
+ */
69
+ export interface StarknetIndexerBatch {
70
+ readonly fromBlock: bigint
71
+ readonly toBlock: bigint
72
+ readonly events: ReadonlyArray<StarknetEvent>
73
+ }
74
+
75
+ /**
76
+ * The default `maxBlockRange`. Starknet nodes do not limit the block range of `starknet_getEvents` (they cap the page
77
+ * size), so a range only bounds the work a restart redoes: 10000 blocks is a few hours of mainnet.
78
+ *
79
+ * @since 0.1.0
80
+ * @category constants
81
+ */
82
+ export const DEFAULT_MAX_BLOCK_RANGE = 10_000
83
+
84
+ /**
85
+ * The {@link StarknetIndexer.Service.streamEvents} options.
86
+ *
87
+ * @since 0.1.0
88
+ * @category models
89
+ */
90
+ export interface StarknetIndexerStreamOptions {
91
+ readonly filter: Omit<StarknetIndexerFilter, "fromBlock" | "toBlock">
92
+ readonly fromBlock: bigint
93
+ /** The stream ends after the batch reaching it, and is empty when `fromBlock > toBlock`. */
94
+ readonly toBlock?: bigint | undefined
95
+ /**
96
+ * When to read the head again once caught up, `Schedule.spaced(DEFAULT_POLL_INTERVAL)` by default. It restarts after
97
+ * each batch, and its end ends the stream: `Schedule.recurs(0)` drains to the head and stops.
98
+ */
99
+ readonly poll?: Schedule.Schedule<unknown> | undefined
100
+ /** Retries a step failing with a transient reason ({@link JsonRpc.isTransient}) at the same block. Off by default. */
101
+ readonly retry?: Schedule.Schedule<unknown, StarknetRpcError> | undefined
102
+ }
103
+
104
+ /**
105
+ * @since 0.1.0
106
+ * @category services
107
+ */
108
+ export class StarknetIndexer extends Context.Service<StarknetIndexer, {
109
+ /** The latest block with at least `confirmations` blocks on top of it, never below 0. */
110
+ readonly lastConfirmedBlock: Effect.Effect<bigint, StarknetRpcError>
111
+ /**
112
+ * Every event matching `filter` in `[fromBlock, toBlock]`, in chain order. `fromBlock > toBlock` returns no events.
113
+ * A `toBlock` above `lastConfirmedBlock` is accepted.
114
+ */
115
+ readonly fetchEvents: (filter: StarknetIndexerFilter) => Effect.Effect<ReadonlyArray<StarknetEvent>, StarknetRpcError>
116
+ /**
117
+ * The events matching `filter` from `fromBlock` on, in batches of at most `maxBlockRange` confirmed blocks, following
118
+ * the confirmed head.
119
+ */
120
+ readonly streamEvents: (
121
+ options: StarknetIndexerStreamOptions
122
+ ) => Stream.Stream<StarknetIndexerBatch, StarknetRpcError>
123
+ }>()("@effect-blockchain/starknet/StarknetIndexer") {}
124
+
125
+ /**
126
+ * The default `poll` spacing of {@link StarknetIndexer.Service.streamEvents}: 10 seconds.
127
+ *
128
+ * @since 0.1.0
129
+ * @category constants
130
+ */
131
+ export const DEFAULT_POLL_INTERVAL: Duration.Duration = Duration.seconds(10)
132
+
133
+ // the confirmed blocks [next, head] not indexed yet, empty once the stream reaches the head it last read
134
+ interface StreamPosition {
135
+ readonly next: bigint
136
+ readonly head: bigint
137
+ }
138
+
139
+ /**
140
+ * Builds a {@link StarknetIndexer} over the provided {@link StarknetRpc}.
141
+ *
142
+ * - `confirmations` defaults to {@link StarknetNetwork.defaultConfirmations} for the RPC's network.
143
+ * - `maxBlockRange` is the largest range in blocks, a positive integer, default {@link DEFAULT_MAX_BLOCK_RANGE}.
144
+ * - `chunkSize` is the `starknet_getEvents` page size, default 1000: lower it for a provider with a smaller cap.
145
+ *
146
+ * @since 0.1.0
147
+ * @category layers
148
+ */
149
+ export const layer = (options: {
150
+ readonly confirmations?: number | undefined
151
+ readonly maxBlockRange?: number | undefined
152
+ readonly chunkSize?: number | undefined
153
+ } = {}): Layer.Layer<StarknetIndexer, never, StarknetRpc> =>
154
+ Layer.effect(
155
+ StarknetIndexer,
156
+ Effect.gen(function*() {
157
+ const rpc = yield* StarknetRpc
158
+ const maxBlockRange = options.maxBlockRange ?? DEFAULT_MAX_BLOCK_RANGE
159
+ if (!Number.isSafeInteger(maxBlockRange) || maxBlockRange < 1) {
160
+ return yield* Effect.die(new RangeError(`maxBlockRange must be a positive integer, got ${maxBlockRange}`))
161
+ }
162
+ const confirmations = BigInt(options.confirmations ?? StarknetNetwork.defaultConfirmations(rpc.network))
163
+ const size = BigInt(maxBlockRange)
164
+ const lastConfirmedBlock = rpc.blockNumber.pipe(
165
+ Effect.map((head) => BigInt_.max(head - confirmations, BigInt(0))),
166
+ Effect.withSpan("StarknetIndexer.lastConfirmedBlock")
167
+ )
168
+ const fetchEvents = Effect.fn("StarknetIndexer.fetchEvents")((filter: StarknetIndexerFilter) =>
169
+ Effect.forEach(
170
+ filter.fromBlock > filter.toBlock ? [] : Arr.makeBy(
171
+ Number((filter.toBlock - filter.fromBlock) / size) + 1,
172
+ (i) => filter.fromBlock + BigInt(i) * size
173
+ ),
174
+ (fromBlock) => {
175
+ const toBlock = BigInt_.min(fromBlock + size - BigInt(1), filter.toBlock)
176
+ const range = { ...filter, fromBlock, toBlock, chunkSize: options.chunkSize }
177
+ // a cursor page has no fallback: when it fails, the range restarts once from its first page
178
+ return Stream.paginate(
179
+ Option.none<StarknetEventsCursor>(),
180
+ (cursor) =>
181
+ rpc.getEvents({ ...range, cursor: Option.getOrUndefined(cursor) }).pipe(Effect.mapBoth({
182
+ onFailure: (error) => Option.isNone(cursor) ? error : { cursorPage: error },
183
+ onSuccess: (page) =>
184
+ [page.events, Option.map(Option.fromUndefinedOr(page.cursor), Option.some)] as const
185
+ }))
186
+ ).pipe(
187
+ Stream.runCollect,
188
+ Effect.retry({ times: 1, while: (error) => "cursorPage" in error }),
189
+ Effect.mapError((error) => "cursorPage" in error ? error.cursorPage : error)
190
+ )
191
+ }
192
+ ).pipe(Effect.map(Arr.flatten))
193
+ )
194
+ return StarknetIndexer.of({
195
+ lastConfirmedBlock,
196
+ fetchEvents,
197
+ streamEvents: ({ filter, fromBlock, poll = Schedule.spaced(DEFAULT_POLL_INTERVAL), retry, toBlock }) => {
198
+ 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
+ const step = (
201
+ { head, next }: StreamPosition
202
+ ): Effect.Effect<
203
+ readonly [ReadonlyArray<StarknetIndexerBatch>, Option.Option<StreamPosition>],
204
+ StarknetRpcError
205
+ > =>
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
+ )
226
+ }
227
+ })
228
+ })
229
+ )
230
+
231
+ /**
232
+ * Builds an {@link StarknetIndexer} like {@link layer}, reading the options from `Config`.
233
+ *
234
+ * @example
235
+ * ```ts
236
+ * import * as StarknetIndexer from "@effect-blockchain/starknet/StarknetIndexer"
237
+ * import * as Config from "effect/Config"
238
+ *
239
+ * const IndexerLive = StarknetIndexer.layerConfig({ confirmations: Config.Int("STARKNET_CONFIRMATIONS") })
240
+ * ```
241
+ *
242
+ * @since 0.1.0
243
+ * @category layers
244
+ */
245
+ export const layerConfig = (
246
+ options: Config.Wrap<NonNullable<Parameters<typeof layer>[0]>>
247
+ ): Layer.Layer<StarknetIndexer, Config.ConfigError, StarknetRpc> =>
248
+ Layer.unwrap(Effect.map(Config.unwrap(options), layer))