@kaspacom/kcc20-tx-builder 0.2.5 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +54 -8
  3. package/RELEASING.md +93 -0
  4. package/SECURITY.md +16 -0
  5. package/artifacts/KCC20SnapshotBootstrap.placeholder.json +101677 -0
  6. package/artifacts/KCC20SnapshotController.placeholder.json +46547 -0
  7. package/artifacts/kcc20-snapshot-bootstrap/KCC20SnapshotBootstrap.placeholder.json +101677 -0
  8. package/artifacts/kcc20-snapshot-controller/KCC20SnapshotController.placeholder.json +46547 -0
  9. package/artifacts/snapshot-standards.lock.json +56 -0
  10. package/dist/artifacts.d.ts +31 -0
  11. package/dist/artifacts.d.ts.map +1 -1
  12. package/dist/artifacts.js +31 -0
  13. package/dist/artifacts.js.map +1 -1
  14. package/dist/cjs/artifacts.d.ts +31 -0
  15. package/dist/cjs/artifacts.js +32 -1
  16. package/dist/cjs/artifacts.js.map +1 -1
  17. package/dist/cjs/engine.js +58 -44
  18. package/dist/cjs/engine.js.map +1 -1
  19. package/dist/cjs/index.d.ts +7 -0
  20. package/dist/cjs/index.js +8 -1
  21. package/dist/cjs/index.js.map +1 -1
  22. package/dist/cjs/operations.d.ts +1 -1
  23. package/dist/cjs/operations.js +4 -0
  24. package/dist/cjs/operations.js.map +1 -1
  25. package/dist/cjs/sale-common.d.ts +1 -1
  26. package/dist/cjs/sale-common.js +39 -4
  27. package/dist/cjs/sale-common.js.map +1 -1
  28. package/dist/cjs/snapshot-deployment.d.ts +82 -0
  29. package/dist/cjs/snapshot-deployment.js +82 -0
  30. package/dist/cjs/snapshot-deployment.js.map +1 -0
  31. package/dist/cjs/snapshot-operation.d.ts +26 -0
  32. package/dist/cjs/snapshot-operation.js +1308 -0
  33. package/dist/cjs/snapshot-operation.js.map +1 -0
  34. package/dist/cjs/snapshot-signerless-transactions.d.ts +132 -0
  35. package/dist/cjs/snapshot-signerless-transactions.js +746 -0
  36. package/dist/cjs/snapshot-signerless-transactions.js.map +1 -0
  37. package/dist/cjs/snapshot-signerless.d.ts +226 -0
  38. package/dist/cjs/snapshot-signerless.js +1022 -0
  39. package/dist/cjs/snapshot-signerless.js.map +1 -0
  40. package/dist/cjs/snapshot-verification.d.ts +57 -0
  41. package/dist/cjs/snapshot-verification.js +100 -0
  42. package/dist/cjs/snapshot-verification.js.map +1 -0
  43. package/dist/cjs/token-operation.js +3 -3
  44. package/dist/cjs/token-operation.js.map +1 -1
  45. package/dist/engine.d.ts.map +1 -1
  46. package/dist/engine.js +58 -44
  47. package/dist/engine.js.map +1 -1
  48. package/dist/index.d.ts +7 -0
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +7 -0
  51. package/dist/index.js.map +1 -1
  52. package/dist/operations.d.ts +1 -1
  53. package/dist/operations.d.ts.map +1 -1
  54. package/dist/operations.js +4 -0
  55. package/dist/operations.js.map +1 -1
  56. package/dist/sale-common.d.ts +1 -1
  57. package/dist/sale-common.d.ts.map +1 -1
  58. package/dist/sale-common.js +39 -4
  59. package/dist/sale-common.js.map +1 -1
  60. package/dist/snapshot-deployment.d.ts +83 -0
  61. package/dist/snapshot-deployment.d.ts.map +1 -0
  62. package/dist/snapshot-deployment.js +78 -0
  63. package/dist/snapshot-deployment.js.map +1 -0
  64. package/dist/snapshot-operation.d.ts +27 -0
  65. package/dist/snapshot-operation.d.ts.map +1 -0
  66. package/dist/snapshot-operation.js +1303 -0
  67. package/dist/snapshot-operation.js.map +1 -0
  68. package/dist/snapshot-signerless-transactions.d.ts +133 -0
  69. package/dist/snapshot-signerless-transactions.d.ts.map +1 -0
  70. package/dist/snapshot-signerless-transactions.js +735 -0
  71. package/dist/snapshot-signerless-transactions.js.map +1 -0
  72. package/dist/snapshot-signerless.d.ts +227 -0
  73. package/dist/snapshot-signerless.d.ts.map +1 -0
  74. package/dist/snapshot-signerless.js +993 -0
  75. package/dist/snapshot-signerless.js.map +1 -0
  76. package/dist/snapshot-verification.d.ts +58 -0
  77. package/dist/snapshot-verification.d.ts.map +1 -0
  78. package/dist/snapshot-verification.js +96 -0
  79. package/dist/snapshot-verification.js.map +1 -0
  80. package/dist/token-operation.js +3 -3
  81. package/dist/token-operation.js.map +1 -1
  82. package/docs/API.md +67 -0
  83. package/docs/COMPATIBILITY.json +84 -0
  84. package/docs/INTEGRATION.md +215 -0
  85. package/docs/LIVE_TRANSFER.md +106 -0
  86. package/docs/RECIPES.md +175 -0
  87. package/docs/TRANSACTION_GUIDE.md +163 -0
  88. package/docs/snapshot-start.md +27 -0
  89. package/examples/README.md +81 -0
  90. package/examples/backend/cli.ts +55 -0
  91. package/examples/backend/recipe.ts +39 -0
  92. package/examples/backend/runtime.ts +13 -0
  93. package/examples/frontend/index.html +48 -0
  94. package/examples/frontend/main.ts +213 -0
  95. package/examples/frontend/runtime.ts +14 -0
  96. package/examples/package-lock.json +1287 -0
  97. package/examples/package.json +23 -0
  98. package/examples/shared/build.ts +179 -0
  99. package/examples/shared/fixture.ts +24 -0
  100. package/examples/shared/live-transfer.ts +155 -0
  101. package/examples/shared/recipe-fixtures.ts +543 -0
  102. package/examples/shared/recipes.ts +55 -0
  103. package/examples/shared/signing.ts +110 -0
  104. package/examples/shared/timeout.ts +8 -0
  105. package/examples/test/browser.ts +116 -0
  106. package/examples/test/build.test.ts +197 -0
  107. package/examples/test/recipes.test.ts +59 -0
  108. package/examples/test/sources.test.ts +73 -0
  109. package/examples/tsconfig.json +26 -0
  110. package/examples/vendor/NOTICE.md +15 -0
  111. package/examples/vendor/kaspa/LICENSE +15 -0
  112. package/examples/vendor/kaspa/kaspa.d.ts +8908 -0
  113. package/examples/vendor/kaspa/kaspa.js +15202 -0
  114. package/examples/vendor/kaspa/kaspa_bg.wasm +0 -0
  115. package/examples/vendor/kaspa/package.json +24 -0
  116. package/package.json +21 -4
  117. package/src/artifacts.ts +35 -0
  118. package/src/engine.ts +91 -97
  119. package/src/index.ts +8 -0
  120. package/src/operations.ts +4 -0
  121. package/src/sale-common.ts +44 -3
  122. package/src/snapshot-deployment.ts +108 -0
  123. package/src/snapshot-operation.ts +1920 -0
  124. package/src/snapshot-signerless-transactions.ts +1272 -0
  125. package/src/snapshot-signerless.ts +1525 -0
  126. package/src/snapshot-verification.ts +90 -0
  127. package/src/token-operation.ts +3 -3
@@ -0,0 +1,1920 @@
1
+ /* eslint-disable @typescript-eslint/ban-ts-comment, @typescript-eslint/no-unused-vars */
2
+ // @ts-nocheck
3
+ import { blake2b } from "@noble/hashes/blake2b";
4
+ import { sha256 } from "@noble/hashes/sha256";
5
+ import type { KaspaWasmRuntime } from "./runtime.js";
6
+ import {
7
+ bytesToHex,
8
+ hexToBytes,
9
+ requireHex32,
10
+ selectFundingEntry,
11
+ setVersionOneInputMassFields,
12
+ utxoAmountSompi,
13
+ ZERO_HASH,
14
+ } from "./sale-common.js";
15
+ import {
16
+ buildKcc20ScriptForState,
17
+ buildKcc20TransferSigScript,
18
+ dispatchTagFor,
19
+ encodeKcc20StateRecordArrays,
20
+ normalizeSilverScriptArtifact,
21
+ templateParts,
22
+ } from "./abi.js";
23
+ import {
24
+ buildBootstrapGenesisPlan as buildSignerlessBootstrapPlan,
25
+ buildControllerGenesisPlan as createSignerlessControllerPlan,
26
+ buildClaimPlan as buildSignerlessClaimPlan,
27
+ buildSnapshotStartPlan,
28
+ snapshotControllerStateCommitment as signerlessControllerStateCommitment,
29
+ snapshotPeerPlanCommitment,
30
+ } from "./snapshot-signerless.js";
31
+ import {
32
+ buildBootstrapGenesisUnsignedTransaction,
33
+ buildControllerGenesisUnsignedTransaction,
34
+ buildSnapshotBootstrapScriptForState as buildSignerlessBootstrapScript,
35
+ buildSnapshotControllerScriptForState as buildSignerlessControllerScript,
36
+ buildSnapshotKcc20DeploymentPayload,
37
+ buildSnapshotStartUnsignedTransaction,
38
+ deriveSnapshotTokenId,
39
+ } from "./snapshot-signerless-transactions.js";
40
+
41
+ export const KCC20_SNAPSHOT_BUILDER_KEYS = [
42
+ "kcc20-snapshot.deploy-bootstrap",
43
+ "kcc20-snapshot.deploy-controller",
44
+ "kcc20-snapshot.start",
45
+ "kcc20-snapshot.claim",
46
+ ] as const;
47
+
48
+ /**
49
+ * KAS the public funding input must add to an immutable snapshot start.
50
+ * The consumed bootstrap cell is recycled while every reserve output must be
51
+ * funded. Accept the start plan itself so callers cannot accidentally read
52
+ * reserve fields from the narrower bootstrap-genesis plan.
53
+ */
54
+ export function calculateSnapshotStartRequiredFunding(
55
+ startPlan: {
56
+ reserveCellKas: string | number | bigint;
57
+ bootstrapCellKas: string | number | bigint;
58
+ },
59
+ shardCount: number,
60
+ priorityFeeSompi: string | number | bigint,
61
+ safetyMarginSompi: string | number | bigint = 10_000n,
62
+ ): bigint {
63
+ if (!Number.isSafeInteger(shardCount) || shardCount < 1) {
64
+ throw new Error("start shard count must be a positive safe integer");
65
+ }
66
+ const reserveCellKas = snapshotFundingI64(
67
+ startPlan?.reserveCellKas,
68
+ "start reserve cell KAS",
69
+ false,
70
+ );
71
+ const bootstrapCellKas = snapshotFundingI64(
72
+ startPlan?.bootstrapCellKas,
73
+ "start bootstrap cell KAS",
74
+ false,
75
+ );
76
+ const priorityFee = snapshotFundingI64(
77
+ priorityFeeSompi,
78
+ "snapshot priority fee",
79
+ true,
80
+ );
81
+ const safetyMargin = snapshotFundingI64(
82
+ safetyMarginSompi,
83
+ "snapshot start safety margin",
84
+ true,
85
+ );
86
+ return (
87
+ reserveCellKas * BigInt(shardCount) -
88
+ bootstrapCellKas +
89
+ priorityFee +
90
+ safetyMargin
91
+ );
92
+ }
93
+
94
+ function snapshotFundingI64(
95
+ value: unknown,
96
+ label: string,
97
+ allowZero: boolean,
98
+ ): bigint {
99
+ let amount: bigint;
100
+ try {
101
+ if (typeof value === "number" && !Number.isSafeInteger(value)) {
102
+ throw new Error("unsafe integer");
103
+ }
104
+ amount = BigInt(value as string | number | bigint);
105
+ } catch {
106
+ throw new Error(
107
+ `${label} must be a ${allowZero ? "nonnegative" : "positive"} signed 64-bit integer`,
108
+ );
109
+ }
110
+ if (
111
+ amount > 9_223_372_036_854_775_807n ||
112
+ (allowZero ? amount < 0n : amount <= 0n)
113
+ ) {
114
+ throw new Error(
115
+ `${label} must be a ${allowZero ? "nonnegative" : "positive"} signed 64-bit integer`,
116
+ );
117
+ }
118
+ return amount;
119
+ }
120
+
121
+ export interface Kcc20SnapshotBuilderOptions {
122
+ wasm: KaspaWasmRuntime;
123
+ artifacts?: Record<string, unknown>;
124
+ artifactProvider?: (key: string) => Promise<unknown>;
125
+ config?: Record<string, any>;
126
+ sourceProvider?: {
127
+ getUtxosByAddresses(args: { addresses: string[] }): Promise<unknown>;
128
+ };
129
+ rpcClientFactory?: (config: unknown) => any;
130
+ transactionWithCalculatedFeeChange: (...args: any[]) => any;
131
+ }
132
+
133
+ export function createKcc20SnapshotPsktBuilder(
134
+ options: Kcc20SnapshotBuilderOptions,
135
+ ): (input: unknown) => Promise<Record<string, unknown>> {
136
+ const config = options.config ?? {};
137
+ const transactionWithCalculatedFeeChange =
138
+ options.transactionWithCalculatedFeeChange;
139
+ class InjectedRpcClient {
140
+ private readonly inner: any;
141
+ constructor(rpcConfig: unknown) {
142
+ this.inner = options.sourceProvider
143
+ ? undefined
144
+ : options.rpcClientFactory?.(rpcConfig);
145
+ }
146
+ connect() {
147
+ if (options.sourceProvider) return Promise.resolve();
148
+ return this.inner?.connect?.() ?? Promise.resolve();
149
+ }
150
+ disconnect() {
151
+ if (options.sourceProvider) return Promise.resolve();
152
+ return this.inner?.disconnect?.() ?? Promise.resolve();
153
+ }
154
+ getUtxosByAddresses(args: { addresses: string[] }) {
155
+ if (options.sourceProvider)
156
+ return options.sourceProvider.getUtxosByAddresses(args);
157
+ if (this.inner?.getUtxosByAddresses)
158
+ return this.inner.getUtxosByAddresses(args);
159
+ throw new Error(
160
+ "No source provider or RPC client was supplied to the snapshot builder",
161
+ );
162
+ }
163
+ }
164
+ const kaspaWasm = new Proxy(options.wasm, {
165
+ get(target, property, receiver) {
166
+ if (property === "RpcClient") return InjectedRpcClient;
167
+ return Reflect.get(target, property, receiver);
168
+ },
169
+ });
170
+ const INPUT_SCHEMA = "kcc20-in-process-pskt-builder-input/v1";
171
+ const OUTPUT_SCHEMA = "kcc20-in-process-pskt-builder-output/v1";
172
+ const NATIVE_SUBNETWORK_ID = "00".repeat(20);
173
+ const DEFAULT_WRPC_URL =
174
+ "wss://tn10-node.kaspa.com/kaspa/testnet-10/wrpc/borsh";
175
+ const DEFAULT_PRIORITY_FEE = 10_000n;
176
+ const DEFAULT_CELL_SOMPI = 50_000_000n;
177
+ const MAX_I64 = 9_223_372_036_854_775_807n;
178
+ const MAX_U32 = 0xffffffff;
179
+ const BOOTSTRAP_COMPUTE_BUDGET = 2_000;
180
+ const CONTROLLER_COMPUTE_BUDGET = 2_000;
181
+ const KCC20_COMPUTE_BUDGET = 200;
182
+ const PUBLIC_INPUT_COMPUTE_BUDGET = 30;
183
+ const KCC20_ARTIFACT_PATH = "KCC20.placeholder.json";
184
+ const BOOTSTRAP_ARTIFACT_PATH = "KCC20SnapshotBootstrap.placeholder.json";
185
+ const CONTROLLER_ARTIFACT_PATH = "KCC20SnapshotController.placeholder.json";
186
+ const CONTROLLER_STATE_COMMITMENT_DOMAIN = new TextEncoder().encode(
187
+ "kcc20-snapshot-controller-state/v1",
188
+ );
189
+ const artifactCache = new Map();
190
+
191
+ async function buildSnapshotMigrationPskt(input) {
192
+ if (input?.schema !== INPUT_SCHEMA) {
193
+ throw new Error(
194
+ `unsupported in-process PSKT builder input schema: ${input?.schema || "missing"}`,
195
+ );
196
+ }
197
+ switch (input.request?.builderKey) {
198
+ case "kcc20-snapshot.deploy-bootstrap":
199
+ return buildSignerlessBootstrapGenesis(input);
200
+ case "kcc20-snapshot.deploy-controller":
201
+ return buildSignerlessControllerGenesis(input);
202
+ case "kcc20-snapshot.start":
203
+ return buildSignerlessStart(input);
204
+ case "kcc20-snapshot.claim":
205
+ return buildClaim(input);
206
+ default:
207
+ throw new Error(
208
+ `unsupported snapshot builderKey: ${input.request?.builderKey || "missing"}`,
209
+ );
210
+ }
211
+ }
212
+
213
+ async function buildSignerlessControllerGenesis(input) {
214
+ const request = input.request || {};
215
+ const params = request.params || {};
216
+ const network = networkOf(request);
217
+ const walletAddress = walletAddressOf(request);
218
+ const artifacts = await readPinnedArtifacts(
219
+ params.artifactPins,
220
+ true,
221
+ true,
222
+ );
223
+ const shard = snapshotShard(params.shard);
224
+ const allShards = normalizedSignerlessShards(
225
+ params.allShards ?? [params.shard],
226
+ );
227
+ const plan = signerlessControllerPlan(params, artifacts, shard, allShards);
228
+ const rpc = rpcFor(network);
229
+ await rpc.connect();
230
+ try {
231
+ const walletUtxos = await rpc.getUtxosByAddresses({
232
+ addresses: [walletAddress],
233
+ });
234
+ const cellKas = BigInt(plan.controllerCellKas);
235
+ const fundingEntry = selectFundingEntry(
236
+ walletUtxos.entries,
237
+ cellKas + priorityFee() + 10_000n,
238
+ [],
239
+ params.fundingOutpoint,
240
+ );
241
+ const built = buildControllerGenesisUnsignedTransaction(kaspaWasm, {
242
+ plan,
243
+ controllerArtifact: artifacts.controller,
244
+ fundingInput: portableInput(fundingEntry, network),
245
+ changeAddress: walletAddress,
246
+ feeSompi: priorityFee(),
247
+ });
248
+ const adjusted = transactionWithCalculatedFeeChange(
249
+ kaspaWasm,
250
+ built.transaction,
251
+ built.unsignedTransaction.outputs.length - 1,
252
+ network,
253
+ "signerless snapshot controller genesis",
254
+ );
255
+ const json = JSON.parse(adjusted.serializeToSafeJSON());
256
+ const controllerId = requireHex32(
257
+ json.outputs?.[0]?.covenant?.covenantId,
258
+ "controller covenant id",
259
+ );
260
+ const revealScript = buildSignerlessControllerScript(
261
+ artifacts.controller,
262
+ plan.controllerState,
263
+ );
264
+ return outputEnvelope(adjusted, [{ index: 0 }], [], {
265
+ migrationId: requireHex32(params.migrationId, "migration id"),
266
+ stage: "controller-deploy",
267
+ controllerId,
268
+ shard: shard.shardIndex,
269
+ controllerState: plan.controllerState,
270
+ controllerStateCommitment: signerlessControllerStateCommitment(
271
+ plan.controllerState,
272
+ ),
273
+ holderExtensionCommitment: requireHex32(
274
+ params.holderExtensionCommitment,
275
+ "holder extension commitment",
276
+ ),
277
+ maximumFeeSompi: feeOf(adjusted).toString(),
278
+ intentInputs: [{ role: "creator-funding", index: 0 }],
279
+ intentOutputs: [
280
+ {
281
+ role: "snapshot-controller",
282
+ index: 0,
283
+ shard: shard.shardIndex,
284
+ covenantId: controllerId,
285
+ revealScriptHex: bytesToHex(revealScript),
286
+ },
287
+ ],
288
+ });
289
+ } finally {
290
+ await rpc.disconnect();
291
+ }
292
+ }
293
+
294
+ async function buildSignerlessBootstrapGenesis(input) {
295
+ const request = input.request || {};
296
+ const params = request.params || {};
297
+ const network = networkOf(request);
298
+ const walletAddress = walletAddressOf(request);
299
+ const artifacts = await readPinnedArtifacts(
300
+ params.artifactPins,
301
+ true,
302
+ true,
303
+ );
304
+ const prepared = signerlessDeploymentPlans(params, artifacts);
305
+ const rpc = rpcFor(network);
306
+ await rpc.connect();
307
+ try {
308
+ const walletUtxos = await rpc.getUtxosByAddresses({
309
+ addresses: [walletAddress],
310
+ });
311
+ const cellKas = BigInt(prepared.bootstrapPlan.bootstrapCellKas);
312
+ const fundingEntry = selectFundingEntry(
313
+ walletUtxos.entries,
314
+ cellKas + priorityFee() + 10_000n,
315
+ [],
316
+ params.fundingOutpoint,
317
+ );
318
+ const built = buildBootstrapGenesisUnsignedTransaction(kaspaWasm, {
319
+ plan: prepared.bootstrapPlan,
320
+ bootstrapArtifact: artifacts.bootstrap,
321
+ fundingInput: portableInput(fundingEntry, network),
322
+ changeAddress: walletAddress,
323
+ feeSompi: priorityFee(),
324
+ });
325
+ const adjusted = transactionWithCalculatedFeeChange(
326
+ kaspaWasm,
327
+ built.transaction,
328
+ built.unsignedTransaction.outputs.length - 1,
329
+ network,
330
+ "signerless snapshot bootstrap genesis",
331
+ );
332
+ const json = JSON.parse(adjusted.serializeToSafeJSON());
333
+ const covenantId = requireHex32(
334
+ json.outputs?.[0]?.covenant?.covenantId,
335
+ "bootstrap covenant id",
336
+ );
337
+ const revealScript = buildSignerlessBootstrapScript(
338
+ artifacts.bootstrap,
339
+ prepared.bootstrapPlan.bootstrapState,
340
+ );
341
+ return outputEnvelope(adjusted, [{ index: 0 }], [], {
342
+ migrationId: requireHex32(params.migrationId, "migration id"),
343
+ stage: "bootstrap-deploy",
344
+ covenantId,
345
+ tokenId: prepared.tokenId,
346
+ bootstrapState: prepared.bootstrapPlan.bootstrapState,
347
+ maximumFeeSompi: feeOf(adjusted).toString(),
348
+ intentInputs: [{ role: "creator-funding", index: 0 }],
349
+ intentOutputs: [
350
+ {
351
+ role: "snapshot-bootstrap",
352
+ index: 0,
353
+ covenantId,
354
+ revealScriptHex: bytesToHex(revealScript),
355
+ },
356
+ ],
357
+ });
358
+ } finally {
359
+ await rpc.disconnect();
360
+ }
361
+ }
362
+
363
+ async function buildSignerlessStart(input) {
364
+ const request = input.request || {};
365
+ const params = request.params || {};
366
+ const network = networkOf(request);
367
+ const walletAddress = walletAddressOf(request);
368
+ const artifacts = await readPinnedArtifacts(
369
+ params.artifactPins,
370
+ true,
371
+ true,
372
+ );
373
+ const prepared = signerlessDeploymentPlans(params, artifacts);
374
+ const bootstrapId = requireHex32(
375
+ params.bootstrapId,
376
+ "bootstrap covenant id",
377
+ );
378
+ const startPlan = buildSnapshotStartPlan({
379
+ migrationId: requireHex32(params.migrationId, "migration id"),
380
+ bootstrapArtifact: artifacts.bootstrap,
381
+ controllerArtifact: artifacts.controller,
382
+ kcc20Artifact: artifacts.kcc20,
383
+ bootstrapId,
384
+ bootstrapState: prepared.bootstrapPlan.bootstrapState,
385
+ shards: prepared.startShards,
386
+ });
387
+ const bootstrapScript = buildSignerlessBootstrapScript(
388
+ artifacts.bootstrap,
389
+ prepared.bootstrapPlan.bootstrapState,
390
+ );
391
+ const controllerScripts = prepared.controllerPlans.map((plan) =>
392
+ buildSignerlessControllerScript(
393
+ artifacts.controller,
394
+ plan.controllerState,
395
+ ),
396
+ );
397
+ const bootstrapSource = sourceDescriptor(
398
+ params.bootstrapSource,
399
+ "bootstrap source",
400
+ scriptAddress(bootstrapScript, network),
401
+ );
402
+ const controllerSources = prepared.shards.map((shard, index) =>
403
+ sourceDescriptor(
404
+ shard.controllerSource,
405
+ `controller ${index} source`,
406
+ scriptAddress(controllerScripts[index], network),
407
+ ),
408
+ );
409
+ const rpc = rpcFor(network);
410
+ await rpc.connect();
411
+ try {
412
+ const addresses = [
413
+ bootstrapSource.address,
414
+ ...controllerSources.map((source) => source.address),
415
+ ];
416
+ const covenantUtxos = await rpc.getUtxosByAddresses({
417
+ addresses: [...new Set(addresses)],
418
+ });
419
+ const bootstrapEntry = findExactEntry(
420
+ covenantUtxos.entries,
421
+ bootstrapSource,
422
+ );
423
+ assertCovenantSource(bootstrapEntry, {
424
+ covenantId: bootstrapId,
425
+ script: bootstrapScript,
426
+ amount: prepared.bootstrapPlan.bootstrapCellKas,
427
+ label: "snapshot bootstrap source",
428
+ });
429
+ const controllerEntries = controllerSources.map((source, index) => {
430
+ const entry = findExactEntry(covenantUtxos.entries, source);
431
+ assertCovenantSource(entry, {
432
+ covenantId: prepared.shards[index].controllerId,
433
+ script: controllerScripts[index],
434
+ amount: prepared.controllerPlans[index].controllerCellKas,
435
+ label: `snapshot controller ${index} source`,
436
+ });
437
+ return entry;
438
+ });
439
+ const walletUtxos = await rpc.getUtxosByAddresses({
440
+ addresses: [walletAddress],
441
+ });
442
+ const requiredFunding = calculateSnapshotStartRequiredFunding(
443
+ startPlan,
444
+ prepared.shards.length,
445
+ priorityFee(),
446
+ );
447
+ const fundingEntry = selectFundingEntry(
448
+ walletUtxos.entries,
449
+ requiredFunding > 0n ? requiredFunding : priorityFee() + 10_000n,
450
+ [bootstrapEntry, ...controllerEntries],
451
+ params.fundingOutpoint,
452
+ );
453
+ const tokenMetadata = requiredRecord(
454
+ params.tokenMetadata,
455
+ "snapshot token metadata",
456
+ );
457
+ const payload = buildSnapshotKcc20DeploymentPayload({
458
+ creator: tokenMetadata.creator,
459
+ ticker: tokenMetadata.ticker,
460
+ name: tokenMetadata.name,
461
+ displayScale: tokenMetadata.displayScale,
462
+ totalSupply: params.totalSupply,
463
+ holderExtensionCommitment: params.holderExtensionCommitment,
464
+ migrationId: params.migrationCommitment ?? params.migrationId,
465
+ manifestCommitment: params.manifestCommitment,
466
+ reserves: startPlan.reserves,
467
+ treasury: tokenMetadata.treasury ?? tokenMetadata.creator,
468
+ protocolFeeRecipient:
469
+ tokenMetadata.protocolFeeRecipient ?? tokenMetadata.creator,
470
+ protocolFeeBps: tokenMetadata.protocolFeeBps ?? 0,
471
+ });
472
+ const built = buildSnapshotStartUnsignedTransaction(kaspaWasm, {
473
+ plan: startPlan,
474
+ bootstrapArtifact: artifacts.bootstrap,
475
+ controllerArtifact: artifacts.controller,
476
+ kcc20Artifact: artifacts.kcc20,
477
+ bootstrapInput: portableInput(bootstrapEntry, network, bootstrapScript),
478
+ controllerInputs: controllerEntries.map((entry, index) =>
479
+ portableInput(entry, network, controllerScripts[index]),
480
+ ),
481
+ fundingInput: portableInput(fundingEntry, network),
482
+ changeAddress: walletAddress,
483
+ feeSompi: priorityFee(),
484
+ payload,
485
+ });
486
+ const changeIndex = built.unsignedTransaction.outputs.length - 1;
487
+ const adjusted = transactionWithCalculatedFeeChange(
488
+ kaspaWasm,
489
+ built.transaction,
490
+ changeIndex,
491
+ network,
492
+ "signerless snapshot start",
493
+ );
494
+ return outputEnvelope(
495
+ adjusted,
496
+ [{ index: 1 + prepared.shards.length }],
497
+ [],
498
+ {
499
+ migrationId: requireHex32(params.migrationId, "migration id"),
500
+ stage: "snapshot-start",
501
+ tokenId: prepared.tokenId,
502
+ covenantId: prepared.tokenId,
503
+ bootstrapId,
504
+ bootstrapState: prepared.bootstrapPlan.bootstrapState,
505
+ bootstrapConsumed: true,
506
+ shards: prepared.shards.map((shard) => shard.shardIndex),
507
+ maximumFeeSompi: feeOf(adjusted).toString(),
508
+ intentInputs: [
509
+ {
510
+ role: "snapshot-bootstrap",
511
+ index: 0,
512
+ covenantId: bootstrapId,
513
+ revealScriptHex: bytesToHex(bootstrapScript),
514
+ staticSignatureScriptHex: signatureScriptHex(adjusted, 0),
515
+ },
516
+ ...prepared.shards.map((shard, index) => ({
517
+ role: "snapshot-controller",
518
+ index: index + 1,
519
+ shard: shard.shardIndex,
520
+ covenantId: shard.controllerId,
521
+ revealScriptHex: bytesToHex(controllerScripts[index]),
522
+ staticSignatureScriptHex: signatureScriptHex(adjusted, index + 1),
523
+ })),
524
+ { role: "creator-funding", index: 1 + prepared.shards.length },
525
+ ],
526
+ intentOutputs: [
527
+ ...prepared.shards.map((shard, index) => ({
528
+ role: "shard-reserve",
529
+ index,
530
+ shard: shard.shardIndex,
531
+ covenantId: prepared.tokenId,
532
+ tokenAmount: shard.allocationTotal.toString(),
533
+ owner: shard.controllerId,
534
+ ownerScheme: 4,
535
+ borrowScheme: 0,
536
+ borrowGuard: ZERO_HASH,
537
+ extensionCommitment: requireHex32(
538
+ params.holderExtensionCommitment,
539
+ "holder extension commitment",
540
+ ),
541
+ revealScriptHex: bytesToHex(
542
+ buildKcc20ScriptForState(
543
+ artifacts.kcc20,
544
+ kcc20State(startPlan.reserves[index]),
545
+ ),
546
+ ),
547
+ })),
548
+ ...prepared.shards.map((shard, index) => ({
549
+ role: "snapshot-controller",
550
+ index: prepared.shards.length + index,
551
+ shard: shard.shardIndex,
552
+ covenantId: shard.controllerId,
553
+ revealScriptHex: bytesToHex(
554
+ buildSignerlessControllerScript(
555
+ artifacts.controller,
556
+ startPlan.controllers[index].stateAfter,
557
+ ),
558
+ ),
559
+ })),
560
+ ],
561
+ },
562
+ );
563
+ } finally {
564
+ await rpc.disconnect();
565
+ }
566
+ }
567
+
568
+ function signerlessDeploymentPlans(params, artifacts) {
569
+ const shards = normalizedSignerlessShards(params.allShards);
570
+ if (
571
+ shards.some((shard) => !shard.controllerId || !shard.controllerSource)
572
+ ) {
573
+ throw new Error(
574
+ "signerless bootstrap/start requires every indexed controller identity and source",
575
+ );
576
+ }
577
+ const controllerPlans = shards.map((shard) =>
578
+ signerlessControllerPlan(params, artifacts, shard, shards),
579
+ );
580
+ const startShards = shards.map((shard, index) => ({
581
+ controllerId: shard.controllerId,
582
+ state: controllerPlans[index].controllerState,
583
+ }));
584
+ const reserves = shards.map((shard) => ({
585
+ amount: shard.allocationTotal.toString(),
586
+ owner: shard.controllerId,
587
+ ownerScheme: 4,
588
+ borrowScheme: 0,
589
+ borrowGuard: ZERO_HASH,
590
+ extensionCommitment: requireHex32(
591
+ params.holderExtensionCommitment,
592
+ "holder extension commitment",
593
+ ),
594
+ }));
595
+ const tokenId = deriveSnapshotTokenId(kaspaWasm, {
596
+ controllerGenesisOutpoint: outpointOfSource(
597
+ shards[0].controllerSource,
598
+ "shard-zero controller source",
599
+ ),
600
+ reserves,
601
+ kcc20Artifact: artifacts.kcc20,
602
+ reserveCellKas: minimumCell(params.reserveCellKas, "reserve cell KAS"),
603
+ });
604
+ const bootstrapPlan = buildSignerlessBootstrapPlan({
605
+ migrationId: requireHex32(params.migrationId, "migration id"),
606
+ migrationCommitment: requireHex32(
607
+ params.migrationCommitment ?? params.migrationId,
608
+ "migration commitment",
609
+ ),
610
+ bootstrapArtifact: artifacts.bootstrap,
611
+ controllerArtifact: artifacts.controller,
612
+ kcc20Artifact: artifacts.kcc20,
613
+ manifestCommitment: requireHex32(
614
+ params.manifestCommitment,
615
+ "manifest commitment",
616
+ ),
617
+ holderExtensionCommitment: requireHex32(
618
+ params.holderExtensionCommitment,
619
+ "holder extension commitment",
620
+ ),
621
+ totalSupply: positiveI64(params.totalSupply, "total supply"),
622
+ claimNotBeforeDaaScore: positiveI64(
623
+ params.claimNotBeforeDaaScore,
624
+ "claim-not-before DAA score",
625
+ ),
626
+ expectedTokenId: tokenId,
627
+ shards: startShards,
628
+ reserveCellKas: minimumCell(params.reserveCellKas, "reserve cell KAS"),
629
+ controllerCellKas: minimumCell(
630
+ params.controllerCellKas,
631
+ "controller cell KAS",
632
+ ),
633
+ bootstrapCellKas: minimumCell(
634
+ params.bootstrapCellKas,
635
+ "bootstrap cell KAS",
636
+ ),
637
+ });
638
+ return { shards, controllerPlans, startShards, tokenId, bootstrapPlan };
639
+ }
640
+
641
+ function signerlessControllerPlan(params, artifacts, shard, allShards) {
642
+ const common = {
643
+ migrationId: requireHex32(params.migrationId, "migration id"),
644
+ migrationCommitment: requireHex32(
645
+ params.migrationCommitment ?? params.migrationId,
646
+ "migration commitment",
647
+ ),
648
+ controllerArtifact: artifacts.controller,
649
+ bootstrapArtifact: artifacts.bootstrap,
650
+ kcc20Artifact: artifacts.kcc20,
651
+ holderExtensionCommitment: requireHex32(
652
+ params.holderExtensionCommitment,
653
+ "holder extension commitment",
654
+ ),
655
+ manifestCommitment: requireHex32(
656
+ params.manifestCommitment,
657
+ "manifest commitment",
658
+ ),
659
+ context: requireHex32(params.snapshotContext, "snapshot context"),
660
+ shardCount: allShards.length,
661
+ controllerCellKas: minimumCell(
662
+ params.controllerCellKas,
663
+ "controller cell KAS",
664
+ ),
665
+ reserveCellKas: minimumCell(params.reserveCellKas, "reserve cell KAS"),
666
+ recipientMinCellKas: minimumCell(
667
+ params.recipientMinCellKas,
668
+ "recipient minimum cell KAS",
669
+ ),
670
+ claimNotBeforeDaaScore: positiveI64(
671
+ params.claimNotBeforeDaaScore,
672
+ "claim-not-before DAA score",
673
+ ),
674
+ };
675
+ if (shard.shardIndex !== 0) {
676
+ return createSignerlessControllerPlan({
677
+ ...common,
678
+ shard,
679
+ deploymentGuardCommitment: ZERO_HASH,
680
+ });
681
+ }
682
+ const provisional = createSignerlessControllerPlan({
683
+ ...common,
684
+ shard,
685
+ deploymentGuardCommitment: "01".repeat(32),
686
+ });
687
+ const peerPlans = allShards.slice(1).map((peer) => {
688
+ if (!peer.controllerId)
689
+ throw new Error(
690
+ "deploy shard zero only after every peer controller is indexed",
691
+ );
692
+ const plan = createSignerlessControllerPlan({
693
+ ...common,
694
+ shard: peer,
695
+ deploymentGuardCommitment: ZERO_HASH,
696
+ });
697
+ return { controllerId: peer.controllerId, state: plan.controllerState };
698
+ });
699
+ const guard = snapshotPeerPlanCommitment({
700
+ migrationCommitment: common.migrationCommitment,
701
+ manifestCommitment: common.manifestCommitment,
702
+ shards: [
703
+ { controllerId: "01".repeat(32), state: provisional.controllerState },
704
+ ...peerPlans,
705
+ ],
706
+ });
707
+ return createSignerlessControllerPlan({
708
+ ...common,
709
+ shard,
710
+ deploymentGuardCommitment: guard,
711
+ });
712
+ }
713
+
714
+ function normalizedSignerlessShards(values) {
715
+ if (!Array.isArray(values) || values.length < 1 || values.length > 8) {
716
+ throw new Error("signerless snapshot requires 1..8 ordered shards");
717
+ }
718
+ const shards = values.map((value) => ({
719
+ ...snapshotShard(value),
720
+ controllerId: value?.controllerId
721
+ ? requireHex32(value.controllerId, "controller id")
722
+ : undefined,
723
+ controllerSource: value?.controllerSource,
724
+ }));
725
+ shards.sort((left, right) => left.shardIndex - right.shardIndex);
726
+ if (shards.some((shard, index) => shard.shardIndex !== index)) {
727
+ throw new Error(
728
+ "signerless snapshot shards must be contiguous from zero",
729
+ );
730
+ }
731
+ return shards;
732
+ }
733
+
734
+ function portableInput(entry, network, script) {
735
+ return {
736
+ previousOutpoint: entry.outpoint,
737
+ utxo: entry,
738
+ networkId: network,
739
+ ...(script ? { script } : {}),
740
+ };
741
+ }
742
+
743
+ function outpointOfSource(source, label) {
744
+ return {
745
+ transactionId: requireHex32(source?.txidHex, `${label} txid`),
746
+ index: unsignedInteger(source?.vout, `${label} vout`),
747
+ };
748
+ }
749
+
750
+ async function buildClaim(input) {
751
+ const request = input.request || {};
752
+ const params = request.params || {};
753
+ const network = networkOf(request);
754
+ const walletAddress = walletAddressOf(request);
755
+ const owner = requireHex32(request.owner?.kcc20Owner, "claim owner");
756
+ const artifacts = await readPinnedArtifacts(
757
+ params.artifactPins,
758
+ true,
759
+ true,
760
+ );
761
+ const definition = snapshotDefinition(params, artifacts);
762
+ const tokenId = definition.tokenId;
763
+ const controllerId = requireHex32(params.controllerId, "controller id");
764
+ const proof = claimProof(params.proof, definition.shard);
765
+ if (proof.ownerScheme !== 0 && proof.ownerScheme !== 3) {
766
+ throw new Error(
767
+ "snapshot claim builder supports only P2PK Schnorr and P2SH entitlements",
768
+ );
769
+ }
770
+ if (proof.ownerScheme === 0 && proof.owner !== owner) {
771
+ throw new Error("P2PK claim proof owner does not match the wallet owner");
772
+ }
773
+ const p2shAuthority =
774
+ proof.ownerScheme === 3
775
+ ? p2shAuthorityDescriptor(
776
+ params.p2shAuthority,
777
+ proof.owner,
778
+ network,
779
+ "P2SH claim authority",
780
+ )
781
+ : null;
782
+ const currentRoot = requireHex32(params.currentRoot, "current root");
783
+ if (proof.previousRoot !== currentRoot) {
784
+ throw new Error("claim proof is stale for the current shard root");
785
+ }
786
+ assertClaimProofRoots(proof, definition.snapshotContext, currentRoot);
787
+ const currentReserveAmount = positiveI64(
788
+ params.currentReserveAmount,
789
+ "current reserve amount",
790
+ );
791
+ const currentClaimsProcessed = unsignedInteger(
792
+ params.currentClaimsProcessed,
793
+ "current claims processed",
794
+ );
795
+ const allShards = normalizedSignerlessShards(
796
+ params.allShards ?? [params.shard],
797
+ );
798
+ const controllerGenesisPlan = signerlessControllerPlan(
799
+ params,
800
+ artifacts,
801
+ definition.shard,
802
+ allShards,
803
+ );
804
+ const claimPlan = buildSignerlessClaimPlan({
805
+ migrationId: definition.migrationId,
806
+ migrationCommitment: requireHex32(
807
+ params.migrationCommitment ?? params.migrationId,
808
+ "migration commitment",
809
+ ),
810
+ controllerArtifact: artifacts.controller,
811
+ bootstrapArtifact: artifacts.bootstrap,
812
+ kcc20Artifact: artifacts.kcc20,
813
+ controllerId,
814
+ tokenId,
815
+ holderExtensionCommitment: definition.holderExtensionCommitment,
816
+ manifestCommitment: definition.manifestCommitment,
817
+ context: definition.snapshotContext,
818
+ shard: definition.shard,
819
+ shardCount: allShards.length,
820
+ deploymentGuardCommitment:
821
+ controllerGenesisPlan.controllerState.deploymentGuardCommitment,
822
+ currentRoot,
823
+ currentReserveAmount,
824
+ currentClaimsProcessed,
825
+ claim: {
826
+ globalIndex: proof.globalIndex,
827
+ shardLeafIndex: proof.shardLeafIndex,
828
+ ownerScheme: proof.ownerScheme,
829
+ owner: proof.owner,
830
+ amount: proof.amount,
831
+ siblings: proof.siblings,
832
+ },
833
+ controllerCellKas: definition.controllerCellKas,
834
+ reserveCellKas: definition.reserveCellKas,
835
+ recipientMinCellKas: definition.recipientMinCellKas,
836
+ reserveInputCellKas: definition.reserveCellKas,
837
+ claimNotBeforeDaaScore: definition.claimNotBeforeDaaScore,
838
+ });
839
+ const nextReserveAmount = currentReserveAmount - proof.amount;
840
+ const terminal = claimPlan.terminal === true;
841
+ const controllerState = claimPlan.controllerStateBefore;
842
+ const nextControllerState = claimPlan.controllerStateAfter;
843
+ const reserveState = {
844
+ amount: currentReserveAmount,
845
+ owner: hexToBytes(controllerId),
846
+ ownerScheme: 4,
847
+ borrowScheme: 0,
848
+ borrowGuard: hexToBytes(ZERO_HASH),
849
+ extensionCommitment: hexToBytes(definition.holderExtensionCommitment),
850
+ };
851
+ const nextReserveState = terminal
852
+ ? null
853
+ : { ...reserveState, amount: nextReserveAmount };
854
+ const recipientState = {
855
+ amount: proof.amount,
856
+ owner: hexToBytes(proof.owner),
857
+ ownerScheme: proof.ownerScheme,
858
+ borrowScheme: 0,
859
+ borrowGuard: hexToBytes(ZERO_HASH),
860
+ extensionCommitment: hexToBytes(definition.holderExtensionCommitment),
861
+ };
862
+ const controllerScript = buildSignerlessControllerScript(
863
+ artifacts.controller,
864
+ controllerState,
865
+ );
866
+ const reserveScript = buildKcc20ScriptForState(
867
+ artifacts.kcc20,
868
+ reserveState,
869
+ );
870
+ const controllerSource = sourceDescriptor(
871
+ params.controllerSource,
872
+ "controller source",
873
+ scriptAddress(controllerScript, network),
874
+ );
875
+ const reserveSource = sourceDescriptor(
876
+ params.reserveSource,
877
+ "reserve source",
878
+ scriptAddress(reserveScript, network),
879
+ );
880
+ const rpc = rpcFor(network);
881
+ await rpc.connect();
882
+ try {
883
+ const [controllerUtxos, reserveUtxos, walletUtxos, authorityUtxos] =
884
+ await Promise.all([
885
+ rpc.getUtxosByAddresses({ addresses: [controllerSource.address] }),
886
+ rpc.getUtxosByAddresses({ addresses: [reserveSource.address] }),
887
+ rpc.getUtxosByAddresses({ addresses: [walletAddress] }),
888
+ ...(p2shAuthority
889
+ ? [
890
+ rpc.getUtxosByAddresses({
891
+ addresses: [p2shAuthority.source.address],
892
+ }),
893
+ ]
894
+ : []),
895
+ ]);
896
+ const controllerEntry = findExactEntry(
897
+ controllerUtxos.entries,
898
+ controllerSource,
899
+ );
900
+ const reserveEntry = findExactEntry(reserveUtxos.entries, reserveSource);
901
+ const authorityEntry = p2shAuthority
902
+ ? findExactEntry(authorityUtxos.entries, p2shAuthority.source)
903
+ : null;
904
+ assertCovenantSource(controllerEntry, {
905
+ covenantId: controllerId,
906
+ script: controllerScript,
907
+ amount: definition.controllerCellKas,
908
+ label: "claim controller source",
909
+ });
910
+ assertCovenantSource(reserveEntry, {
911
+ covenantId: tokenId,
912
+ script: reserveScript,
913
+ amount: definition.reserveCellKas,
914
+ label: "claim reserve source",
915
+ });
916
+ if (p2shAuthority && authorityEntry) {
917
+ assertScriptPublicKey(
918
+ authorityEntry,
919
+ p2shAuthority.scriptPublicKeyHex,
920
+ "P2SH claim authority source",
921
+ );
922
+ }
923
+ const fundingEntry = selectFundingEntry(
924
+ withoutOutpoints(walletUtxos.entries, [
925
+ controllerEntry.outpoint,
926
+ reserveEntry.outpoint,
927
+ ...(authorityEntry ? [authorityEntry.outpoint] : []),
928
+ ]),
929
+ priorityFee() + definition.recipientMinCellKas + 10_000n,
930
+ [],
931
+ params.fundingOutpoint,
932
+ );
933
+ const tokenStates = [
934
+ ...(nextReserveState ? [nextReserveState] : []),
935
+ recipientState,
936
+ ];
937
+ const outputs = tokenStates.map((state, index) => {
938
+ const recipientIndex = tokenStates.length - 1;
939
+ const cellKas =
940
+ index === recipientIndex && terminal
941
+ ? definition.reserveCellKas + definition.controllerCellKas
942
+ : index === recipientIndex
943
+ ? definition.recipientMinCellKas
944
+ : definition.reserveCellKas;
945
+ return new kaspaWasm.TransactionOutput(
946
+ cellKas,
947
+ kaspaWasm.payToScriptHashScript(
948
+ buildKcc20ScriptForState(artifacts.kcc20, state),
949
+ ),
950
+ new kaspaWasm.CovenantBinding(1, new kaspaWasm.Hash(tokenId)),
951
+ );
952
+ });
953
+ if (nextControllerState) {
954
+ outputs.push(
955
+ new kaspaWasm.TransactionOutput(
956
+ definition.controllerCellKas,
957
+ kaspaWasm.payToScriptHashScript(
958
+ buildSignerlessControllerScript(
959
+ artifacts.controller,
960
+ nextControllerState,
961
+ ),
962
+ ),
963
+ new kaspaWasm.CovenantBinding(0, new kaspaWasm.Hash(controllerId)),
964
+ ),
965
+ );
966
+ }
967
+ const authorityReturnIndex = authorityEntry ? outputs.length : null;
968
+ if (authorityEntry) {
969
+ outputs.push(
970
+ new kaspaWasm.TransactionOutput(
971
+ utxoAmountSompi(authorityEntry),
972
+ authorityEntry.scriptPublicKey,
973
+ ),
974
+ );
975
+ }
976
+ const outputSompi = outputs.reduce(
977
+ (sum, output) => sum + BigInt(output.value),
978
+ 0n,
979
+ );
980
+ const fundingChangeOutputIndex = appendFundingChange(
981
+ outputs,
982
+ [
983
+ controllerEntry,
984
+ reserveEntry,
985
+ ...(authorityEntry ? [authorityEntry] : []),
986
+ fundingEntry,
987
+ ],
988
+ walletAddress,
989
+ outputSompi,
990
+ priorityFee(),
991
+ );
992
+ const transaction = new kaspaWasm.Transaction({
993
+ version: 1,
994
+ lockTime: definition.claimNotBeforeDaaScore,
995
+ inputs: [
996
+ covenantInput(controllerEntry, CONTROLLER_COMPUTE_BUDGET),
997
+ covenantInput(reserveEntry, KCC20_COMPUTE_BUDGET),
998
+ ...(authorityEntry
999
+ ? [publicInput(authorityEntry, PUBLIC_INPUT_COMPUTE_BUDGET)]
1000
+ : []),
1001
+ publicInput(fundingEntry, PUBLIC_INPUT_COMPUTE_BUDGET),
1002
+ ],
1003
+ outputs,
1004
+ subnetworkId: NATIVE_SUBNETWORK_ID,
1005
+ gas: 0n,
1006
+ payload: "",
1007
+ });
1008
+ setVersionOneInputMassFields(transaction, PUBLIC_INPUT_COMPUTE_BUDGET);
1009
+ transaction.inputs[0].computeBudget = CONTROLLER_COMPUTE_BUDGET;
1010
+ transaction.inputs[1].computeBudget = KCC20_COMPUTE_BUDGET;
1011
+ for (let index = 2; index < transaction.inputs.length; index += 1) {
1012
+ transaction.inputs[index].computeBudget = PUBLIC_INPUT_COMPUTE_BUDGET;
1013
+ }
1014
+ transaction.inputs[0].sequence = 0n;
1015
+ const template = templateParts(artifacts.kcc20);
1016
+ const controllerArgs = controllerClaimOrderedArgs({
1017
+ controllerArtifact: artifacts.controller,
1018
+ proof,
1019
+ nextReserveState,
1020
+ recipientState,
1021
+ template,
1022
+ ownerWitness:
1023
+ proof.ownerScheme === 3
1024
+ ? dataArg(Uint8Array.of(2))
1025
+ : { type: "signature" },
1026
+ });
1027
+ const controllerScriptHint = {
1028
+ inputIndex: 0,
1029
+ scriptHex: bytesToHex(controllerScript),
1030
+ signatureScript: { mode: "ordered-args", args: controllerArgs },
1031
+ };
1032
+ const reservePrefix = buildKcc20TransferSigScript(
1033
+ kaspaWasm,
1034
+ artifacts.kcc20,
1035
+ {
1036
+ nextStates: tokenStates,
1037
+ witness: Uint8Array.of(0),
1038
+ },
1039
+ );
1040
+ transaction.inputs[1].signatureScript = encodeP2sh(
1041
+ reservePrefix,
1042
+ reserveScript,
1043
+ );
1044
+ if (p2shAuthority && authorityEntry) {
1045
+ transaction.inputs[2].signatureScript = encodeP2sh(
1046
+ p2shAuthority.unlockPrefix,
1047
+ p2shAuthority.revealScript,
1048
+ );
1049
+ }
1050
+ const adjusted = transactionWithCalculatedFeeChange(
1051
+ kaspaWasm,
1052
+ transaction,
1053
+ fundingChangeOutputIndex,
1054
+ network,
1055
+ "snapshot claim",
1056
+ [controllerScriptHint],
1057
+ );
1058
+ const recipientIndex = tokenStates.length - 1;
1059
+ const reserveOutput = nextReserveState
1060
+ ? {
1061
+ role: "reserve-successor",
1062
+ index: 0,
1063
+ covenantId: tokenId,
1064
+ revealScriptHex: bytesToHex(
1065
+ buildKcc20ScriptForState(artifacts.kcc20, nextReserveState),
1066
+ ),
1067
+ owner: controllerId,
1068
+ ownerScheme: 4,
1069
+ borrowScheme: 0,
1070
+ borrowGuard: ZERO_HASH,
1071
+ extensionCommitment: definition.holderExtensionCommitment,
1072
+ tokenAmount: nextReserveAmount.toString(),
1073
+ }
1074
+ : null;
1075
+ const recipientOutput = {
1076
+ role: "recipient",
1077
+ index: recipientIndex,
1078
+ covenantId: tokenId,
1079
+ revealScriptHex: bytesToHex(
1080
+ buildKcc20ScriptForState(artifacts.kcc20, recipientState),
1081
+ ),
1082
+ owner: proof.owner,
1083
+ ownerScheme: proof.ownerScheme,
1084
+ borrowScheme: 0,
1085
+ borrowGuard: ZERO_HASH,
1086
+ extensionCommitment: definition.holderExtensionCommitment,
1087
+ tokenAmount: proof.amount.toString(),
1088
+ };
1089
+ const controllerOutput = nextControllerState
1090
+ ? {
1091
+ role: "controller-successor",
1092
+ index: tokenStates.length,
1093
+ covenantId: controllerId,
1094
+ revealScriptHex: bytesToHex(
1095
+ buildSignerlessControllerScript(
1096
+ artifacts.controller,
1097
+ nextControllerState,
1098
+ ),
1099
+ ),
1100
+ }
1101
+ : null;
1102
+ const authorityReturnOutput =
1103
+ authorityEntry && p2shAuthority && authorityReturnIndex !== null
1104
+ ? {
1105
+ role: "p2sh-authority-return",
1106
+ index: authorityReturnIndex,
1107
+ scriptPublicKey: p2shAuthority.scriptPublicKeyHex,
1108
+ valueSompi: utxoAmountSompi(authorityEntry).toString(),
1109
+ }
1110
+ : null;
1111
+ const fundingInputIndex = authorityEntry ? 3 : 2;
1112
+ return outputEnvelope(
1113
+ adjusted,
1114
+ [{ index: fundingInputIndex }],
1115
+ [controllerScriptHint],
1116
+ {
1117
+ migrationId: definition.migrationId,
1118
+ stage: "claim",
1119
+ tokenId,
1120
+ controllerId,
1121
+ shard: definition.shard.shardIndex,
1122
+ globalIndex: proof.globalIndex,
1123
+ terminal,
1124
+ recipient: proof.owner,
1125
+ recipientOwnerScheme: proof.ownerScheme,
1126
+ amount: proof.amount.toString(),
1127
+ previousRoot: currentRoot,
1128
+ nextRoot: proof.nextRoot,
1129
+ maximumFeeSompi: feeOf(adjusted).toString(),
1130
+ intentInputs: [
1131
+ {
1132
+ role: "controller",
1133
+ index: 0,
1134
+ covenantId: controllerId,
1135
+ revealScriptHex: bytesToHex(controllerScript),
1136
+ },
1137
+ {
1138
+ role: "reserve",
1139
+ index: 1,
1140
+ covenantId: tokenId,
1141
+ revealScriptHex: bytesToHex(reserveScript),
1142
+ staticSignatureScriptHex: signatureScriptHex(adjusted, 1),
1143
+ },
1144
+ ...(authorityEntry && p2shAuthority
1145
+ ? [
1146
+ {
1147
+ role: "p2sh-authority",
1148
+ index: 2,
1149
+ owner: proof.owner,
1150
+ revealScriptHex: bytesToHex(p2shAuthority.revealScript),
1151
+ scriptPublicKey: p2shAuthority.scriptPublicKeyHex,
1152
+ staticSignatureScriptHex: signatureScriptHex(adjusted, 2),
1153
+ },
1154
+ ]
1155
+ : []),
1156
+ ],
1157
+ intentOutputs: [
1158
+ ...(reserveOutput ? [reserveOutput] : []),
1159
+ recipientOutput,
1160
+ ...(controllerOutput ? [controllerOutput] : []),
1161
+ ...(authorityReturnOutput ? [authorityReturnOutput] : []),
1162
+ ],
1163
+ },
1164
+ );
1165
+ } finally {
1166
+ await rpc.disconnect();
1167
+ }
1168
+ }
1169
+
1170
+ function snapshotDefinition(params, artifacts) {
1171
+ const migrationId = requireHex32(params.migrationId, "migration id");
1172
+ const tokenId = requireHex32(params.tokenId, "token covenant id");
1173
+ const holderExtensionCommitment = requireHex32(
1174
+ params.holderExtensionCommitment,
1175
+ "holder extension commitment",
1176
+ );
1177
+ const manifestCommitment = requireHex32(
1178
+ params.manifestCommitment,
1179
+ "manifest commitment",
1180
+ );
1181
+ const snapshotContext = requireHex32(
1182
+ params.snapshotContext,
1183
+ "snapshot context",
1184
+ );
1185
+ const claimNotBeforeDaaScore = positiveI64(
1186
+ params.claimNotBeforeDaaScore,
1187
+ "claim-not-before DAA score",
1188
+ );
1189
+ if (claimNotBeforeDaaScore >= 500_000_000_000n) {
1190
+ throw new Error("claim-not-before must use DAA-score locktime mode");
1191
+ }
1192
+ const shard = snapshotShard(params.shard);
1193
+ const controllerCellKas = minimumCell(
1194
+ params.controllerCellKas,
1195
+ "controller cell KAS",
1196
+ );
1197
+ const reserveCellKas = minimumCell(
1198
+ params.reserveCellKas,
1199
+ "reserve cell KAS",
1200
+ );
1201
+ const recipientMinCellKas = minimumCell(
1202
+ params.recipientMinCellKas,
1203
+ "recipient minimum cell KAS",
1204
+ );
1205
+ if (controllerCellKas + reserveCellKas < recipientMinCellKas) {
1206
+ throw new Error(
1207
+ "terminal cell disposition is below the recipient minimum",
1208
+ );
1209
+ }
1210
+ const template = templateParts(artifacts.kcc20);
1211
+ const expectedTemplateHash = requireHex32(
1212
+ params.kcc20TemplateHash,
1213
+ "KCC20 template hash",
1214
+ );
1215
+ if (bytesToHex(template.hash) !== expectedTemplateHash) {
1216
+ throw new Error("KCC20 template hash does not match the migration pin");
1217
+ }
1218
+ return {
1219
+ migrationId,
1220
+ tokenId,
1221
+ holderExtensionCommitment,
1222
+ manifestCommitment,
1223
+ snapshotContext,
1224
+ claimNotBeforeDaaScore,
1225
+ shard,
1226
+ controllerCellKas,
1227
+ reserveCellKas,
1228
+ recipientMinCellKas,
1229
+ kcc20TemplateHash: expectedTemplateHash,
1230
+ kcc20TemplatePrefixLen: template.prefix.length,
1231
+ kcc20TemplateSuffixLen: template.suffix.length,
1232
+ };
1233
+ }
1234
+
1235
+ function encodeControllerState(state) {
1236
+ return concatBytes(
1237
+ pushData(state.tokenId),
1238
+ pushData(state.holderExtensionCommitment),
1239
+ pushData(state.manifestCommitment),
1240
+ pushData(state.snapshotContext),
1241
+ pushData(state.kcc20TemplateHash),
1242
+ pushData(i64(state.claimNotBeforeDaaScore)),
1243
+ pushData(i64(state.shardIndex)),
1244
+ pushData(i64(state.globalIndexStart)),
1245
+ pushData(i64(state.holderCount)),
1246
+ pushData(i64(state.treeDepth)),
1247
+ pushData(i64(state.kcc20TemplatePrefixLen)),
1248
+ pushData(i64(state.kcc20TemplateSuffixLen)),
1249
+ pushData(i64(state.controllerCellKas)),
1250
+ pushData(i64(state.reserveCellKas)),
1251
+ pushData(i64(state.recipientMinCellKas)),
1252
+ pushData(state.remainingRoot),
1253
+ pushData(i64(state.remainingAmount)),
1254
+ pushData(i64(state.claimsProcessed)),
1255
+ );
1256
+ }
1257
+
1258
+ function snapshotControllerStateCommitment(state): string {
1259
+ return bytesToHex(
1260
+ blake2b(
1261
+ concatBytes(
1262
+ CONTROLLER_STATE_COMMITMENT_DOMAIN,
1263
+ encodeControllerState(state),
1264
+ ),
1265
+ { dkLen: 32 },
1266
+ ),
1267
+ );
1268
+ }
1269
+
1270
+ function controllerClaimOrderedArgs({
1271
+ controllerArtifact,
1272
+ proof,
1273
+ nextReserveState,
1274
+ recipientState,
1275
+ template,
1276
+ ownerWitness,
1277
+ }) {
1278
+ return [
1279
+ i64Arg(proof.globalIndex),
1280
+ i64Arg(proof.shardLeafIndex),
1281
+ byteArg(proof.ownerScheme),
1282
+ dataArg(hexToBytes(proof.owner)),
1283
+ ownerWitness,
1284
+ i64Arg(proof.amount),
1285
+ dataArg(concatBytes(...proof.siblings.map(hexToBytes))),
1286
+ ...kcc20StateArgs(nextReserveState),
1287
+ ...kcc20StateArgs(recipientState),
1288
+ dataArg(template.prefix),
1289
+ dataArg(template.suffix),
1290
+ dataArg(dispatchTagFor(controllerArtifact, "claim")),
1291
+ ];
1292
+ }
1293
+
1294
+ function kcc20StateArgs(state) {
1295
+ const value =
1296
+ state ||
1297
+ ({
1298
+ amount: 0n,
1299
+ owner: hexToBytes(ZERO_HASH),
1300
+ ownerScheme: 0,
1301
+ borrowScheme: 0,
1302
+ borrowGuard: hexToBytes(ZERO_HASH),
1303
+ extensionCommitment: hexToBytes(ZERO_HASH),
1304
+ } as const);
1305
+ return [
1306
+ i64Arg(value.amount),
1307
+ dataArg(value.owner),
1308
+ byteArg(value.ownerScheme),
1309
+ byteArg(value.borrowScheme),
1310
+ dataArg(value.borrowGuard),
1311
+ dataArg(value.extensionCommitment),
1312
+ ];
1313
+ }
1314
+
1315
+ function outputEnvelope(transaction, signInputs, scripts, metadata) {
1316
+ const psktTransactionJson = transaction.serializeToSafeJSON();
1317
+ if (typeof psktTransactionJson !== "string") {
1318
+ throw new Error("snapshot transaction serialization did not return JSON");
1319
+ }
1320
+ return {
1321
+ schema: OUTPUT_SCHEMA,
1322
+ psktTransactionJson,
1323
+ signInputs,
1324
+ ...(scripts.length ? { scripts } : {}),
1325
+ submitTransactionSupported: true,
1326
+ metadata,
1327
+ };
1328
+ }
1329
+
1330
+ async function readPinnedArtifacts(
1331
+ pins,
1332
+ requireController,
1333
+ requireBootstrap = false,
1334
+ ) {
1335
+ const kcc20 = await readPinnedArtifact(
1336
+ KCC20_ARTIFACT_PATH,
1337
+ pins?.kcc20ArtifactSha256,
1338
+ "KCC20",
1339
+ );
1340
+ const controller = requireController
1341
+ ? await readPinnedArtifact(
1342
+ CONTROLLER_ARTIFACT_PATH,
1343
+ pins?.controllerArtifactSha256,
1344
+ "KCC20SnapshotController",
1345
+ )
1346
+ : undefined;
1347
+ const bootstrap = requireBootstrap
1348
+ ? await readPinnedArtifact(
1349
+ BOOTSTRAP_ARTIFACT_PATH,
1350
+ pins?.bootstrapArtifactSha256,
1351
+ "KCC20SnapshotBootstrap",
1352
+ )
1353
+ : undefined;
1354
+ dispatchTagFor(kcc20, "transfer");
1355
+ if (controller) dispatchTagFor(controller, "claim");
1356
+ if (bootstrap) dispatchTagFor(bootstrap, "start");
1357
+ return { kcc20, controller, bootstrap };
1358
+ }
1359
+
1360
+ async function readPinnedArtifact(path, expectedHash, contractName) {
1361
+ const expected = requireHex32(
1362
+ expectedHash,
1363
+ `${contractName} artifact hash`,
1364
+ );
1365
+ let cached = artifactCache.get(path);
1366
+ if (!cached) {
1367
+ cached = Promise.resolve(
1368
+ options.artifacts?.[path] ?? options.artifactProvider?.(path),
1369
+ ).then(async (supplied) => {
1370
+ if (!supplied)
1371
+ throw new Error(`Missing supplied snapshot artifact: ${path}`);
1372
+ const envelope =
1373
+ supplied && typeof supplied === "object" && !Array.isArray(supplied)
1374
+ ? supplied
1375
+ : undefined;
1376
+ const artifactValue = envelope?.artifact ?? supplied;
1377
+ const rawValue = envelope?.rawBytes ?? envelope?.rawText;
1378
+ const raw =
1379
+ rawValue instanceof Uint8Array
1380
+ ? rawValue
1381
+ : typeof rawValue === "string"
1382
+ ? new TextEncoder().encode(rawValue)
1383
+ : typeof supplied === "string"
1384
+ ? new TextEncoder().encode(supplied)
1385
+ : undefined;
1386
+ if (!raw) {
1387
+ throw new Error(
1388
+ `${contractName} artifact provider must include the exact raw bytes`,
1389
+ );
1390
+ }
1391
+ const parsed =
1392
+ typeof artifactValue === "string"
1393
+ ? JSON.parse(artifactValue)
1394
+ : artifactValue;
1395
+ return {
1396
+ raw,
1397
+ artifact: normalizeSilverScriptArtifact(parsed),
1398
+ };
1399
+ });
1400
+ artifactCache.set(path, cached);
1401
+ }
1402
+ const value = await cached;
1403
+ const actual = bytesToHex(sha256(value.raw));
1404
+ if (actual !== expected) {
1405
+ throw new Error(
1406
+ `${contractName} artifact does not match the migration pin`,
1407
+ );
1408
+ }
1409
+ const artifact = value.artifact;
1410
+ if (artifact.contract_name !== contractName) {
1411
+ throw new Error(`pinned artifact is not ${contractName}`);
1412
+ }
1413
+ return artifact;
1414
+ }
1415
+ function snapshotShard(value) {
1416
+ const shard = value || {};
1417
+ const normalized = {
1418
+ shardIndex: unsignedInteger(shard.shardIndex, "shard index"),
1419
+ globalIndexStart: unsignedInteger(
1420
+ shard.globalIndexStart,
1421
+ "shard global index start",
1422
+ ),
1423
+ holderCount: unsignedInteger(shard.holderCount, "shard holder count"),
1424
+ depth: unsignedInteger(shard.depth, "shard tree depth"),
1425
+ allocationTotal: positiveI64(
1426
+ shard.allocationTotal,
1427
+ "shard allocation total",
1428
+ ),
1429
+ initialRoot: requireHex32(shard.initialRoot, "shard initial root"),
1430
+ };
1431
+ if (normalized.holderCount < 1)
1432
+ throw new Error("shard must contain holders");
1433
+ if (normalized.depth < 1 || normalized.depth > 32) {
1434
+ throw new Error("shard tree depth must be 1..32");
1435
+ }
1436
+ if (normalized.holderCount > 2 ** normalized.depth) {
1437
+ throw new Error("shard holder count exceeds its Merkle width");
1438
+ }
1439
+ return normalized;
1440
+ }
1441
+
1442
+ function claimProof(value, shard) {
1443
+ const proof = value || {};
1444
+ const normalized = {
1445
+ globalIndex: unsignedInteger(proof.globalIndex, "claim global index"),
1446
+ shardIndex: unsignedInteger(proof.shardIndex, "claim shard index"),
1447
+ shardLeafIndex: unsignedInteger(
1448
+ proof.shardLeafIndex,
1449
+ "claim shard leaf index",
1450
+ ),
1451
+ ownerScheme: unsignedInteger(proof.ownerScheme, "claim owner scheme"),
1452
+ owner: requireHex32(proof.owner, "claim owner"),
1453
+ amount: positiveI64(proof.amount, "claim amount"),
1454
+ siblings: Array.isArray(proof.siblings)
1455
+ ? proof.siblings.map((value) => requireHex32(value, "proof sibling"))
1456
+ : [],
1457
+ previousRoot: requireHex32(proof.previousRoot, "proof previous root"),
1458
+ nextRoot: requireHex32(proof.nextRoot, "proof next root"),
1459
+ };
1460
+ if (
1461
+ normalized.shardIndex !== shard.shardIndex ||
1462
+ normalized.globalIndex !==
1463
+ shard.globalIndexStart + normalized.shardLeafIndex ||
1464
+ normalized.shardLeafIndex >= shard.holderCount ||
1465
+ normalized.siblings.length !== shard.depth
1466
+ ) {
1467
+ throw new Error("claim proof identity does not match the shard");
1468
+ }
1469
+ return normalized;
1470
+ }
1471
+
1472
+ function assertClaimProofRoots(proof, snapshotContext, currentRoot) {
1473
+ const context = hexToBytes(snapshotContext);
1474
+ const entitlement = hashMerkle(
1475
+ Uint8Array.of(0x10),
1476
+ context,
1477
+ leI64(proof.globalIndex),
1478
+ Uint8Array.of(proof.ownerScheme),
1479
+ hexToBytes(proof.owner),
1480
+ leI64(proof.amount),
1481
+ );
1482
+ const claimed = hashMerkle(
1483
+ Uint8Array.of(0x12),
1484
+ context,
1485
+ leI64(proof.globalIndex),
1486
+ );
1487
+ const current = foldMerkle(
1488
+ entitlement,
1489
+ proof.siblings,
1490
+ proof.shardLeafIndex,
1491
+ );
1492
+ const next = foldMerkle(claimed, proof.siblings, proof.shardLeafIndex);
1493
+ if (bytesToHex(current) !== currentRoot) {
1494
+ throw new Error(
1495
+ "claim proof does not reconstruct the current shard root",
1496
+ );
1497
+ }
1498
+ if (bytesToHex(next) !== proof.nextRoot) {
1499
+ throw new Error("claim proof next root does not match leaf retirement");
1500
+ }
1501
+ }
1502
+
1503
+ function foldMerkle(start, siblings, leafIndex) {
1504
+ let node = Uint8Array.from(start);
1505
+ let cursor = leafIndex;
1506
+ for (const siblingHex of siblings) {
1507
+ const sibling = hexToBytes(siblingHex);
1508
+ node =
1509
+ cursor % 2 === 0
1510
+ ? hashMerkle(Uint8Array.of(0x11), node, sibling)
1511
+ : hashMerkle(Uint8Array.of(0x11), sibling, node);
1512
+ cursor >>= 1;
1513
+ }
1514
+ return node;
1515
+ }
1516
+
1517
+ function hashMerkle(...parts) {
1518
+ return Uint8Array.from(blake2b(concatBytes(...parts), { dkLen: 32 }));
1519
+ }
1520
+
1521
+ function leI64(value) {
1522
+ let cursor = BigInt(value);
1523
+ const bytes = new Uint8Array(8);
1524
+ for (let index = 0; index < bytes.length; index += 1) {
1525
+ bytes[index] = Number(cursor & 0xffn);
1526
+ cursor >>= 8n;
1527
+ }
1528
+ return bytes;
1529
+ }
1530
+
1531
+ function kcc20State(value) {
1532
+ return {
1533
+ amount: positiveI64(value?.amount, "KCC20 amount"),
1534
+ owner: hexToBytes(requireHex32(value?.owner, "KCC20 owner")),
1535
+ ownerScheme: unsignedInteger(value?.ownerScheme, "KCC20 owner scheme"),
1536
+ borrowScheme: unsignedInteger(
1537
+ value?.borrowScheme ?? 0,
1538
+ "KCC20 borrow scheme",
1539
+ ),
1540
+ borrowGuard: hexToBytes(
1541
+ requireHex32(value?.borrowGuard ?? ZERO_HASH, "KCC20 borrow guard"),
1542
+ ),
1543
+ extensionCommitment: hexToBytes(
1544
+ requireHex32(value?.extensionCommitment, "KCC20 extension commitment"),
1545
+ ),
1546
+ };
1547
+ }
1548
+
1549
+ function sourceDescriptor(value, label, derivedAddress) {
1550
+ const txid = requireHex32(value?.txidHex, `${label} txid`);
1551
+ const vout = unsignedInteger(value?.vout, `${label} vout`);
1552
+ if (vout > MAX_U32) {
1553
+ throw new Error(`${label} vout must fit in uint32`);
1554
+ }
1555
+ const suppliedAddress = String(value?.address || "")
1556
+ .trim()
1557
+ .toLowerCase();
1558
+ const address =
1559
+ suppliedAddress || String(derivedAddress || "").toLowerCase();
1560
+ if (!/^(?:kaspa|kaspatest):[a-z0-9]{40,100}$/.test(address)) {
1561
+ throw new Error(`${label} address is invalid`);
1562
+ }
1563
+ if (
1564
+ suppliedAddress &&
1565
+ derivedAddress &&
1566
+ suppliedAddress !== derivedAddress
1567
+ ) {
1568
+ throw new Error(`${label} address does not match reconstructed state`);
1569
+ }
1570
+ return { txid, vout, address };
1571
+ }
1572
+
1573
+ function findExactEntry(entries, source) {
1574
+ const entry = (entries || []).find(
1575
+ (candidate) =>
1576
+ String(candidate.outpoint?.transactionId).toLowerCase() ===
1577
+ source.txid && Number(candidate.outpoint?.index) === source.vout,
1578
+ );
1579
+ if (!entry)
1580
+ throw new Error(`active UTXO ${source.txid}:${source.vout} not found`);
1581
+ return entry;
1582
+ }
1583
+
1584
+ function assertCovenantId(entry, expected, label) {
1585
+ const candidates = [
1586
+ entry?.covenantId,
1587
+ entry?.entry?.covenantId,
1588
+ entry?.utxoEntry?.covenantId,
1589
+ entry?.covenant?.covenantId,
1590
+ entry?.entry?.covenant?.covenantId,
1591
+ entry?.utxoEntry?.covenant?.covenantId,
1592
+ ].filter((value) => value !== undefined && value !== null);
1593
+ const covenantIds = candidates.map((value) =>
1594
+ String(value?.toString?.() ?? value)
1595
+ .trim()
1596
+ .toLowerCase(),
1597
+ );
1598
+ if (covenantIds.some((value) => !/^[a-f0-9]{64}$/.test(value))) {
1599
+ throw new Error(`${label} covenant ID is malformed`);
1600
+ }
1601
+ const unique = [...new Set(covenantIds)];
1602
+ if (unique.length > 1) {
1603
+ throw new Error(`${label} covenant ID fields conflict`);
1604
+ }
1605
+ const actual = unique[0] ?? "";
1606
+ if (actual !== expected)
1607
+ throw new Error(`${label} covenant ID does not match`);
1608
+ }
1609
+
1610
+ function assertCovenantSource(entry, { covenantId, script, amount, label }) {
1611
+ assertCovenantId(entry, covenantId, label);
1612
+ const expectedScriptPublicKey = String(
1613
+ kaspaWasm.payToScriptHashScript(script).script,
1614
+ ).toLowerCase();
1615
+ const actualScriptPublicKey = scriptPublicKeyHex(entry?.scriptPublicKey);
1616
+ if (actualScriptPublicKey !== expectedScriptPublicKey) {
1617
+ throw new Error(`${label} script public key does not match`);
1618
+ }
1619
+ if (utxoAmountSompi(entry) !== BigInt(amount)) {
1620
+ throw new Error(`${label} cell KAS does not match`);
1621
+ }
1622
+ }
1623
+
1624
+ function scriptPublicKeyHex(scriptPublicKey) {
1625
+ const hex = String(scriptPublicKey?.script ?? scriptPublicKey ?? "")
1626
+ .trim()
1627
+ .toLowerCase();
1628
+ if (!/^(?:[0-9a-f]{2})+$/.test(hex)) {
1629
+ throw new Error("snapshot source script public key is malformed");
1630
+ }
1631
+ return hex;
1632
+ }
1633
+
1634
+ function assertScriptPublicKey(entry, expectedHex, label) {
1635
+ if (scriptPublicKeyHex(entry?.scriptPublicKey) !== expectedHex) {
1636
+ throw new Error(`${label} script public key does not match`);
1637
+ }
1638
+ }
1639
+
1640
+ function p2shAuthorityDescriptor(value, expectedOwner, network, label) {
1641
+ const owner = requireHex32(expectedOwner, `${label} owner`);
1642
+ const revealScript = arbitraryBytes(
1643
+ value?.revealScriptHex,
1644
+ `${label} reveal script`,
1645
+ );
1646
+ const unlockPrefix = arbitraryBytes(
1647
+ value?.unlockPrefixHex ?? "",
1648
+ `${label} unlock prefix`,
1649
+ true,
1650
+ );
1651
+ const scriptPublicKey = kaspaWasm.payToScriptHashScript(revealScript);
1652
+ const scriptPublicKeyHexValue = scriptPublicKeyHex(scriptPublicKey);
1653
+ if (
1654
+ !scriptPublicKeyHexValue.match(/^aa20[0-9a-f]{64}87$/) ||
1655
+ scriptPublicKeyHexValue.slice(4, 68) !== owner
1656
+ ) {
1657
+ throw new Error(
1658
+ `${label} reveal script does not match the entitlement owner`,
1659
+ );
1660
+ }
1661
+ const address = kaspaWasm
1662
+ .addressFromScriptPublicKey(scriptPublicKey, network)
1663
+ .toString();
1664
+ const source = sourceDescriptor(value?.source, `${label} source`, address);
1665
+ return {
1666
+ owner,
1667
+ revealScript,
1668
+ unlockPrefix,
1669
+ scriptPublicKeyHex: scriptPublicKeyHexValue,
1670
+ source,
1671
+ };
1672
+ }
1673
+
1674
+ function withoutOutpoints(entries, outpoints) {
1675
+ const excluded = new Set(
1676
+ outpoints.map(
1677
+ (outpoint) =>
1678
+ `${String(outpoint?.transactionId).toLowerCase()}:${Number(outpoint?.index)}`,
1679
+ ),
1680
+ );
1681
+ return (entries || []).filter(
1682
+ (entry) =>
1683
+ !excluded.has(
1684
+ `${String(entry.outpoint?.transactionId).toLowerCase()}:${Number(entry.outpoint?.index)}`,
1685
+ ),
1686
+ );
1687
+ }
1688
+
1689
+ function appendFundingChange(
1690
+ outputs,
1691
+ inputs,
1692
+ walletAddress,
1693
+ covenantOutputSompi,
1694
+ minimumFee,
1695
+ ) {
1696
+ const inputSompi = inputs.reduce(
1697
+ (sum, entry) => sum + utxoAmountSompi(entry),
1698
+ 0n,
1699
+ );
1700
+ const change =
1701
+ BigInt(inputSompi) - BigInt(covenantOutputSompi) - BigInt(minimumFee);
1702
+ if (change <= 10_000n) {
1703
+ throw new Error("snapshot builder selected insufficient funding change");
1704
+ }
1705
+ outputs.push(
1706
+ new kaspaWasm.TransactionOutput(
1707
+ change,
1708
+ kaspaWasm.payToAddressScript(walletAddress),
1709
+ ),
1710
+ );
1711
+ return outputs.length - 1;
1712
+ }
1713
+
1714
+ function publicInput(entry, computeBudget) {
1715
+ return {
1716
+ previousOutpoint: entry.outpoint,
1717
+ utxo: entry,
1718
+ sequence: 0n,
1719
+ sigOpCount: 0,
1720
+ computeBudget,
1721
+ };
1722
+ }
1723
+
1724
+ function covenantInput(entry, computeBudget) {
1725
+ return publicInput(entry, computeBudget);
1726
+ }
1727
+
1728
+ function encodeP2sh(prefix, script) {
1729
+ return kaspaWasm.ScriptBuilder.fromScript(script, {
1730
+ flags: { covenantsEnabled: true },
1731
+ }).encodePayToScriptHashSignatureScript(prefix);
1732
+ }
1733
+
1734
+ function feeOf(transaction) {
1735
+ const inputs = [...transaction.inputs].reduce(
1736
+ (sum, input) => sum + BigInt(input.utxo?.amount ?? input.utxo?.value),
1737
+ 0n,
1738
+ );
1739
+ const outputs = [...transaction.outputs].reduce(
1740
+ (sum, output) => sum + BigInt(output.value ?? output.amount),
1741
+ 0n,
1742
+ );
1743
+ return inputs - outputs;
1744
+ }
1745
+
1746
+ function requiredRecord(value: unknown, label: string) {
1747
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1748
+ throw new Error(`${label} is required`);
1749
+ }
1750
+ return value as Record<string, unknown>;
1751
+ }
1752
+
1753
+ function signatureScriptHex(transaction, inputIndex) {
1754
+ const json = JSON.parse(transaction.serializeToSafeJSON());
1755
+ const value = json?.inputs?.[inputIndex]?.signatureScript;
1756
+ if (typeof value !== "string" || !/^(?:[0-9a-f]{2})+$/i.test(value)) {
1757
+ throw new Error(
1758
+ "snapshot transaction static signature script is invalid",
1759
+ );
1760
+ }
1761
+ return value.toLowerCase();
1762
+ }
1763
+
1764
+ function scriptAddress(script, network) {
1765
+ return kaspaWasm
1766
+ .addressFromScriptPublicKey(
1767
+ kaspaWasm.payToScriptHashScript(script),
1768
+ network,
1769
+ )
1770
+ .toString();
1771
+ }
1772
+
1773
+ function rpcFor(network) {
1774
+ return new kaspaWasm.RpcClient({
1775
+ url: config.KASPA_WRPC_URL || DEFAULT_WRPC_URL,
1776
+ encoding: kaspaWasm.Encoding.Borsh,
1777
+ networkId: network,
1778
+ });
1779
+ }
1780
+
1781
+ function networkOf(request) {
1782
+ const network = String(
1783
+ request.network || config.KASPA_NETWORK || "testnet-10",
1784
+ )
1785
+ .trim()
1786
+ .toLowerCase();
1787
+ if (!/^[a-z0-9-]{2,32}$/.test(network))
1788
+ throw new Error("network is invalid");
1789
+ return network;
1790
+ }
1791
+
1792
+ function walletAddressOf(request) {
1793
+ const address = String(request.owner?.walletAddress || "")
1794
+ .trim()
1795
+ .toLowerCase();
1796
+ if (!/^(?:kaspa|kaspatest):[a-z0-9]{40,100}$/.test(address)) {
1797
+ throw new Error("authenticated wallet address is invalid");
1798
+ }
1799
+ return address;
1800
+ }
1801
+
1802
+ function priorityFee() {
1803
+ return nonnegativeI64(
1804
+ config.KCC20_SNAPSHOT_PRIORITY_FEE_SOMPI || DEFAULT_PRIORITY_FEE,
1805
+ "snapshot priority fee",
1806
+ );
1807
+ }
1808
+
1809
+ function minimumCell(value, label) {
1810
+ const amount = positiveI64(value ?? DEFAULT_CELL_SOMPI, label);
1811
+ if (amount < DEFAULT_CELL_SOMPI) {
1812
+ throw new Error(`${label} must be at least ${DEFAULT_CELL_SOMPI}`);
1813
+ }
1814
+ return amount;
1815
+ }
1816
+
1817
+ function positiveI64(value, label) {
1818
+ let amount;
1819
+ try {
1820
+ if (typeof value === "number" && !Number.isSafeInteger(value)) {
1821
+ throw new Error("unsafe integer");
1822
+ }
1823
+ amount = BigInt(value);
1824
+ } catch {
1825
+ throw new Error(`${label} must be a positive signed 64-bit integer`);
1826
+ }
1827
+ if (amount <= 0n || amount > MAX_I64) {
1828
+ throw new Error(`${label} must be a positive signed 64-bit integer`);
1829
+ }
1830
+ return amount;
1831
+ }
1832
+
1833
+ function nonnegativeI64(value, label) {
1834
+ let amount;
1835
+ try {
1836
+ if (typeof value === "number" && !Number.isSafeInteger(value)) {
1837
+ throw new Error("unsafe integer");
1838
+ }
1839
+ amount = BigInt(value);
1840
+ } catch {
1841
+ throw new Error(`${label} must be a nonnegative signed 64-bit integer`);
1842
+ }
1843
+ if (amount < 0n || amount > MAX_I64) {
1844
+ throw new Error(`${label} must be a nonnegative signed 64-bit integer`);
1845
+ }
1846
+ return amount;
1847
+ }
1848
+
1849
+ function unsignedInteger(value, label) {
1850
+ const number = Number(value);
1851
+ if (!Number.isSafeInteger(number) || number < 0) {
1852
+ throw new Error(`${label} must be a nonnegative safe integer`);
1853
+ }
1854
+ return number;
1855
+ }
1856
+
1857
+ function dataArg(value) {
1858
+ return { type: "data", hex: bytesToHex(Uint8Array.from(value || [])) };
1859
+ }
1860
+
1861
+ function arbitraryBytes(value, label, allowEmpty = false) {
1862
+ const normalized = String(value ?? "")
1863
+ .trim()
1864
+ .toLowerCase();
1865
+ if (
1866
+ (!allowEmpty && normalized.length === 0) ||
1867
+ normalized.length % 2 !== 0
1868
+ ) {
1869
+ throw new Error(`${label} must be complete hexadecimal bytes`);
1870
+ }
1871
+ if (!/^[0-9a-f]*$/.test(normalized)) {
1872
+ throw new Error(`${label} must be complete hexadecimal bytes`);
1873
+ }
1874
+ return hexToBytes(normalized);
1875
+ }
1876
+
1877
+ function byteArg(value) {
1878
+ const number = Number(value);
1879
+ if (!Number.isInteger(number) || number < 0 || number > 255) {
1880
+ throw new Error("signature-script byte argument is invalid");
1881
+ }
1882
+ return { type: "byte", value: number };
1883
+ }
1884
+
1885
+ function i64Arg(value) {
1886
+ return { type: "i64", value: BigInt(value).toString() };
1887
+ }
1888
+
1889
+ function pushData(value) {
1890
+ const bytes = Uint8Array.from(value);
1891
+ if (bytes.length > 75)
1892
+ throw new Error("controller state push is too large");
1893
+ return concatBytes(Uint8Array.of(bytes.length), bytes);
1894
+ }
1895
+
1896
+ function i64(value) {
1897
+ let cursor = nonnegativeI64(value, "controller state integer");
1898
+ const bytes = new Uint8Array(8);
1899
+ for (let index = 0; index < 8; index += 1) {
1900
+ bytes[index] = Number(cursor & 0xffn);
1901
+ cursor >>= 8n;
1902
+ }
1903
+ return bytes;
1904
+ }
1905
+
1906
+ function concatBytes(...values) {
1907
+ const arrays = values.map((value) => Uint8Array.from(value));
1908
+ const output = new Uint8Array(
1909
+ arrays.reduce((sum, value) => sum + value.length, 0),
1910
+ );
1911
+ let offset = 0;
1912
+ for (const value of arrays) {
1913
+ output.set(value, offset);
1914
+ offset += value.length;
1915
+ }
1916
+ return output;
1917
+ }
1918
+
1919
+ return buildSnapshotMigrationPskt;
1920
+ }