@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,105 @@
1
+ /**
2
+ * Named Solana clusters and their genesis hashes.
3
+ *
4
+ * @since 0.1.0
5
+ */
6
+ import { isBlockhash } from "@solana/kit"
7
+ import * as Schema from "effect/Schema"
8
+
9
+ /**
10
+ * @since 0.1.0
11
+ * @category constants
12
+ */
13
+ export const mainnets = ["Solana"] as const
14
+
15
+ /**
16
+ * @since 0.1.0
17
+ * @category constants
18
+ */
19
+ export const testnets = ["SolanaDevnet", "SolanaTestnet"] as const
20
+
21
+ /**
22
+ * Every supported network, mainnets first.
23
+ *
24
+ * @since 0.1.0
25
+ * @category constants
26
+ */
27
+ export const networks = [...mainnets, ...testnets] as const
28
+
29
+ /**
30
+ * A named Solana cluster.
31
+ *
32
+ * @since 0.1.0
33
+ * @category schemas
34
+ */
35
+ export const SolanaNetwork = Schema.Literals(networks).annotate({
36
+ identifier: "SolanaNetwork",
37
+ title: "Solana network",
38
+ description: "a named Solana cluster: Solana (mainnet-beta), SolanaDevnet or SolanaTestnet"
39
+ })
40
+
41
+ /**
42
+ * @since 0.1.0
43
+ * @category models
44
+ */
45
+ export type SolanaNetwork = typeof SolanaNetwork.Type
46
+
47
+ // like `SolanaAddress`: always 32 bytes once decoded
48
+ const solanaGenesisHashPattern = "^[2-9A-H][1-9A-HJ-NP-Za-km-z]{43}$"
49
+
50
+ /**
51
+ * A Solana genesis hash: a base58-encoded 32-byte hash, validated with `@solana/kit`.
52
+ *
53
+ * @since 0.1.0
54
+ * @category schemas
55
+ */
56
+ export const SolanaGenesisHash = Schema.String.annotate({
57
+ title: "Solana genesis hash",
58
+ description: "a valid Solana genesis hash (base58-encoded 32-byte hash)"
59
+ }).pipe(
60
+ Schema.check(
61
+ Schema.makeFilter((s: string) => isBlockhash(s) || `${s} is not a valid Solana genesis hash`, {
62
+ arbitraryConstraint: { patterns: [{ source: solanaGenesisHashPattern, flags: "" }] }
63
+ })
64
+ ),
65
+ Schema.brand("SolanaGenesisHash"),
66
+ Schema.annotate({ identifier: "SolanaGenesisHash" })
67
+ )
68
+
69
+ /**
70
+ * @since 0.1.0
71
+ * @category models
72
+ */
73
+ export type SolanaGenesisHash = typeof SolanaGenesisHash.Type
74
+
75
+ // `--expected-genesis-hash` of each cluster, https://docs.anza.xyz/clusters/available
76
+ const genesisHashes: Record<SolanaNetwork, SolanaGenesisHash> = {
77
+ Solana: SolanaGenesisHash.make("5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d"),
78
+ SolanaDevnet: SolanaGenesisHash.make("EtWTRABZaYq6iMfeYKouRu166VU2xqa1wcaWoxPkrZBG"),
79
+ SolanaTestnet: SolanaGenesisHash.make("4uhcVJyU9pJkvQyS88uRDiswHXSCkY3zQawwpjk2NsNY")
80
+ }
81
+
82
+ /**
83
+ * The cluster's genesis hash, reported by `getGenesisHash`.
84
+ *
85
+ * @since 0.1.0
86
+ * @category conversions
87
+ */
88
+ export const toGenesisHash = (network: SolanaNetwork): SolanaGenesisHash => genesisHashes[network]
89
+
90
+ /**
91
+ * @since 0.1.0
92
+ * @category predicates
93
+ */
94
+ export const isTestnet = (network: SolanaNetwork): boolean =>
95
+ (testnets as ReadonlyArray<SolanaNetwork>).includes(network)
96
+
97
+ /**
98
+ * Default number of slots `SolanaIndexer` stays behind the head: 0 on every network. The indexer reads at `finalized`
99
+ * commitment, and a block is finalized once 31+ confirmed blocks are built on top of it
100
+ * (https://docs.anza.xyz/consensus/commitments), so the finalized slot needs no further margin.
101
+ *
102
+ * @since 0.1.0
103
+ * @category getters
104
+ */
105
+ export const defaultConfirmations = (_network: SolanaNetwork): number => 0
@@ -0,0 +1,493 @@
1
+ /**
2
+ * Solana transaction relaying on top of {@link SolanaRpc.SolanaRpc}: signing a transaction, broadcasting it and
3
+ * following it until it is final.
4
+ *
5
+ * A relayer here sends an account's own transactions and manages their fees, as OpenZeppelin Relayer does. It is not
6
+ * a meta-transaction relayer paying for someone else's transaction. It keeps no state: storing signatures and their
7
+ * `lastValidBlockHeight`, deciding when to resend and holding keys belong to the application. Solana has no nonce:
8
+ * the recent blockhash plays that role, so concurrent senders from one address need no coordination, but two
9
+ * transactions with the same instructions, signers, fees and blockhash are one transaction and land once.
10
+ *
11
+ * Only v0 transactions with a recent blockhash are sent: address lookup tables and durable nonces are not. `sign`
12
+ * returns the transaction's signature before anything is broadcast, so it can be stored first, and `broadcast` can be
13
+ * repeated with the same bytes.
14
+ *
15
+ * Every transaction starts with the two Compute Budget instructions. Unless `sign` receives them, the compute unit
16
+ * limit is what a simulation consumed times the layer's `computeUnitMultiplier`, and the compute unit price comes from
17
+ * `getRecentPrioritizationFees` for the accounts the transaction writes to (see {@link defaultFees}). The price sets
18
+ * the priority fee only: the base fee of 5000 lamports per signature is charged on top.
19
+ *
20
+ * A transaction is in one {@link SolanaTransactionStatus}:
21
+ *
22
+ * | status | meaning | final |
23
+ * |---|---|---|
24
+ * | `Pending` | never reported: a node does not expose the transactions it has not processed | no |
25
+ * | `Included` | in `block`, not finalized or above the last confirmed slot: a fork can still drop it | no |
26
+ * | `Confirmed` | succeeded in `block`, finalized, at or below the last confirmed slot | yes |
27
+ * | `Failed` | failed in `block`, finalized, at or below the last confirmed slot: it paid its fee | yes |
28
+ * | `Expired` | unknown to the node, and its blockhash expired: it can no longer land | yes |
29
+ * | `NotFound` | unknown to the node: not processed yet, dropped, or never sent | no |
30
+ *
31
+ * A node reports a transaction as soon as it has processed its block, then the block reaches the `confirmed`
32
+ * commitment (voted by a supermajority) and the `finalized` one. `processed` and `confirmed` are both `Included`:
33
+ * the `Confirmed` status is not the `confirmed` commitment. A `finalized` transaction is `Confirmed` or `Failed` once
34
+ * its slot is at or below the last confirmed slot, the finalized slot minus `confirmations` (0 by default), as
35
+ * `SolanaIndexer.lastConfirmedBlock`.
36
+ *
37
+ * A transaction can land only while the block height is at most the `lastValidBlockHeight` returned with its recent
38
+ * blockhash. `Expired` is reported when the caller passes that height and the `finalized` block height is above it,
39
+ * so a transaction that can still land is never `Expired`. A durable-nonce transaction does not expire: leave
40
+ * `lastValidBlockHeight` out.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * import { type SolanaInstruction, SolanaRelayer } from "@effect-blockchain/solana/SolanaRelayer"
45
+ * import type { SolanaSigner } from "@effect-blockchain/solana/SolanaSigner"
46
+ * import type { SolanaTransactionHash } from "@effect-blockchain/solana/SolanaTransactionHash"
47
+ * import * as Effect from "effect/Effect"
48
+ *
49
+ * declare const feePayer: SolanaSigner
50
+ * declare const instructions: ReadonlyArray<SolanaInstruction>
51
+ * declare const store: (hash: SolanaTransactionHash, lastValidBlockHeight: bigint) => Effect.Effect<void>
52
+ *
53
+ * const program = Effect.gen(function*() {
54
+ * const relayer = yield* SolanaRelayer
55
+ * const { hash, lastValidBlockHeight, signed } = yield* relayer.sign({ feePayer, instructions })
56
+ * // stored before the broadcast: a crash in between leaves a signature to look up, never an unknown transaction
57
+ * yield* store(hash, lastValidBlockHeight)
58
+ * yield* relayer.broadcast({ signed })
59
+ * // a lagging endpoint can answer `NotFound` for a while: the timeout bounds the wait
60
+ * const status = yield* relayer.awaitConfirmation({ hash, lastValidBlockHeight }).pipe(Effect.timeout("5 minutes"))
61
+ * if (status._tag === "Failed") {
62
+ * yield* Effect.logError(`failed in slot ${status.block}`, status.reason)
63
+ * }
64
+ * if (status._tag === "Expired") {
65
+ * yield* Effect.logError("never landed: sign it again with a new blockhash")
66
+ * }
67
+ * })
68
+ * ```
69
+ *
70
+ * @since 0.2.0
71
+ */
72
+ import {
73
+ AccountRole,
74
+ address,
75
+ appendTransactionMessageInstructions,
76
+ assertIsSignatureBytes,
77
+ blockhash,
78
+ compileTransaction,
79
+ createTransactionMessage,
80
+ getBase64EncodedWireTransaction,
81
+ getBase64Encoder,
82
+ getSignatureFromTransaction,
83
+ getTransactionDecoder,
84
+ pipe,
85
+ setTransactionMessageFeePayer,
86
+ setTransactionMessageLifetimeUsingBlockhash,
87
+ SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE
88
+ } from "@solana/kit"
89
+ import * as Arr from "effect/Array"
90
+ import * as BigInt_ from "effect/BigInt"
91
+ import * as Context from "effect/Context"
92
+ import * as Effect from "effect/Effect"
93
+ import * as Layer from "effect/Layer"
94
+ import * as Order from "effect/Order"
95
+ import * as Schedule from "effect/Schedule"
96
+ import * as Schema from "effect/Schema"
97
+ import * as Confirmations from "./internal/confirmations.ts"
98
+ import * as RpcMethods from "./internal/rpcMethods.ts"
99
+ import { SolanaAddress } from "./SolanaAddress.ts"
100
+ import { DEFAULT_POLL_INTERVAL } from "./SolanaIndexer.ts"
101
+ import * as SolanaRpc from "./SolanaRpc.ts"
102
+ import { type SolanaSigner, SolanaSignerError } from "./SolanaSigner.ts"
103
+ import { SolanaTransactionHash } from "./SolanaTransactionHash.ts"
104
+
105
+ /**
106
+ * Where a transaction stands, by `_tag`: see the module's table. `block` is the slot holding it, and `reason` the
107
+ * transaction error as the node returns it.
108
+ *
109
+ * @since 0.2.0
110
+ * @category models
111
+ */
112
+ export type SolanaTransactionStatus =
113
+ | { readonly _tag: "Pending" }
114
+ | { readonly _tag: "Included"; readonly block: bigint }
115
+ | { readonly _tag: "Confirmed"; readonly block: bigint }
116
+ | { readonly _tag: "Failed"; readonly block: bigint; readonly reason: SolanaRpc.SolanaTransactionError }
117
+ | { readonly _tag: "Expired" }
118
+ | { readonly _tag: "NotFound" }
119
+
120
+ /**
121
+ * The transaction to look up: its `hash` (its first signature) and the `lastValidBlockHeight` returned with its
122
+ * recent blockhash. Without `lastValidBlockHeight`, an unknown transaction is `NotFound`, never `Expired`.
123
+ *
124
+ * @since 0.2.0
125
+ * @category models
126
+ */
127
+ export interface SolanaTransactionStatusOptions {
128
+ readonly hash: SolanaTransactionHash
129
+ readonly lastValidBlockHeight?: bigint | undefined
130
+ }
131
+
132
+ /**
133
+ * An account an instruction reads, `writable` when the instruction changes it and `signer` when it must sign the
134
+ * transaction.
135
+ *
136
+ * @since 0.2.0
137
+ * @category models
138
+ */
139
+ export interface SolanaAccountMeta {
140
+ readonly address: SolanaAddress
141
+ readonly signer?: boolean | undefined
142
+ readonly writable?: boolean | undefined
143
+ }
144
+
145
+ /**
146
+ * An instruction of a transaction: the program to call, the accounts it takes, in the program's order, and its `data`
147
+ * as the program encodes it.
148
+ *
149
+ * @since 0.2.0
150
+ * @category models
151
+ */
152
+ export interface SolanaInstruction {
153
+ readonly programAddress: SolanaAddress
154
+ readonly accounts?: ReadonlyArray<SolanaAccountMeta> | undefined
155
+ readonly data?: Uint8Array | undefined
156
+ }
157
+
158
+ /**
159
+ * A transaction signed by {@link SolanaRelayer.sign}: `signed` is the base64 wire transaction `broadcast` takes,
160
+ * `hash` the fee payer's signature and `lastValidBlockHeight` the last block height it can land at.
161
+ *
162
+ * @since 0.2.0
163
+ * @category models
164
+ */
165
+ export interface SolanaSignedTransaction {
166
+ readonly hash: SolanaTransactionHash
167
+ readonly signed: string
168
+ readonly lastValidBlockHeight: bigint
169
+ }
170
+
171
+ /**
172
+ * The node does not know the transaction's blockhash: it has expired, or the node is behind the one that returned
173
+ * it. Past `lastValidBlockHeight`, sign the transaction again.
174
+ *
175
+ * @since 0.2.0
176
+ * @category reasons
177
+ */
178
+ export class BlockhashNotFound extends Schema.TaggedError<BlockhashNotFound>()("BlockhashNotFound", {}) {}
179
+
180
+ /**
181
+ * The fee payer cannot pay the transaction fee: its balance is too low, or it holds no account.
182
+ *
183
+ * @since 0.2.0
184
+ * @category reasons
185
+ */
186
+ export class InsufficientFundsForFee
187
+ extends Schema.TaggedError<InsufficientFundsForFee>()("InsufficientFundsForFee", {})
188
+ {}
189
+
190
+ const TransactionError: Schema.Codec<SolanaRpc.SolanaTransactionError> = Schema.toType(RpcMethods.TransactionError)
191
+
192
+ /**
193
+ * The node simulated the transaction and it failed: `error` is the transaction error and `logs` the program logs up
194
+ * to it. {@link SolanaRelayer.sign} fails with it when it estimates the compute unit limit.
195
+ *
196
+ * @since 0.2.0
197
+ * @category reasons
198
+ */
199
+ export class SimulationFailed extends Schema.TaggedError<SimulationFailed>()("SimulationFailed", {
200
+ error: TransactionError,
201
+ logs: Schema.Array(Schema.String)
202
+ }) {}
203
+
204
+ /**
205
+ * Why a node refused a transaction, the `reason` of a {@link SolanaBroadcastError}, matched with `Effect.catchReason`.
206
+ *
207
+ * @since 0.2.0
208
+ * @category reasons
209
+ */
210
+ export const SolanaBroadcastReason = Schema.Union([BlockhashNotFound, InsufficientFundsForFee, SimulationFailed])
211
+
212
+ /**
213
+ * @since 0.2.0
214
+ * @category reasons
215
+ */
216
+ export type SolanaBroadcastReason = typeof SolanaBroadcastReason.Type
217
+
218
+ /**
219
+ * A node refused the transaction at its preflight simulation for a `reason` the sender can act on: `cause` is the
220
+ * {@link SolanaRpc.SolanaRpcError} holding the node's message. Any other refusal stays a `SolanaRpcError`.
221
+ *
222
+ * @since 0.2.0
223
+ * @category errors
224
+ */
225
+ export class SolanaBroadcastError extends Schema.TaggedError<SolanaBroadcastError>()("SolanaBroadcastError", {
226
+ reason: SolanaBroadcastReason,
227
+ cause: Schema.Defect()
228
+ }) {}
229
+
230
+ /**
231
+ * @since 0.2.0
232
+ * @category services
233
+ */
234
+ export class SolanaRelayer extends Context.Service<SolanaRelayer, {
235
+ /**
236
+ * Signs a v0 transaction of `instructions` paid by `feePayer` without sending it. `signers` are the other accounts
237
+ * the instructions mark as signer. A missing `blockhash` is the latest one at `confirmed` commitment, a missing
238
+ * `computeUnitLimit` is the units a simulation consumed times the layer's `computeUnitMultiplier` (a transaction
239
+ * that would fail fails with `SimulationFailed`), and a missing `computeUnitPrice`, in micro-lamports, comes from
240
+ * the layer's fee strategy.
241
+ */
242
+ readonly sign: (options: {
243
+ readonly feePayer: SolanaSigner
244
+ readonly signers?: ReadonlyArray<SolanaSigner> | undefined
245
+ readonly instructions: ReadonlyArray<SolanaInstruction>
246
+ readonly blockhash?: Pick<SolanaRpc.SolanaLatestBlockhash, "blockhash" | "lastValidBlockHeight"> | undefined
247
+ readonly computeUnitLimit?: number | undefined
248
+ readonly computeUnitPrice?: bigint | undefined
249
+ }) => Effect.Effect<SolanaSignedTransaction, SolanaRpc.SolanaRpcError | SolanaSignerError | SimulationFailed>
250
+ /**
251
+ * Sends a signed transaction with `sendTransaction` and returns its hash. The node simulates it first at
252
+ * `confirmed` commitment, then rebroadcasts it to the leaders until its blockhash expires (the node's default
253
+ * `maxRetries`). Sending the same bytes again is safe: a node answering that it has already processed the
254
+ * transaction is a success.
255
+ */
256
+ readonly broadcast: (options: {
257
+ readonly signed: string
258
+ }) => Effect.Effect<SolanaTransactionHash, SolanaBroadcastError | SolanaRpc.SolanaRpcError>
259
+ /**
260
+ * The status of the transaction as the answering endpoint sees it. An endpoint behind the head, or one that never
261
+ * received the transaction, answers `NotFound`, or `Expired` when `lastValidBlockHeight` has passed, for a
262
+ * transaction another one has in a block.
263
+ */
264
+ readonly fetchTransactionStatus: (
265
+ options: SolanaTransactionStatusOptions
266
+ ) => Effect.Effect<SolanaTransactionStatus, SolanaRpc.SolanaRpcError>
267
+ /**
268
+ * Reads {@link fetchTransactionStatus} on `poll` (`Schedule.spaced(SolanaIndexer.DEFAULT_POLL_INTERVAL)` by
269
+ * default) until it is `Confirmed`, `Failed` or `Expired`, and returns it. `NotFound` keeps polling, so bound the
270
+ * wait with a timeout. A `poll` that ends first returns the last status read.
271
+ */
272
+ readonly awaitConfirmation: (
273
+ options: SolanaTransactionStatusOptions & { readonly poll?: Schedule.Schedule<unknown> | undefined }
274
+ ) => Effect.Effect<SolanaTransactionStatus, SolanaRpc.SolanaRpcError>
275
+ }>()("@effect-blockchain/solana/SolanaRelayer") {}
276
+
277
+ // a slot reports the lowest price that landed in it, 0 as soon as one transaction paid none: any price above 0 is
278
+ // ordered before those transactions
279
+ const PRIORITY_FEE_FLOOR = BigInt(1)
280
+
281
+ /**
282
+ * The library's fee strategy: the compute unit price is the 75th percentile of the recent slots' prioritization fees,
283
+ * at least 1 micro-lamport.
284
+ *
285
+ * @since 0.2.0
286
+ * @category fees
287
+ */
288
+ export const defaultFees = (fees: ReadonlyArray<SolanaRpc.SolanaPrioritizationFee>): bigint => {
289
+ const sorted = Arr.sort(fees.map(({ prioritizationFee }) => prioritizationFee), Order.BigInt)
290
+ return BigInt_.max(sorted[Math.floor(sorted.length * 0.75)] ?? PRIORITY_FEE_FLOOR, PRIORITY_FEE_FLOOR)
291
+ }
292
+
293
+ const COMPUTE_BUDGET_PROGRAM = SolanaAddress.make("ComputeBudget111111111111111111111111111111")
294
+
295
+ // the most a transaction can ask for, and what the simulation runs with
296
+ const MAX_COMPUTE_UNITS = 1_400_000
297
+
298
+ // `getRecentPrioritizationFees` takes at most 128 addresses
299
+ const MAX_FEE_ADDRESSES = 128
300
+
301
+ // `SetComputeUnitLimit` (discriminator 2, u32) and `SetComputeUnitPrice` (discriminator 3, u64), little-endian
302
+ const computeBudget = (limit: number, price: bigint): ReadonlyArray<SolanaInstruction> => {
303
+ const unitLimit = new DataView(new ArrayBuffer(5))
304
+ unitLimit.setUint8(0, 2)
305
+ unitLimit.setUint32(1, limit, true)
306
+ const unitPrice = new DataView(new ArrayBuffer(9))
307
+ unitPrice.setUint8(0, 3)
308
+ unitPrice.setBigUint64(1, price, true)
309
+ return [
310
+ { programAddress: COMPUTE_BUDGET_PROGRAM, data: new Uint8Array(unitLimit.buffer) },
311
+ { programAddress: COMPUTE_BUDGET_PROGRAM, data: new Uint8Array(unitPrice.buffer) }
312
+ ]
313
+ }
314
+
315
+ const roleOf = ({ signer = false, writable = false }: SolanaAccountMeta) =>
316
+ signer
317
+ ? (writable ? AccountRole.WRITABLE_SIGNER : AccountRole.READONLY_SIGNER)
318
+ : (writable ? AccountRole.WRITABLE : AccountRole.READONLY)
319
+
320
+ const compile = (
321
+ feePayer: SolanaAddress,
322
+ lifetime: Pick<SolanaRpc.SolanaLatestBlockhash, "blockhash" | "lastValidBlockHeight">,
323
+ instructions: ReadonlyArray<SolanaInstruction>
324
+ ) =>
325
+ Effect.try({
326
+ try: () =>
327
+ compileTransaction(pipe(
328
+ createTransactionMessage({ version: 0 }),
329
+ (message) => setTransactionMessageFeePayer(address(feePayer), message),
330
+ (message) =>
331
+ setTransactionMessageLifetimeUsingBlockhash({
332
+ blockhash: blockhash(lifetime.blockhash),
333
+ lastValidBlockHeight: lifetime.lastValidBlockHeight
334
+ }, message),
335
+ (message) =>
336
+ appendTransactionMessageInstructions(
337
+ instructions.map(({ accounts = [], data, programAddress }) => ({
338
+ programAddress: address(programAddress),
339
+ accounts: accounts.map((account) => ({ address: address(account.address), role: roleOf(account) })),
340
+ ...(data === undefined ? {} : { data })
341
+ })),
342
+ message
343
+ )
344
+ )),
345
+ catch: (cause) => new SolanaSignerError({ cause })
346
+ })
347
+
348
+ /**
349
+ * Builds a {@link SolanaRelayer} over the provided {@link SolanaRpc.SolanaRpc}. `confirmations` overrides the
350
+ * network's default, as in `SolanaIndexer.layer`: both agree on the last confirmed slot. `fees` (default
351
+ * {@link defaultFees}) prices the transactions signed without a compute unit price, and `computeUnitMultiplier`
352
+ * (default 1.2) is the margin applied to a simulated compute unit limit.
353
+ *
354
+ * @since 0.2.0
355
+ * @category layers
356
+ */
357
+ export const layer = (options: {
358
+ readonly confirmations?: number | undefined
359
+ readonly fees?: ((fees: ReadonlyArray<SolanaRpc.SolanaPrioritizationFee>) => bigint) | undefined
360
+ readonly computeUnitMultiplier?: number | undefined
361
+ } = {}): Layer.Layer<SolanaRelayer, never, SolanaRpc.SolanaRpc> =>
362
+ Layer.effect(
363
+ SolanaRelayer,
364
+ Effect.gen(function*() {
365
+ const rpc = yield* SolanaRpc.SolanaRpc
366
+ const sign = Effect.fn("SolanaRelayer.sign")(
367
+ function*(
368
+ { feePayer, instructions, signers = [], ...given }: Parameters<SolanaRelayer["Service"]["sign"]>[0]
369
+ ) {
370
+ const writable = Arr.dedupe([
371
+ feePayer.address,
372
+ ...instructions.flatMap(({ accounts = [] }) =>
373
+ accounts.filter((account) => account.writable === true).map((account) => account.address)
374
+ )
375
+ ])
376
+ const { lifetime, price } = yield* Effect.all({
377
+ lifetime: given.blockhash === undefined
378
+ ? rpc.getLatestBlockhash({ commitment: "confirmed" })
379
+ : Effect.succeed(given.blockhash),
380
+ price: given.computeUnitPrice === undefined
381
+ ? Effect.map(
382
+ rpc.getRecentPrioritizationFees({ addresses: writable.slice(0, MAX_FEE_ADDRESSES) }),
383
+ options.fees ?? defaultFees
384
+ )
385
+ : Effect.succeed(given.computeUnitPrice)
386
+ }, { concurrency: "unbounded" })
387
+ const build = (limit: number) =>
388
+ compile(feePayer.address, lifetime, [...computeBudget(limit, price), ...instructions])
389
+ const estimate = Effect.gen(function*() {
390
+ const simulation = yield* rpc.simulateTransaction({
391
+ transaction: getBase64EncodedWireTransaction(yield* build(MAX_COMPUTE_UNITS)),
392
+ commitment: "confirmed",
393
+ sigVerify: false,
394
+ replaceRecentBlockhash: true
395
+ })
396
+ if (simulation.err !== null) {
397
+ return yield* new SimulationFailed({ error: simulation.err, logs: simulation.logs ?? [] })
398
+ }
399
+ const units = Number(simulation.unitsConsumed ?? MAX_COMPUTE_UNITS)
400
+ return Math.min(MAX_COMPUTE_UNITS, Math.ceil(units * (options.computeUnitMultiplier ?? 1.2)))
401
+ })
402
+ const compiled = yield* build(given.computeUnitLimit ?? (yield* estimate))
403
+ const message = Uint8Array.from(compiled.messageBytes)
404
+ const required = Object.keys(compiled.signatures)
405
+ const signatures = yield* Effect.forEach(required, (account) => {
406
+ const signer = [feePayer, ...signers].find((signer) => signer.address === account)
407
+ return signer === undefined
408
+ ? Effect.fail(new SolanaSignerError({ cause: new Error(`no signer for ${account}`) }))
409
+ : Effect.flatMap(signer.signTransactionMessage(message), (signature) =>
410
+ Effect.try({
411
+ try: () => {
412
+ assertIsSignatureBytes(signature)
413
+ return signature
414
+ },
415
+ catch: (cause) => new SolanaSignerError({ cause })
416
+ }))
417
+ }, { concurrency: "unbounded" })
418
+ const transaction = { ...compiled, signatures: Object.fromEntries(Arr.zip(required, signatures)) }
419
+ return {
420
+ hash: SolanaTransactionHash.make(getSignatureFromTransaction(transaction)),
421
+ signed: getBase64EncodedWireTransaction(transaction),
422
+ lastValidBlockHeight: lifetime.lastValidBlockHeight
423
+ }
424
+ }
425
+ )
426
+ const broadcast = Effect.fn("SolanaRelayer.broadcast")(
427
+ function*({ signed }: { readonly signed: string }) {
428
+ // the blockhash is read at `confirmed`: a preflight at the default `finalized` would not know it yet
429
+ const sent = yield* Effect.result(
430
+ rpc.sendTransaction({ transaction: signed, preflightCommitment: "confirmed" })
431
+ )
432
+ if (sent._tag === "Success") return sent.success
433
+ const cause = sent.failure
434
+ if (cause.code !== SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE) {
435
+ return yield* cause
436
+ }
437
+ // the JSON-RPC error only carries a message: the simulation run again returns the transaction error
438
+ const { err, logs } = yield* rpc.simulateTransaction({
439
+ transaction: signed,
440
+ commitment: "confirmed",
441
+ sigVerify: true
442
+ })
443
+ if (err === null) return yield* cause
444
+ if (err === "AlreadyProcessed") {
445
+ return SolanaTransactionHash.make(
446
+ getSignatureFromTransaction(getTransactionDecoder().decode(getBase64Encoder().encode(signed)))
447
+ )
448
+ }
449
+ const reason = err === "BlockhashNotFound"
450
+ ? new BlockhashNotFound()
451
+ // `AccountNotFound` is the fee payer's: the only account a transaction needs to exist
452
+ : err === "InsufficientFundsForFee" || err === "AccountNotFound"
453
+ ? new InsufficientFundsForFee()
454
+ : new SimulationFailed({ error: err, logs: logs ?? [] })
455
+ return yield* new SolanaBroadcastError({ reason, cause })
456
+ }
457
+ )
458
+ const fetchTransactionStatus = Effect.fn("SolanaRelayer.fetchTransactionStatus")(
459
+ function*({ hash, lastValidBlockHeight }: SolanaTransactionStatusOptions) {
460
+ // read before the status: once the finalized height has passed `lastValidBlockHeight`, a block holding the
461
+ // transaction is finalized too, and the status read that follows finds it
462
+ const expired = lastValidBlockHeight !== undefined
463
+ && (yield* rpc.getBlockHeight({ commitment: "finalized" })) > lastValidBlockHeight
464
+ // the node's status cache only covers recent slots: without the history, an old transaction would be unknown
465
+ const { value } = yield* rpc.getSignatureStatuses({ signatures: [hash], searchTransactionHistory: true })
466
+ const status = value[0] ?? null
467
+ if (status === null) return expired ? { _tag: "Expired" } as const : { _tag: "NotFound" } as const
468
+ const block = status.slot
469
+ if (status.confirmationStatus !== "finalized") return { _tag: "Included", block } as const
470
+ // read after the status: a finalized slot older than the transaction's could only delay `Confirmed`
471
+ if (block > (yield* Confirmations.lastConfirmedBlock(rpc, options.confirmations))) {
472
+ return { _tag: "Included", block } as const
473
+ }
474
+ return status.err === null
475
+ ? { _tag: "Confirmed", block } as const
476
+ : { _tag: "Failed", block, reason: status.err } as const
477
+ }
478
+ )
479
+ return SolanaRelayer.of({
480
+ sign,
481
+ broadcast,
482
+ fetchTransactionStatus,
483
+ awaitConfirmation: ({ poll = Schedule.spaced(DEFAULT_POLL_INTERVAL), ...transaction }) =>
484
+ fetchTransactionStatus(transaction).pipe(
485
+ Effect.repeat({
486
+ schedule: poll,
487
+ until: ({ _tag }) => _tag === "Confirmed" || _tag === "Failed" || _tag === "Expired"
488
+ }),
489
+ Effect.withSpan("SolanaRelayer.awaitConfirmation")
490
+ )
491
+ })
492
+ })
493
+ )