@effect-blockchain/solana 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/SolanaAddress.d.ts +21 -0
  4. package/dist/SolanaAddress.d.ts.map +1 -0
  5. package/dist/SolanaAddress.js +33 -0
  6. package/dist/SolanaAddress.js.map +1 -0
  7. package/dist/SolanaIndexer.d.ts +198 -0
  8. package/dist/SolanaIndexer.d.ts.map +1 -0
  9. package/dist/SolanaIndexer.js +344 -0
  10. package/dist/SolanaIndexer.js.map +1 -0
  11. package/dist/SolanaNetwork.d.ts +64 -0
  12. package/dist/SolanaNetwork.d.ts.map +1 -0
  13. package/dist/SolanaNetwork.js +84 -0
  14. package/dist/SolanaNetwork.js.map +1 -0
  15. package/dist/SolanaRelayer.d.ts +207 -0
  16. package/dist/SolanaRelayer.d.ts.map +1 -0
  17. package/dist/SolanaRelayer.js +377 -0
  18. package/dist/SolanaRelayer.js.map +1 -0
  19. package/dist/SolanaRpc.d.ts +427 -0
  20. package/dist/SolanaRpc.d.ts.map +1 -0
  21. package/dist/SolanaRpc.js +216 -0
  22. package/dist/SolanaRpc.js.map +1 -0
  23. package/dist/SolanaSigner.d.ts +49 -0
  24. package/dist/SolanaSigner.d.ts.map +1 -0
  25. package/dist/SolanaSigner.js +82 -0
  26. package/dist/SolanaSigner.js.map +1 -0
  27. package/dist/SolanaTransactionHash.d.ts +14 -0
  28. package/dist/SolanaTransactionHash.d.ts.map +1 -0
  29. package/dist/SolanaTransactionHash.js +34 -0
  30. package/dist/SolanaTransactionHash.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/bigIntJson.d.ts +2 -0
  36. package/dist/internal/bigIntJson.d.ts.map +1 -0
  37. package/dist/internal/bigIntJson.js +9 -0
  38. package/dist/internal/bigIntJson.js.map +1 -0
  39. package/dist/internal/confirmations.d.ts +2 -0
  40. package/dist/internal/confirmations.d.ts.map +1 -0
  41. package/dist/internal/confirmations.js +15 -0
  42. package/dist/internal/confirmations.js.map +1 -0
  43. package/dist/internal/rpcMethods.d.ts +2 -0
  44. package/dist/internal/rpcMethods.d.ts.map +1 -0
  45. package/dist/internal/rpcMethods.js +223 -0
  46. package/dist/internal/rpcMethods.js.map +1 -0
  47. package/package.json +66 -3
  48. package/src/SolanaAddress.ts +40 -0
  49. package/src/SolanaIndexer.ts +552 -0
  50. package/src/SolanaNetwork.ts +105 -0
  51. package/src/SolanaRelayer.ts +493 -0
  52. package/src/SolanaRpc.ts +595 -0
  53. package/src/SolanaSigner.ts +98 -0
  54. package/src/SolanaTransactionHash.ts +41 -0
  55. package/src/index.ts +40 -0
  56. package/src/internal/bigIntJson.ts +18 -0
  57. package/src/internal/confirmations.ts +17 -0
  58. package/src/internal/rpcMethods.ts +260 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Spiko
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ # `@effect-blockchain/solana`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Solana blockchain toolkit for Effect.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @effect-blockchain/solana effect @solana/kit
9
+ ```
10
+
11
+ ## License
12
+
13
+ MIT
@@ -0,0 +1,21 @@
1
+ import * as Schema from "effect/Schema";
2
+ /**
3
+ * A base58-encoded Solana address (32 bytes), validated with `@solana/kit`.
4
+ *
5
+ * @since 0.1.0
6
+ * @category schemas
7
+ */
8
+ export declare const SolanaAddress: Schema.brand<Schema.String, "SolanaAddress">;
9
+ /**
10
+ * @since 0.1.0
11
+ * @category models
12
+ */
13
+ export type SolanaAddress = typeof SolanaAddress.Type;
14
+ /**
15
+ * The Solana System Program address.
16
+ *
17
+ * @since 0.1.0
18
+ * @category constants
19
+ */
20
+ export declare const SYSTEM_PROGRAM_ADDRESS: SolanaAddress;
21
+ //# sourceMappingURL=SolanaAddress.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SolanaAddress.d.ts","sourceRoot":"","sources":["../src/SolanaAddress.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAIvC;;;;;GAKG;AACH,eAAO,MAAM,aAAa,8CAWzB,CAAA;AAED;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG,OAAO,aAAa,CAAC,IAAI,CAAA;AAErD;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,EAAE,aAAsE,CAAA"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * @since 0.1.0
3
+ */
4
+ import { isAddress } from "@solana/kit";
5
+ import * as Schema from "effect/Schema";
6
+ const solanaAddressOf32BytesPattern = "^[2-9A-H][1-9A-HJ-NP-Za-km-z]{43}$";
7
+ /**
8
+ * A base58-encoded Solana address (32 bytes), validated with `@solana/kit`.
9
+ *
10
+ * @since 0.1.0
11
+ * @category schemas
12
+ */
13
+ export const SolanaAddress = /*#__PURE__*/Schema.String.annotate({
14
+ title: "Solana address",
15
+ description: "a valid Solana address, consisting of 32 to 44 base58 characters"
16
+ }).pipe(/*#__PURE__*/Schema.check(/*#__PURE__*/Schema.makeFilter(a => isAddress(a) || `${a} is not a valid Solana address`, {
17
+ arbitraryConstraint: {
18
+ patterns: [{
19
+ source: solanaAddressOf32BytesPattern,
20
+ flags: ""
21
+ }]
22
+ }
23
+ })), /*#__PURE__*/Schema.brand("SolanaAddress"), /*#__PURE__*/Schema.annotate({
24
+ identifier: "SolanaAddress"
25
+ }));
26
+ /**
27
+ * The Solana System Program address.
28
+ *
29
+ * @since 0.1.0
30
+ * @category constants
31
+ */
32
+ export const SYSTEM_PROGRAM_ADDRESS = /*#__PURE__*/SolanaAddress.make("11111111111111111111111111111111");
33
+ //# sourceMappingURL=SolanaAddress.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SolanaAddress.js","names":[],"sources":["../src/SolanaAddress.ts"],"sourcesContent":[null],"mappings":"AAAA;;;AAGA,SAAS,SAAS,QAAQ,aAAa;AACvC,OAAO,KAAK,MAAM,MAAM,eAAe;AAEvC,MAAM,6BAA6B,GAAG,oCAAoC;AAE1E;;;;;;AAMA,OAAO,MAAM,aAAa,gBAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC;EAClD,KAAK,EAAE,gBAAgB;EACvB,WAAW,EAAE;CACd,CAAC,CAAC,IAAI,cACL,MAAM,CAAC,KAAK,cACV,MAAM,CAAC,UAAU,CAAE,CAAS,IAAK,SAAS,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,gCAAgC,EAAE;EACrF,mBAAmB,EAAE;IAAE,QAAQ,EAAE,CAAC;MAAE,MAAM,EAAE,6BAA6B;MAAE,KAAK,EAAE;IAAE,CAAE;EAAC;CACxF,CAAC,CACH,eACD,MAAM,CAAC,KAAK,CAAC,eAAe,CAAC,eAC7B,MAAM,CAAC,QAAQ,CAAC;EAAE,UAAU,EAAE;AAAe,CAAE,CAAC,CACjD;AAQD;;;;;;AAMA,OAAO,MAAM,sBAAsB,gBAAkB,aAAa,CAAC,IAAI,CAAC,kCAAkC,CAAC","ignoreList":[]}
@@ -0,0 +1,198 @@
1
+ import * as Config from "effect/Config";
2
+ import * as Context from "effect/Context";
3
+ import * as Duration from "effect/Duration";
4
+ import * as Effect from "effect/Effect";
5
+ import * as Layer from "effect/Layer";
6
+ import * as Schedule from "effect/Schedule";
7
+ import type * as Schema from "effect/Schema";
8
+ import * as Stream from "effect/Stream";
9
+ import type { SolanaAddress } from "./SolanaAddress.ts";
10
+ import type { SolanaTransactionEncoding, SolanaTransactionInfo } from "./SolanaRpc.ts";
11
+ import { SolanaRpc, SolanaRpcError } from "./SolanaRpc.ts";
12
+ import type { SolanaTransactionHash } from "./SolanaTransactionHash.ts";
13
+ /**
14
+ * A transaction touching the indexed address, kept raw: the `getTransaction` result with its `signature` and the
15
+ * `err` listed by `getSignaturesForAddress` (raw JSON, `null` when it succeeded). Failed transactions are kept: they
16
+ * still paid their fee. `transaction` follows the requested encoding.
17
+ *
18
+ * @since 0.1.0
19
+ * @category models
20
+ */
21
+ export interface SolanaIndexedTransaction<Encoding extends SolanaTransactionEncoding = "base64"> extends SolanaTransactionInfo<Encoding> {
22
+ readonly signature: SolanaTransactionHash;
23
+ readonly err: Schema.Json;
24
+ }
25
+ /**
26
+ * A {@link SolanaIndexer} `fetchTransactions` filter: the address whose transactions are read, over the inclusive slot
27
+ * range `[fromBlock, toBlock]`.
28
+ *
29
+ * @since 0.1.0
30
+ * @category models
31
+ */
32
+ export interface SolanaIndexerFilter {
33
+ readonly address: SolanaAddress;
34
+ readonly fromBlock: bigint;
35
+ readonly toBlock: bigint;
36
+ }
37
+ /**
38
+ * The transactions of slots `[fromBlock, toBlock]` (both inclusive), in chain order, emitted by
39
+ * {@link SolanaIndexer.Service.streamTransactions}.
40
+ *
41
+ * A batch is emitted for every range, even without transactions. Delivery is at-least-once: save `batch.toBlock` once
42
+ * the batch is handled and resume from `toBlock + 1`. A batch holds at most `maxBatchSize` transactions, more when a
43
+ * single slot has more, as a slot is never split.
44
+ *
45
+ * @since 0.1.0
46
+ * @category models
47
+ */
48
+ export interface SolanaIndexerBatch<Encoding extends SolanaTransactionEncoding = "base64"> {
49
+ readonly fromBlock: bigint;
50
+ readonly toBlock: bigint;
51
+ readonly transactions: ReadonlyArray<SolanaIndexedTransaction<Encoding>>;
52
+ }
53
+ /**
54
+ * The {@link SolanaIndexer.Service.streamTransactions} options, `encoding` aside.
55
+ *
56
+ * @since 0.1.0
57
+ * @category models
58
+ */
59
+ export interface SolanaIndexerStreamOptions {
60
+ readonly filter: Omit<SolanaIndexerFilter, "fromBlock" | "toBlock">;
61
+ readonly fromBlock: bigint;
62
+ /** The stream ends after the batch reaching it, and is empty when `fromBlock > toBlock`. */
63
+ readonly toBlock?: bigint | undefined;
64
+ /**
65
+ * When to read the head again once caught up, `Schedule.spaced(DEFAULT_POLL_INTERVAL)` by default. It restarts after
66
+ * each batch, and its end ends the stream: `Schedule.recurs(0)` drains to the head and stops.
67
+ */
68
+ readonly poll?: Schedule.Schedule<unknown> | undefined;
69
+ /**
70
+ * Retries a step (the signature paging or one batch's transactions) failing with a transient reason
71
+ * ({@link JsonRpc.isTransient}) at the same position. Off by default.
72
+ */
73
+ readonly retry?: Schedule.Schedule<unknown, SolanaRpcError> | undefined;
74
+ }
75
+ /**
76
+ * The lamports of an address at the end of slot `block`, emitted by {@link SolanaIndexer.Service.streamNativeBalance}.
77
+ *
78
+ * @since 0.2.0
79
+ * @category models
80
+ */
81
+ export interface SolanaNativeBalance {
82
+ readonly block: bigint;
83
+ readonly balance: bigint;
84
+ }
85
+ /**
86
+ * The {@link SolanaIndexer.Service.streamNativeBalance} options: a sample of the balance of `address` at `fromBlock`,
87
+ * `fromBlock + step`, `fromBlock + 2 * step`... `poll` and `retry` behave as in {@link SolanaIndexerStreamOptions}.
88
+ *
89
+ * @since 0.2.0
90
+ * @category models
91
+ */
92
+ export interface SolanaIndexerNativeBalanceOptions {
93
+ readonly address: SolanaAddress;
94
+ readonly fromBlock: bigint;
95
+ /** The stream ends after the last sample not above it, and is empty when `fromBlock > toBlock`. */
96
+ readonly toBlock?: bigint | undefined;
97
+ /** The slots between two samples, a positive safe integer. */
98
+ readonly step: number;
99
+ readonly poll?: Schedule.Schedule<unknown> | undefined;
100
+ readonly retry?: Schedule.Schedule<unknown, SolanaRpcError> | undefined;
101
+ }
102
+ declare const SolanaIndexer_base: Context.ServiceClass<SolanaIndexer, "@effect-blockchain/solana/SolanaIndexer", {
103
+ /** The `finalized` slot minus the confirmations, never below 0. */
104
+ readonly lastConfirmedBlock: Effect.Effect<bigint, SolanaRpcError>;
105
+ /**
106
+ * The transactions touching `address` in slots `fromBlock..toBlock` (both inclusive), in chain order. Empty when
107
+ * `fromBlock > toBlock`. `encoding` defaults to `base64`.
108
+ */
109
+ readonly fetchTransactions: {
110
+ (filter: SolanaIndexerFilter, options?: {
111
+ readonly encoding?: "base64" | undefined;
112
+ }): Effect.Effect<ReadonlyArray<SolanaIndexedTransaction>, SolanaRpcError>;
113
+ <Encoding extends SolanaTransactionEncoding>(filter: SolanaIndexerFilter, options: {
114
+ readonly encoding: Encoding;
115
+ }): Effect.Effect<ReadonlyArray<SolanaIndexedTransaction<Encoding>>, SolanaRpcError>;
116
+ };
117
+ /**
118
+ * The transactions touching `filter.address` from slot `fromBlock` on, in batches of at most `maxBatchSize`
119
+ * signatures, following the confirmed head. `encoding` defaults to `base64`.
120
+ */
121
+ readonly streamTransactions: {
122
+ (options: SolanaIndexerStreamOptions & {
123
+ readonly encoding?: "base64" | undefined;
124
+ }): Stream.Stream<SolanaIndexerBatch, SolanaRpcError>;
125
+ <Encoding extends SolanaTransactionEncoding>(options: SolanaIndexerStreamOptions & {
126
+ readonly encoding: Encoding;
127
+ }): Stream.Stream<SolanaIndexerBatch<Encoding>, SolanaRpcError>;
128
+ };
129
+ /**
130
+ * The lamports of `address` at the end of slot `block`: the `postBalances` of its newest transaction at or before
131
+ * `block`, else the `preBalances` of its first one after. At or above the confirmed head with no newer transaction,
132
+ * its `getBalance`: an address without any transaction reads its current balance there and 0 below.
133
+ */
134
+ readonly fetchNativeBalance: (options: {
135
+ readonly address: SolanaAddress;
136
+ readonly block: bigint;
137
+ }) => Effect.Effect<bigint, SolanaRpcError>;
138
+ /**
139
+ * The lamports of `address` at every `step` slots from `fromBlock`, following the confirmed head. A sample only
140
+ * reads the meta of the newest transaction since the previous one, so epoch rewards, which change a balance without
141
+ * a transaction, show from the next transaction on.
142
+ */
143
+ readonly streamNativeBalance: (options: SolanaIndexerNativeBalanceOptions) => Stream.Stream<SolanaNativeBalance, SolanaRpcError>;
144
+ }>;
145
+ /**
146
+ * @since 0.1.0
147
+ * @category services
148
+ */
149
+ export declare class SolanaIndexer extends SolanaIndexer_base {
150
+ }
151
+ /**
152
+ * The default `maxBatchSize`: each signature costs one sequential `getTransaction`, so 100 keeps a batch to a few
153
+ * dozen seconds of calls and about 100 transactions in memory between two saved cursors.
154
+ *
155
+ * @since 0.1.0
156
+ * @category constants
157
+ */
158
+ export declare const DEFAULT_MAX_BATCH_SIZE = 100;
159
+ /**
160
+ * The default `poll` spacing of {@link SolanaIndexer.Service.streamTransactions}: 10 seconds.
161
+ *
162
+ * @since 0.1.0
163
+ * @category constants
164
+ */
165
+ export declare const DEFAULT_POLL_INTERVAL: Duration.Duration;
166
+ /**
167
+ * Builds a {@link SolanaIndexer} on the provided {@link SolanaRpc}.
168
+ *
169
+ * - `confirmations` defaults to `SolanaNetwork.defaultConfirmations` for the RPC's network.
170
+ * - `maxBatchSize`, a positive integer, the signatures per `streamTransactions` batch, defaults to
171
+ * {@link DEFAULT_MAX_BATCH_SIZE}.
172
+ *
173
+ * There is no `maxBlockRange`: `getSignaturesForAddress` takes no slot range to split.
174
+ *
175
+ * @since 0.1.0
176
+ * @category layers
177
+ */
178
+ export declare const layer: (options?: {
179
+ readonly confirmations?: number | undefined;
180
+ readonly maxBatchSize?: number | undefined;
181
+ }) => Layer.Layer<SolanaIndexer, never, SolanaRpc>;
182
+ /**
183
+ * Builds an {@link SolanaIndexer} like {@link layer}, reading the options from `Config`.
184
+ *
185
+ * @example
186
+ * ```ts
187
+ * import * as SolanaIndexer from "@effect-blockchain/solana/SolanaIndexer"
188
+ * import * as Config from "effect/Config"
189
+ *
190
+ * const IndexerLive = SolanaIndexer.layerConfig({ confirmations: Config.Int("SOLANA_CONFIRMATIONS") })
191
+ * ```
192
+ *
193
+ * @since 0.1.0
194
+ * @category layers
195
+ */
196
+ export declare const layerConfig: (options: Config.Wrap<NonNullable<Parameters<typeof layer>[0]>>) => Layer.Layer<SolanaIndexer, Config.ConfigError, SolanaRpc>;
197
+ export {};
198
+ //# sourceMappingURL=SolanaIndexer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SolanaIndexer.d.ts","sourceRoot":"","sources":["../src/SolanaIndexer.ts"],"names":[],"mappings":"AAgDA,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAA;AACzC,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AAErC,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,KAAK,MAAM,MAAM,eAAe,CAAA;AAC5C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAEvC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AACvD,OAAO,KAAK,EAAuB,yBAAyB,EAAE,q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WAAW,CAAC,UAAU,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAC7D,KAAK,CAAC,KAAK,CAAC,aAAa,EAAE,MAAM,CAAC,WAAW,EAAE,SAAS,CAA4D,CAAA"}
@@ -0,0 +1,344 @@
1
+ /**
2
+ * Solana transaction indexing on top of {@link SolanaRpc}: the last confirmed slot, the transactions touching an
3
+ * address over a slot range, its lamport balance at a slot, and streams of both following the confirmed head. Blocks
4
+ * are slots.
5
+ *
6
+ * Everything is read at `finalized` commitment. `getSignaturesForAddress` has no slot range, so a range is paged from
7
+ * the head backwards until it passes `fromBlock`: the cost grows with the address's history since `fromBlock`, then
8
+ * each transaction costs one `getTransaction`. Each page sends `minContextSlot: toBlock`, so a lagging endpoint that
9
+ * honours it falls back. Any failure fails the whole call and nothing is returned: the caller retries the same range.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import type { SolanaAddress } from "@effect-blockchain/solana/SolanaAddress"
14
+ * import type { SolanaIndexerFilter } from "@effect-blockchain/solana/SolanaIndexer"
15
+ * import { SolanaIndexer } from "@effect-blockchain/solana/SolanaIndexer"
16
+ * import * as Effect from "effect/Effect"
17
+ * import * as Schedule from "effect/Schedule"
18
+ * import * as Stream from "effect/Stream"
19
+ *
20
+ * declare const filter: Omit<SolanaIndexerFilter, "fromBlock" | "toBlock">
21
+ * declare const cursor: bigint
22
+ * declare const save: (slot: bigint) => Effect.Effect<void>
23
+ *
24
+ * const program = Effect.gen(function*() {
25
+ * const indexer = yield* SolanaIndexer
26
+ * // once caught up, read the head after 1 s, 2 s, 4 s... at most every minute
27
+ * const poll = Schedule.min([Schedule.exponential("1 second"), Schedule.spaced("1 minute")])
28
+ * yield* indexer.streamTransactions({ filter, fromBlock: cursor + BigInt(1), poll }).pipe(
29
+ * Stream.runForEach((batch) => save(batch.toBlock))
30
+ * )
31
+ * })
32
+ *
33
+ * declare const address: SolanaAddress
34
+ *
35
+ * // the lamports of `address` every 9000 slots (about an hour) from slot 400000000
36
+ * const balances = Effect.gen(function*() {
37
+ * const indexer = yield* SolanaIndexer
38
+ * yield* indexer.streamNativeBalance({ address, fromBlock: BigInt(400000000), step: 9000 }).pipe(
39
+ * Stream.runForEach(({ balance, block }) => Effect.log(`${block}: ${balance}`))
40
+ * )
41
+ * })
42
+ * ```
43
+ *
44
+ * @since 0.1.0
45
+ */
46
+ import * as JsonRpc from "@effect-blockchain/core/JsonRpc";
47
+ import * as Arr from "effect/Array";
48
+ import * as BigInt_ from "effect/BigInt";
49
+ import * as Config from "effect/Config";
50
+ import * as Context from "effect/Context";
51
+ import * as Duration from "effect/Duration";
52
+ import * as Effect from "effect/Effect";
53
+ import * as Layer from "effect/Layer";
54
+ import * as Option from "effect/Option";
55
+ import * as Schedule from "effect/Schedule";
56
+ import * as Stream from "effect/Stream";
57
+ import * as Confirmations from "./internal/confirmations.js";
58
+ import { SolanaRpc, SolanaRpcError } from "./SolanaRpc.js";
59
+ /**
60
+ * @since 0.1.0
61
+ * @category services
62
+ */
63
+ export class SolanaIndexer extends /*#__PURE__*/Context.Service()("@effect-blockchain/solana/SolanaIndexer") {}
64
+ // the node's maximum `limit`
65
+ const PAGE_SIZE = 1000;
66
+ const COMMITMENT = "finalized";
67
+ /**
68
+ * The default `maxBatchSize`: each signature costs one sequential `getTransaction`, so 100 keeps a batch to a few
69
+ * dozen seconds of calls and about 100 transactions in memory between two saved cursors.
70
+ *
71
+ * @since 0.1.0
72
+ * @category constants
73
+ */
74
+ export const DEFAULT_MAX_BATCH_SIZE = 100;
75
+ /**
76
+ * The default `poll` spacing of {@link SolanaIndexer.Service.streamTransactions}: 10 seconds.
77
+ *
78
+ * @since 0.1.0
79
+ * @category constants
80
+ */
81
+ export const DEFAULT_POLL_INTERVAL = /*#__PURE__*/Duration.seconds(10);
82
+ // consecutive groups of at most `max` signatures, a slot never split: a full group still takes its last slot's others
83
+ const groupBySlot = (signatures, max) => {
84
+ const groups = [];
85
+ for (const info of signatures) {
86
+ const last = groups.at(-1);
87
+ if (last !== undefined && (last.length < max || Arr.lastNonEmpty(last).slot === info.slot)) last.push(info);else groups.push([info]);
88
+ }
89
+ return groups;
90
+ };
91
+ // the lamports of `address` before and after `transaction`, none when it is not one of its accounts. An account's
92
+ // index runs over the static account keys, then the addresses loaded from lookup tables, writable then readonly
93
+ // (https://solana.com/docs/advanced/versions)
94
+ const balanceChange = ({
95
+ meta,
96
+ transaction
97
+ }, address) => {
98
+ if (meta === null) return Option.none();
99
+ const index = [...transaction.message.accountKeys, ...(meta.loadedAddresses?.writable ?? []), ...(meta.loadedAddresses?.readonly ?? [])].indexOf(address);
100
+ const pre = meta.preBalances[index];
101
+ const post = meta.postBalances[index];
102
+ return pre === undefined || post === undefined ? Option.none() : Option.some({
103
+ pre,
104
+ post
105
+ });
106
+ };
107
+ // retries a stream step failing with a transient reason at the same position
108
+ const withRetry = (retry, step) => retry === undefined ? step : position => Effect.retry(step(position), {
109
+ schedule: retry,
110
+ while: error => JsonRpc.isTransient(error.reason)
111
+ });
112
+ /**
113
+ * Builds a {@link SolanaIndexer} on the provided {@link SolanaRpc}.
114
+ *
115
+ * - `confirmations` defaults to `SolanaNetwork.defaultConfirmations` for the RPC's network.
116
+ * - `maxBatchSize`, a positive integer, the signatures per `streamTransactions` batch, defaults to
117
+ * {@link DEFAULT_MAX_BATCH_SIZE}.
118
+ *
119
+ * There is no `maxBlockRange`: `getSignaturesForAddress` takes no slot range to split.
120
+ *
121
+ * @since 0.1.0
122
+ * @category layers
123
+ */
124
+ export const layer = (options = {}) => Layer.effect(SolanaIndexer, Effect.gen(function* () {
125
+ const rpc = yield* SolanaRpc;
126
+ const maxBatchSize = options.maxBatchSize ?? DEFAULT_MAX_BATCH_SIZE;
127
+ if (!Number.isSafeInteger(maxBatchSize) || maxBatchSize < 1) {
128
+ return yield* Effect.die(new RangeError(`maxBatchSize must be a positive integer, got ${maxBatchSize}`));
129
+ }
130
+ const lastConfirmedBlock = Confirmations.lastConfirmedBlock(rpc, options.confirmations).pipe(Effect.withSpan("SolanaIndexer.lastConfirmedBlock"));
131
+ // the signatures of `address`, newest first, a page read only when the previous one is consumed
132
+ const signatures = (address, minContextSlot) => Stream.paginate(Option.none(), before => rpc.getSignaturesForAddress({
133
+ address,
134
+ before: Option.getOrUndefined(before),
135
+ limit: PAGE_SIZE,
136
+ commitment: COMMITMENT,
137
+ minContextSlot
138
+ }).pipe(Effect.map(page => {
139
+ const last = page.at(-1);
140
+ return [page, last === undefined || page.length < PAGE_SIZE ? Option.none() : Option.some(Option.some(last.signature))];
141
+ })));
142
+ // the signatures of `[fromBlock, toBlock]` in chain order, paged from the head back to the first short page or
143
+ // the first page reaching below `fromBlock`
144
+ const fetchSignatures = filter => signatures(filter.address, filter.toBlock).pipe(Stream.takeWhile(({
145
+ slot
146
+ }) => slot >= filter.fromBlock), Stream.runCollect,
147
+ // newest first, so reversed slots ascend. The order within a slot is undocumented: reversing it is a best
148
+ // guess at execution order (`transactionIndex`, which some providers add, is not in the RPC model)
149
+ Effect.map(signatures => Arr.reverse(Arr.filter(signatures, ({
150
+ slot
151
+ }) => slot <= filter.toBlock))));
152
+ const fetchEach = (signatures, encoding) => Effect.forEach(signatures, ({
153
+ err,
154
+ signature
155
+ }) => rpc.getTransaction({
156
+ signature,
157
+ commitment: COMMITMENT,
158
+ encoding
159
+ }).pipe(Effect.map(tx => ({
160
+ signature,
161
+ err,
162
+ ...tx
163
+ }))));
164
+ const fetchRange = Effect.fn("SolanaIndexer.fetchTransactions")(function* (filter, encoding) {
165
+ if (filter.fromBlock > filter.toBlock) {
166
+ return [];
167
+ }
168
+ return yield* fetchEach(yield* fetchSignatures(filter), encoding);
169
+ });
170
+ function fetchTransactions(filter, {
171
+ encoding = "base64"
172
+ } = {}) {
173
+ return fetchRange(filter, encoding);
174
+ }
175
+ function streamTransactions(options) {
176
+ const {
177
+ encoding = "base64",
178
+ filter,
179
+ fromBlock,
180
+ retry,
181
+ toBlock
182
+ } = options;
183
+ const poll = options.poll ?? Schedule.spaced(DEFAULT_POLL_INTERVAL);
184
+ if (toBlock !== undefined && fromBlock > toBlock) {
185
+ return Stream.empty;
186
+ }
187
+ const after = (end, cap, groups) => end === toBlock ? Option.none() : Option.some({
188
+ next: end + BigInt(1),
189
+ cap,
190
+ groups
191
+ });
192
+ // one step: the transactions of the next pending group, else the signatures up to the polled confirmed head
193
+ const step = position => {
194
+ const {
195
+ cap,
196
+ groups,
197
+ next
198
+ } = position;
199
+ if (Arr.isReadonlyArrayNonEmpty(groups)) {
200
+ const [group, ...rest] = groups;
201
+ const end = rest.length === 0 ? cap : Arr.lastNonEmpty(group).slot;
202
+ return fetchEach(group, encoding).pipe(Effect.map(transactions => [[{
203
+ fromBlock: next,
204
+ toBlock: end,
205
+ transactions
206
+ }], after(end, cap, rest)]), Effect.withSpan("SolanaIndexer.streamTransactions.fetchGroup"));
207
+ }
208
+ return lastConfirmedBlock.pipe(Effect.repeat({
209
+ schedule: poll,
210
+ until: confirmed => confirmed >= next
211
+ }), Effect.flatMap(confirmed => {
212
+ const end = toBlock === undefined ? confirmed : BigInt_.min(confirmed, toBlock);
213
+ if (next > end) {
214
+ return Effect.succeed([[], Option.none()]);
215
+ }
216
+ return fetchSignatures({
217
+ address: filter.address,
218
+ fromBlock: next,
219
+ toBlock: end
220
+ }).pipe(Effect.map(signatures => Arr.isReadonlyArrayNonEmpty(signatures) ? [[], Option.some({
221
+ next,
222
+ cap: end,
223
+ groups: groupBySlot(signatures, maxBatchSize)
224
+ })] : [[{
225
+ fromBlock: next,
226
+ toBlock: end,
227
+ transactions: []
228
+ }], after(end, end, [])]), Effect.withSpan("SolanaIndexer.streamTransactions.fetchSignatures"));
229
+ }));
230
+ };
231
+ return Stream.paginate({
232
+ next: fromBlock,
233
+ cap: fromBlock,
234
+ groups: []
235
+ }, withRetry(retry, step));
236
+ }
237
+ const balanceOf = (address, signature, side) => rpc.getTransaction({
238
+ signature,
239
+ commitment: COMMITMENT,
240
+ encoding: "json"
241
+ }).pipe(Effect.flatMap(tx => Option.match(balanceChange(tx, address), {
242
+ onSome: change => Effect.succeed(change[side]),
243
+ onNone: () => Effect.fail(new SolanaRpcError({
244
+ reason: new JsonRpc.InvalidResponse(),
245
+ method: "getTransaction",
246
+ endpoint: "SolanaIndexer",
247
+ cause: new Error(`transaction ${signature} has no balance for ${address}`)
248
+ }))
249
+ })));
250
+ // the balance at the end of `block`, at or below `confirmed`, given the sample before it when there is one
251
+ const balanceAt = Effect.fnUntraced(function* (address, block, confirmed, previous) {
252
+ // read before the signatures, so that a transaction landing in between is listed
253
+ const current = Option.isNone(previous) && block >= confirmed ? Option.some(yield* rpc.getBalance({
254
+ address
255
+ })) : Option.none();
256
+ // the newest signature, and the newest at or before `block` or else the oldest
257
+ const {
258
+ last,
259
+ newest
260
+ } = yield* signatures(address, BigInt_.min(block, confirmed)).pipe(Stream.takeUntil(({
261
+ slot
262
+ }) => slot <= block), Stream.runFold(() => ({
263
+ newest: Option.none(),
264
+ last: Option.none()
265
+ }), (acc, info) => ({
266
+ newest: Option.orElseSome(acc.newest, () => info),
267
+ last: Option.some(info)
268
+ })));
269
+ if (Option.isSome(current) && Option.match(newest, {
270
+ onNone: () => true,
271
+ onSome: ({
272
+ slot
273
+ }) => slot <= BigInt_.min(block, current.value.slot)
274
+ })) {
275
+ return current.value.value;
276
+ }
277
+ if (Option.isSome(last) && last.value.slot <= block) {
278
+ return Option.isSome(previous) && last.value.slot <= previous.value.block ? previous.value.balance : yield* balanceOf(address, last.value.signature, "post");
279
+ }
280
+ if (Option.isSome(previous)) return previous.value.balance;
281
+ return Option.isSome(last) ? yield* balanceOf(address, last.value.signature, "pre") : BigInt(0);
282
+ });
283
+ const fetchNativeBalance = Effect.fn("SolanaIndexer.fetchNativeBalance")(function* ({
284
+ address,
285
+ block
286
+ }) {
287
+ return yield* balanceAt(address, block, yield* lastConfirmedBlock, Option.none());
288
+ });
289
+ const streamNativeBalance = ({
290
+ address,
291
+ fromBlock,
292
+ poll = Schedule.spaced(DEFAULT_POLL_INTERVAL),
293
+ retry,
294
+ step,
295
+ toBlock
296
+ }) => {
297
+ if (!Number.isSafeInteger(step) || step < 1) {
298
+ return Stream.die(new RangeError(`step must be a positive safe integer, got ${step}`));
299
+ }
300
+ if (toBlock !== undefined && fromBlock > toBlock) {
301
+ return Stream.empty;
302
+ }
303
+ const sample = previous => {
304
+ const block = Option.match(previous, {
305
+ onNone: () => fromBlock,
306
+ onSome: p => p.block + BigInt(step)
307
+ });
308
+ return lastConfirmedBlock.pipe(Effect.repeat({
309
+ schedule: poll,
310
+ until: confirmed => confirmed >= block
311
+ }), Effect.flatMap(confirmed => confirmed < block ? Effect.succeed([[], Option.none()]) : balanceAt(address, block, confirmed, previous).pipe(Effect.map(balance => {
312
+ const current = {
313
+ block,
314
+ balance
315
+ };
316
+ return [[current], toBlock !== undefined && block + BigInt(step) > toBlock ? Option.none() : Option.some(Option.some(current))];
317
+ }))), Effect.withSpan("SolanaIndexer.streamNativeBalance.sample"));
318
+ };
319
+ return Stream.paginate(Option.none(), withRetry(retry, sample));
320
+ };
321
+ return SolanaIndexer.of({
322
+ lastConfirmedBlock,
323
+ fetchTransactions,
324
+ streamTransactions,
325
+ fetchNativeBalance,
326
+ streamNativeBalance
327
+ });
328
+ }));
329
+ /**
330
+ * Builds an {@link SolanaIndexer} like {@link layer}, reading the options from `Config`.
331
+ *
332
+ * @example
333
+ * ```ts
334
+ * import * as SolanaIndexer from "@effect-blockchain/solana/SolanaIndexer"
335
+ * import * as Config from "effect/Config"
336
+ *
337
+ * const IndexerLive = SolanaIndexer.layerConfig({ confirmations: Config.Int("SOLANA_CONFIRMATIONS") })
338
+ * ```
339
+ *
340
+ * @since 0.1.0
341
+ * @category layers
342
+ */
343
+ export const layerConfig = options => Layer.unwrap(Effect.map(Config.unwrap(options), layer));
344
+ //# sourceMappingURL=SolanaIndexer.js.map