@thru/programs 0.3.3 → 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 (122) 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-7DRJVAYI.js +8587 -0
  17. package/dist/chunk-7DRJVAYI.js.map +1 -0
  18. package/dist/chunk-7FBCBZIY.js +41 -0
  19. package/dist/chunk-7FBCBZIY.js.map +1 -0
  20. package/dist/chunk-BNYDH4ZP.js +4351 -0
  21. package/dist/chunk-BNYDH4ZP.js.map +1 -0
  22. package/dist/chunk-OODN6LJA.js +6567 -0
  23. package/dist/chunk-OODN6LJA.js.map +1 -0
  24. package/dist/chunk-YX7BLFQZ.js +81 -0
  25. package/dist/chunk-YX7BLFQZ.js.map +1 -0
  26. package/dist/clob/index.cjs +19361 -6851
  27. package/dist/clob/index.cjs.map +1 -1
  28. package/dist/clob/index.d.cts +1243 -63
  29. package/dist/clob/index.d.ts +1243 -63
  30. package/dist/clob/index.js +6826 -2818
  31. package/dist/clob/index.js.map +1 -1
  32. package/dist/deploy/index.cjs +24734 -0
  33. package/dist/deploy/index.cjs.map +1 -0
  34. package/dist/deploy/index.d.cts +180 -0
  35. package/dist/deploy/index.d.ts +180 -0
  36. package/dist/deploy/index.js +1846 -0
  37. package/dist/deploy/index.js.map +1 -0
  38. package/dist/helpers-DD7q61nr.d.cts +7 -0
  39. package/dist/helpers-DD7q61nr.d.ts +7 -0
  40. package/dist/manager/index.cjs +6680 -0
  41. package/dist/manager/index.cjs.map +1 -0
  42. package/dist/manager/index.d.cts +1279 -0
  43. package/dist/manager/index.d.ts +1279 -0
  44. package/dist/manager/index.js +4 -0
  45. package/dist/manager/index.js.map +1 -0
  46. package/dist/passkey-manager/index.cjs +4 -5
  47. package/dist/passkey-manager/index.cjs.map +1 -1
  48. package/dist/passkey-manager/index.js +2 -2
  49. package/dist/token/index.js +1 -8585
  50. package/dist/token/index.js.map +1 -1
  51. package/dist/uploader/index.cjs +4442 -0
  52. package/dist/uploader/index.cjs.map +1 -0
  53. package/dist/uploader/index.d.cts +761 -0
  54. package/dist/uploader/index.d.ts +761 -0
  55. package/dist/uploader/index.js +4 -0
  56. package/dist/uploader/index.js.map +1 -0
  57. package/package.json +22 -2
  58. package/src/abi-manager/abi/thru/blockchain/state_proof/types.ts +1906 -0
  59. package/src/abi-manager/abi/thru/common/primitives/types.ts +2428 -0
  60. package/src/abi-manager/abi/thru/program/abi_manager/types.ts +7037 -0
  61. package/src/abi-manager/accounts.ts +91 -0
  62. package/src/abi-manager/constants.ts +19 -0
  63. package/src/abi-manager/derivation.ts +86 -0
  64. package/src/abi-manager/errors.ts +48 -0
  65. package/src/abi-manager/index.test.ts +136 -0
  66. package/src/abi-manager/index.ts +56 -0
  67. package/src/abi-manager/instructions.ts +573 -0
  68. package/src/abi-manager/types.ts +150 -0
  69. package/src/amm/index.test.ts +8 -2
  70. package/src/amm/index.ts +1 -1
  71. package/src/clob/abi/thru/program/clob/types.ts +6981 -3070
  72. package/src/clob/exchange-client.test.ts +592 -0
  73. package/src/clob/exchange-client.ts +953 -0
  74. package/src/clob/exchange.test.ts +18 -16
  75. package/src/clob/exchange.ts +4 -0
  76. package/src/clob/index.test.ts +134 -7
  77. package/src/clob/index.ts +303 -10
  78. package/src/clob/price.test.ts +32 -0
  79. package/src/clob/price.ts +77 -0
  80. package/src/deploy/accounts.ts +208 -0
  81. package/src/deploy/chain.ts +163 -0
  82. package/src/deploy/constants.ts +25 -0
  83. package/src/deploy/deploy.test.ts +349 -0
  84. package/src/deploy/errors.ts +72 -0
  85. package/src/deploy/index.ts +44 -0
  86. package/src/deploy/inspection.ts +146 -0
  87. package/src/deploy/seeds.ts +29 -0
  88. package/src/deploy/types.ts +178 -0
  89. package/src/deploy/uploader.test.ts +326 -0
  90. package/src/deploy/uploader.ts +558 -0
  91. package/src/deploy/validation-imports.test.ts +55 -0
  92. package/src/deploy/validation.ts +183 -0
  93. package/src/deploy/workflows.test.ts +422 -0
  94. package/src/deploy/workflows.ts +1088 -0
  95. package/src/helpers/bytes.test.ts +58 -0
  96. package/src/helpers/bytes.ts +28 -3
  97. package/src/manager/abi/thru/blockchain/state_proof/types.ts +1906 -0
  98. package/src/manager/abi/thru/common/primitives/types.ts +2428 -0
  99. package/src/manager/abi/thru/program/manager/types.ts +3814 -0
  100. package/src/manager/accounts.ts +44 -0
  101. package/src/manager/constants.ts +16 -0
  102. package/src/manager/derivation.ts +32 -0
  103. package/src/manager/errors.ts +47 -0
  104. package/src/manager/index.test.ts +108 -0
  105. package/src/manager/index.ts +68 -0
  106. package/src/manager/instructions.ts +281 -0
  107. package/src/manager/types.ts +95 -0
  108. package/src/manager/validation.ts +35 -0
  109. package/src/uploader/abi/thru/common/primitives/types.ts +2428 -0
  110. package/src/uploader/abi/thru/program/uploader/types.ts +3022 -0
  111. package/src/uploader/accounts.ts +38 -0
  112. package/src/uploader/constants.ts +14 -0
  113. package/src/uploader/derivation.ts +34 -0
  114. package/src/uploader/errors.ts +25 -0
  115. package/src/uploader/index.test.ts +107 -0
  116. package/src/uploader/index.ts +34 -0
  117. package/src/uploader/instructions.ts +163 -0
  118. package/src/uploader/types.ts +67 -0
  119. package/src/utils/helpers.ts +121 -0
  120. package/tsup.config.ts +4 -0
  121. package/dist/chunk-P5OABVJI.js +0 -28
  122. package/dist/chunk-P5OABVJI.js.map +0 -1
@@ -0,0 +1,183 @@
1
+ import { Pubkey } from "@thru/sdk";
2
+ import {
3
+ buildLayoutIrWithManifest,
4
+ OnchainFetcher,
5
+ resolveImports,
6
+ } from "@thru/sdk/abi";
7
+ import type { Thru } from "@thru/sdk/client";
8
+ import { hexToBytes, isHexString } from "@thru/sdk/helpers";
9
+ import { bytesEqual } from "../helpers/bytes";
10
+ import { validateManagerProgramImage } from "../manager";
11
+ import {
12
+ DEFAULT_CHUNK_SIZE,
13
+ MAX_CHUNK_SIZE,
14
+ MIN_CHUNK_SIZE,
15
+ } from "./constants";
16
+ import { DeployError, asDeployError } from "./errors";
17
+ import { seedBytes } from "./seeds";
18
+ import type { DeploymentBytes, DeploymentPrivateKey } from "./types";
19
+
20
+ export interface ResolvedSigner {
21
+ address: string;
22
+ publicKey: Uint8Array;
23
+ privateKey: Uint8Array;
24
+ }
25
+
26
+ export function normalizeBytes(
27
+ value: DeploymentBytes,
28
+ field: string,
29
+ ): Uint8Array {
30
+ if (value instanceof Uint8Array) return new Uint8Array(value);
31
+ if (value instanceof ArrayBuffer) return new Uint8Array(value.slice(0));
32
+ if (ArrayBuffer.isView(value)) {
33
+ return new Uint8Array(
34
+ value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength),
35
+ );
36
+ }
37
+ throw new DeployError("INVALID_INPUT", `${field} must be binary data`);
38
+ }
39
+
40
+ export function normalizePrivateKey(value: DeploymentPrivateKey): Uint8Array {
41
+ let bytes: Uint8Array;
42
+ if (value instanceof Uint8Array) {
43
+ bytes = new Uint8Array(value);
44
+ } else if (typeof value === "string" && isHexString(value)) {
45
+ bytes = hexToBytes(value);
46
+ } else {
47
+ throw new DeployError(
48
+ "INVALID_INPUT",
49
+ "signer.privateKey must be 32-byte hex or Uint8Array",
50
+ );
51
+ }
52
+ if (bytes.length !== 32) {
53
+ throw new DeployError(
54
+ "INVALID_INPUT",
55
+ `signer.privateKey must be 32 bytes, got ${bytes.length}`,
56
+ );
57
+ }
58
+ return bytes;
59
+ }
60
+
61
+ export function validateSeedAndChunkSize(
62
+ seed: string,
63
+ chunkSize?: number,
64
+ ): number {
65
+ seedBytes(seed);
66
+ const resolved = chunkSize ?? DEFAULT_CHUNK_SIZE;
67
+ if (
68
+ !Number.isInteger(resolved) ||
69
+ resolved < MIN_CHUNK_SIZE ||
70
+ resolved > MAX_CHUNK_SIZE
71
+ ) {
72
+ throw new DeployError(
73
+ "INVALID_INPUT",
74
+ `chunkSize must be an integer from ${MIN_CHUNK_SIZE} to ${MAX_CHUNK_SIZE}`,
75
+ );
76
+ }
77
+ return resolved;
78
+ }
79
+
80
+ export async function resolveSigner(
81
+ client: Thru,
82
+ address: string,
83
+ privateKeyInput: DeploymentPrivateKey,
84
+ ): Promise<ResolvedSigner> {
85
+ let expected: Uint8Array;
86
+ try {
87
+ expected = Pubkey.from(address).toBytes();
88
+ } catch (error) {
89
+ throw asDeployError(
90
+ error,
91
+ "INVALID_INPUT",
92
+ "signer.address is not a valid Thru address",
93
+ );
94
+ }
95
+ const privateKey = normalizePrivateKey(privateKeyInput);
96
+ let publicKey: Uint8Array;
97
+ try {
98
+ publicKey = await client.keys.fromPrivateKey(privateKey);
99
+ } catch (error) {
100
+ throw asDeployError(
101
+ error,
102
+ "INVALID_INPUT",
103
+ "Unable to derive signer public key",
104
+ );
105
+ }
106
+ if (!bytesEqual(publicKey, expected)) {
107
+ throw new DeployError(
108
+ "SIGNER_MISMATCH",
109
+ "signer.privateKey does not match signer.address",
110
+ );
111
+ }
112
+ return { address: Pubkey.from(expected).toThruFmt(), publicKey, privateKey };
113
+ }
114
+
115
+ export function validateProgramImage(program: Uint8Array): void {
116
+ if (
117
+ program.length >= 4 &&
118
+ program[0] === 0x7f &&
119
+ program[1] === 0x45 &&
120
+ program[2] === 0x4c &&
121
+ program[3] === 0x46
122
+ ) {
123
+ throw new DeployError(
124
+ "INVALID_INPUT",
125
+ "ELF file detected; supply the compiled ThruVM .bin program image",
126
+ );
127
+ }
128
+ try {
129
+ validateManagerProgramImage(program);
130
+ } catch (error) {
131
+ throw asDeployError(
132
+ error,
133
+ "INVALID_INPUT",
134
+ error instanceof Error ? error.message : "Invalid program image",
135
+ );
136
+ }
137
+ }
138
+
139
+ export async function validateABI(
140
+ abi: Uint8Array,
141
+ client?: Thru,
142
+ ): Promise<string> {
143
+ let yaml: string;
144
+ try {
145
+ yaml = new TextDecoder("utf-8", { fatal: true }).decode(abi);
146
+ } catch (error) {
147
+ throw asDeployError(error, "INVALID_INPUT", "ABI must be valid UTF-8 YAML");
148
+ }
149
+ if (yaml.trim().length === 0) {
150
+ throw new DeployError("INVALID_INPUT", "ABI cannot be empty");
151
+ }
152
+ if (/^\s*-\s*type:\s*path\s*$/im.test(yaml)) {
153
+ throw new DeployError(
154
+ "INVALID_INPUT",
155
+ "ABI contains local path imports; flatten or prepare it for publishing first",
156
+ );
157
+ }
158
+ try {
159
+ const importClient = client
160
+ ? {
161
+ query: {
162
+ getRawAccount: (request: {
163
+ address: { value: Uint8Array };
164
+ versionContext: Record<string, unknown>;
165
+ }) =>
166
+ client.accounts.getRaw(request.address.value, {
167
+ versionContext: request.versionContext as never,
168
+ }),
169
+ },
170
+ }
171
+ : undefined;
172
+ const resolved = await resolveImports(yaml, {
173
+ onchainFetcher: new OnchainFetcher({ thruClient: importClient }),
174
+ });
175
+ await buildLayoutIrWithManifest(
176
+ resolved.manifest,
177
+ resolved.root.id.packageName,
178
+ );
179
+ } catch (error) {
180
+ throw asDeployError(error, "INVALID_INPUT", "ABI analysis failed");
181
+ }
182
+ return yaml;
183
+ }
@@ -0,0 +1,422 @@
1
+ import {
2
+ Pubkey,
3
+ createThruClient,
4
+ type Account,
5
+ type InstructionContext,
6
+ } from "@thru/sdk";
7
+ import type { Thru } from "@thru/sdk/client";
8
+ import { beforeEach, describe, expect, it, vi } from "vitest";
9
+ import { MulticallArgs } from "../multicall";
10
+ import { deriveProgramABIAddresses } from "../abi-manager";
11
+ import { deriveManagedProgramAddresses } from "../manager";
12
+ import {
13
+ ABI_MANAGER_PROGRAM_ADDRESS,
14
+ MANAGER_PROGRAM_ADDRESS,
15
+ MULTICALL_PROGRAM_ADDRESS,
16
+ } from "./constants";
17
+ import { DeployError } from "./errors";
18
+ import type { DeploymentTransaction } from "./chain";
19
+ import type { PreparedUpload } from "./uploader";
20
+ import { deployProgram, upgradeProgram } from "./workflows";
21
+
22
+ const mocks = vi.hoisted(() => ({
23
+ submitTransaction: vi.fn(),
24
+ uploadArtifact: vi.fn(),
25
+ cleanupUpload: vi.fn(),
26
+ }));
27
+
28
+ function creationProof(): Uint8Array {
29
+ const proof = new Uint8Array(104);
30
+ new DataView(proof.buffer).setBigUint64(0, 2n << 62n, true);
31
+ return proof;
32
+ }
33
+
34
+ vi.mock("@thru/sdk/abi", () => ({
35
+ buildLayoutIrWithManifest: vi.fn(async () => ({ rootTypes: [] })),
36
+ OnchainFetcher: class {},
37
+ resolveImports: vi.fn(async (yaml: string) => ({
38
+ root: { id: { packageName: "test.deploy.workflow" } },
39
+ manifest: { "test.deploy.workflow": yaml },
40
+ })),
41
+ }));
42
+
43
+ vi.mock("./chain", async (importOriginal) => {
44
+ const actual = await importOriginal<typeof import("./chain")>();
45
+ return {
46
+ ...actual,
47
+ creationProof: vi.fn(async () => creationProof()),
48
+ submitTransaction: mocks.submitTransaction,
49
+ };
50
+ });
51
+
52
+ vi.mock("./uploader", async (importOriginal) => {
53
+ const actual = await importOriginal<typeof import("./uploader")>();
54
+ return {
55
+ ...actual,
56
+ uploadArtifact: mocks.uploadArtifact,
57
+ cleanupUpload: mocks.cleanupUpload,
58
+ };
59
+ });
60
+
61
+ const ABI_BYTES = new TextEncoder().encode(`
62
+ abi:
63
+ package: "test.deploy.workflow"
64
+ abi-version: 1
65
+ package-version: "1.0.0"
66
+ description: "workflow test"
67
+ imports: []
68
+ types:
69
+ - name: "Value"
70
+ kind:
71
+ struct:
72
+ packed: true
73
+ fields:
74
+ - name: "value"
75
+ field-type:
76
+ primitive: u64
77
+ `);
78
+
79
+ function image(fill: number): Uint8Array {
80
+ const bytes = new Uint8Array(20).fill(fill);
81
+ bytes[0] = 1;
82
+ bytes.fill(0, bytes.length - 8);
83
+ return bytes;
84
+ }
85
+
86
+ function missing(): never {
87
+ throw Object.assign(new Error("not found"), { code: 5 });
88
+ }
89
+
90
+ function storedAccount(
91
+ address: string,
92
+ owner: string,
93
+ data: Uint8Array,
94
+ isProgram = false,
95
+ ): Account {
96
+ return {
97
+ address: Pubkey.from(address),
98
+ meta: {
99
+ owner: Pubkey.from(owner),
100
+ flags: { isProgram },
101
+ },
102
+ data: { data },
103
+ } as Account;
104
+ }
105
+
106
+ interface Harness {
107
+ client: Thru;
108
+ signer: { address: string; privateKey: Uint8Array };
109
+ program: ReturnType<typeof deriveManagedProgramAddresses>;
110
+ abi: Awaited<ReturnType<typeof deriveProgramABIAddresses>>;
111
+ state: {
112
+ committed: boolean;
113
+ submitMode: "success" | "failure" | "unknown";
114
+ wrongProgramReadback: boolean;
115
+ duplicateTarget: boolean;
116
+ encoded?: Uint8Array;
117
+ transaction?: DeploymentTransaction;
118
+ };
119
+ }
120
+
121
+ function instructionContext(
122
+ feePayer: string,
123
+ transaction: DeploymentTransaction,
124
+ ): InstructionContext {
125
+ const normalize = (values: string[] = []) =>
126
+ values.slice().sort((left, right) => {
127
+ const a = Pubkey.from(left).toBytes();
128
+ const b = Pubkey.from(right).toBytes();
129
+ for (let index = 0; index < a.length; index += 1) {
130
+ if (a[index] !== b[index]) return a[index] - b[index];
131
+ }
132
+ return 0;
133
+ });
134
+ const addresses = [
135
+ feePayer,
136
+ transaction.program,
137
+ ...normalize(transaction.readWrite),
138
+ ...normalize(transaction.readOnly),
139
+ ];
140
+ return {
141
+ accounts: addresses.map((address) => Pubkey.from(address)),
142
+ getAccountIndex: (value) => {
143
+ const address = Pubkey.from(value).toThruFmt();
144
+ const index = addresses.indexOf(address);
145
+ if (index < 0) throw new Error(`account not found: ${address}`);
146
+ return index;
147
+ },
148
+ };
149
+ }
150
+
151
+ async function makeHarness(upgrade = false): Promise<Harness> {
152
+ const privateKey = new Uint8Array(32).fill(0x19);
153
+ const localClient = createThruClient();
154
+ const publicKey = await localClient.keys.fromPrivateKey(privateKey);
155
+ const signer = { address: Pubkey.from(publicKey).toThruFmt(), privateKey };
156
+ const program = deriveManagedProgramAddresses("workflow");
157
+ const abi = deriveProgramABIAddresses(program.programAccountAddress);
158
+ const state: Harness["state"] = {
159
+ committed: false,
160
+ submitMode: "success",
161
+ wrongProgramReadback: false,
162
+ duplicateTarget: false,
163
+ };
164
+
165
+ const oldProgram = image(0x22);
166
+ const newProgram = image(0x33);
167
+ const oldABI = ABI_BYTES.slice();
168
+ oldABI[oldABI.length - 1] = 0x0a;
169
+
170
+ function permanentAccounts(final: boolean): Map<string, Account> {
171
+ const version = upgrade && final ? 6n : upgrade ? 5n : 0n;
172
+ const revision = upgrade && final ? 3n : upgrade ? 2n : 0n;
173
+ const managerData = new Uint8Array(73);
174
+ managerData.set(publicKey);
175
+ new DataView(managerData.buffer).setBigUint64(64, version, true);
176
+
177
+ const abiMetaData = new Uint8Array(100);
178
+ abiMetaData[0] = 1;
179
+ abiMetaData.set(Pubkey.from(program.programAccountAddress).toBytes(), 4);
180
+
181
+ const abiBytes = final ? ABI_BYTES : oldABI;
182
+ const abiData = new Uint8Array(45 + abiBytes.length);
183
+ abiData.set(Pubkey.from(abi.abiMetaAccountAddress).toBytes());
184
+ new DataView(abiData.buffer).setBigUint64(32, revision, true);
185
+ new DataView(abiData.buffer).setUint32(41, abiBytes.length, true);
186
+ abiData.set(abiBytes, 45);
187
+
188
+ const programBytes = final
189
+ ? state.wrongProgramReadback
190
+ ? image(0x77)
191
+ : newProgram
192
+ : oldProgram;
193
+ return new Map([
194
+ [
195
+ program.programMetaAccountAddress,
196
+ storedAccount(
197
+ program.programMetaAccountAddress,
198
+ MANAGER_PROGRAM_ADDRESS,
199
+ managerData,
200
+ ),
201
+ ],
202
+ [
203
+ program.programAccountAddress,
204
+ storedAccount(
205
+ program.programAccountAddress,
206
+ MANAGER_PROGRAM_ADDRESS,
207
+ programBytes,
208
+ true,
209
+ ),
210
+ ],
211
+ [
212
+ abi.abiMetaAccountAddress,
213
+ storedAccount(
214
+ abi.abiMetaAccountAddress,
215
+ ABI_MANAGER_PROGRAM_ADDRESS,
216
+ abiMetaData,
217
+ ),
218
+ ],
219
+ [
220
+ abi.abiAccountAddress,
221
+ storedAccount(
222
+ abi.abiAccountAddress,
223
+ ABI_MANAGER_PROGRAM_ADDRESS,
224
+ abiData,
225
+ ),
226
+ ],
227
+ ]);
228
+ }
229
+
230
+ const client = {
231
+ keys: { fromPrivateKey: vi.fn(async () => publicKey) },
232
+ accounts: {
233
+ get: vi.fn(async (address: string) => {
234
+ if (upgrade)
235
+ return permanentAccounts(state.committed).get(address) ?? missing();
236
+ if (state.committed)
237
+ return permanentAccounts(true).get(address) ?? missing();
238
+ if (
239
+ state.duplicateTarget &&
240
+ address === program.programMetaAccountAddress
241
+ ) {
242
+ return permanentAccounts(false).get(address)!;
243
+ }
244
+ return missing();
245
+ }),
246
+ },
247
+ } as unknown as Thru;
248
+
249
+ mocks.submitTransaction.mockImplementation(
250
+ async (
251
+ _client: Thru,
252
+ _signer: unknown,
253
+ _operation: unknown,
254
+ phase: string,
255
+ transaction: DeploymentTransaction,
256
+ ) => {
257
+ expect(phase).toBe("commit");
258
+ state.transaction = transaction;
259
+ state.encoded =
260
+ typeof transaction.instructionData === "function"
261
+ ? await transaction.instructionData(
262
+ instructionContext(signer.address, transaction),
263
+ )
264
+ : transaction.instructionData;
265
+ if (state.submitMode === "failure") {
266
+ throw new DeployError("TRANSACTION_FAILED", "ABI manager failed", {
267
+ transactionSignature: "failed-signature",
268
+ vmError: 4,
269
+ });
270
+ }
271
+ state.committed = true;
272
+ if (state.submitMode === "unknown") {
273
+ throw new DeployError("OUTCOME_UNKNOWN", "tracking timeout", {
274
+ transactionSignature: "unknown-signature",
275
+ });
276
+ }
277
+ return "final-signature";
278
+ },
279
+ );
280
+
281
+ return { client, signer, program, abi, state };
282
+ }
283
+
284
+ describe("deployment workflows", () => {
285
+ beforeEach(() => {
286
+ mocks.submitTransaction.mockReset();
287
+ mocks.uploadArtifact.mockReset();
288
+ mocks.cleanupUpload.mockReset();
289
+ mocks.uploadArtifact.mockImplementation(
290
+ async (_client: Thru, _signer: unknown, upload: PreparedUpload) =>
291
+ upload.result,
292
+ );
293
+ mocks.cleanupUpload.mockImplementation(
294
+ async (_client: Thru, _signer: unknown, upload: PreparedUpload) => {
295
+ upload.result.cleanup = { status: "not-needed" };
296
+ return upload.result.cleanup;
297
+ },
298
+ );
299
+ });
300
+
301
+ it("commits a program plus ABI in one ordered multicall and reports cleanup warnings", async () => {
302
+ const harness = await makeHarness();
303
+ mocks.cleanupUpload.mockImplementation(
304
+ async (_client: Thru, _signer: unknown, upload: PreparedUpload) => {
305
+ upload.result.cleanup =
306
+ upload.artifact === "abi"
307
+ ? { status: "failed", error: "cleanup unavailable" }
308
+ : { status: "not-needed" };
309
+ return upload.result.cleanup;
310
+ },
311
+ );
312
+
313
+ const result = await deployProgram({
314
+ seed: "workflow",
315
+ signer: harness.signer,
316
+ client: harness.client,
317
+ program: image(0x33),
318
+ abi: ABI_BYTES,
319
+ });
320
+
321
+ expect(mocks.submitTransaction).toHaveBeenCalledTimes(1);
322
+ expect(harness.state.transaction?.program).toBe(MULTICALL_PROGRAM_ADDRESS);
323
+ const calls = MulticallArgs.from_array(harness.state.encoded!)?.get_calls();
324
+ expect(calls).toHaveLength(3);
325
+ expect(calls?.map((call) => call.get_data()[0])).toEqual([0, 0, 4]);
326
+ const context = instructionContext(
327
+ harness.signer.address,
328
+ harness.state.transaction!,
329
+ );
330
+ expect(calls?.map((call) => call.get_program_idx())).toEqual([
331
+ context.getAccountIndex(MANAGER_PROGRAM_ADDRESS),
332
+ context.getAccountIndex(ABI_MANAGER_PROGRAM_ADDRESS),
333
+ context.getAccountIndex(ABI_MANAGER_PROGRAM_ADDRESS),
334
+ ]);
335
+ expect(result.transactionSignature).toBe("final-signature");
336
+ expect(result.programVersion).toBe(0n);
337
+ expect(result.abiRevision).toBe(0n);
338
+ expect(result.warnings).toHaveLength(1);
339
+ expect(result.abiUpload?.cleanup).toEqual({
340
+ status: "failed",
341
+ error: "cleanup unavailable",
342
+ });
343
+ });
344
+
345
+ it("fails duplicate creates before any upload", async () => {
346
+ const harness = await makeHarness();
347
+ harness.state.duplicateTarget = true;
348
+ await expect(
349
+ deployProgram({
350
+ seed: "workflow",
351
+ signer: harness.signer,
352
+ client: harness.client,
353
+ program: image(0x33),
354
+ }),
355
+ ).rejects.toMatchObject({ code: "TARGET_EXISTS", phase: "preflight" });
356
+ expect(mocks.uploadArtifact).not.toHaveBeenCalled();
357
+ expect(mocks.submitTransaction).not.toHaveBeenCalled();
358
+ });
359
+
360
+ it("does not expose a program change when the combined ABI manager call fails", async () => {
361
+ const harness = await makeHarness();
362
+ harness.state.submitMode = "failure";
363
+ await expect(
364
+ deployProgram({
365
+ seed: "workflow",
366
+ signer: harness.signer,
367
+ client: harness.client,
368
+ program: image(0x33),
369
+ abi: ABI_BYTES,
370
+ }),
371
+ ).rejects.toMatchObject({ code: "TRANSACTION_FAILED" });
372
+ expect(harness.state.committed).toBe(false);
373
+ await expect(
374
+ harness.client.accounts.get(harness.program.programAccountAddress),
375
+ ).rejects.toMatchObject({
376
+ code: 5,
377
+ });
378
+ });
379
+
380
+ it("rejects a successful transaction whose program readback does not match", async () => {
381
+ const harness = await makeHarness();
382
+ harness.state.wrongProgramReadback = true;
383
+ await expect(
384
+ deployProgram({
385
+ seed: "workflow",
386
+ signer: harness.signer,
387
+ client: harness.client,
388
+ program: image(0x33),
389
+ }),
390
+ ).rejects.toMatchObject({ code: "VERIFICATION_FAILED" });
391
+ });
392
+
393
+ it("reconciles an unknown final submission from verified account state", async () => {
394
+ const harness = await makeHarness();
395
+ harness.state.submitMode = "unknown";
396
+ const result = await deployProgram({
397
+ seed: "workflow",
398
+ signer: harness.signer,
399
+ client: harness.client,
400
+ program: image(0x33),
401
+ });
402
+ expect(result.transactionSignature).toBe("unknown-signature");
403
+ expect(result.programVersion).toBe(0n);
404
+ });
405
+
406
+ it("commits a program plus ABI upgrade in one ordered multicall", async () => {
407
+ const harness = await makeHarness(true);
408
+ const result = await upgradeProgram({
409
+ seed: "workflow",
410
+ signer: harness.signer,
411
+ client: harness.client,
412
+ program: image(0x33),
413
+ abi: ABI_BYTES,
414
+ });
415
+ expect(mocks.submitTransaction).toHaveBeenCalledTimes(1);
416
+ const calls = MulticallArgs.from_array(harness.state.encoded!)?.get_calls();
417
+ expect(calls).toHaveLength(2);
418
+ expect(calls?.map((call) => call.get_data()[0])).toEqual([2, 8]);
419
+ expect(result.programVersion).toBe(6n);
420
+ expect(result.abiRevision).toBe(3n);
421
+ });
422
+ });