@thru/programs 0.3.4 → 0.3.5

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