@thru/programs 0.3.4 → 0.3.6

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 (152) hide show
  1. package/README.md +124 -39
  2. package/dist/abi-manager/index.cjs +9568 -0
  3. package/dist/abi-manager/index.cjs.map +1 -0
  4. package/dist/abi-manager/index.d.cts +2169 -0
  5. package/dist/abi-manager/index.d.ts +2169 -0
  6. package/dist/abi-manager/index.js +4 -0
  7. package/dist/abi-manager/index.js.map +1 -0
  8. package/dist/amm/index.cjs +132 -33
  9. package/dist/amm/index.cjs.map +1 -1
  10. package/dist/amm/index.d.cts +1 -1
  11. package/dist/amm/index.d.ts +1 -1
  12. package/dist/amm/index.js +5 -2
  13. package/dist/amm/index.js.map +1 -1
  14. package/dist/bootstrap-addresses/index.cjs +118 -0
  15. package/dist/bootstrap-addresses/index.cjs.map +1 -0
  16. package/dist/bootstrap-addresses/index.d.cts +44 -0
  17. package/dist/bootstrap-addresses/index.d.ts +44 -0
  18. package/dist/bootstrap-addresses/index.js +5 -0
  19. package/dist/bootstrap-addresses/index.js.map +1 -0
  20. package/dist/chunk-6IC6CO5S.js +9443 -0
  21. package/dist/chunk-6IC6CO5S.js.map +1 -0
  22. package/dist/chunk-7DHFYBRW.js +51 -0
  23. package/dist/chunk-7DHFYBRW.js.map +1 -0
  24. package/dist/chunk-7FBCBZIY.js +41 -0
  25. package/dist/chunk-7FBCBZIY.js.map +1 -0
  26. package/dist/chunk-BNYDH4ZP.js +4351 -0
  27. package/dist/chunk-BNYDH4ZP.js.map +1 -0
  28. package/dist/{chunk-J7B7XYOI.js → chunk-CYG4PB65.js} +14 -41
  29. package/dist/chunk-CYG4PB65.js.map +1 -0
  30. package/dist/chunk-VNTPD4AR.js +37 -0
  31. package/dist/chunk-VNTPD4AR.js.map +1 -0
  32. package/dist/chunk-YX7BLFQZ.js +81 -0
  33. package/dist/chunk-YX7BLFQZ.js.map +1 -0
  34. package/dist/chunk-ZHF2PH5H.js +6536 -0
  35. package/dist/chunk-ZHF2PH5H.js.map +1 -0
  36. package/dist/clob/index.cjs +8461 -4922
  37. package/dist/clob/index.cjs.map +1 -1
  38. package/dist/clob/index.d.cts +1115 -53
  39. package/dist/clob/index.d.ts +1115 -53
  40. package/dist/clob/index.js +6817 -3395
  41. package/dist/clob/index.js.map +1 -1
  42. package/dist/deploy/index.cjs +24751 -0
  43. package/dist/deploy/index.cjs.map +1 -0
  44. package/dist/deploy/index.d.cts +180 -0
  45. package/dist/deploy/index.d.ts +180 -0
  46. package/dist/deploy/index.js +1849 -0
  47. package/dist/deploy/index.js.map +1 -0
  48. package/dist/helpers-DD7q61nr.d.cts +7 -0
  49. package/dist/helpers-DD7q61nr.d.ts +7 -0
  50. package/dist/manager/index.cjs +6680 -0
  51. package/dist/manager/index.cjs.map +1 -0
  52. package/dist/manager/index.d.cts +1279 -0
  53. package/dist/manager/index.d.ts +1279 -0
  54. package/dist/manager/index.js +5 -0
  55. package/dist/manager/index.js.map +1 -0
  56. package/dist/multicall/index.cjs +117 -40
  57. package/dist/multicall/index.cjs.map +1 -1
  58. package/dist/multicall/index.d.cts +5 -2
  59. package/dist/multicall/index.d.ts +5 -2
  60. package/dist/multicall/index.js +4 -1
  61. package/dist/oracle/index.cjs +122 -14
  62. package/dist/oracle/index.cjs.map +1 -1
  63. package/dist/oracle/index.d.cts +3 -1
  64. package/dist/oracle/index.d.ts +3 -1
  65. package/dist/oracle/index.js +7 -1
  66. package/dist/oracle/index.js.map +1 -1
  67. package/dist/passkey-manager/index.cjs +107 -6
  68. package/dist/passkey-manager/index.cjs.map +1 -1
  69. package/dist/passkey-manager/index.d.cts +1 -1
  70. package/dist/passkey-manager/index.d.ts +1 -1
  71. package/dist/passkey-manager/index.js +6 -3
  72. package/dist/passkey-manager/index.js.map +1 -1
  73. package/dist/uploader/index.cjs +4442 -0
  74. package/dist/uploader/index.cjs.map +1 -0
  75. package/dist/uploader/index.d.cts +761 -0
  76. package/dist/uploader/index.d.ts +761 -0
  77. package/dist/uploader/index.js +4 -0
  78. package/dist/uploader/index.js.map +1 -0
  79. package/package.json +27 -2
  80. package/src/abi-manager/abi/thru/blockchain/state_proof/types.ts +1906 -0
  81. package/src/abi-manager/abi/thru/common/primitives/types.ts +2428 -0
  82. package/src/abi-manager/abi/thru/program/abi_manager/types.ts +7037 -0
  83. package/src/abi-manager/accounts.ts +91 -0
  84. package/src/abi-manager/constants.ts +19 -0
  85. package/src/abi-manager/derivation.ts +86 -0
  86. package/src/abi-manager/errors.ts +48 -0
  87. package/src/abi-manager/index.test.ts +136 -0
  88. package/src/abi-manager/index.ts +56 -0
  89. package/src/abi-manager/instructions.ts +573 -0
  90. package/src/abi-manager/types.ts +150 -0
  91. package/src/amm/index.test.ts +2 -6
  92. package/src/amm/index.ts +2 -2
  93. package/src/bootstrap-addresses/index.test.ts +59 -0
  94. package/src/bootstrap-addresses/index.ts +58 -0
  95. package/src/clob/abi/thru/program/clob/types.ts +6981 -3070
  96. package/src/clob/exchange-client.test.ts +115 -2
  97. package/src/clob/exchange-client.ts +52 -13
  98. package/src/clob/exchange.test.ts +18 -16
  99. package/src/clob/exchange.ts +4 -0
  100. package/src/clob/index.test.ts +140 -7
  101. package/src/clob/index.ts +304 -12
  102. package/src/clob/price.test.ts +32 -0
  103. package/src/clob/price.ts +77 -0
  104. package/src/deploy/accounts.ts +208 -0
  105. package/src/deploy/chain.ts +163 -0
  106. package/src/deploy/constants.ts +30 -0
  107. package/src/deploy/deploy.test.ts +349 -0
  108. package/src/deploy/errors.ts +72 -0
  109. package/src/deploy/index.ts +44 -0
  110. package/src/deploy/inspection.ts +146 -0
  111. package/src/deploy/seeds.ts +29 -0
  112. package/src/deploy/types.ts +178 -0
  113. package/src/deploy/uploader.test.ts +326 -0
  114. package/src/deploy/uploader.ts +558 -0
  115. package/src/deploy/validation-imports.test.ts +55 -0
  116. package/src/deploy/validation.ts +183 -0
  117. package/src/deploy/workflows.test.ts +422 -0
  118. package/src/deploy/workflows.ts +1088 -0
  119. package/src/helpers/bytes.test.ts +58 -0
  120. package/src/helpers/bytes.ts +28 -3
  121. package/src/manager/abi/thru/blockchain/state_proof/types.ts +1906 -0
  122. package/src/manager/abi/thru/common/primitives/types.ts +2428 -0
  123. package/src/manager/abi/thru/program/manager/types.ts +3814 -0
  124. package/src/manager/accounts.ts +44 -0
  125. package/src/manager/constants.ts +16 -0
  126. package/src/manager/derivation.ts +32 -0
  127. package/src/manager/errors.ts +47 -0
  128. package/src/manager/index.test.ts +108 -0
  129. package/src/manager/index.ts +68 -0
  130. package/src/manager/instructions.ts +281 -0
  131. package/src/manager/types.ts +95 -0
  132. package/src/manager/validation.ts +35 -0
  133. package/src/multicall/index.test.ts +11 -2
  134. package/src/multicall/index.ts +12 -5
  135. package/src/oracle/index.ts +4 -0
  136. package/src/passkey-manager/constants.ts +2 -1
  137. package/src/passkey-manager/validate.test.ts +2 -2
  138. package/src/uploader/abi/thru/common/primitives/types.ts +2428 -0
  139. package/src/uploader/abi/thru/program/uploader/types.ts +3022 -0
  140. package/src/uploader/accounts.ts +38 -0
  141. package/src/uploader/constants.ts +14 -0
  142. package/src/uploader/derivation.ts +34 -0
  143. package/src/uploader/errors.ts +25 -0
  144. package/src/uploader/index.test.ts +107 -0
  145. package/src/uploader/index.ts +34 -0
  146. package/src/uploader/instructions.ts +163 -0
  147. package/src/uploader/types.ts +67 -0
  148. package/src/utils/helpers.ts +121 -0
  149. package/tsup.config.ts +5 -0
  150. package/dist/chunk-J7B7XYOI.js.map +0 -1
  151. package/dist/chunk-P5OABVJI.js +0 -28
  152. package/dist/chunk-P5OABVJI.js.map +0 -1
@@ -0,0 +1,1849 @@
1
+ import { deriveProgramABIAddresses, ABI_MANAGER_PROGRAM_ADDRESS, parseABIMetaAccount, parseABIAccount, createOfficialABIMetaInstruction, createOfficialABIInstruction, ABI_STATE_FINALIZED, ABI_STATE_OPEN, createUpgradeOfficialABIInstruction } from '../chunk-6IC6CO5S.js';
2
+ import { deriveUploadAddresses, UPLOADER_DEFAULT_CHUNK_SIZE, UPLOADER_MIN_CHUNK_SIZE, UPLOADER_MAX_CHUNK_SIZE, createUploadBufferInstruction, UPLOADER_PROGRAM_ADDRESS, UPLOADER_STATE_FINALIZED, createWriteUploadInstruction, createFinalizeUploadInstruction, createDestroyUploadInstruction, UPLOADER_STATE_OPEN, parseUploaderProgramMeta } from '../chunk-BNYDH4ZP.js';
3
+ import { bytesEqual, sha256, bytesToHex } from '../chunk-7FBCBZIY.js';
4
+ import { GENESIS_MULTICALL_PROGRAM_ADDRESS, buildMulticallInstruction } from '../chunk-CYG4PB65.js';
5
+ import '../chunk-7DHFYBRW.js';
6
+ import { validateManagerProgramImage, parseManagerProgramMeta, createEphemeralProgramInstruction, createPermanentProgramInstruction, createUpgradeProgramInstruction } from '../chunk-ZHF2PH5H.js';
7
+ import { deriveManagedProgramAddresses, MANAGER_PROGRAM_ADDRESS, MANAGER_STATE_FINALIZED, MANAGER_STATE_OPEN } from '../chunk-VNTPD4AR.js';
8
+ import { normalizeSeed } from '../chunk-YX7BLFQZ.js';
9
+ import { Pubkey, createThruClient, Signature, SubmissionStatus, ConsensusStatus } from '@thru/sdk';
10
+ import { StateProofType } from '@thru/sdk/proto';
11
+ import { resolveImports, OnchainFetcher, buildLayoutIrWithManifest } from '@thru/sdk/abi';
12
+ import { isHexString, hexToBytes } from '@thru/sdk/helpers';
13
+
14
+ // src/deploy/errors.ts
15
+ var DeployError = class extends Error {
16
+ constructor(code, message, options = {}) {
17
+ super(message);
18
+ if (options.cause !== void 0) {
19
+ Object.defineProperty(this, "cause", {
20
+ configurable: true,
21
+ value: options.cause
22
+ });
23
+ }
24
+ this.name = "DeployError";
25
+ this.code = code;
26
+ this.operation = options.operation;
27
+ this.phase = options.phase;
28
+ this.transactionSignature = options.transactionSignature;
29
+ this.vmError = options.vmError;
30
+ this.userErrorCode = options.userErrorCode;
31
+ this.addresses = options.addresses;
32
+ this.cleanup = options.cleanup;
33
+ }
34
+ };
35
+ function asDeployError(error, code, message, options = {}) {
36
+ if (error instanceof DeployError) return error;
37
+ return new DeployError(code, message, { ...options, cause: error });
38
+ }
39
+
40
+ // src/deploy/seeds.ts
41
+ var TEXT_ENCODER = new TextEncoder();
42
+ function seedBytes(seed) {
43
+ const bytes = TEXT_ENCODER.encode(seed);
44
+ try {
45
+ return normalizeSeed(bytes);
46
+ } catch (error) {
47
+ throw new DeployError(
48
+ "INVALID_INPUT",
49
+ `seed must be 1-32 UTF-8 bytes, got ${bytes.length}`,
50
+ { cause: error }
51
+ );
52
+ }
53
+ }
54
+ async function temporarySeed(seed, suffix) {
55
+ const combined = `${seed}_${suffix}`;
56
+ const combinedBytes = TEXT_ENCODER.encode(combined);
57
+ if (combinedBytes.length <= 32) return combined;
58
+ const digest = await sha256(combinedBytes);
59
+ return bytesToHex(digest.slice(0, 16));
60
+ }
61
+
62
+ // src/deploy/constants.ts
63
+ var DEPLOYMENT_MULTICALL_PROGRAM_ADDRESS = GENESIS_MULTICALL_PROGRAM_ADDRESS;
64
+ var TRANSACTION_TIMEOUT_MS = 6e4;
65
+
66
+ // src/deploy/accounts.ts
67
+ async function getOptionalAccount(client, address) {
68
+ try {
69
+ return await client.accounts.get(address);
70
+ } catch (error) {
71
+ if (error?.code === 5) return void 0;
72
+ throw asDeployError(
73
+ error,
74
+ "RPC_ERROR",
75
+ `Failed to read account ${address}`
76
+ );
77
+ }
78
+ }
79
+ function requireAccountData(account, label) {
80
+ const data = account.data?.data;
81
+ if (!data)
82
+ throw new DeployError("VERIFICATION_FAILED", `${label} data is missing`);
83
+ return data;
84
+ }
85
+ function assertOwner(account, owner, label) {
86
+ if (!account.meta?.owner?.equals(owner)) {
87
+ throw new DeployError(
88
+ "VERIFICATION_FAILED",
89
+ `${label} has an unexpected owner`
90
+ );
91
+ }
92
+ }
93
+ function assertManagedProgramAccount(account, label = "managed program account") {
94
+ assertOwner(account, MANAGER_PROGRAM_ADDRESS, label);
95
+ if (!account.meta?.flags.isProgram) {
96
+ throw new DeployError("VERIFICATION_FAILED", `${label} is not executable`);
97
+ }
98
+ }
99
+ function parseManagerMeta(account) {
100
+ assertOwner(account, MANAGER_PROGRAM_ADDRESS, "program metadata account");
101
+ try {
102
+ const parsed = parseManagerProgramMeta(account);
103
+ return {
104
+ authority: Pubkey.from(parsed.authorityAddress).toBytes(),
105
+ version: parsed.version,
106
+ state: parsed.state
107
+ };
108
+ } catch (error) {
109
+ throw asDeployError(
110
+ error,
111
+ "VERIFICATION_FAILED",
112
+ "program metadata account is invalid"
113
+ );
114
+ }
115
+ }
116
+ function parseABIMeta(account) {
117
+ assertOwner(account, ABI_MANAGER_PROGRAM_ADDRESS, "ABI metadata account");
118
+ const data = requireAccountData(account, "ABI metadata account");
119
+ let parsed;
120
+ try {
121
+ parsed = parseABIMetaAccount(data);
122
+ } catch (error) {
123
+ throw asDeployError(
124
+ error,
125
+ "VERIFICATION_FAILED",
126
+ "official ABI metadata account is invalid"
127
+ );
128
+ }
129
+ if (parsed.kind !== "official") {
130
+ throw new DeployError(
131
+ "VERIFICATION_FAILED",
132
+ "ABI metadata account is not official"
133
+ );
134
+ }
135
+ for (let index = 36; index < data.length; index += 1) {
136
+ if (data[index] !== 0) {
137
+ throw new DeployError(
138
+ "VERIFICATION_FAILED",
139
+ "official ABI metadata reserved bytes are invalid"
140
+ );
141
+ }
142
+ }
143
+ return { program: Pubkey.from(parsed.programAddress).toBytes() };
144
+ }
145
+ function parseABIAccount2(account) {
146
+ assertOwner(account, ABI_MANAGER_PROGRAM_ADDRESS, "ABI account");
147
+ try {
148
+ const parsed = parseABIAccount(account);
149
+ return {
150
+ abiMetaAccount: Pubkey.from(parsed.abiMetaAccountAddress).toBytes(),
151
+ revision: parsed.revision,
152
+ state: parsed.state,
153
+ content: parsed.contents
154
+ };
155
+ } catch (error) {
156
+ throw asDeployError(error, "VERIFICATION_FAILED", "ABI account is invalid");
157
+ }
158
+ }
159
+ function parseUploaderMeta(account) {
160
+ if (!account.meta?.owner?.equals(UPLOADER_PROGRAM_ADDRESS)) {
161
+ throw new DeployError(
162
+ "UPLOAD_CONFLICT",
163
+ "uploader metadata account has an unexpected owner"
164
+ );
165
+ }
166
+ try {
167
+ const parsed = parseUploaderProgramMeta(account);
168
+ return {
169
+ authority: Pubkey.from(parsed.authorityAddress).toBytes(),
170
+ expectedHash: parsed.expectedHash,
171
+ state: parsed.state
172
+ };
173
+ } catch (error) {
174
+ throw asDeployError(
175
+ error,
176
+ "UPLOAD_CONFLICT",
177
+ "uploader metadata account is invalid"
178
+ );
179
+ }
180
+ }
181
+ function assertManagerOpen(meta) {
182
+ if (meta.state === MANAGER_STATE_FINALIZED) {
183
+ throw new DeployError("TARGET_FINALIZED", "managed program is finalized");
184
+ }
185
+ if (meta.state !== MANAGER_STATE_OPEN) {
186
+ throw new DeployError(
187
+ "VERIFICATION_FAILED",
188
+ `managed program is not open (state ${meta.state})`
189
+ );
190
+ }
191
+ }
192
+ function assertABIOpen(abi) {
193
+ if (abi.state === ABI_STATE_FINALIZED) {
194
+ throw new DeployError("TARGET_FINALIZED", "program ABI is finalized");
195
+ }
196
+ if (abi.state !== ABI_STATE_OPEN) {
197
+ throw new DeployError(
198
+ "VERIFICATION_FAILED",
199
+ `program ABI is not open (state ${abi.state})`
200
+ );
201
+ }
202
+ }
203
+ function assertPubkeyBytes(actual, expected, message) {
204
+ const expectedBytes = expected instanceof Uint8Array ? expected : Pubkey.from(expected).toBytes();
205
+ if (!bytesEqual(actual, expectedBytes))
206
+ throw new DeployError("VERIFICATION_FAILED", message);
207
+ }
208
+ function emitProgress(onProgress, event2) {
209
+ if (!onProgress) return;
210
+ try {
211
+ onProgress(event2);
212
+ } catch {
213
+ }
214
+ }
215
+ async function creationProof(client, address, ephemeral) {
216
+ if (ephemeral) return new Uint8Array();
217
+ try {
218
+ const proof = await client.proofs.generate({
219
+ address,
220
+ proofType: StateProofType.CREATING
221
+ });
222
+ if (!proof.proof.length) {
223
+ throw new Error("empty state proof");
224
+ }
225
+ return proof.proof;
226
+ } catch (error) {
227
+ throw asDeployError(
228
+ error,
229
+ "RPC_ERROR",
230
+ `Failed to create state proof for ${address}`
231
+ );
232
+ }
233
+ }
234
+ async function submitTransaction(client, signer, operation, phase, transaction) {
235
+ let rawTransaction;
236
+ let signature;
237
+ try {
238
+ const signed = await client.transactions.buildAndSign({
239
+ feePayer: {
240
+ publicKey: signer.publicKey,
241
+ privateKey: signer.privateKey
242
+ },
243
+ program: transaction.program,
244
+ header: {
245
+ fee: 0n,
246
+ computeUnits: transaction.computeUnits ?? 5e8,
247
+ stateUnits: transaction.stateUnits ?? 5e3,
248
+ memoryUnits: transaction.memoryUnits ?? 5e3,
249
+ expiryAfter: transaction.expiryAfter ?? 1e4
250
+ },
251
+ accounts: {
252
+ readWrite: transaction.readWrite,
253
+ readOnly: transaction.readOnly
254
+ },
255
+ instructionData: transaction.instructionData
256
+ });
257
+ rawTransaction = signed.rawTransaction;
258
+ signature = signed.signature.toThruFmt();
259
+ } catch (error) {
260
+ throw asDeployError(
261
+ error,
262
+ "RPC_ERROR",
263
+ "Failed to build deployment transaction",
264
+ {
265
+ operation,
266
+ phase
267
+ }
268
+ );
269
+ }
270
+ let accepted = false;
271
+ let finalized = false;
272
+ try {
273
+ for await (const update of client.transactions.sendAndTrack(
274
+ rawTransaction,
275
+ {
276
+ timeoutMs: TRANSACTION_TIMEOUT_MS
277
+ }
278
+ )) {
279
+ if (update.signature?.value) {
280
+ signature = Signature.from(update.signature.value).toThruFmt();
281
+ }
282
+ if (update.status === SubmissionStatus.ACCEPTED) accepted = true;
283
+ if (update.consensusStatus === ConsensusStatus.FINALIZED || update.consensusStatus === ConsensusStatus.CLUSTER_EXECUTED) {
284
+ finalized = true;
285
+ }
286
+ if (!update.executionResult) continue;
287
+ const { vmError, userErrorCode } = update.executionResult;
288
+ if (vmError !== 0 || userErrorCode !== 0n) {
289
+ throw new DeployError(
290
+ "TRANSACTION_FAILED",
291
+ "Deployment transaction failed",
292
+ {
293
+ operation,
294
+ phase,
295
+ transactionSignature: signature,
296
+ vmError,
297
+ userErrorCode
298
+ }
299
+ );
300
+ }
301
+ return signature;
302
+ }
303
+ } catch (error) {
304
+ if (error instanceof DeployError) throw error;
305
+ throw new DeployError(
306
+ "OUTCOME_UNKNOWN",
307
+ accepted || finalized ? "Transaction was submitted but its final outcome is unknown" : "Transaction submission may have succeeded, but no outcome was received",
308
+ { operation, phase, transactionSignature: signature, cause: error }
309
+ );
310
+ }
311
+ throw new DeployError(
312
+ "OUTCOME_UNKNOWN",
313
+ "Transaction tracking ended before execution was confirmed",
314
+ { operation, phase, transactionSignature: signature }
315
+ );
316
+ }
317
+
318
+ // src/deploy/uploader.ts
319
+ async function waitForUploadPair(client, metaAddress, bufferAddress) {
320
+ let metaAccount;
321
+ let bufferAccount;
322
+ for (let attempt = 0; attempt < 12; attempt += 1) {
323
+ [metaAccount, bufferAccount] = await Promise.all([
324
+ getOptionalAccount(client, metaAddress),
325
+ getOptionalAccount(client, bufferAddress)
326
+ ]);
327
+ if (metaAccount && bufferAccount) break;
328
+ if (attempt < 11) await new Promise((resolve) => setTimeout(resolve, 250));
329
+ }
330
+ return { metaAccount, bufferAccount };
331
+ }
332
+ async function waitForBufferContent(client, bufferAddress, expected, offset = 0) {
333
+ let account;
334
+ for (let attempt = 0; attempt < 12; attempt += 1) {
335
+ account = await getOptionalAccount(client, bufferAddress);
336
+ if (account && bytesEqual(
337
+ requireAccountData(account, "uploader buffer account").slice(
338
+ offset,
339
+ offset + expected.length
340
+ ),
341
+ expected
342
+ )) {
343
+ return account;
344
+ }
345
+ if (attempt < 11) await new Promise((resolve) => setTimeout(resolve, 250));
346
+ }
347
+ return account;
348
+ }
349
+ async function prepareUpload(operation, artifact, seed, bytes) {
350
+ const hash = await sha256(bytes);
351
+ const addresses = deriveUploadAddresses(seed);
352
+ return {
353
+ operation,
354
+ artifact,
355
+ seed,
356
+ bytes,
357
+ hash,
358
+ addresses,
359
+ result: {
360
+ artifact,
361
+ size: bytes.length,
362
+ sha256: bytesToHex(hash),
363
+ metaAccountAddress: addresses.metaAccountAddress,
364
+ bufferAccountAddress: addresses.bufferAccountAddress,
365
+ reused: false,
366
+ transactionSignatures: [],
367
+ cleanup: { status: "not-needed" }
368
+ }
369
+ };
370
+ }
371
+ function assertUploaderOwner(account, label) {
372
+ if (!account.meta?.owner?.equals(UPLOADER_PROGRAM_ADDRESS)) {
373
+ throw new DeployError(
374
+ "UPLOAD_CONFLICT",
375
+ `${label} has an unexpected owner`
376
+ );
377
+ }
378
+ }
379
+ function assertMatchingUpload(upload, signer, metaAccount, bufferAccount) {
380
+ const meta = parseUploaderMeta(metaAccount);
381
+ assertUploaderOwner(bufferAccount, "uploader buffer account");
382
+ if (!bytesEqual(meta.authority, signer.publicKey)) {
383
+ throw new DeployError(
384
+ "UPLOAD_CONFLICT",
385
+ "temporary upload belongs to another authority"
386
+ );
387
+ }
388
+ if (!bytesEqual(meta.expectedHash, upload.hash)) {
389
+ throw new DeployError(
390
+ "UPLOAD_CONFLICT",
391
+ "temporary upload has a conflicting SHA-256"
392
+ );
393
+ }
394
+ const buffer = requireAccountData(bufferAccount, "uploader buffer account");
395
+ if (buffer.length !== upload.bytes.length) {
396
+ throw new DeployError(
397
+ "UPLOAD_CONFLICT",
398
+ "temporary upload has a conflicting size"
399
+ );
400
+ }
401
+ if (meta.state !== UPLOADER_STATE_OPEN && meta.state !== UPLOADER_STATE_FINALIZED) {
402
+ throw new DeployError(
403
+ "UPLOAD_CONFLICT",
404
+ `temporary upload has invalid state ${meta.state}`
405
+ );
406
+ }
407
+ return meta.state;
408
+ }
409
+ function event(upload, status, fields = {}) {
410
+ return {
411
+ operation: upload.operation,
412
+ phase: "upload",
413
+ status,
414
+ artifact: upload.artifact,
415
+ ...fields
416
+ };
417
+ }
418
+ async function uploadArtifact(client, signer, upload, chunkSize, onProgress) {
419
+ const metaAddress = upload.result.metaAccountAddress;
420
+ const bufferAddress = upload.result.bufferAccountAddress;
421
+ emitProgress(onProgress, event(upload, "started"));
422
+ let metaAccount = await getOptionalAccount(client, metaAddress);
423
+ let bufferAccount = await getOptionalAccount(client, bufferAddress);
424
+ if (!!metaAccount !== !!bufferAccount) {
425
+ throw new DeployError(
426
+ "UPLOAD_CONFLICT",
427
+ "temporary upload is only partly present"
428
+ );
429
+ }
430
+ if (!metaAccount || !bufferAccount) {
431
+ let signature;
432
+ let unknownOutcome;
433
+ try {
434
+ signature = await submitTransaction(
435
+ client,
436
+ signer,
437
+ upload.operation,
438
+ "upload",
439
+ {
440
+ program: UPLOADER_PROGRAM_ADDRESS,
441
+ readWrite: [metaAddress, bufferAddress],
442
+ instructionData: createUploadBufferInstruction({
443
+ bufferAccount: upload.addresses.bufferAccountBytes,
444
+ metaAccount: upload.addresses.metaAccountBytes,
445
+ authorityAccount: signer.publicKey,
446
+ bufferSize: upload.bytes.length,
447
+ expectedHash: upload.hash,
448
+ seed: upload.seed
449
+ }),
450
+ computeUnits: 5e4 + upload.bytes.length * 2,
451
+ stateUnits: 1e4,
452
+ memoryUnits: 1e4,
453
+ expiryAfter: 10
454
+ }
455
+ );
456
+ } catch (error) {
457
+ if (!(error instanceof DeployError) || error.code !== "OUTCOME_UNKNOWN") {
458
+ throw error;
459
+ }
460
+ unknownOutcome = error;
461
+ signature = error.transactionSignature;
462
+ }
463
+ if (signature) upload.result.transactionSignatures.push(signature);
464
+ ({ metaAccount, bufferAccount } = await waitForUploadPair(
465
+ client,
466
+ metaAddress,
467
+ bufferAddress
468
+ ));
469
+ if (!metaAccount || !bufferAccount) {
470
+ if (unknownOutcome) throw unknownOutcome;
471
+ throw new DeployError(
472
+ "VERIFICATION_FAILED",
473
+ "temporary upload creation was not visible"
474
+ );
475
+ }
476
+ emitProgress(
477
+ onProgress,
478
+ event(upload, "progress", { uploadStep: "create", signature })
479
+ );
480
+ } else {
481
+ upload.result.reused = true;
482
+ }
483
+ const state = assertMatchingUpload(
484
+ upload,
485
+ signer,
486
+ metaAccount,
487
+ bufferAccount
488
+ );
489
+ if (state === UPLOADER_STATE_FINALIZED) {
490
+ if (!bytesEqual(
491
+ requireAccountData(bufferAccount, "uploader buffer account"),
492
+ upload.bytes
493
+ )) {
494
+ throw new DeployError(
495
+ "UPLOAD_CONFLICT",
496
+ "finalized temporary upload contents do not match"
497
+ );
498
+ }
499
+ emitProgress(
500
+ onProgress,
501
+ event(upload, "succeeded", { uploadStep: "finalize" })
502
+ );
503
+ return upload.result;
504
+ }
505
+ const totalChunks = Math.ceil(upload.bytes.length / chunkSize);
506
+ for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex += 1) {
507
+ const offset = chunkIndex * chunkSize;
508
+ const chunk = upload.bytes.slice(
509
+ offset,
510
+ Math.min(offset + chunkSize, upload.bytes.length)
511
+ );
512
+ const current = requireAccountData(
513
+ bufferAccount,
514
+ "uploader buffer account"
515
+ );
516
+ if (bytesEqual(current.slice(offset, offset + chunk.length), chunk)) {
517
+ emitProgress(
518
+ onProgress,
519
+ event(upload, "progress", {
520
+ uploadStep: "write",
521
+ completedChunks: chunkIndex + 1,
522
+ totalChunks
523
+ })
524
+ );
525
+ continue;
526
+ }
527
+ let written = false;
528
+ let lastError;
529
+ for (let attempt = 0; attempt < 3 && !written; attempt += 1) {
530
+ try {
531
+ const signature = await submitTransaction(
532
+ client,
533
+ signer,
534
+ upload.operation,
535
+ "upload",
536
+ {
537
+ program: UPLOADER_PROGRAM_ADDRESS,
538
+ readWrite: [metaAddress, bufferAddress],
539
+ instructionData: createWriteUploadInstruction({
540
+ bufferAccount: upload.addresses.bufferAccountBytes,
541
+ metaAccount: upload.addresses.metaAccountBytes,
542
+ data: chunk,
543
+ offset
544
+ }),
545
+ computeUnits: 5e8,
546
+ stateUnits: 5e3,
547
+ memoryUnits: 5e3,
548
+ expiryAfter: 1e4
549
+ }
550
+ );
551
+ upload.result.transactionSignatures.push(signature);
552
+ written = true;
553
+ } catch (error) {
554
+ lastError = error;
555
+ if (error instanceof DeployError && error.transactionSignature) {
556
+ upload.result.transactionSignatures.push(error.transactionSignature);
557
+ }
558
+ bufferAccount = await getOptionalAccount(client, bufferAddress);
559
+ if (bufferAccount && bytesEqual(
560
+ requireAccountData(bufferAccount, "uploader buffer account").slice(
561
+ offset,
562
+ offset + chunk.length
563
+ ),
564
+ chunk
565
+ )) {
566
+ written = true;
567
+ } else if (error instanceof DeployError && error.code === "TRANSACTION_FAILED") {
568
+ throw error;
569
+ }
570
+ }
571
+ }
572
+ if (!written) throw lastError;
573
+ bufferAccount = await waitForBufferContent(
574
+ client,
575
+ bufferAddress,
576
+ chunk,
577
+ offset
578
+ );
579
+ if (!bufferAccount || !bytesEqual(
580
+ requireAccountData(bufferAccount, "uploader buffer account").slice(
581
+ offset,
582
+ offset + chunk.length
583
+ ),
584
+ chunk
585
+ )) {
586
+ throw new DeployError(
587
+ "VERIFICATION_FAILED",
588
+ "temporary upload chunk verification failed"
589
+ );
590
+ }
591
+ emitProgress(
592
+ onProgress,
593
+ event(upload, "progress", {
594
+ uploadStep: "write",
595
+ completedChunks: chunkIndex + 1,
596
+ totalChunks,
597
+ signature: upload.result.transactionSignatures.at(-1)
598
+ })
599
+ );
600
+ }
601
+ const finalBuffer = await waitForBufferContent(
602
+ client,
603
+ bufferAddress,
604
+ upload.bytes
605
+ );
606
+ if (!finalBuffer || !bytesEqual(
607
+ requireAccountData(finalBuffer, "uploader buffer account"),
608
+ upload.bytes
609
+ )) {
610
+ throw new DeployError(
611
+ "VERIFICATION_FAILED",
612
+ "temporary upload content verification failed"
613
+ );
614
+ }
615
+ let finalizeSignature;
616
+ let unknownFinalizeOutcome;
617
+ try {
618
+ finalizeSignature = await submitTransaction(
619
+ client,
620
+ signer,
621
+ upload.operation,
622
+ "upload",
623
+ {
624
+ program: UPLOADER_PROGRAM_ADDRESS,
625
+ readWrite: [metaAddress, bufferAddress],
626
+ instructionData: createFinalizeUploadInstruction({
627
+ bufferAccount: upload.addresses.bufferAccountBytes,
628
+ metaAccount: upload.addresses.metaAccountBytes,
629
+ expectedHash: upload.hash
630
+ }),
631
+ computeUnits: 5e4 + upload.bytes.length * 200,
632
+ stateUnits: 5e3,
633
+ memoryUnits: 5e3,
634
+ expiryAfter: 1e4
635
+ }
636
+ );
637
+ } catch (error) {
638
+ if (!(error instanceof DeployError) || error.code !== "OUTCOME_UNKNOWN") {
639
+ throw error;
640
+ }
641
+ unknownFinalizeOutcome = error;
642
+ finalizeSignature = error.transactionSignature;
643
+ }
644
+ if (finalizeSignature) {
645
+ upload.result.transactionSignatures.push(finalizeSignature);
646
+ }
647
+ let finalizedMeta;
648
+ for (let attempt = 0; attempt < 12; attempt += 1) {
649
+ finalizedMeta = await getOptionalAccount(client, metaAddress);
650
+ if (finalizedMeta && parseUploaderMeta(finalizedMeta).state === UPLOADER_STATE_FINALIZED)
651
+ break;
652
+ if (attempt < 11) await new Promise((resolve) => setTimeout(resolve, 250));
653
+ }
654
+ if (!finalizedMeta || parseUploaderMeta(finalizedMeta).state !== UPLOADER_STATE_FINALIZED) {
655
+ if (unknownFinalizeOutcome) throw unknownFinalizeOutcome;
656
+ throw new DeployError(
657
+ "VERIFICATION_FAILED",
658
+ "temporary upload did not finalize"
659
+ );
660
+ }
661
+ emitProgress(
662
+ onProgress,
663
+ event(upload, "succeeded", {
664
+ uploadStep: "finalize",
665
+ signature: finalizeSignature
666
+ })
667
+ );
668
+ return upload.result;
669
+ }
670
+ async function cleanupUpload(client, signer, upload, onProgress) {
671
+ const metaAddress = upload.result.metaAccountAddress;
672
+ const bufferAddress = upload.result.bufferAccountAddress;
673
+ const meta = await getOptionalAccount(client, metaAddress);
674
+ const buffer = await getOptionalAccount(client, bufferAddress);
675
+ if (!meta && !buffer) {
676
+ upload.result.cleanup = { status: "not-needed" };
677
+ return upload.result.cleanup;
678
+ }
679
+ emitProgress(onProgress, {
680
+ operation: upload.operation,
681
+ phase: "cleanup",
682
+ status: "started",
683
+ artifact: upload.artifact
684
+ });
685
+ let cleanupSignature;
686
+ let remainingAccountAddresses;
687
+ try {
688
+ if (!meta || !buffer)
689
+ throw new Error("temporary upload is only partly present");
690
+ const signature = await submitTransaction(
691
+ client,
692
+ signer,
693
+ upload.operation,
694
+ "cleanup",
695
+ {
696
+ program: UPLOADER_PROGRAM_ADDRESS,
697
+ readWrite: [metaAddress, bufferAddress],
698
+ instructionData: createDestroyUploadInstruction({
699
+ bufferAccount: upload.addresses.bufferAccountBytes,
700
+ metaAccount: upload.addresses.metaAccountBytes
701
+ }),
702
+ computeUnits: 5e4,
703
+ stateUnits: 5e3,
704
+ memoryUnits: 5e3,
705
+ expiryAfter: 1e4
706
+ }
707
+ );
708
+ cleanupSignature = signature;
709
+ let remaining = true;
710
+ for (let attempt = 0; attempt < 4 && remaining; attempt += 1) {
711
+ const [remainingMeta, remainingBuffer] = await Promise.all([
712
+ getOptionalAccount(client, metaAddress),
713
+ getOptionalAccount(client, bufferAddress)
714
+ ]);
715
+ remaining = !!remainingMeta || !!remainingBuffer;
716
+ remainingAccountAddresses = [
717
+ ...remainingMeta ? [metaAddress] : [],
718
+ ...remainingBuffer ? [bufferAddress] : []
719
+ ];
720
+ if (remaining && attempt < 3) {
721
+ await new Promise((resolve) => setTimeout(resolve, 250));
722
+ }
723
+ }
724
+ if (remaining) {
725
+ throw new Error("temporary upload accounts remain after cleanup");
726
+ }
727
+ upload.result.cleanup = {
728
+ status: "succeeded",
729
+ transactionSignature: signature
730
+ };
731
+ emitProgress(onProgress, {
732
+ operation: upload.operation,
733
+ phase: "cleanup",
734
+ status: "succeeded",
735
+ artifact: upload.artifact,
736
+ signature
737
+ });
738
+ } catch (error) {
739
+ const message = error instanceof Error ? error.message : String(error);
740
+ if (error instanceof DeployError && error.transactionSignature) {
741
+ cleanupSignature ?? (cleanupSignature = error.transactionSignature);
742
+ }
743
+ upload.result.cleanup = {
744
+ status: "failed",
745
+ error: message,
746
+ transactionSignature: cleanupSignature,
747
+ remainingAccountAddresses: remainingAccountAddresses ?? [
748
+ metaAddress,
749
+ bufferAddress
750
+ ]
751
+ };
752
+ emitProgress(onProgress, {
753
+ operation: upload.operation,
754
+ phase: "cleanup",
755
+ status: "failed",
756
+ artifact: upload.artifact,
757
+ message
758
+ });
759
+ }
760
+ return upload.result.cleanup;
761
+ }
762
+ function normalizeBytes(value, field) {
763
+ if (value instanceof Uint8Array) return new Uint8Array(value);
764
+ if (value instanceof ArrayBuffer) return new Uint8Array(value.slice(0));
765
+ if (ArrayBuffer.isView(value)) {
766
+ return new Uint8Array(
767
+ value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength)
768
+ );
769
+ }
770
+ throw new DeployError("INVALID_INPUT", `${field} must be binary data`);
771
+ }
772
+ function normalizePrivateKey(value) {
773
+ let bytes;
774
+ if (value instanceof Uint8Array) {
775
+ bytes = new Uint8Array(value);
776
+ } else if (typeof value === "string" && isHexString(value)) {
777
+ bytes = hexToBytes(value);
778
+ } else {
779
+ throw new DeployError(
780
+ "INVALID_INPUT",
781
+ "signer.privateKey must be 32-byte hex or Uint8Array"
782
+ );
783
+ }
784
+ if (bytes.length !== 32) {
785
+ throw new DeployError(
786
+ "INVALID_INPUT",
787
+ `signer.privateKey must be 32 bytes, got ${bytes.length}`
788
+ );
789
+ }
790
+ return bytes;
791
+ }
792
+ function validateSeedAndChunkSize(seed, chunkSize) {
793
+ seedBytes(seed);
794
+ const resolved = chunkSize ?? UPLOADER_DEFAULT_CHUNK_SIZE;
795
+ if (!Number.isInteger(resolved) || resolved < UPLOADER_MIN_CHUNK_SIZE || resolved > UPLOADER_MAX_CHUNK_SIZE) {
796
+ throw new DeployError(
797
+ "INVALID_INPUT",
798
+ `chunkSize must be an integer from ${UPLOADER_MIN_CHUNK_SIZE} to ${UPLOADER_MAX_CHUNK_SIZE}`
799
+ );
800
+ }
801
+ return resolved;
802
+ }
803
+ async function resolveSigner(client, address, privateKeyInput) {
804
+ let expected;
805
+ try {
806
+ expected = Pubkey.from(address).toBytes();
807
+ } catch (error) {
808
+ throw asDeployError(
809
+ error,
810
+ "INVALID_INPUT",
811
+ "signer.address is not a valid Thru address"
812
+ );
813
+ }
814
+ const privateKey = normalizePrivateKey(privateKeyInput);
815
+ let publicKey;
816
+ try {
817
+ publicKey = await client.keys.fromPrivateKey(privateKey);
818
+ } catch (error) {
819
+ throw asDeployError(
820
+ error,
821
+ "INVALID_INPUT",
822
+ "Unable to derive signer public key"
823
+ );
824
+ }
825
+ if (!bytesEqual(publicKey, expected)) {
826
+ throw new DeployError(
827
+ "SIGNER_MISMATCH",
828
+ "signer.privateKey does not match signer.address"
829
+ );
830
+ }
831
+ return { address: Pubkey.from(expected).toThruFmt(), publicKey, privateKey };
832
+ }
833
+ function validateProgramImage(program) {
834
+ if (program.length >= 4 && program[0] === 127 && program[1] === 69 && program[2] === 76 && program[3] === 70) {
835
+ throw new DeployError(
836
+ "INVALID_INPUT",
837
+ "ELF file detected; supply the compiled ThruVM .bin program image"
838
+ );
839
+ }
840
+ try {
841
+ validateManagerProgramImage(program);
842
+ } catch (error) {
843
+ throw asDeployError(
844
+ error,
845
+ "INVALID_INPUT",
846
+ error instanceof Error ? error.message : "Invalid program image"
847
+ );
848
+ }
849
+ }
850
+ async function validateABI(abi, client) {
851
+ let yaml;
852
+ try {
853
+ yaml = new TextDecoder("utf-8", { fatal: true }).decode(abi);
854
+ } catch (error) {
855
+ throw asDeployError(error, "INVALID_INPUT", "ABI must be valid UTF-8 YAML");
856
+ }
857
+ if (yaml.trim().length === 0) {
858
+ throw new DeployError("INVALID_INPUT", "ABI cannot be empty");
859
+ }
860
+ if (/^\s*-\s*type:\s*path\s*$/im.test(yaml)) {
861
+ throw new DeployError(
862
+ "INVALID_INPUT",
863
+ "ABI contains local path imports; flatten or prepare it for publishing first"
864
+ );
865
+ }
866
+ try {
867
+ const importClient = client ? {
868
+ query: {
869
+ getRawAccount: (request) => client.accounts.getRaw(request.address.value, {
870
+ versionContext: request.versionContext
871
+ })
872
+ }
873
+ } : void 0;
874
+ const resolved = await resolveImports(yaml, {
875
+ onchainFetcher: new OnchainFetcher({ thruClient: importClient })
876
+ });
877
+ await buildLayoutIrWithManifest(
878
+ resolved.manifest,
879
+ resolved.root.id.packageName
880
+ );
881
+ } catch (error) {
882
+ throw asDeployError(error, "INVALID_INPUT", "ABI analysis failed");
883
+ }
884
+ return yaml;
885
+ }
886
+
887
+ // src/deploy/workflows.ts
888
+ function createProgramInstruction(context, upload, sourceSize, metaStateProof, programStateProof) {
889
+ const common = {
890
+ metaAccount: context.program.programMetaAccountBytes,
891
+ programAccount: context.program.programAccountBytes,
892
+ sourceBufferAccount: upload.addresses.bufferAccountBytes,
893
+ authorityAccount: context.signer.publicKey,
894
+ sourceSize,
895
+ seed: context.seed
896
+ };
897
+ return context.ephemeral ? createEphemeralProgramInstruction(common) : createPermanentProgramInstruction({
898
+ ...common,
899
+ metaStateProof,
900
+ programStateProof
901
+ });
902
+ }
903
+ function createABIMetaInstruction(context, stateProof) {
904
+ const common = {
905
+ abiMetaAccount: context.abi.abiMetaAccountBytes,
906
+ programMetaAccount: context.program.programMetaAccountBytes,
907
+ authorityAccount: context.signer.publicKey
908
+ };
909
+ return context.ephemeral ? createOfficialABIMetaInstruction({ ...common, ephemeral: true }) : createOfficialABIMetaInstruction({
910
+ ...common,
911
+ stateProof
912
+ });
913
+ }
914
+ function createABIInstruction(context, upload, sourceSize, stateProof) {
915
+ const common = {
916
+ abiMetaAccount: context.abi.abiMetaAccountBytes,
917
+ programMetaAccount: context.program.programMetaAccountBytes,
918
+ abiAccount: context.abi.abiAccountBytes,
919
+ sourceBufferAccount: upload.addresses.bufferAccountBytes,
920
+ authorityAccount: context.signer.publicKey,
921
+ sourceSize
922
+ };
923
+ return context.ephemeral ? createOfficialABIInstruction({ ...common, ephemeral: true }) : createOfficialABIInstruction({
924
+ ...common,
925
+ stateProof
926
+ });
927
+ }
928
+ function upgradeProgramInstruction(context, upload, sourceSize) {
929
+ return createUpgradeProgramInstruction({
930
+ metaAccount: context.program.programMetaAccountBytes,
931
+ programAccount: context.program.programAccountBytes,
932
+ sourceBufferAccount: upload.addresses.bufferAccountBytes,
933
+ sourceSize
934
+ });
935
+ }
936
+ function upgradeABIInstruction(context, upload, sourceSize) {
937
+ return createUpgradeOfficialABIInstruction({
938
+ abiMetaAccount: context.abi.abiMetaAccountBytes,
939
+ programMetaAccount: context.program.programMetaAccountBytes,
940
+ abiAccount: context.abi.abiAccountBytes,
941
+ sourceBufferAccount: upload.addresses.bufferAccountBytes,
942
+ authorityAccount: context.signer.publicKey,
943
+ sourceSize
944
+ });
945
+ }
946
+ function progress(context, phase, status, fields = {}) {
947
+ emitProgress(context.onProgress, {
948
+ operation: context.operation,
949
+ phase,
950
+ status,
951
+ ...fields
952
+ });
953
+ }
954
+ async function createContext(operation, request, programAddressAssertion) {
955
+ const client = request.client ?? createThruClient();
956
+ const chunkSize = validateSeedAndChunkSize(request.seed, request.chunkSize);
957
+ const signer = await resolveSigner(
958
+ client,
959
+ request.signer.address,
960
+ request.signer.privateKey
961
+ );
962
+ const ephemeral = request.ephemeral ?? false;
963
+ const program = deriveManagedProgramAddresses(request.seed, ephemeral);
964
+ if (programAddressAssertion) {
965
+ let supplied;
966
+ try {
967
+ supplied = Pubkey.from(programAddressAssertion);
968
+ } catch (error) {
969
+ throw asDeployError(
970
+ error,
971
+ "INVALID_INPUT",
972
+ "programAddress is not a valid Thru address"
973
+ );
974
+ }
975
+ if (!supplied.equals(program.programAccountAddress)) {
976
+ throw new DeployError(
977
+ "INVALID_INPUT",
978
+ "programAddress does not match the address derived from seed and ephemeral"
979
+ );
980
+ }
981
+ }
982
+ const abi = deriveProgramABIAddresses(
983
+ program.programAccountAddress,
984
+ ephemeral
985
+ );
986
+ return {
987
+ operation,
988
+ client,
989
+ signer,
990
+ seed: request.seed,
991
+ ephemeral,
992
+ chunkSize,
993
+ program,
994
+ abi,
995
+ onProgress: request.onProgress
996
+ };
997
+ }
998
+ function addressDetails(context) {
999
+ return {
1000
+ programMetaAccountAddress: context.program.programMetaAccountAddress,
1001
+ programAccountAddress: context.program.programAccountAddress,
1002
+ abiMetaAccountAddress: context.abi.abiMetaAccountAddress,
1003
+ abiAccountAddress: context.abi.abiAccountAddress
1004
+ };
1005
+ }
1006
+ async function assertAbsent(context, entries) {
1007
+ const accounts = await Promise.all(
1008
+ entries.map(([, address]) => getOptionalAccount(context.client, address))
1009
+ );
1010
+ const existing = entries.filter((_, index) => accounts[index]).map(([label]) => label);
1011
+ if (existing.length) {
1012
+ throw new DeployError(
1013
+ "TARGET_EXISTS",
1014
+ `deployment target already exists: ${existing.join(", ")}`,
1015
+ {
1016
+ operation: context.operation,
1017
+ phase: "preflight",
1018
+ addresses: addressDetails(context)
1019
+ }
1020
+ );
1021
+ }
1022
+ }
1023
+ async function requireProgram(context) {
1024
+ const [metaAccount, programAccount] = await Promise.all([
1025
+ getOptionalAccount(
1026
+ context.client,
1027
+ context.program.programMetaAccountAddress
1028
+ ),
1029
+ getOptionalAccount(context.client, context.program.programAccountAddress)
1030
+ ]);
1031
+ if (!metaAccount || !programAccount) {
1032
+ throw new DeployError(
1033
+ "TARGET_NOT_FOUND",
1034
+ "managed program or its metadata account is missing",
1035
+ {
1036
+ operation: context.operation,
1037
+ phase: "preflight",
1038
+ addresses: addressDetails(context)
1039
+ }
1040
+ );
1041
+ }
1042
+ const meta = parseManagerMeta(metaAccount);
1043
+ assertManagerOpen(meta);
1044
+ if (!bytesEqual(meta.authority, context.signer.publicKey)) {
1045
+ throw new DeployError(
1046
+ "SIGNER_MISMATCH",
1047
+ "signer is not the managed program authority",
1048
+ {
1049
+ operation: context.operation,
1050
+ phase: "preflight",
1051
+ addresses: addressDetails(context)
1052
+ }
1053
+ );
1054
+ }
1055
+ assertManagedProgramAccount(programAccount);
1056
+ return { meta };
1057
+ }
1058
+ async function requireABI(context) {
1059
+ const [metaAccount, abiAccount] = await Promise.all([
1060
+ getOptionalAccount(context.client, context.abi.abiMetaAccountAddress),
1061
+ getOptionalAccount(context.client, context.abi.abiAccountAddress)
1062
+ ]);
1063
+ if (!metaAccount || !abiAccount) {
1064
+ throw new DeployError(
1065
+ "TARGET_NOT_FOUND",
1066
+ "program ABI or its metadata account is missing",
1067
+ {
1068
+ operation: context.operation,
1069
+ phase: "preflight",
1070
+ addresses: addressDetails(context)
1071
+ }
1072
+ );
1073
+ }
1074
+ const meta = parseABIMeta(metaAccount);
1075
+ const abi = parseABIAccount2(abiAccount);
1076
+ assertABIOpen(abi);
1077
+ assertPubkeyBytes(
1078
+ meta.program,
1079
+ context.program.programAccountAddress,
1080
+ "ABI metadata points to another program"
1081
+ );
1082
+ assertPubkeyBytes(
1083
+ abi.abiMetaAccount,
1084
+ context.abi.abiMetaAccountAddress,
1085
+ "ABI account points to another metadata account"
1086
+ );
1087
+ return { abi };
1088
+ }
1089
+ async function verifyProgram(context, expectedBytes, expectedVersion) {
1090
+ const [metaAccount, programAccount] = await Promise.all([
1091
+ getOptionalAccount(
1092
+ context.client,
1093
+ context.program.programMetaAccountAddress
1094
+ ),
1095
+ getOptionalAccount(context.client, context.program.programAccountAddress)
1096
+ ]);
1097
+ if (!metaAccount || !programAccount) {
1098
+ throw new DeployError(
1099
+ "VERIFICATION_FAILED",
1100
+ "managed program readback is missing"
1101
+ );
1102
+ }
1103
+ const meta = parseManagerMeta(metaAccount);
1104
+ assertManagerOpen(meta);
1105
+ assertPubkeyBytes(
1106
+ meta.authority,
1107
+ context.signer.publicKey,
1108
+ "managed program authority mismatch"
1109
+ );
1110
+ if (meta.version !== expectedVersion) {
1111
+ throw new DeployError(
1112
+ "VERIFICATION_FAILED",
1113
+ `program version mismatch: expected ${expectedVersion}, got ${meta.version}`
1114
+ );
1115
+ }
1116
+ assertManagedProgramAccount(programAccount);
1117
+ if (expectedBytes && !bytesEqual(
1118
+ requireAccountData(programAccount, "program account"),
1119
+ expectedBytes
1120
+ )) {
1121
+ throw new DeployError(
1122
+ "VERIFICATION_FAILED",
1123
+ "managed program bytes do not match the upload"
1124
+ );
1125
+ }
1126
+ return meta.version;
1127
+ }
1128
+ async function verifyABI(context, expectedBytes, expectedRevision) {
1129
+ const [metaAccount, abiAccount] = await Promise.all([
1130
+ getOptionalAccount(context.client, context.abi.abiMetaAccountAddress),
1131
+ getOptionalAccount(context.client, context.abi.abiAccountAddress)
1132
+ ]);
1133
+ if (!metaAccount || !abiAccount) {
1134
+ throw new DeployError(
1135
+ "VERIFICATION_FAILED",
1136
+ "program ABI readback is missing"
1137
+ );
1138
+ }
1139
+ const meta = parseABIMeta(metaAccount);
1140
+ const abi = parseABIAccount2(abiAccount);
1141
+ assertABIOpen(abi);
1142
+ assertPubkeyBytes(
1143
+ meta.program,
1144
+ context.program.programAccountAddress,
1145
+ "ABI metadata program mismatch"
1146
+ );
1147
+ assertPubkeyBytes(
1148
+ abi.abiMetaAccount,
1149
+ context.abi.abiMetaAccountAddress,
1150
+ "ABI metadata link mismatch"
1151
+ );
1152
+ if (abi.revision !== expectedRevision) {
1153
+ throw new DeployError(
1154
+ "VERIFICATION_FAILED",
1155
+ `ABI revision mismatch: expected ${expectedRevision}, got ${abi.revision}`
1156
+ );
1157
+ }
1158
+ if (!bytesEqual(abi.content, expectedBytes)) {
1159
+ throw new DeployError(
1160
+ "VERIFICATION_FAILED",
1161
+ "ABI contents do not match the upload"
1162
+ );
1163
+ }
1164
+ return abi.revision;
1165
+ }
1166
+ function delay(milliseconds) {
1167
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
1168
+ }
1169
+ async function retryVerification(verify) {
1170
+ let lastError;
1171
+ for (let attempt = 0; attempt < 8; attempt += 1) {
1172
+ try {
1173
+ return await verify();
1174
+ } catch (error) {
1175
+ lastError = error;
1176
+ if (attempt < 7) await delay(250);
1177
+ }
1178
+ }
1179
+ throw asDeployError(
1180
+ lastError,
1181
+ "VERIFICATION_FAILED",
1182
+ "Deployment readback verification failed"
1183
+ );
1184
+ }
1185
+ async function commitAndVerify(context, transaction, verify) {
1186
+ progress(context, "commit", "started");
1187
+ let signature;
1188
+ try {
1189
+ signature = await submitTransaction(
1190
+ context.client,
1191
+ context.signer,
1192
+ context.operation,
1193
+ "commit",
1194
+ transaction
1195
+ );
1196
+ } catch (error) {
1197
+ if (error instanceof DeployError && error.code === "OUTCOME_UNKNOWN" && error.transactionSignature) {
1198
+ try {
1199
+ try {
1200
+ const status = await context.client.transactions.getStatus(
1201
+ error.transactionSignature
1202
+ );
1203
+ const execution = status.executionResult;
1204
+ if (execution && (execution.vmError !== 0 || execution.userErrorCode !== 0n)) {
1205
+ throw new DeployError(
1206
+ "TRANSACTION_FAILED",
1207
+ "Deployment transaction failed",
1208
+ {
1209
+ operation: context.operation,
1210
+ phase: "commit",
1211
+ transactionSignature: error.transactionSignature,
1212
+ vmError: execution.vmError,
1213
+ userErrorCode: execution.userErrorCode
1214
+ }
1215
+ );
1216
+ }
1217
+ } catch (statusError) {
1218
+ if (statusError instanceof DeployError) throw statusError;
1219
+ }
1220
+ const verified2 = await retryVerification(verify);
1221
+ progress(context, "commit", "succeeded", {
1222
+ signature: error.transactionSignature
1223
+ });
1224
+ progress(context, "verification", "succeeded");
1225
+ return { signature: error.transactionSignature, verified: verified2 };
1226
+ } catch (reconciliationError) {
1227
+ if (reconciliationError instanceof DeployError && reconciliationError.code === "TRANSACTION_FAILED") {
1228
+ throw reconciliationError;
1229
+ }
1230
+ throw error;
1231
+ }
1232
+ }
1233
+ throw error;
1234
+ }
1235
+ progress(context, "commit", "succeeded", { signature });
1236
+ progress(context, "verification", "started");
1237
+ const verified = await retryVerification(verify);
1238
+ progress(context, "verification", "succeeded");
1239
+ return { signature, verified };
1240
+ }
1241
+ async function cleanupAll(context, uploads) {
1242
+ const warnings = [];
1243
+ for (const upload of uploads) {
1244
+ try {
1245
+ const result = await cleanupUpload(
1246
+ context.client,
1247
+ context.signer,
1248
+ upload,
1249
+ context.onProgress
1250
+ );
1251
+ if (result.status === "failed") {
1252
+ const remaining = result.remainingAccountAddresses ?? [
1253
+ upload.result.metaAccountAddress,
1254
+ upload.result.bufferAccountAddress
1255
+ ];
1256
+ warnings.push(
1257
+ `Failed to clean ${upload.artifact} upload; remaining accounts: ${remaining.join(", ")}: ${result.error}`
1258
+ );
1259
+ }
1260
+ } catch (error) {
1261
+ const message = error instanceof Error ? error.message : String(error);
1262
+ upload.result.cleanup = {
1263
+ status: "failed",
1264
+ error: message,
1265
+ remainingAccountAddresses: [
1266
+ upload.result.metaAccountAddress,
1267
+ upload.result.bufferAccountAddress
1268
+ ]
1269
+ };
1270
+ warnings.push(
1271
+ `Failed to clean ${upload.artifact} upload (${upload.result.metaAccountAddress}, ${upload.result.bufferAccountAddress}): ${message}`
1272
+ );
1273
+ }
1274
+ }
1275
+ return warnings;
1276
+ }
1277
+ async function withCleanup(context, uploads, work) {
1278
+ try {
1279
+ const value = await work();
1280
+ const warnings = await cleanupAll(context, uploads);
1281
+ return { value, warnings };
1282
+ } catch (error) {
1283
+ await cleanupAll(context, uploads);
1284
+ const deployError = asDeployError(error, "RPC_ERROR", "Deployment failed", {
1285
+ operation: context.operation,
1286
+ addresses: addressDetails(context)
1287
+ });
1288
+ deployError.cleanup = uploads.map((upload) => upload.result.cleanup);
1289
+ deployError.addresses ?? (deployError.addresses = addressDetails(context));
1290
+ throw deployError;
1291
+ }
1292
+ }
1293
+ async function multicall(context, calls) {
1294
+ return buildMulticallInstruction(
1295
+ await Promise.all(
1296
+ calls.map(async (call) => ({
1297
+ programIdx: context.getAccountIndex(call.program),
1298
+ instructionData: await call.instructionData(context)
1299
+ }))
1300
+ )
1301
+ );
1302
+ }
1303
+ function commonResult(context, signature, version, warnings) {
1304
+ return {
1305
+ seed: context.seed,
1306
+ ephemeral: context.ephemeral,
1307
+ authorityAddress: context.signer.address,
1308
+ programMetaAccountAddress: context.program.programMetaAccountAddress,
1309
+ programAccountAddress: context.program.programAccountAddress,
1310
+ programVersion: version,
1311
+ transactionSignature: signature,
1312
+ warnings
1313
+ };
1314
+ }
1315
+ async function deployProgram(request) {
1316
+ const operation = "deployProgram";
1317
+ const programBytes = normalizeBytes(request.program, "program");
1318
+ const abiBytes = request.abi === void 0 ? void 0 : normalizeBytes(request.abi, "abi");
1319
+ validateProgramImage(programBytes);
1320
+ const context = await createContext(operation, request);
1321
+ if (abiBytes) await validateABI(abiBytes, context.client);
1322
+ progress(context, "validation", "succeeded");
1323
+ progress(context, "preflight", "started");
1324
+ const absent = [
1325
+ ["program metadata", context.program.programMetaAccountAddress],
1326
+ ["program", context.program.programAccountAddress]
1327
+ ];
1328
+ if (abiBytes) {
1329
+ absent.push(
1330
+ ["ABI metadata", context.abi.abiMetaAccountAddress],
1331
+ ["ABI", context.abi.abiAccountAddress]
1332
+ );
1333
+ }
1334
+ await assertAbsent(context, absent);
1335
+ progress(context, "preflight", "succeeded");
1336
+ const programUpload = await prepareUpload(
1337
+ operation,
1338
+ "program",
1339
+ await temporarySeed(request.seed, "temporary"),
1340
+ programBytes
1341
+ );
1342
+ const abiUpload = abiBytes ? await prepareUpload(
1343
+ operation,
1344
+ "abi",
1345
+ await temporarySeed(request.seed, "abi_temp"),
1346
+ abiBytes
1347
+ ) : void 0;
1348
+ const uploads = abiUpload ? [programUpload, abiUpload] : [programUpload];
1349
+ const { value, warnings } = await withCleanup(context, uploads, async () => {
1350
+ await uploadArtifact(
1351
+ context.client,
1352
+ context.signer,
1353
+ programUpload,
1354
+ context.chunkSize,
1355
+ context.onProgress
1356
+ );
1357
+ if (abiUpload) {
1358
+ await uploadArtifact(
1359
+ context.client,
1360
+ context.signer,
1361
+ abiUpload,
1362
+ context.chunkSize,
1363
+ context.onProgress
1364
+ );
1365
+ }
1366
+ const [programMetaProof, programProof] = await Promise.all([
1367
+ creationProof(
1368
+ context.client,
1369
+ context.program.programMetaAccountAddress,
1370
+ context.ephemeral
1371
+ ),
1372
+ creationProof(
1373
+ context.client,
1374
+ context.program.programAccountAddress,
1375
+ context.ephemeral
1376
+ )
1377
+ ]);
1378
+ let transaction;
1379
+ if (!abiBytes || !abiUpload) {
1380
+ transaction = {
1381
+ program: MANAGER_PROGRAM_ADDRESS,
1382
+ readWrite: [
1383
+ context.program.programMetaAccountAddress,
1384
+ context.program.programAccountAddress
1385
+ ],
1386
+ readOnly: [programUpload.result.bufferAccountAddress],
1387
+ instructionData: createProgramInstruction(
1388
+ context,
1389
+ programUpload,
1390
+ programBytes.length,
1391
+ programMetaProof,
1392
+ programProof
1393
+ )
1394
+ };
1395
+ } else {
1396
+ const [abiMetaProof, abiProof] = await Promise.all([
1397
+ creationProof(
1398
+ context.client,
1399
+ context.abi.abiMetaAccountAddress,
1400
+ context.ephemeral
1401
+ ),
1402
+ creationProof(
1403
+ context.client,
1404
+ context.abi.abiAccountAddress,
1405
+ context.ephemeral
1406
+ )
1407
+ ]);
1408
+ transaction = {
1409
+ program: DEPLOYMENT_MULTICALL_PROGRAM_ADDRESS,
1410
+ stateUnits: 1e4,
1411
+ memoryUnits: 1e4,
1412
+ readWrite: [
1413
+ context.program.programMetaAccountAddress,
1414
+ context.program.programAccountAddress,
1415
+ context.abi.abiMetaAccountAddress,
1416
+ context.abi.abiAccountAddress
1417
+ ],
1418
+ readOnly: [
1419
+ MANAGER_PROGRAM_ADDRESS,
1420
+ ABI_MANAGER_PROGRAM_ADDRESS,
1421
+ programUpload.result.bufferAccountAddress,
1422
+ abiUpload.result.bufferAccountAddress
1423
+ ],
1424
+ instructionData: (tx) => multicall(tx, [
1425
+ {
1426
+ program: MANAGER_PROGRAM_ADDRESS,
1427
+ instructionData: createProgramInstruction(
1428
+ context,
1429
+ programUpload,
1430
+ programBytes.length,
1431
+ programMetaProof,
1432
+ programProof
1433
+ )
1434
+ },
1435
+ {
1436
+ program: ABI_MANAGER_PROGRAM_ADDRESS,
1437
+ instructionData: createABIMetaInstruction(context, abiMetaProof)
1438
+ },
1439
+ {
1440
+ program: ABI_MANAGER_PROGRAM_ADDRESS,
1441
+ instructionData: createABIInstruction(
1442
+ context,
1443
+ abiUpload,
1444
+ abiBytes.length,
1445
+ abiProof
1446
+ )
1447
+ }
1448
+ ])
1449
+ };
1450
+ }
1451
+ return commitAndVerify(context, transaction, async () => ({
1452
+ version: await verifyProgram(context, programBytes, 0n),
1453
+ revision: abiBytes ? await verifyABI(context, abiBytes, 0n) : void 0
1454
+ }));
1455
+ });
1456
+ return {
1457
+ ...commonResult(context, value.signature, value.verified.version, warnings),
1458
+ programSize: programBytes.length,
1459
+ abiSize: abiBytes?.length,
1460
+ abiMetaAccountAddress: abiBytes ? context.abi.abiMetaAccountAddress : void 0,
1461
+ abiAccountAddress: abiBytes ? context.abi.abiAccountAddress : void 0,
1462
+ abiRevision: value.verified.revision,
1463
+ programUpload: programUpload.result,
1464
+ abiUpload: abiUpload?.result
1465
+ };
1466
+ }
1467
+ async function deployProgramABI(request) {
1468
+ const operation = "deployProgramABI";
1469
+ const abiBytes = normalizeBytes(request.abi, "abi");
1470
+ const context = await createContext(
1471
+ operation,
1472
+ request,
1473
+ request.programAddress
1474
+ );
1475
+ await validateABI(abiBytes, context.client);
1476
+ progress(context, "validation", "succeeded");
1477
+ progress(context, "preflight", "started");
1478
+ const programState = await requireProgram(context);
1479
+ await assertAbsent(context, [
1480
+ ["ABI metadata", context.abi.abiMetaAccountAddress],
1481
+ ["ABI", context.abi.abiAccountAddress]
1482
+ ]);
1483
+ progress(context, "preflight", "succeeded");
1484
+ const abiUpload = await prepareUpload(
1485
+ operation,
1486
+ "abi",
1487
+ await temporarySeed(request.seed, "abi_temp"),
1488
+ abiBytes
1489
+ );
1490
+ const { value, warnings } = await withCleanup(
1491
+ context,
1492
+ [abiUpload],
1493
+ async () => {
1494
+ await uploadArtifact(
1495
+ context.client,
1496
+ context.signer,
1497
+ abiUpload,
1498
+ context.chunkSize,
1499
+ context.onProgress
1500
+ );
1501
+ const [metaProof, abiProof] = await Promise.all([
1502
+ creationProof(
1503
+ context.client,
1504
+ context.abi.abiMetaAccountAddress,
1505
+ context.ephemeral
1506
+ ),
1507
+ creationProof(
1508
+ context.client,
1509
+ context.abi.abiAccountAddress,
1510
+ context.ephemeral
1511
+ )
1512
+ ]);
1513
+ const transaction = {
1514
+ program: DEPLOYMENT_MULTICALL_PROGRAM_ADDRESS,
1515
+ stateUnits: 1e4,
1516
+ memoryUnits: 1e4,
1517
+ readWrite: [
1518
+ context.abi.abiMetaAccountAddress,
1519
+ context.abi.abiAccountAddress
1520
+ ],
1521
+ readOnly: [
1522
+ ABI_MANAGER_PROGRAM_ADDRESS,
1523
+ context.program.programMetaAccountAddress,
1524
+ abiUpload.result.bufferAccountAddress
1525
+ ],
1526
+ instructionData: (tx) => multicall(tx, [
1527
+ {
1528
+ program: ABI_MANAGER_PROGRAM_ADDRESS,
1529
+ instructionData: createABIMetaInstruction(context, metaProof)
1530
+ },
1531
+ {
1532
+ program: ABI_MANAGER_PROGRAM_ADDRESS,
1533
+ instructionData: createABIInstruction(
1534
+ context,
1535
+ abiUpload,
1536
+ abiBytes.length,
1537
+ abiProof
1538
+ )
1539
+ }
1540
+ ])
1541
+ };
1542
+ return commitAndVerify(context, transaction, async () => ({
1543
+ version: await verifyProgram(
1544
+ context,
1545
+ void 0,
1546
+ programState.meta.version
1547
+ ),
1548
+ revision: await verifyABI(context, abiBytes, 0n)
1549
+ }));
1550
+ }
1551
+ );
1552
+ return {
1553
+ ...commonResult(context, value.signature, value.verified.version, warnings),
1554
+ abiMetaAccountAddress: context.abi.abiMetaAccountAddress,
1555
+ abiAccountAddress: context.abi.abiAccountAddress,
1556
+ abiRevision: value.verified.revision,
1557
+ abiSize: abiBytes.length,
1558
+ abiUpload: abiUpload.result
1559
+ };
1560
+ }
1561
+ async function upgradeProgram(request) {
1562
+ const operation = "upgradeProgram";
1563
+ const programBytes = normalizeBytes(request.program, "program");
1564
+ const abiBytes = request.abi === void 0 ? void 0 : normalizeBytes(request.abi, "abi");
1565
+ validateProgramImage(programBytes);
1566
+ const context = await createContext(
1567
+ operation,
1568
+ request,
1569
+ request.programAddress
1570
+ );
1571
+ if (abiBytes) await validateABI(abiBytes, context.client);
1572
+ progress(context, "validation", "succeeded");
1573
+ progress(context, "preflight", "started");
1574
+ const programState = await requireProgram(context);
1575
+ const abiState = abiBytes ? await requireABI(context) : void 0;
1576
+ progress(context, "preflight", "succeeded");
1577
+ const programUpload = await prepareUpload(
1578
+ operation,
1579
+ "program",
1580
+ await temporarySeed(request.seed, "upgrade_temporary"),
1581
+ programBytes
1582
+ );
1583
+ const abiUpload = abiBytes ? await prepareUpload(
1584
+ operation,
1585
+ "abi",
1586
+ await temporarySeed(request.seed, "abi_upgrade"),
1587
+ abiBytes
1588
+ ) : void 0;
1589
+ const uploads = abiUpload ? [programUpload, abiUpload] : [programUpload];
1590
+ const expectedVersion = programState.meta.version + 1n;
1591
+ const expectedRevision = abiState ? abiState.abi.revision + 1n : void 0;
1592
+ const { value, warnings } = await withCleanup(context, uploads, async () => {
1593
+ await uploadArtifact(
1594
+ context.client,
1595
+ context.signer,
1596
+ programUpload,
1597
+ context.chunkSize,
1598
+ context.onProgress
1599
+ );
1600
+ if (abiUpload) {
1601
+ await uploadArtifact(
1602
+ context.client,
1603
+ context.signer,
1604
+ abiUpload,
1605
+ context.chunkSize,
1606
+ context.onProgress
1607
+ );
1608
+ }
1609
+ const transaction = abiBytes && abiUpload ? {
1610
+ program: DEPLOYMENT_MULTICALL_PROGRAM_ADDRESS,
1611
+ stateUnits: 1e4,
1612
+ memoryUnits: 1e4,
1613
+ readWrite: [
1614
+ context.program.programMetaAccountAddress,
1615
+ context.program.programAccountAddress,
1616
+ context.abi.abiAccountAddress
1617
+ ],
1618
+ readOnly: [
1619
+ MANAGER_PROGRAM_ADDRESS,
1620
+ ABI_MANAGER_PROGRAM_ADDRESS,
1621
+ context.abi.abiMetaAccountAddress,
1622
+ programUpload.result.bufferAccountAddress,
1623
+ abiUpload.result.bufferAccountAddress
1624
+ ],
1625
+ instructionData: (tx) => multicall(tx, [
1626
+ {
1627
+ program: MANAGER_PROGRAM_ADDRESS,
1628
+ instructionData: upgradeProgramInstruction(
1629
+ context,
1630
+ programUpload,
1631
+ programBytes.length
1632
+ )
1633
+ },
1634
+ {
1635
+ program: ABI_MANAGER_PROGRAM_ADDRESS,
1636
+ instructionData: upgradeABIInstruction(
1637
+ context,
1638
+ abiUpload,
1639
+ abiBytes.length
1640
+ )
1641
+ }
1642
+ ])
1643
+ } : {
1644
+ program: MANAGER_PROGRAM_ADDRESS,
1645
+ readWrite: [
1646
+ context.program.programMetaAccountAddress,
1647
+ context.program.programAccountAddress
1648
+ ],
1649
+ readOnly: [programUpload.result.bufferAccountAddress],
1650
+ instructionData: upgradeProgramInstruction(
1651
+ context,
1652
+ programUpload,
1653
+ programBytes.length
1654
+ )
1655
+ };
1656
+ return commitAndVerify(context, transaction, async () => ({
1657
+ version: await verifyProgram(context, programBytes, expectedVersion),
1658
+ revision: abiBytes && expectedRevision !== void 0 ? await verifyABI(context, abiBytes, expectedRevision) : void 0
1659
+ }));
1660
+ });
1661
+ return {
1662
+ ...commonResult(context, value.signature, value.verified.version, warnings),
1663
+ programSize: programBytes.length,
1664
+ abiSize: abiBytes?.length,
1665
+ abiMetaAccountAddress: abiBytes ? context.abi.abiMetaAccountAddress : void 0,
1666
+ abiAccountAddress: abiBytes ? context.abi.abiAccountAddress : void 0,
1667
+ abiRevision: value.verified.revision,
1668
+ programUpload: programUpload.result,
1669
+ abiUpload: abiUpload?.result
1670
+ };
1671
+ }
1672
+ async function upgradeProgramABI(request) {
1673
+ const operation = "upgradeProgramABI";
1674
+ const abiBytes = normalizeBytes(request.abi, "abi");
1675
+ const context = await createContext(
1676
+ operation,
1677
+ request,
1678
+ request.programAddress
1679
+ );
1680
+ await validateABI(abiBytes, context.client);
1681
+ progress(context, "validation", "succeeded");
1682
+ progress(context, "preflight", "started");
1683
+ const programState = await requireProgram(context);
1684
+ const abiState = await requireABI(context);
1685
+ progress(context, "preflight", "succeeded");
1686
+ const abiUpload = await prepareUpload(
1687
+ operation,
1688
+ "abi",
1689
+ await temporarySeed(request.seed, "abi_upgrade"),
1690
+ abiBytes
1691
+ );
1692
+ const expectedRevision = abiState.abi.revision + 1n;
1693
+ const { value, warnings } = await withCleanup(
1694
+ context,
1695
+ [abiUpload],
1696
+ async () => {
1697
+ await uploadArtifact(
1698
+ context.client,
1699
+ context.signer,
1700
+ abiUpload,
1701
+ context.chunkSize,
1702
+ context.onProgress
1703
+ );
1704
+ const transaction = {
1705
+ program: ABI_MANAGER_PROGRAM_ADDRESS,
1706
+ readWrite: [context.abi.abiAccountAddress],
1707
+ readOnly: [
1708
+ context.abi.abiMetaAccountAddress,
1709
+ context.program.programMetaAccountAddress,
1710
+ abiUpload.result.bufferAccountAddress
1711
+ ],
1712
+ instructionData: upgradeABIInstruction(
1713
+ context,
1714
+ abiUpload,
1715
+ abiBytes.length
1716
+ )
1717
+ };
1718
+ return commitAndVerify(context, transaction, async () => ({
1719
+ version: await verifyProgram(
1720
+ context,
1721
+ void 0,
1722
+ programState.meta.version
1723
+ ),
1724
+ revision: await verifyABI(context, abiBytes, expectedRevision)
1725
+ }));
1726
+ }
1727
+ );
1728
+ return {
1729
+ ...commonResult(context, value.signature, value.verified.version, warnings),
1730
+ abiMetaAccountAddress: context.abi.abiMetaAccountAddress,
1731
+ abiAccountAddress: context.abi.abiAccountAddress,
1732
+ abiRevision: value.verified.revision,
1733
+ abiSize: abiBytes.length,
1734
+ abiUpload: abiUpload.result
1735
+ };
1736
+ }
1737
+ function absentPair(metadataPresent, accountPresent) {
1738
+ return metadataPresent || accountPresent ? { status: "partial", metadataPresent, accountPresent } : { status: "missing", metadataPresent: false, accountPresent: false };
1739
+ }
1740
+ async function inspectProgramDeployment(request) {
1741
+ seedBytes(request.seed);
1742
+ const ephemeral = request.ephemeral ?? false;
1743
+ const programAddresses = deriveManagedProgramAddresses(
1744
+ request.seed,
1745
+ ephemeral
1746
+ );
1747
+ const abiAddresses = deriveProgramABIAddresses(
1748
+ programAddresses.programAccountAddress,
1749
+ ephemeral
1750
+ );
1751
+ const inspectABI = request.inspectABI || request.expectedABIBytes !== void 0;
1752
+ const [metadataAccount, programAccount, abiMetadataAccount, abiAccount] = await Promise.all([
1753
+ getOptionalAccount(
1754
+ request.client,
1755
+ programAddresses.programMetaAccountAddress
1756
+ ),
1757
+ getOptionalAccount(
1758
+ request.client,
1759
+ programAddresses.programAccountAddress
1760
+ ),
1761
+ inspectABI ? getOptionalAccount(request.client, abiAddresses.abiMetaAccountAddress) : void 0,
1762
+ inspectABI ? getOptionalAccount(request.client, abiAddresses.abiAccountAddress) : void 0
1763
+ ]);
1764
+ let program;
1765
+ if (!metadataAccount || !programAccount) {
1766
+ program = absentPair(!!metadataAccount, !!programAccount);
1767
+ } else {
1768
+ const metadata = parseManagerMeta(metadataAccount);
1769
+ assertManagedProgramAccount(programAccount);
1770
+ const authorityAddress = Pubkey.from(metadata.authority).toThruFmt();
1771
+ if (request.authorityAddress !== void 0) {
1772
+ let expectedAuthority;
1773
+ try {
1774
+ expectedAuthority = Pubkey.from(request.authorityAddress).toBytes();
1775
+ } catch (error) {
1776
+ throw asDeployError(
1777
+ error,
1778
+ "INVALID_INPUT",
1779
+ "authorityAddress is not a valid Thru address"
1780
+ );
1781
+ }
1782
+ if (!bytesEqual(metadata.authority, expectedAuthority)) {
1783
+ throw new DeployError(
1784
+ "SIGNER_MISMATCH",
1785
+ `program authority mismatch: expected ${request.authorityAddress}, found ${authorityAddress}`
1786
+ );
1787
+ }
1788
+ }
1789
+ program = {
1790
+ status: "present",
1791
+ metadataPresent: true,
1792
+ accountPresent: true,
1793
+ authorityAddress,
1794
+ version: metadata.version,
1795
+ state: metadata.state,
1796
+ bytesMatch: request.expectedProgramBytes === void 0 ? void 0 : bytesEqual(
1797
+ requireAccountData(programAccount, "managed program account"),
1798
+ request.expectedProgramBytes
1799
+ )
1800
+ };
1801
+ }
1802
+ let abi;
1803
+ if (inspectABI) {
1804
+ if (!abiMetadataAccount || !abiAccount) {
1805
+ abi = absentPair(!!abiMetadataAccount, !!abiAccount);
1806
+ } else {
1807
+ const metadata = parseABIMeta(abiMetadataAccount);
1808
+ const account = parseABIAccount2(abiAccount);
1809
+ assertPubkeyBytes(
1810
+ metadata.program,
1811
+ programAddresses.programAccountAddress,
1812
+ "ABI metadata points to another program"
1813
+ );
1814
+ assertPubkeyBytes(
1815
+ account.abiMetaAccount,
1816
+ abiAddresses.abiMetaAccountAddress,
1817
+ "ABI account points to another metadata account"
1818
+ );
1819
+ abi = {
1820
+ status: "present",
1821
+ metadataPresent: true,
1822
+ accountPresent: true,
1823
+ revision: account.revision,
1824
+ state: account.state,
1825
+ bytesMatch: request.expectedABIBytes === void 0 ? void 0 : bytesEqual(account.content, request.expectedABIBytes)
1826
+ };
1827
+ }
1828
+ }
1829
+ return {
1830
+ programMetaAccountAddress: programAddresses.programMetaAccountAddress,
1831
+ programAccountAddress: programAddresses.programAccountAddress,
1832
+ abiMetaAccountAddress: abiAddresses.abiMetaAccountAddress,
1833
+ abiAccountAddress: abiAddresses.abiAccountAddress,
1834
+ program,
1835
+ abi
1836
+ };
1837
+ }
1838
+
1839
+ // src/deploy/index.ts
1840
+ var deploy = Object.freeze({
1841
+ deployProgram,
1842
+ deployProgramABI,
1843
+ upgradeProgram,
1844
+ upgradeProgramABI
1845
+ });
1846
+
1847
+ export { DeployError, deploy, deployProgram, deployProgramABI, inspectProgramDeployment, upgradeProgram, upgradeProgramABI };
1848
+ //# sourceMappingURL=index.js.map
1849
+ //# sourceMappingURL=index.js.map