@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
@@ -0,0 +1,595 @@
1
+ /**
2
+ * Typed Solana 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 (`getGenesisHash`). Every method but `sendTransaction` is a read,
6
+ * so retries and fallback are safe; `sendTransaction` documents its own case. Methods are named after the JSON-RPC
7
+ * method. Every JSON integer in a reply is read as an exact `bigint`, so lamport amounts above 2^53 are never rounded.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import type { SolanaAddress } from "@effect-blockchain/solana/SolanaAddress"
12
+ * import * as SolanaRpc from "@effect-blockchain/solana/SolanaRpc"
13
+ * import * as Effect from "effect/Effect"
14
+ *
15
+ * declare const address: SolanaAddress
16
+ *
17
+ * // the 10 latest finalized transactions touching `address`
18
+ * const latest = Effect.gen(function*() {
19
+ * const rpc = yield* SolanaRpc.SolanaRpc
20
+ * const signatures = yield* rpc.getSignaturesForAddress({ address, limit: 10, commitment: "finalized" })
21
+ * return yield* Effect.forEach(signatures, ({ signature }) =>
22
+ * rpc.getTransaction({ signature, commitment: "finalized" }))
23
+ * })
24
+ * ```
25
+ *
26
+ * @since 0.1.0
27
+ */
28
+ import * as JsonRpc from "@effect-blockchain/core/JsonRpc"
29
+ import {
30
+ SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,
31
+ SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,
32
+ SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,
33
+ SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,
34
+ SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,
35
+ SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,
36
+ SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE,
37
+ SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED,
38
+ SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY,
39
+ SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,
40
+ SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE
41
+ } from "@solana/kit"
42
+ import type * as Arr from "effect/Array"
43
+ import * as Config from "effect/Config"
44
+ import * as Context from "effect/Context"
45
+ import type * as Duration from "effect/Duration"
46
+ import * as Effect from "effect/Effect"
47
+ import type * as HttpClient from "effect/http/HttpClient"
48
+ import * as Layer from "effect/Layer"
49
+ import type * as Redacted from "effect/Redacted"
50
+ import * as Schema from "effect/Schema"
51
+ import * as BigIntJson from "./internal/bigIntJson.ts"
52
+ import * as RpcMethods from "./internal/rpcMethods.ts"
53
+ import type { SolanaAddress } from "./SolanaAddress.ts"
54
+ import { type SolanaGenesisHash, type SolanaNetwork, toGenesisHash } from "./SolanaNetwork.ts"
55
+ import type { SolanaTransactionHash } from "./SolanaTransactionHash.ts"
56
+
57
+ /**
58
+ * A JSON-RPC endpoint. The `name` is shown in errors and spans, the `url` is never logged.
59
+ *
60
+ * @since 0.1.0
61
+ * @category models
62
+ */
63
+ export interface SolanaRpcEndpoint {
64
+ readonly name: string
65
+ readonly url: Redacted.Redacted<string>
66
+ }
67
+
68
+ /**
69
+ * A failed call: its `reason` (a {@link JsonRpc.Reason}, matched with `Effect.catchReason`), the JSON-RPC error code or
70
+ * HTTP status as `code`, and a `cause` without the endpoint URL. After several endpoints, the error is the last one
71
+ * and `cause` is an `AggregateError` of each endpoint's error, in order.
72
+ *
73
+ * On Solana, `Unavailable` includes the codes 429, -32603, -32005 and -32019, `Lagging` a `minContextSlot` not reached
74
+ * or a block not available yet, and `Pruned` a cleaned-up or skipped slot or a `getTransaction` returning `null`.
75
+ *
76
+ * @since 0.1.0
77
+ * @category errors
78
+ */
79
+ export class SolanaRpcError extends Schema.TaggedError<SolanaRpcError>()("SolanaRpcError", {
80
+ reason: JsonRpc.Reason,
81
+ method: Schema.String,
82
+ endpoint: Schema.String,
83
+ code: Schema.optional(Schema.Number),
84
+ cause: Schema.Defect()
85
+ }) {
86
+ /**
87
+ * @since 0.1.0
88
+ */
89
+ override get message(): string {
90
+ return `${this.method} failed on ${this.endpoint}: ${this.reason._tag}${
91
+ this.code === undefined ? "" : ` (${this.code})`
92
+ }`
93
+ }
94
+ }
95
+
96
+ /**
97
+ * The commitment a read waits for. `processed` is left out: a processed block can still be dropped.
98
+ *
99
+ * @since 0.1.0
100
+ * @category models
101
+ */
102
+ export type SolanaCommitment = "confirmed" | "finalized"
103
+
104
+ /**
105
+ * One `getSignaturesForAddress` page: signatures touching `address`, newest first, older than `before` and newer than
106
+ * `until` when given, at most `limit` (the node's default and maximum is 1000).
107
+ *
108
+ * @since 0.1.0
109
+ * @category models
110
+ */
111
+ export interface SolanaSignaturesQuery {
112
+ readonly address: SolanaAddress
113
+ readonly before?: SolanaTransactionHash | undefined
114
+ readonly until?: SolanaTransactionHash | undefined
115
+ readonly limit?: number | undefined
116
+ readonly commitment: SolanaCommitment
117
+ /**
118
+ * An endpoint that honours it answers `Lagging` until it has reached this slot. Some providers ignore it and answer
119
+ * from wherever they are, so a caller that needs the guarantee checks the head itself, e.g. with `getSlot`.
120
+ */
121
+ readonly minContextSlot?: bigint | undefined
122
+ }
123
+
124
+ /**
125
+ * A `getSignaturesForAddress` entry. `blockTime` is a Unix timestamp in seconds, `null` when the node does not know
126
+ * it. `err` is the raw transaction error as JSON (integers as decimal strings), `null` when the transaction succeeded.
127
+ *
128
+ * @since 0.1.0
129
+ * @category models
130
+ */
131
+ export interface SolanaSignatureInfo {
132
+ readonly signature: SolanaTransactionHash
133
+ readonly slot: bigint
134
+ readonly blockTime: bigint | null
135
+ readonly err: Schema.Json
136
+ readonly memo: string | null
137
+ }
138
+
139
+ /**
140
+ * The `getTransaction` encodings. `base64` is the signed wire transaction, for the `@solana/kit` decoders (e.g.
141
+ * `getTransactionDecoder`) and for storing the exact bytes. `json` splits it into signatures, account keys and compiled
142
+ * instructions; `jsonParsed` is not offered, as its shape depends on the programs the node knows.
143
+ *
144
+ * @since 0.1.0
145
+ * @category models
146
+ */
147
+ export type SolanaTransactionEncoding = "base64" | "json"
148
+
149
+ /**
150
+ * A compiled instruction of a `json` transaction: `programIdIndex` and `accounts` index the message's account keys,
151
+ * followed by the addresses loaded from the lookup tables (writable then readonly), and `data` is base58.
152
+ *
153
+ * @since 0.1.0
154
+ * @category models
155
+ */
156
+ export interface SolanaCompiledInstruction {
157
+ readonly programIdIndex: number
158
+ readonly accounts: ReadonlyArray<number>
159
+ readonly data: string
160
+ }
161
+
162
+ /**
163
+ * A `json` transaction. `addressTableLookups` is absent from legacy transactions.
164
+ *
165
+ * @since 0.1.0
166
+ * @category models
167
+ */
168
+ export interface SolanaJsonTransaction {
169
+ readonly signatures: ReadonlyArray<SolanaTransactionHash>
170
+ readonly message: {
171
+ readonly accountKeys: ReadonlyArray<SolanaAddress>
172
+ readonly header: {
173
+ readonly numRequiredSignatures: number
174
+ readonly numReadonlySignedAccounts: number
175
+ readonly numReadonlyUnsignedAccounts: number
176
+ }
177
+ readonly recentBlockhash: string
178
+ readonly instructions: ReadonlyArray<SolanaCompiledInstruction>
179
+ readonly addressTableLookups?: ReadonlyArray<{
180
+ readonly accountKey: SolanaAddress
181
+ readonly writableIndexes: ReadonlyArray<number>
182
+ readonly readonlyIndexes: ReadonlyArray<number>
183
+ }>
184
+ }
185
+ }
186
+
187
+ /**
188
+ * The `transaction` of a `getTransaction` result, by encoding: the base64 wire transaction or a
189
+ * {@link SolanaJsonTransaction}.
190
+ *
191
+ * @since 0.1.0
192
+ * @category models
193
+ */
194
+ export interface SolanaEncodedTransaction {
195
+ readonly base64: string
196
+ readonly json: SolanaJsonTransaction
197
+ }
198
+
199
+ /**
200
+ * The status meta of a transaction, reduced to its outcome and lamport balances. `err` is the raw transaction error as
201
+ * JSON (integers as decimal strings), `null` when it succeeded. `preBalances` and `postBalances` follow the account
202
+ * keys, then `loadedAddresses` (absent from transactions older than versioned transactions).
203
+ *
204
+ * @since 0.2.0
205
+ * @category models
206
+ */
207
+ export interface SolanaTransactionMeta {
208
+ readonly err: Schema.Json
209
+ readonly fee: bigint
210
+ readonly preBalances: ReadonlyArray<bigint>
211
+ readonly postBalances: ReadonlyArray<bigint>
212
+ readonly loadedAddresses?: {
213
+ readonly writable: ReadonlyArray<SolanaAddress>
214
+ readonly readonly: ReadonlyArray<SolanaAddress>
215
+ }
216
+ }
217
+
218
+ /**
219
+ * A `getTransaction` result. `transaction` follows the requested encoding (see {@link SolanaEncodedTransaction}).
220
+ * `meta` is `null` when the node does not have it.
221
+ *
222
+ * @since 0.1.0
223
+ * @category models
224
+ */
225
+ export interface SolanaTransactionInfo<Encoding extends SolanaTransactionEncoding = "base64"> {
226
+ readonly slot: bigint
227
+ readonly blockTime: bigint | null
228
+ readonly transaction: SolanaEncodedTransaction[Encoding]
229
+ readonly meta: SolanaTransactionMeta | null
230
+ }
231
+
232
+ /**
233
+ * A `getBalance` result: the lamports of the account (`value`) at the context `slot`.
234
+ *
235
+ * @since 0.2.0
236
+ * @category models
237
+ */
238
+ export interface SolanaBalance {
239
+ readonly slot: bigint
240
+ readonly value: bigint
241
+ }
242
+
243
+ /**
244
+ * Why an instruction failed, as the node returns it: the variant's name (`"ProgramFailedToComplete"`), the program's
245
+ * own error code (`{ Custom: 6001 }`), or any other variant carrying data as raw JSON (integers as decimal strings).
246
+ *
247
+ * @since 0.2.0
248
+ * @category models
249
+ */
250
+ export type SolanaInstructionError =
251
+ | string
252
+ | { readonly Custom: number }
253
+ | { readonly [variant: string]: Schema.Json }
254
+
255
+ /**
256
+ * Why a transaction failed, as the node returns it: the variant's name (`"BlockhashNotFound"`), the failing
257
+ * instruction's index and error (`{ InstructionError: [2, { Custom: 6001 }] }`), or any other variant carrying data
258
+ * as raw JSON (integers as decimal strings).
259
+ *
260
+ * @since 0.2.0
261
+ * @category models
262
+ */
263
+ export type SolanaTransactionError =
264
+ | string
265
+ | { readonly InstructionError: readonly [index: number, error: SolanaInstructionError] }
266
+ | { readonly [variant: string]: Schema.Json }
267
+
268
+ /**
269
+ * A `getSignatureStatuses` entry: the `slot` holding the transaction, its `err` (`null` when it succeeded) and the
270
+ * commitment its block has reached. `confirmations` counts the blocks built on it, `null` once it is finalized.
271
+ *
272
+ * @since 0.2.0
273
+ * @category models
274
+ */
275
+ export interface SolanaSignatureStatus {
276
+ readonly slot: bigint
277
+ readonly confirmations: number | null
278
+ readonly err: SolanaTransactionError | null
279
+ readonly confirmationStatus: "processed" | "confirmed" | "finalized" | null
280
+ }
281
+
282
+ /**
283
+ * A `getSignatureStatuses` result: one entry of `value` per signature, in order, `null` for a signature the endpoint
284
+ * does not know, as seen at the context `slot`.
285
+ *
286
+ * @since 0.2.0
287
+ * @category models
288
+ */
289
+ export interface SolanaSignatureStatuses {
290
+ readonly slot: bigint
291
+ readonly value: ReadonlyArray<SolanaSignatureStatus | null>
292
+ }
293
+
294
+ /**
295
+ * A `getLatestBlockhash` result at the context `slot`: a transaction signed with `blockhash` can land while the block
296
+ * height is at most `lastValidBlockHeight`.
297
+ *
298
+ * @since 0.2.0
299
+ * @category models
300
+ */
301
+ export interface SolanaLatestBlockhash {
302
+ readonly slot: bigint
303
+ readonly blockhash: string
304
+ readonly lastValidBlockHeight: bigint
305
+ }
306
+
307
+ /**
308
+ * A `simulateTransaction` result at the context `slot`: `err` is `null` when the transaction would succeed, `logs` the
309
+ * program logs and `unitsConsumed` the compute units used, both `null` when the simulation did not run.
310
+ *
311
+ * @since 0.2.0
312
+ * @category models
313
+ */
314
+ export interface SolanaSimulation {
315
+ readonly slot: bigint
316
+ readonly err: SolanaTransactionError | null
317
+ readonly logs: ReadonlyArray<string> | null
318
+ readonly unitsConsumed: bigint | null
319
+ }
320
+
321
+ /**
322
+ * A `getRecentPrioritizationFees` entry: the lowest compute unit price, in micro-lamports, of a transaction that
323
+ * landed in `slot` and locked the queried accounts. It is 0 for a slot where such a transaction paid none.
324
+ *
325
+ * @since 0.2.0
326
+ * @category models
327
+ */
328
+ export interface SolanaPrioritizationFee {
329
+ readonly slot: bigint
330
+ readonly prioritizationFee: bigint
331
+ }
332
+
333
+ /**
334
+ * The `getTransaction` options.
335
+ *
336
+ * @since 0.1.0
337
+ * @category models
338
+ */
339
+ export interface SolanaTransactionQuery {
340
+ readonly signature: SolanaTransactionHash
341
+ readonly commitment: SolanaCommitment
342
+ }
343
+
344
+ /**
345
+ * @since 0.1.0
346
+ * @category services
347
+ */
348
+ export class SolanaRpc extends Context.Service<SolanaRpc, {
349
+ readonly network: SolanaNetwork
350
+ /** `getGenesisHash`, verified against `network` once per endpoint then served from that check. */
351
+ readonly getGenesisHash: Effect.Effect<SolanaGenesisHash, SolanaRpcError>
352
+ /** `getSlot` */
353
+ readonly getSlot: (options: {
354
+ readonly commitment: SolanaCommitment
355
+ }) => Effect.Effect<bigint, SolanaRpcError>
356
+ /** `getBlockHeight`: the number of blocks below the head, lower than its slot as skipped slots hold no block. */
357
+ readonly getBlockHeight: (options: {
358
+ readonly commitment: SolanaCommitment
359
+ }) => Effect.Effect<bigint, SolanaRpcError>
360
+ /**
361
+ * `getSignatureStatuses` of at most 256 `signatures`, read from the blocks the node has processed, whatever their
362
+ * commitment. Without `searchTransactionHistory`, only the node's cache of recent slots is searched: an older
363
+ * transaction is `null`.
364
+ */
365
+ readonly getSignatureStatuses: (options: {
366
+ readonly signatures: ReadonlyArray<SolanaTransactionHash>
367
+ readonly searchTransactionHistory?: boolean | undefined
368
+ }) => Effect.Effect<SolanaSignatureStatuses, SolanaRpcError>
369
+ /** `getBalance` at `finalized` commitment. */
370
+ readonly getBalance: (options: {
371
+ readonly address: SolanaAddress
372
+ }) => Effect.Effect<SolanaBalance, SolanaRpcError>
373
+ /** `getSignaturesForAddress`, one page. */
374
+ readonly getSignaturesForAddress: (
375
+ query: SolanaSignaturesQuery
376
+ ) => Effect.Effect<ReadonlyArray<SolanaSignatureInfo>, SolanaRpcError>
377
+ /**
378
+ * `getTransaction` in `encoding`, `base64` by default, versioned transactions included. A transaction the endpoint
379
+ * lacks fails `Pruned`.
380
+ */
381
+ readonly getTransaction: {
382
+ (
383
+ options: SolanaTransactionQuery & { readonly encoding?: "base64" | undefined }
384
+ ): Effect.Effect<SolanaTransactionInfo, SolanaRpcError>
385
+ <Encoding extends SolanaTransactionEncoding>(
386
+ options: SolanaTransactionQuery & { readonly encoding: Encoding }
387
+ ): Effect.Effect<SolanaTransactionInfo<Encoding>, SolanaRpcError>
388
+ }
389
+ /** `getLatestBlockhash` */
390
+ readonly getLatestBlockhash: (options: {
391
+ readonly commitment: SolanaCommitment
392
+ }) => Effect.Effect<SolanaLatestBlockhash, SolanaRpcError>
393
+ /**
394
+ * `simulateTransaction` of a base64 wire `transaction`, run against the bank at `commitment` without being sent. A
395
+ * transaction that would fail is a success whose `err` says why. `sigVerify` checks the signatures, and
396
+ * `replaceRecentBlockhash` swaps the blockhash for the latest one, which unsigned transactions need: the node
397
+ * refuses both together.
398
+ */
399
+ readonly simulateTransaction: (options: {
400
+ readonly transaction: string
401
+ readonly commitment: SolanaCommitment
402
+ readonly sigVerify?: boolean | undefined
403
+ readonly replaceRecentBlockhash?: boolean | undefined
404
+ }) => Effect.Effect<SolanaSimulation, SolanaRpcError>
405
+ /**
406
+ * `getRecentPrioritizationFees` over the node's cache of recent slots (up to 150) for the transactions locking every
407
+ * one of `addresses` as writable, at most 128 of them. Without `addresses`, any transaction counts.
408
+ */
409
+ readonly getRecentPrioritizationFees: (options: {
410
+ readonly addresses: ReadonlyArray<SolanaAddress>
411
+ }) => Effect.Effect<ReadonlyArray<SolanaPrioritizationFee>, SolanaRpcError>
412
+ /**
413
+ * `sendTransaction`: submits a signed base64 wire `transaction` and returns its first signature. The node simulates
414
+ * it first at `preflightCommitment` (`finalized` by default) unless `skipPreflight`, then forwards it to the leader
415
+ * and rebroadcasts it `maxRetries` times, or until its blockhash expires when left out. A retry or a fallback sends
416
+ * the same bytes, so it never creates a second transaction, but a node that has processed them refuses the second
417
+ * copy. A refusal (a failed preflight, `BlockhashNotFound`, `AlreadyProcessed`...) is `Rejected`, with the node's
418
+ * message in `cause`.
419
+ */
420
+ readonly sendTransaction: (options: {
421
+ readonly transaction: string
422
+ readonly skipPreflight?: boolean | undefined
423
+ readonly preflightCommitment?: SolanaCommitment | undefined
424
+ readonly maxRetries?: number | undefined
425
+ }) => Effect.Effect<SolanaTransactionHash, SolanaRpcError>
426
+ }>()("@effect-blockchain/solana/SolanaRpc") {}
427
+
428
+ // JSON-RPC codes from @solana/errors, any other code is `Rejected`
429
+ const codes: ReadonlyMap<number, JsonRpc.CodeReason> = new Map([
430
+ [429, "Unavailable"],
431
+ [SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR, "Unavailable"],
432
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY, "Unavailable"],
433
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE, "Unavailable"],
434
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED, "Lagging"],
435
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE, "Lagging"],
436
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET, "Lagging"],
437
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP, "Pruned"],
438
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED, "Pruned"],
439
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED, "Pruned"],
440
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE, "Pruned"],
441
+ [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX, "Pruned"]
442
+ ])
443
+
444
+ /**
445
+ * Builds a {@link SolanaRpc} over `endpoints`, tried in order, sending requests with the provided `HttpClient`
446
+ * (e.g. `FetchHttpClient.layer`). `timeout` (default 30 seconds) bounds each attempt, `retries` (default 3) and
447
+ * `retryDelay` (default 500 millis) set the backoff before falling back: see {@link JsonRpc.Unavailable}.
448
+ * `genesisHash` replaces the genesis hash of `network`, for a local validator or a private cluster, which have their
449
+ * own.
450
+ *
451
+ * @since 0.1.0
452
+ * @category layers
453
+ */
454
+ export const layer = (options: {
455
+ readonly network: SolanaNetwork
456
+ readonly genesisHash?: SolanaGenesisHash | undefined
457
+ readonly endpoints: Arr.NonEmptyReadonlyArray<SolanaRpcEndpoint>
458
+ readonly timeout?: Duration.Input | undefined
459
+ readonly retries?: number | undefined
460
+ readonly retryDelay?: Duration.Input | undefined
461
+ }): Layer.Layer<SolanaRpc, never, HttpClient.HttpClient> =>
462
+ Layer.effect(
463
+ SolanaRpc,
464
+ Effect.gen(function*() {
465
+ const { network } = options
466
+ const expectedGenesisHash = options.genesisHash ?? toGenesisHash(network)
467
+ const rpc = yield* JsonRpc.make({
468
+ spanPrefix: "SolanaRpc",
469
+ network,
470
+ endpoints: options.endpoints,
471
+ timeout: options.timeout,
472
+ retries: options.retries,
473
+ retryDelay: options.retryDelay,
474
+ codes,
475
+ parseBody: BigIntJson.parse,
476
+ checkNetwork: (send, endpoint) =>
477
+ send(RpcMethods.getGenesisHash, []).pipe(
478
+ Effect.flatMap((genesisHash) =>
479
+ genesisHash === expectedGenesisHash
480
+ ? Effect.succeed(expectedGenesisHash)
481
+ : Effect.fail(
482
+ new SolanaRpcError({
483
+ reason: new JsonRpc.WrongNetwork({ expected: expectedGenesisHash, actual: genesisHash }),
484
+ method: RpcMethods.getGenesisHash.name,
485
+ endpoint,
486
+ cause: new Error(`expected genesis hash ${expectedGenesisHash} for ${network}, got ${genesisHash}`)
487
+ })
488
+ )
489
+ )
490
+ ),
491
+ makeError: (fields: JsonRpc.ErrorFields) => new SolanaRpcError(fields)
492
+ })
493
+ type Endpoint = JsonRpc.Endpoint<SolanaGenesisHash, SolanaRpcError>
494
+
495
+ const getTransactionOn = (
496
+ endpoint: Endpoint,
497
+ { commitment, encoding, signature }: SolanaTransactionQuery & { readonly encoding: SolanaTransactionEncoding }
498
+ ) =>
499
+ rpc.call(endpoint, RpcMethods.getTransaction(encoding), [signature, {
500
+ commitment,
501
+ encoding,
502
+ maxSupportedTransactionVersion: 0
503
+ }]).pipe(
504
+ Effect.flatMap((tx) =>
505
+ tx === null
506
+ ? Effect.fail(
507
+ rpc.fail(
508
+ endpoint,
509
+ RpcMethods.getTransaction.name,
510
+ new JsonRpc.Pruned(),
511
+ new Error(`transaction ${signature} not found`)
512
+ )
513
+ )
514
+ : Effect.succeed(tx)
515
+ )
516
+ )
517
+ function getTransaction(
518
+ options: SolanaTransactionQuery & { readonly encoding?: "base64" | undefined }
519
+ ): Effect.Effect<SolanaTransactionInfo, SolanaRpcError>
520
+ function getTransaction<Encoding extends SolanaTransactionEncoding>(
521
+ options: SolanaTransactionQuery & { readonly encoding: Encoding }
522
+ ): Effect.Effect<SolanaTransactionInfo<Encoding>, SolanaRpcError>
523
+ function getTransaction(
524
+ { encoding = "base64", ...options }: SolanaTransactionQuery & {
525
+ readonly encoding?: SolanaTransactionEncoding | undefined
526
+ }
527
+ ): Effect.Effect<SolanaTransactionInfo<SolanaTransactionEncoding>, SolanaRpcError> {
528
+ return rpc.withFallback((endpoint) => getTransactionOn(endpoint, { ...options, encoding }))
529
+ }
530
+
531
+ return SolanaRpc.of({
532
+ network,
533
+ getGenesisHash: rpc.withFallback(rpc.checkNetwork),
534
+ getSlot: ({ commitment }) =>
535
+ rpc.withFallback((endpoint) => rpc.call(endpoint, RpcMethods.getSlot, [{ commitment }])),
536
+ getBlockHeight: ({ commitment }) =>
537
+ rpc.withFallback((endpoint) => rpc.call(endpoint, RpcMethods.getBlockHeight, [{ commitment }])),
538
+ getSignatureStatuses: ({ signatures, ...config }) =>
539
+ rpc.withFallback((endpoint) =>
540
+ rpc.call(endpoint, RpcMethods.getSignatureStatuses, [signatures, config]).pipe(
541
+ Effect.map(({ context, value }) => ({ slot: context.slot, value }))
542
+ )
543
+ ),
544
+ getBalance: ({ address }) =>
545
+ rpc.withFallback((endpoint) =>
546
+ rpc.call(endpoint, RpcMethods.getBalance, [address, { commitment: "finalized" }]).pipe(
547
+ Effect.map(({ context, value }) => ({ slot: context.slot, value }))
548
+ )
549
+ ),
550
+ getSignaturesForAddress: ({ address, ...config }) =>
551
+ rpc.withFallback((endpoint) => rpc.call(endpoint, RpcMethods.getSignaturesForAddress, [address, config])),
552
+ getTransaction,
553
+ getLatestBlockhash: ({ commitment }) =>
554
+ rpc.withFallback((endpoint) =>
555
+ rpc.call(endpoint, RpcMethods.getLatestBlockhash, [{ commitment }]).pipe(
556
+ Effect.map(({ context, value }) => ({ slot: context.slot, ...value }))
557
+ )
558
+ ),
559
+ simulateTransaction: ({ transaction, ...config }) =>
560
+ rpc.withFallback((endpoint) =>
561
+ rpc.call(endpoint, RpcMethods.simulateTransaction, [transaction, { encoding: "base64", ...config }]).pipe(
562
+ Effect.map(({ context, value }) => ({ slot: context.slot, ...value }))
563
+ )
564
+ ),
565
+ getRecentPrioritizationFees: ({ addresses }) =>
566
+ rpc.withFallback((endpoint) => rpc.call(endpoint, RpcMethods.getRecentPrioritizationFees, [addresses])),
567
+ sendTransaction: ({ transaction, ...config }) =>
568
+ rpc.withFallback((endpoint) =>
569
+ rpc.call(endpoint, RpcMethods.sendTransaction, [transaction, { encoding: "base64", ...config }])
570
+ )
571
+ })
572
+ })
573
+ )
574
+
575
+ /**
576
+ * Builds an {@link SolanaRpc} like {@link layer}, reading the options from `Config`. Endpoint URLs stay `Redacted`.
577
+ *
578
+ * @example
579
+ * ```ts
580
+ * import * as SolanaRpc from "@effect-blockchain/solana/SolanaRpc"
581
+ * import * as Config from "effect/Config"
582
+ *
583
+ * const RpcLive = SolanaRpc.layerConfig({
584
+ * network: Config.succeed("Solana"),
585
+ * endpoints: Config.all([Config.all({ name: Config.succeed("main"), url: Config.Redacted("SOLANA_RPC_URL") })])
586
+ * })
587
+ * ```
588
+ *
589
+ * @since 0.1.0
590
+ * @category layers
591
+ */
592
+ export const layerConfig = (
593
+ options: Config.Wrap<Parameters<typeof layer>[0]>
594
+ ): Layer.Layer<SolanaRpc, Config.ConfigError, HttpClient.HttpClient> =>
595
+ Layer.unwrap(Effect.map(Config.unwrap(options), layer))
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Signers of Solana transactions: a local private key, or a custody API that signs raw bytes.
3
+ *
4
+ * A signer is a value and receives the whole serialized transaction message. Solana signs these bytes themselves,
5
+ * without hashing them first, so what is being authorised can always be decoded from them. A transaction carries one
6
+ * signature per signer account of its message, the fee payer's first.
7
+ *
8
+ * @since 0.2.0
9
+ */
10
+ import {
11
+ address,
12
+ assertIsSignatureBytes,
13
+ createKeyPairFromBytes,
14
+ getAddressFromPublicKey,
15
+ getBase58Encoder,
16
+ getPublicKeyFromAddress,
17
+ signBytes,
18
+ verifySignature
19
+ } from "@solana/kit"
20
+ import * as Effect from "effect/Effect"
21
+ import * as Redacted from "effect/Redacted"
22
+ import * as Schema from "effect/Schema"
23
+ import { SolanaAddress } from "./SolanaAddress.ts"
24
+
25
+ /**
26
+ * A signature could not be produced: `cause` is the signer's own failure, or why its signature was refused. It never
27
+ * holds a private key.
28
+ *
29
+ * @since 0.2.0
30
+ * @category errors
31
+ */
32
+ export class SolanaSignerError extends Schema.TaggedError<SolanaSignerError>()("SolanaSignerError", {
33
+ cause: Schema.Defect()
34
+ }) {}
35
+
36
+ /**
37
+ * Signs transactions as `address`. `signTransactionMessage` receives the serialized transaction message and returns
38
+ * the 64-byte ed25519 signature of these bytes.
39
+ *
40
+ * @since 0.2.0
41
+ * @category models
42
+ */
43
+ export interface SolanaSigner {
44
+ readonly address: SolanaAddress
45
+ readonly signTransactionMessage: (message: Uint8Array) => Effect.Effect<Uint8Array, SolanaSignerError>
46
+ }
47
+
48
+ const toError = (cause: unknown) => new SolanaSignerError({ cause })
49
+
50
+ /**
51
+ * A signer holding an ed25519 key in memory: the 64-byte secret key (the private key followed by its public key) in
52
+ * base58, as wallets export it. An invalid key fails with a {@link SolanaSignerError} that does not repeat it.
53
+ *
54
+ * @since 0.2.0
55
+ * @category constructors
56
+ */
57
+ export const fromPrivateKey = (key: Redacted.Redacted<string>): Effect.Effect<SolanaSigner, SolanaSignerError> =>
58
+ Effect.tryPromise({
59
+ try: async () => {
60
+ const keyPair = await createKeyPairFromBytes(getBase58Encoder().encode(Redacted.value(key)))
61
+ return { keyPair, address: SolanaAddress.make(await getAddressFromPublicKey(keyPair.publicKey)) }
62
+ },
63
+ // the thrown error can quote the key
64
+ catch: () => new SolanaSignerError({ cause: new Error("invalid private key") })
65
+ }).pipe(Effect.map(({ address, keyPair }) => ({
66
+ address,
67
+ signTransactionMessage: (message) =>
68
+ Effect.tryPromise({ try: () => signBytes(keyPair.privateKey, message), catch: toError })
69
+ })))
70
+
71
+ /**
72
+ * A signer for a key held elsewhere (a custody API, an HSM) that signs raw bytes. `signMessage` receives the
73
+ * serialized transaction message and returns its 64-byte ed25519 signature. A failure of `signMessage`, a malformed
74
+ * signature or one that `address` did not make fails with a {@link SolanaSignerError}.
75
+ *
76
+ * @since 0.2.0
77
+ * @category constructors
78
+ */
79
+ export const fromMessageSigner = <E>(options: {
80
+ readonly address: SolanaAddress
81
+ readonly signMessage: (message: Uint8Array) => Effect.Effect<Uint8Array, E>
82
+ }): SolanaSigner => ({
83
+ address: options.address,
84
+ signTransactionMessage: Effect.fnUntraced(function*(message) {
85
+ const signature = yield* Effect.mapError(options.signMessage(message), toError)
86
+ return yield* Effect.tryPromise({
87
+ try: async () => {
88
+ assertIsSignatureBytes(signature)
89
+ const publicKey = await getPublicKeyFromAddress(address(options.address))
90
+ if (!(await verifySignature(publicKey, signature, message))) {
91
+ throw new Error(`not a signature of ${options.address}`)
92
+ }
93
+ return signature
94
+ },
95
+ catch: toError
96
+ })
97
+ })
98
+ })