@kaspacom/kcc20-tx-builder 0.4.0 → 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.
@@ -48,7 +48,6 @@ function snapshotFundingI64(value, label, allowZero) {
48
48
  }
49
49
  return amount;
50
50
  }
51
- export const SNAPSHOT_CANCEL_SINK_P2SH = "d379e50f3e2203f9a92584916335bb7cd014b237ceaa8b36f1d3d80d0cc88b32";
52
51
  export function createKcc20SnapshotPsktBuilder(options) {
53
52
  const config = options.config ?? {};
54
53
  const transactionWithCalculatedFeeChange = options.transactionWithCalculatedFeeChange;
@@ -482,804 +481,6 @@ export function createKcc20SnapshotPsktBuilder(options) {
482
481
  index: unsignedInteger(source?.vout, `${label} vout`),
483
482
  };
484
483
  }
485
- async function buildBootstrapCancellation(input) {
486
- const request = input.request || {};
487
- const params = request.params || {};
488
- const network = networkOf(request);
489
- const walletAddress = walletAddressOf(request);
490
- const artifacts = await readPinnedArtifacts(params.artifactPins, false, true);
491
- const template = templateParts(artifacts.kcc20);
492
- const base = bootstrapBaseState(params, template);
493
- const migrationId = requireHex32(params.migrationId, "migration ID");
494
- const bootstrapId = requireHex32(params.bootstrapId, "bootstrap ID");
495
- const phase = String(params.bootstrapPhase || "").toUpperCase();
496
- if (!["UNBOUND", "TOKEN_BOUND", "SEALED"].includes(phase)) {
497
- throw new Error("bootstrap cancellation phase is not terminally cancellable");
498
- }
499
- const bound = phase !== "UNBOUND";
500
- const tokenId = bound
501
- ? requireHex32(params.tokenId, "token ID")
502
- : ZERO_HASH;
503
- const beforeState = {
504
- ...base,
505
- phase: phase === "UNBOUND" ? 0n : phase === "TOKEN_BOUND" ? 1n : 2n,
506
- tokenId: hexToBytes(tokenId),
507
- shardPlanCommitment: phase === "SEALED"
508
- ? hexToBytes(requireHex32(params.bootstrapShardPlanCommitment, "bootstrap shard plan commitment"))
509
- : hexToBytes(ZERO_HASH),
510
- activationDigest: phase === "SEALED"
511
- ? hexToBytes(requireHex32(params.bootstrapActivationDigest, "bootstrap activation digest"))
512
- : hexToBytes(ZERO_HASH),
513
- shardCount: phase === "SEALED"
514
- ? positiveI64(params.bootstrapShardCount, "bootstrap shard count")
515
- : 0n,
516
- };
517
- if (beforeState.shardCount > 8n) {
518
- throw new Error("bootstrap cancellation shard count exceeds policy");
519
- }
520
- const bootstrapScript = buildSnapshotBootstrapScriptForState(artifacts.bootstrap, beforeState);
521
- const bootstrapSource = sourceDescriptor(params.bootstrapSource, "bootstrap source", scriptAddress(bootstrapScript, network));
522
- const tokenState = bound
523
- ? kcc20State(params.tokenSource?.state)
524
- : undefined;
525
- if (tokenState &&
526
- (tokenState.amount !== base.totalSupply ||
527
- tokenState.ownerScheme !== 4 ||
528
- bytesToHex(tokenState.owner) !== bootstrapId ||
529
- bytesToHex(tokenState.extensionCommitment) !==
530
- bytesToHex(base.holderExtensionCommitment))) {
531
- throw new Error("bootstrap cancellation token source does not match");
532
- }
533
- const tokenScript = tokenState
534
- ? buildKcc20ScriptForState(artifacts.kcc20, tokenState)
535
- : undefined;
536
- const tokenSource = tokenScript
537
- ? sourceDescriptor(params.tokenSource, "token source", scriptAddress(tokenScript, network))
538
- : undefined;
539
- if (!bound && params.tokenSource != null) {
540
- throw new Error("unbound bootstrap cancellation must not include a token");
541
- }
542
- const sinkTokenState = tokenState
543
- ? {
544
- amount: base.totalSupply,
545
- owner: hexToBytes(SNAPSHOT_CANCEL_SINK_P2SH),
546
- ownerScheme: 3,
547
- borrowScheme: 0,
548
- borrowGuard: hexToBytes(ZERO_HASH),
549
- extensionCommitment: base.holderExtensionCommitment,
550
- }
551
- : undefined;
552
- const sinkTokenScript = sinkTokenState
553
- ? buildKcc20ScriptForState(artifacts.kcc20, sinkTokenState)
554
- : undefined;
555
- const rpc = rpcFor(network);
556
- await rpc.connect();
557
- try {
558
- const bootstrapPromise = rpc.getUtxosByAddresses({
559
- addresses: [bootstrapSource.address],
560
- });
561
- const tokenPromise = tokenSource
562
- ? rpc.getUtxosByAddresses({ addresses: [tokenSource.address] })
563
- : Promise.resolve({ entries: [] });
564
- const [bootstrapUtxos, tokenUtxos, walletUtxos] = await Promise.all([
565
- bootstrapPromise,
566
- tokenPromise,
567
- rpc.getUtxosByAddresses({ addresses: [walletAddress] }),
568
- ]);
569
- const bootstrapEntry = findExactEntry(bootstrapUtxos.entries, bootstrapSource);
570
- assertCovenantSource(bootstrapEntry, {
571
- covenantId: bootstrapId,
572
- script: bootstrapScript,
573
- amount: base.bootstrapCellKas,
574
- label: "bootstrap cancellation source",
575
- });
576
- const tokenEntry = tokenSource
577
- ? findExactEntry(tokenUtxos.entries, tokenSource)
578
- : undefined;
579
- if (tokenEntry) {
580
- assertCovenantSource(tokenEntry, {
581
- covenantId: tokenId,
582
- script: tokenScript,
583
- amount: base.tokenCellKas,
584
- label: "bootstrap cancellation token",
585
- });
586
- }
587
- const consumed = [bootstrapEntry, ...(tokenEntry ? [tokenEntry] : [])];
588
- const fundingEntry = selectFundingEntry(withoutOutpoints(walletUtxos.entries, consumed.map(({ outpoint }) => outpoint)), priorityFee() + 10000n, [], params.fundingOutpoint);
589
- const outputs = [];
590
- if (sinkTokenScript) {
591
- outputs.push(new kaspaWasm.TransactionOutput(base.tokenCellKas, kaspaWasm.payToScriptHashScript(sinkTokenScript), new kaspaWasm.CovenantBinding(1, new kaspaWasm.Hash(tokenId))));
592
- }
593
- const sinkOutputIndex = outputs.length;
594
- outputs.push(new kaspaWasm.TransactionOutput(base.bootstrapCellKas, kaspaWasm.payToScriptHashScript(Uint8Array.of(0x6a))));
595
- const fundingChangeOutputIndex = appendFundingChange(outputs, [...consumed, fundingEntry], walletAddress, base.bootstrapCellKas + (bound ? base.tokenCellKas : 0n), priorityFee());
596
- const inputs = [
597
- covenantInput(bootstrapEntry, BOOTSTRAP_COMPUTE_BUDGET),
598
- ...(tokenEntry
599
- ? [covenantInput(tokenEntry, KCC20_COMPUTE_BUDGET)]
600
- : []),
601
- publicInput(fundingEntry, PUBLIC_INPUT_COMPUTE_BUDGET),
602
- ];
603
- const transaction = new kaspaWasm.Transaction({
604
- version: 1,
605
- lockTime: 0n,
606
- inputs,
607
- outputs,
608
- subnetworkId: NATIVE_SUBNETWORK_ID,
609
- gas: 0n,
610
- payload: "",
611
- });
612
- setVersionOneInputMassFields(transaction, PUBLIC_INPUT_COMPUTE_BUDGET);
613
- transaction.inputs[0].computeBudget = BOOTSTRAP_COMPUTE_BUDGET;
614
- if (tokenEntry) {
615
- transaction.inputs[1].computeBudget = KCC20_COMPUTE_BUDGET;
616
- }
617
- const recipes = bootstrapApprovalRecipes(bytesToHex(bootstrapScript), bootstrapCancellationArgs(artifacts, bound, sinkOutputIndex, sinkTokenState));
618
- transaction.inputs[0].signatureScript = encodeP2sh(signatureScriptArgsBytes(recipes.placeholder.args), bootstrapScript);
619
- if (tokenEntry && tokenScript && sinkTokenState) {
620
- transaction.inputs[1].signatureScript = encodeP2sh(buildKcc20TransferSigScript(kaspaWasm, artifacts.kcc20, {
621
- nextStates: [sinkTokenState],
622
- witness: Uint8Array.of(0),
623
- }), tokenScript);
624
- }
625
- const fundingInputIndex = inputs.length - 1;
626
- const adjusted = transactionWithCalculatedFeeChange(kaspaWasm, transaction, fundingChangeOutputIndex, network, "snapshot bootstrap cancellation", [recipes.approval]);
627
- return outputEnvelope(adjusted, [{ index: fundingInputIndex }], [recipes.approval], {
628
- migrationId,
629
- stage: "bootstrap-cancel",
630
- bootstrapId,
631
- ...(bound ? { tokenId } : {}),
632
- cancellationMode: bound ? "BOUND" : "UNBOUND",
633
- cancellationSinkP2sh: SNAPSHOT_CANCEL_SINK_P2SH,
634
- bootstrapState: {
635
- ...bootstrapStateReceipt(beforeState),
636
- phase,
637
- },
638
- bootstrapOutcome: "CANCELLED",
639
- maximumFeeSompi: feeOf(adjusted).toString(),
640
- intentInputs: [
641
- {
642
- role: "snapshot-bootstrap",
643
- index: 0,
644
- covenantId: bootstrapId,
645
- revealScriptHex: bytesToHex(bootstrapScript),
646
- },
647
- ...(tokenEntry && tokenScript
648
- ? [
649
- {
650
- role: "fixed-supply-token",
651
- index: 1,
652
- covenantId: tokenId,
653
- revealScriptHex: bytesToHex(tokenScript),
654
- staticSignatureScriptHex: signatureScriptHex(adjusted, 1),
655
- },
656
- ]
657
- : []),
658
- { role: "creator-funding", index: fundingInputIndex },
659
- ],
660
- intentOutputs: [
661
- ...(sinkTokenScript && sinkTokenState
662
- ? [
663
- {
664
- role: "cancelled-token",
665
- index: 0,
666
- covenantId: tokenId,
667
- revealScriptHex: bytesToHex(sinkTokenScript),
668
- owner: SNAPSHOT_CANCEL_SINK_P2SH,
669
- ownerScheme: 3,
670
- borrowScheme: 0,
671
- borrowGuard: ZERO_HASH,
672
- extensionCommitment: bytesToHex(sinkTokenState.extensionCommitment),
673
- tokenAmount: sinkTokenState.amount.toString(),
674
- },
675
- ]
676
- : []),
677
- {
678
- role: "cancellation-sink",
679
- index: sinkOutputIndex,
680
- revealScriptHex: "6a",
681
- },
682
- ],
683
- });
684
- }
685
- finally {
686
- await rpc.disconnect();
687
- }
688
- }
689
- async function buildBootstrapBind(input) {
690
- const request = input.request || {};
691
- const params = request.params || {};
692
- const network = networkOf(request);
693
- const walletAddress = walletAddressOf(request);
694
- const artifacts = await readPinnedArtifacts(params.artifactPins, false, true);
695
- const template = templateParts(artifacts.kcc20);
696
- const base = bootstrapBaseState(params, template);
697
- const bootstrapId = requireHex32(params.bootstrapId, "bootstrap ID");
698
- const tokenId = requireHex32(params.tokenId, "token ID");
699
- const tokenState = kcc20State(params.tokenSource?.state);
700
- if (tokenState.amount !== base.totalSupply ||
701
- tokenState.ownerScheme !== 4 ||
702
- bytesToHex(tokenState.owner) !== bootstrapId ||
703
- bytesToHex(tokenState.extensionCommitment) !==
704
- bytesToHex(base.holderExtensionCommitment)) {
705
- throw new Error("bootstrap bind token source does not match the migration");
706
- }
707
- const beforeState = {
708
- ...base,
709
- phase: 0n,
710
- tokenId: hexToBytes(ZERO_HASH),
711
- shardPlanCommitment: hexToBytes(ZERO_HASH),
712
- activationDigest: hexToBytes(ZERO_HASH),
713
- shardCount: 0n,
714
- };
715
- const afterState = {
716
- ...base,
717
- phase: 1n,
718
- tokenId: hexToBytes(tokenId),
719
- shardPlanCommitment: hexToBytes(ZERO_HASH),
720
- activationDigest: hexToBytes(ZERO_HASH),
721
- shardCount: 0n,
722
- };
723
- const bootstrapScript = buildSnapshotBootstrapScriptForState(artifacts.bootstrap, beforeState);
724
- const nextBootstrapScript = buildSnapshotBootstrapScriptForState(artifacts.bootstrap, afterState);
725
- const tokenScript = buildKcc20ScriptForState(artifacts.kcc20, tokenState);
726
- const bootstrapSource = sourceDescriptor(params.bootstrapSource, "bootstrap source", scriptAddress(bootstrapScript, network));
727
- const tokenSource = sourceDescriptor(params.tokenSource, "token source", scriptAddress(tokenScript, network));
728
- const rpc = rpcFor(network);
729
- await rpc.connect();
730
- try {
731
- const [bootstrapUtxos, tokenUtxos, walletUtxos] = await Promise.all([
732
- rpc.getUtxosByAddresses({ addresses: [bootstrapSource.address] }),
733
- rpc.getUtxosByAddresses({ addresses: [tokenSource.address] }),
734
- rpc.getUtxosByAddresses({ addresses: [walletAddress] }),
735
- ]);
736
- const bootstrapEntry = findExactEntry(bootstrapUtxos.entries, bootstrapSource);
737
- assertCovenantSource(bootstrapEntry, {
738
- covenantId: bootstrapId,
739
- script: bootstrapScript,
740
- amount: base.bootstrapCellKas,
741
- label: "bootstrap bind source",
742
- });
743
- const tokenEntry = findExactEntry(tokenUtxos.entries, tokenSource);
744
- assertCovenantSource(tokenEntry, {
745
- covenantId: tokenId,
746
- script: tokenScript,
747
- amount: base.tokenCellKas,
748
- label: "bootstrap bind token source",
749
- });
750
- const fundingEntry = selectFundingEntry(withoutOutpoints(walletUtxos.entries, [
751
- bootstrapEntry.outpoint,
752
- tokenEntry.outpoint,
753
- ]), priorityFee() + 10000n, [], params.fundingOutpoint);
754
- const outputs = [
755
- new kaspaWasm.TransactionOutput(base.tokenCellKas, kaspaWasm.payToScriptHashScript(tokenScript), new kaspaWasm.CovenantBinding(1, new kaspaWasm.Hash(tokenId))),
756
- new kaspaWasm.TransactionOutput(base.bootstrapCellKas, kaspaWasm.payToScriptHashScript(nextBootstrapScript), new kaspaWasm.CovenantBinding(0, new kaspaWasm.Hash(bootstrapId))),
757
- ];
758
- const fundingChangeOutputIndex = appendFundingChange(outputs, [bootstrapEntry, tokenEntry, fundingEntry], walletAddress, base.tokenCellKas + base.bootstrapCellKas, priorityFee());
759
- const transaction = new kaspaWasm.Transaction({
760
- version: 1,
761
- lockTime: 0n,
762
- inputs: [
763
- covenantInput(bootstrapEntry, BOOTSTRAP_COMPUTE_BUDGET),
764
- covenantInput(tokenEntry, KCC20_COMPUTE_BUDGET),
765
- publicInput(fundingEntry, PUBLIC_INPUT_COMPUTE_BUDGET),
766
- ],
767
- outputs,
768
- subnetworkId: NATIVE_SUBNETWORK_ID,
769
- gas: 0n,
770
- payload: "",
771
- });
772
- setVersionOneInputMassFields(transaction, PUBLIC_INPUT_COMPUTE_BUDGET);
773
- transaction.inputs[0].computeBudget = BOOTSTRAP_COMPUTE_BUDGET;
774
- transaction.inputs[1].computeBudget = KCC20_COMPUTE_BUDGET;
775
- const recipes = bootstrapApprovalRecipes(bytesToHex(bootstrapScript), bootstrapBindArgs(artifacts, afterState, tokenState));
776
- transaction.inputs[0].signatureScript = encodeP2sh(signatureScriptArgsBytes(recipes.placeholder.args), bootstrapScript);
777
- transaction.inputs[1].signatureScript = encodeP2sh(buildKcc20TransferSigScript(kaspaWasm, artifacts.kcc20, {
778
- nextStates: [tokenState],
779
- witness: Uint8Array.of(0),
780
- }), tokenScript);
781
- const adjusted = transactionWithCalculatedFeeChange(kaspaWasm, transaction, fundingChangeOutputIndex, network, "snapshot bootstrap bind", [recipes.approval]);
782
- return outputEnvelope(adjusted, [{ index: 2 }], [recipes.approval], {
783
- migrationId: requireHex32(params.migrationId, "migration ID"),
784
- stage: "bootstrap-bind",
785
- tokenId,
786
- bootstrapId,
787
- bootstrapState: {
788
- ...bootstrapStateReceipt(afterState),
789
- phase: "TOKEN_BOUND",
790
- },
791
- maximumFeeSompi: feeOf(adjusted).toString(),
792
- intentInputs: [
793
- {
794
- role: "snapshot-bootstrap",
795
- index: 0,
796
- covenantId: bootstrapId,
797
- revealScriptHex: bytesToHex(bootstrapScript),
798
- },
799
- {
800
- role: "fixed-supply-token",
801
- index: 1,
802
- covenantId: tokenId,
803
- revealScriptHex: bytesToHex(tokenScript),
804
- staticSignatureScriptHex: signatureScriptHex(adjusted, 1),
805
- },
806
- { role: "creator-funding", index: 2 },
807
- ],
808
- intentOutputs: [
809
- {
810
- role: "fixed-supply-token",
811
- index: 0,
812
- covenantId: tokenId,
813
- revealScriptHex: bytesToHex(tokenScript),
814
- owner: bootstrapId,
815
- ownerScheme: 4,
816
- borrowScheme: 0,
817
- borrowGuard: bytesToHex(tokenState.borrowGuard),
818
- extensionCommitment: bytesToHex(tokenState.extensionCommitment),
819
- tokenAmount: tokenState.amount.toString(),
820
- },
821
- {
822
- role: "snapshot-bootstrap",
823
- index: 1,
824
- covenantId: bootstrapId,
825
- revealScriptHex: bytesToHex(nextBootstrapScript),
826
- },
827
- ],
828
- });
829
- }
830
- finally {
831
- await rpc.disconnect();
832
- }
833
- }
834
- async function buildBootstrapSeal(input) {
835
- const request = input.request || {};
836
- const params = request.params || {};
837
- const network = networkOf(request);
838
- const walletAddress = walletAddressOf(request);
839
- const artifacts = await readPinnedArtifacts(params.artifactPins, false, true);
840
- const template = templateParts(artifacts.kcc20);
841
- const base = bootstrapBaseState(params, template);
842
- const migrationId = requireHex32(params.migrationId, "migration ID");
843
- const bootstrapId = requireHex32(params.bootstrapId, "bootstrap ID");
844
- const tokenId = requireHex32(params.tokenId, "token ID");
845
- const shards = reserveShards(params.shards, base.totalSupply);
846
- const shardPlanCommitment = snapshotShardPlanCommitment({
847
- migrationCommitment: migrationId,
848
- manifestCommitment: bytesToHex(base.manifestCommitment),
849
- tokenId,
850
- totalSupply: base.totalSupply,
851
- shards,
852
- });
853
- const beforeState = {
854
- ...base,
855
- phase: 1n,
856
- tokenId: hexToBytes(tokenId),
857
- shardPlanCommitment: hexToBytes(ZERO_HASH),
858
- activationDigest: hexToBytes(ZERO_HASH),
859
- shardCount: 0n,
860
- };
861
- const afterState = {
862
- ...base,
863
- phase: 2n,
864
- tokenId: hexToBytes(tokenId),
865
- shardPlanCommitment: hexToBytes(shardPlanCommitment),
866
- activationDigest: hexToBytes(requireHex32(params.activationDigest, "activation digest")),
867
- shardCount: BigInt(shards.length),
868
- };
869
- const bootstrapScript = buildSnapshotBootstrapScriptForState(artifacts.bootstrap, beforeState);
870
- const nextBootstrapScript = buildSnapshotBootstrapScriptForState(artifacts.bootstrap, afterState);
871
- const bootstrapSource = sourceDescriptor(params.bootstrapSource, "bootstrap source", scriptAddress(bootstrapScript, network));
872
- const rpc = rpcFor(network);
873
- await rpc.connect();
874
- try {
875
- const [bootstrapUtxos, walletUtxos] = await Promise.all([
876
- rpc.getUtxosByAddresses({ addresses: [bootstrapSource.address] }),
877
- rpc.getUtxosByAddresses({ addresses: [walletAddress] }),
878
- ]);
879
- const bootstrapEntry = findExactEntry(bootstrapUtxos.entries, bootstrapSource);
880
- assertCovenantSource(bootstrapEntry, {
881
- covenantId: bootstrapId,
882
- script: bootstrapScript,
883
- amount: base.bootstrapCellKas,
884
- label: "bootstrap seal source",
885
- });
886
- const fundingEntry = selectFundingEntry(withoutOutpoints(walletUtxos.entries, [bootstrapEntry.outpoint]), priorityFee() + 10000n, [], params.fundingOutpoint);
887
- const outputs = [
888
- new kaspaWasm.TransactionOutput(base.bootstrapCellKas, kaspaWasm.payToScriptHashScript(nextBootstrapScript), new kaspaWasm.CovenantBinding(0, new kaspaWasm.Hash(bootstrapId))),
889
- ];
890
- const fundingChangeOutputIndex = appendFundingChange(outputs, [bootstrapEntry, fundingEntry], walletAddress, base.bootstrapCellKas, priorityFee());
891
- const transaction = new kaspaWasm.Transaction({
892
- version: 1,
893
- lockTime: 0n,
894
- inputs: [
895
- covenantInput(bootstrapEntry, BOOTSTRAP_COMPUTE_BUDGET),
896
- publicInput(fundingEntry, PUBLIC_INPUT_COMPUTE_BUDGET),
897
- ],
898
- outputs,
899
- subnetworkId: NATIVE_SUBNETWORK_ID,
900
- gas: 0n,
901
- payload: "",
902
- });
903
- setVersionOneInputMassFields(transaction, PUBLIC_INPUT_COMPUTE_BUDGET);
904
- transaction.inputs[0].computeBudget = BOOTSTRAP_COMPUTE_BUDGET;
905
- const recipes = bootstrapApprovalRecipes(bytesToHex(bootstrapScript), bootstrapSealArgs(artifacts, afterState));
906
- transaction.inputs[0].signatureScript = encodeP2sh(signatureScriptArgsBytes(recipes.placeholder.args), bootstrapScript);
907
- const adjusted = transactionWithCalculatedFeeChange(kaspaWasm, transaction, fundingChangeOutputIndex, network, "snapshot bootstrap seal", [recipes.approval]);
908
- return outputEnvelope(adjusted, [{ index: 1 }], [recipes.approval], {
909
- migrationId,
910
- stage: "bootstrap-seal",
911
- tokenId,
912
- bootstrapId,
913
- bootstrapState: {
914
- ...bootstrapStateReceipt(afterState),
915
- phase: "SEALED",
916
- },
917
- shardPlanCommitment,
918
- activationDigest: bytesToHex(afterState.activationDigest),
919
- shards: shards.map((shard) => shard.shardIndex),
920
- maximumFeeSompi: feeOf(adjusted).toString(),
921
- intentInputs: [
922
- {
923
- role: "snapshot-bootstrap",
924
- index: 0,
925
- covenantId: bootstrapId,
926
- revealScriptHex: bytesToHex(bootstrapScript),
927
- },
928
- { role: "creator-funding", index: 1 },
929
- ],
930
- intentOutputs: [
931
- {
932
- role: "snapshot-bootstrap",
933
- index: 0,
934
- covenantId: bootstrapId,
935
- revealScriptHex: bytesToHex(nextBootstrapScript),
936
- },
937
- ],
938
- });
939
- }
940
- finally {
941
- await rpc.disconnect();
942
- }
943
- }
944
- async function buildBootstrapGenesis(input) {
945
- const request = input.request || {};
946
- const params = request.params || {};
947
- const network = networkOf(request);
948
- const walletAddress = walletAddressOf(request);
949
- const [kcc20, bootstrap] = await Promise.all([
950
- readPinnedArtifact(KCC20_ARTIFACT_PATH, params.artifactPins?.kcc20ArtifactSha256, "KCC20"),
951
- readPinnedArtifact(BOOTSTRAP_ARTIFACT_PATH, params.artifactPins?.bootstrapArtifactSha256, "KCC20SnapshotBootstrap"),
952
- ]);
953
- const template = templateParts(kcc20);
954
- const expectedTemplateHash = requireHex32(params.expectedKcc20TemplateHash, "KCC20 template hash");
955
- if (bytesToHex(template.hash) !== expectedTemplateHash) {
956
- throw new Error("KCC20 template hash does not match the migration pin");
957
- }
958
- const approvalKey = requireHex32(params.approvalKey ?? params.approvalKeyA, "approval key");
959
- if (approvalKey === ZERO_HASH) {
960
- throw new Error("bootstrap approval key must be nonzero");
961
- }
962
- const state = {
963
- migrationCommitment: hexToBytes(requireHex32(params.migrationCommitment, "migration commitment")),
964
- manifestCommitment: hexToBytes(requireHex32(params.manifestCommitment, "manifest commitment")),
965
- holderExtensionCommitment: hexToBytes(requireHex32(params.holderExtensionCommitment, "holder extension commitment")),
966
- totalSupply: positiveI64(params.totalSupply, "total supply"),
967
- claimNotBeforeDaaScore: positiveI64(params.claimNotBeforeDaaScore, "claim-not-before DAA score"),
968
- kcc20TemplateHash: hexToBytes(expectedTemplateHash),
969
- kcc20TemplatePrefixLen: BigInt(template.prefix.length),
970
- kcc20TemplateSuffixLen: BigInt(template.suffix.length),
971
- tokenCellKas: minimumCell(params.tokenCellKas, "token cell KAS"),
972
- reserveCellKas: minimumCell(params.reserveCellKas, "reserve cell KAS"),
973
- bootstrapCellKas: minimumCell(params.bootstrapCellKas, "bootstrap cell KAS"),
974
- approvalKey: hexToBytes(approvalKey),
975
- phase: 0n,
976
- tokenId: hexToBytes(ZERO_HASH),
977
- shardPlanCommitment: hexToBytes(ZERO_HASH),
978
- activationDigest: hexToBytes(ZERO_HASH),
979
- shardCount: 0n,
980
- };
981
- if (state.claimNotBeforeDaaScore >= 500000000000n) {
982
- throw new Error("claim-not-before must use DAA-score locktime mode");
983
- }
984
- const bootstrapScript = buildSnapshotBootstrapScriptForState(bootstrap, state);
985
- const rpc = rpcFor(network);
986
- await rpc.connect();
987
- try {
988
- const walletUtxos = await rpc.getUtxosByAddresses({
989
- addresses: [walletAddress],
990
- });
991
- const fundingEntry = selectFundingEntry(walletUtxos.entries, state.bootstrapCellKas + priorityFee() + 10000n, [], params.fundingOutpoint);
992
- const outputs = [
993
- new kaspaWasm.TransactionOutput(state.bootstrapCellKas, kaspaWasm.payToScriptHashScript(bootstrapScript)),
994
- ];
995
- const changeIndex = appendFundingChange(outputs, [fundingEntry], walletAddress, state.bootstrapCellKas, priorityFee());
996
- const stateReceipt = bootstrapStateReceipt(state);
997
- const transaction = new kaspaWasm.Transaction({
998
- version: 1,
999
- lockTime: 0n,
1000
- inputs: [publicInput(fundingEntry, PUBLIC_INPUT_COMPUTE_BUDGET)],
1001
- outputs,
1002
- subnetworkId: NATIVE_SUBNETWORK_ID,
1003
- gas: 0n,
1004
- payload: bytesToHex(new TextEncoder().encode(JSON.stringify({
1005
- tn10: {
1006
- v: 1,
1007
- tmpl: "KCC20SnapshotBootstrap",
1008
- args: [
1009
- {
1010
- name: "bootstrapState",
1011
- type: "object",
1012
- value: stateReceipt,
1013
- },
1014
- ],
1015
- },
1016
- }))),
1017
- });
1018
- setVersionOneInputMassFields(transaction, PUBLIC_INPUT_COMPUTE_BUDGET);
1019
- transaction.populateGenesisCovenants([
1020
- new kaspaWasm.GenesisCovenantGroup(0, [0]),
1021
- ]);
1022
- transaction.finalize();
1023
- const covenantId = requireHex32(transaction.outputs[0]?.covenant?.covenantId?.toString(), "bootstrap covenant id");
1024
- const adjusted = transactionWithCalculatedFeeChange(kaspaWasm, transaction, changeIndex, network, "snapshot bootstrap genesis");
1025
- return outputEnvelope(adjusted, [{ index: 0 }], [], {
1026
- migrationId: requireHex32(params.migrationId, "migration id"),
1027
- stage: "bootstrap-deploy",
1028
- covenantId,
1029
- bootstrapState: { ...stateReceipt, phase: "UNBOUND" },
1030
- maximumFeeSompi: feeOf(adjusted).toString(),
1031
- intentInputs: [{ role: "creator-funding", index: 0 }],
1032
- intentOutputs: [
1033
- {
1034
- role: "snapshot-bootstrap",
1035
- index: 0,
1036
- covenantId,
1037
- revealScriptHex: bytesToHex(bootstrapScript),
1038
- },
1039
- ],
1040
- });
1041
- }
1042
- finally {
1043
- await rpc.disconnect();
1044
- }
1045
- }
1046
- async function buildControllerGenesis(input) {
1047
- const request = input.request || {};
1048
- const params = request.params || {};
1049
- const network = networkOf(request);
1050
- const walletAddress = walletAddressOf(request);
1051
- const artifacts = await readPinnedArtifacts(params.artifactPins, true);
1052
- const definition = snapshotDefinition(params, artifacts);
1053
- const controllerState = initialControllerState(definition);
1054
- const controllerScript = buildSnapshotControllerScriptForState(artifacts.controller, controllerState);
1055
- const outputSompi = definition.controllerCellKas;
1056
- const rpc = rpcFor(network);
1057
- await rpc.connect();
1058
- try {
1059
- const walletUtxos = await rpc.getUtxosByAddresses({
1060
- addresses: [walletAddress],
1061
- });
1062
- const fundingEntry = selectFundingEntry(walletUtxos.entries, outputSompi + priorityFee() + 10000n, [], params.fundingOutpoint);
1063
- const outputs = [
1064
- new kaspaWasm.TransactionOutput(outputSompi, kaspaWasm.payToScriptHashScript(controllerScript)),
1065
- ];
1066
- const fundingChangeOutputIndex = appendFundingChange(outputs, [fundingEntry], walletAddress, outputSompi, priorityFee());
1067
- const transaction = new kaspaWasm.Transaction({
1068
- version: 1,
1069
- lockTime: 0n,
1070
- inputs: [publicInput(fundingEntry, PUBLIC_INPUT_COMPUTE_BUDGET)],
1071
- outputs,
1072
- subnetworkId: NATIVE_SUBNETWORK_ID,
1073
- gas: 0n,
1074
- payload: controllerDeploymentPayload(definition, controllerState),
1075
- });
1076
- setVersionOneInputMassFields(transaction, PUBLIC_INPUT_COMPUTE_BUDGET);
1077
- transaction.populateGenesisCovenants([
1078
- new kaspaWasm.GenesisCovenantGroup(0, [0]),
1079
- ]);
1080
- transaction.finalize();
1081
- const controllerId = requireHex32(transaction.outputs[0]?.covenant?.covenantId?.toString(), "controller covenant id");
1082
- const adjusted = transactionWithCalculatedFeeChange(kaspaWasm, transaction, fundingChangeOutputIndex, network, "snapshot controller genesis");
1083
- return outputEnvelope(adjusted, [{ index: 0 }], [], {
1084
- migrationId: definition.migrationId,
1085
- stage: "controller-deploy",
1086
- controllerId,
1087
- shard: definition.shard.shardIndex,
1088
- controllerStateCommitment: snapshotControllerStateCommitment(controllerState),
1089
- holderExtensionCommitment: definition.holderExtensionCommitment,
1090
- maximumFeeSompi: feeOf(adjusted).toString(),
1091
- intentInputs: [{ role: "creator-funding", index: 0 }],
1092
- intentOutputs: [
1093
- {
1094
- role: "snapshot-controller",
1095
- index: 0,
1096
- shard: definition.shard.shardIndex,
1097
- covenantId: controllerId,
1098
- revealScriptHex: bytesToHex(controllerScript),
1099
- },
1100
- ],
1101
- });
1102
- }
1103
- finally {
1104
- await rpc.disconnect();
1105
- }
1106
- }
1107
- async function buildReserveHandoff(input) {
1108
- const request = input.request || {};
1109
- const params = request.params || {};
1110
- const network = networkOf(request);
1111
- const walletAddress = walletAddressOf(request);
1112
- const migrationId = requireHex32(params.migrationId, "migration id");
1113
- const artifacts = await readPinnedArtifacts(params.artifactPins, false, true);
1114
- const bootstrapId = requireHex32(params.bootstrapId, "bootstrap covenant id");
1115
- const tokenId = requireHex32(params.tokenId, "token covenant id");
1116
- const extensionCommitment = requireHex32(params.holderExtensionCommitment, "holder extension commitment");
1117
- const totalSupply = positiveI64(params.totalSupply, "total supply");
1118
- const tokenState = kcc20State(params.tokenSource?.state);
1119
- if (tokenState.amount !== totalSupply ||
1120
- tokenState.ownerScheme !== 4 ||
1121
- bytesToHex(tokenState.owner) !== bootstrapId ||
1122
- bytesToHex(tokenState.extensionCommitment) !== extensionCommitment) {
1123
- throw new Error("reserve handoff token source does not match the migration");
1124
- }
1125
- const shards = reserveShards(params.shards, totalSupply);
1126
- const template = templateParts(artifacts.kcc20);
1127
- const expectedTemplateHash = requireHex32(params.kcc20TemplateHash, "KCC20 template hash");
1128
- if (bytesToHex(template.hash) !== expectedTemplateHash) {
1129
- throw new Error("KCC20 template hash does not match the migration pin");
1130
- }
1131
- const shardPlanCommitment = snapshotShardPlanCommitment({
1132
- migrationCommitment: migrationId,
1133
- manifestCommitment: requireHex32(params.manifestCommitment, "manifest commitment"),
1134
- tokenId,
1135
- totalSupply,
1136
- shards,
1137
- });
1138
- if (shardPlanCommitment !==
1139
- requireHex32(params.bootstrapShardPlanCommitment, "bootstrap shard plan commitment")) {
1140
- throw new Error("activation shards do not match the sealed bootstrap");
1141
- }
1142
- const bootstrapState = {
1143
- migrationCommitment: hexToBytes(migrationId),
1144
- manifestCommitment: hexToBytes(requireHex32(params.manifestCommitment, "manifest commitment")),
1145
- holderExtensionCommitment: hexToBytes(extensionCommitment),
1146
- totalSupply,
1147
- claimNotBeforeDaaScore: positiveI64(params.claimNotBeforeDaaScore, "claim-not-before DAA score"),
1148
- kcc20TemplateHash: hexToBytes(expectedTemplateHash),
1149
- kcc20TemplatePrefixLen: BigInt(template.prefix.length),
1150
- kcc20TemplateSuffixLen: BigInt(template.suffix.length),
1151
- tokenCellKas: minimumCell(params.tokenCellKas, "token cell KAS"),
1152
- reserveCellKas: minimumCell(params.reserveCellKas, "reserve cell KAS"),
1153
- bootstrapCellKas: minimumCell(params.bootstrapCellKas, "bootstrap cell KAS"),
1154
- approvalKey: hexToBytes(requireHex32(params.approvalKey ?? params.approvalKeyA, "approval key")),
1155
- phase: 2n,
1156
- tokenId: hexToBytes(tokenId),
1157
- shardPlanCommitment: hexToBytes(shardPlanCommitment),
1158
- activationDigest: hexToBytes(requireHex32(params.bootstrapActivationDigest, "bootstrap activation digest")),
1159
- shardCount: BigInt(shards.length),
1160
- };
1161
- const bootstrapScript = buildSnapshotBootstrapScriptForState(artifacts.bootstrap, bootstrapState);
1162
- const bootstrapAddress = scriptAddress(bootstrapScript, network);
1163
- const bootstrapSource = sourceDescriptor(params.bootstrapSource, "bootstrap source", bootstrapAddress);
1164
- const tokenScript = buildKcc20ScriptForState(artifacts.kcc20, tokenState);
1165
- const tokenAddress = scriptAddress(tokenScript, network);
1166
- const tokenSource = sourceDescriptor(params.tokenSource, "token source", tokenAddress);
1167
- const nextStates = shards.map((shard) => ({
1168
- amount: shard.allocationTotal,
1169
- owner: hexToBytes(shard.controllerId),
1170
- ownerScheme: 4,
1171
- borrowScheme: 0,
1172
- borrowGuard: hexToBytes(ZERO_HASH),
1173
- extensionCommitment: hexToBytes(extensionCommitment),
1174
- }));
1175
- const rpc = rpcFor(network);
1176
- await rpc.connect();
1177
- try {
1178
- const [bootstrapUtxos, tokenUtxos, walletUtxos] = await Promise.all([
1179
- rpc.getUtxosByAddresses({ addresses: [bootstrapAddress] }),
1180
- rpc.getUtxosByAddresses({ addresses: [tokenAddress] }),
1181
- rpc.getUtxosByAddresses({ addresses: [walletAddress] }),
1182
- ]);
1183
- const bootstrapEntry = findExactEntry(bootstrapUtxos.entries, bootstrapSource);
1184
- assertCovenantSource(bootstrapEntry, {
1185
- covenantId: bootstrapId,
1186
- script: bootstrapScript,
1187
- amount: bootstrapState.bootstrapCellKas,
1188
- label: "reserve activation bootstrap source",
1189
- });
1190
- const tokenEntry = findExactEntry(tokenUtxos.entries, tokenSource);
1191
- assertCovenantSource(tokenEntry, {
1192
- covenantId: tokenId,
1193
- script: tokenScript,
1194
- amount: bootstrapState.tokenCellKas,
1195
- label: "reserve handoff token source",
1196
- });
1197
- const fundingEntry = selectFundingEntry(withoutOutpoints(walletUtxos.entries, [
1198
- bootstrapEntry.outpoint,
1199
- tokenEntry.outpoint,
1200
- ]), priorityFee() + DEFAULT_CELL_SOMPI * BigInt(shards.length) + 10000n, [], params.fundingOutpoint);
1201
- const outputs = nextStates.map((state) => new kaspaWasm.TransactionOutput(positiveI64(params.reserveCellKas ?? DEFAULT_CELL_SOMPI, "reserve cell KAS"), kaspaWasm.payToScriptHashScript(buildKcc20ScriptForState(artifacts.kcc20, state)), new kaspaWasm.CovenantBinding(1, new kaspaWasm.Hash(tokenId))));
1202
- const outputSompi = outputs.reduce((sum, output) => sum + BigInt(output.value), 0n);
1203
- const fundingChangeOutputIndex = appendFundingChange(outputs, [bootstrapEntry, tokenEntry, fundingEntry], walletAddress, outputSompi, priorityFee());
1204
- const transaction = new kaspaWasm.Transaction({
1205
- version: 1,
1206
- lockTime: 0n,
1207
- inputs: [
1208
- covenantInput(bootstrapEntry, BOOTSTRAP_COMPUTE_BUDGET),
1209
- covenantInput(tokenEntry, KCC20_COMPUTE_BUDGET),
1210
- publicInput(fundingEntry, PUBLIC_INPUT_COMPUTE_BUDGET),
1211
- ],
1212
- outputs,
1213
- subnetworkId: NATIVE_SUBNETWORK_ID,
1214
- gas: 0n,
1215
- payload: "",
1216
- });
1217
- setVersionOneInputMassFields(transaction, PUBLIC_INPUT_COMPUTE_BUDGET);
1218
- transaction.inputs[0].computeBudget = BOOTSTRAP_COMPUTE_BUDGET;
1219
- transaction.inputs[1].computeBudget = KCC20_COMPUTE_BUDGET;
1220
- const bootstrapPrefix = new kaspaWasm.ScriptBuilder();
1221
- for (const field of encodeKcc20StateRecordArrays(nextStates)) {
1222
- bootstrapPrefix.addData(field);
1223
- }
1224
- bootstrapPrefix.addData(template.prefix);
1225
- bootstrapPrefix.addData(template.suffix);
1226
- bootstrapPrefix.addData(dispatchTagFor(artifacts.bootstrap, "activate"));
1227
- transaction.inputs[0].signatureScript = encodeP2sh(bootstrapPrefix.drain(), bootstrapScript);
1228
- transaction.inputs[1].signatureScript = encodeP2sh(buildKcc20TransferSigScript(kaspaWasm, artifacts.kcc20, {
1229
- nextStates,
1230
- witness: Uint8Array.of(0),
1231
- }), tokenScript);
1232
- const scripts = [];
1233
- const adjusted = transactionWithCalculatedFeeChange(kaspaWasm, transaction, fundingChangeOutputIndex, network, "snapshot reserve handoff", scripts);
1234
- return outputEnvelope(adjusted, [{ index: 2 }], scripts, {
1235
- migrationId,
1236
- stage: "reserve-handoff",
1237
- tokenId,
1238
- bootstrapId,
1239
- bootstrapState: {
1240
- ...bootstrapStateReceipt(bootstrapState),
1241
- phase: "ACTIVATED",
1242
- },
1243
- shardPlanCommitment,
1244
- activationDigest: bytesToHex(bootstrapState.activationDigest),
1245
- shards: shards.map((shard) => shard.shardIndex),
1246
- maximumFeeSompi: feeOf(adjusted).toString(),
1247
- intentInputs: [
1248
- {
1249
- role: "snapshot-bootstrap",
1250
- index: 0,
1251
- covenantId: bootstrapId,
1252
- revealScriptHex: bytesToHex(bootstrapScript),
1253
- staticSignatureScriptHex: signatureScriptHex(adjusted, 0),
1254
- },
1255
- {
1256
- role: "fixed-supply-token",
1257
- index: 1,
1258
- covenantId: tokenId,
1259
- revealScriptHex: bytesToHex(tokenScript),
1260
- staticSignatureScriptHex: signatureScriptHex(adjusted, 1),
1261
- },
1262
- { role: "creator-funding", index: 2 },
1263
- ],
1264
- intentOutputs: shards.map((shard, index) => ({
1265
- role: "shard-reserve",
1266
- index,
1267
- shard: shard.shardIndex,
1268
- covenantId: tokenId,
1269
- revealScriptHex: bytesToHex(buildKcc20ScriptForState(artifacts.kcc20, nextStates[index])),
1270
- owner: shard.controllerId,
1271
- ownerScheme: 4,
1272
- borrowScheme: 0,
1273
- borrowGuard: ZERO_HASH,
1274
- extensionCommitment: bytesToHex(bootstrapState.holderExtensionCommitment),
1275
- tokenAmount: shard.allocationTotal.toString(),
1276
- })),
1277
- });
1278
- }
1279
- finally {
1280
- await rpc.disconnect();
1281
- }
1282
- }
1283
484
  async function buildClaim(input) {
1284
485
  const request = input.request || {};
1285
486
  const params = request.params || {};
@@ -1617,207 +818,6 @@ export function createKcc20SnapshotPsktBuilder(options) {
1617
818
  kcc20TemplateSuffixLen: template.suffix.length,
1618
819
  };
1619
820
  }
1620
- function initialControllerState(definition) {
1621
- return {
1622
- tokenId: hexToBytes(definition.tokenId),
1623
- holderExtensionCommitment: hexToBytes(definition.holderExtensionCommitment),
1624
- manifestCommitment: hexToBytes(definition.manifestCommitment),
1625
- snapshotContext: hexToBytes(definition.snapshotContext),
1626
- kcc20TemplateHash: hexToBytes(definition.kcc20TemplateHash),
1627
- claimNotBeforeDaaScore: definition.claimNotBeforeDaaScore,
1628
- shardIndex: BigInt(definition.shard.shardIndex),
1629
- globalIndexStart: BigInt(definition.shard.globalIndexStart),
1630
- holderCount: BigInt(definition.shard.holderCount),
1631
- treeDepth: BigInt(definition.shard.depth),
1632
- kcc20TemplatePrefixLen: BigInt(definition.kcc20TemplatePrefixLen),
1633
- kcc20TemplateSuffixLen: BigInt(definition.kcc20TemplateSuffixLen),
1634
- controllerCellKas: definition.controllerCellKas,
1635
- reserveCellKas: definition.reserveCellKas,
1636
- recipientMinCellKas: definition.recipientMinCellKas,
1637
- remainingRoot: hexToBytes(definition.shard.initialRoot),
1638
- remainingAmount: definition.shard.allocationTotal,
1639
- claimsProcessed: 0n,
1640
- };
1641
- }
1642
- function buildSnapshotControllerScriptForState(artifact, state) {
1643
- const normalized = normalizeSilverScriptArtifact(artifact);
1644
- const encoded = encodeControllerState(state);
1645
- const start = normalized.state_layout?.start;
1646
- const length = normalized.state_layout?.len;
1647
- if (!Number.isInteger(start) ||
1648
- !Number.isInteger(length) ||
1649
- encoded.length !== length) {
1650
- throw new Error("snapshot controller artifact state layout is invalid");
1651
- }
1652
- return concatBytes(Uint8Array.from(normalized.script).slice(0, start), encoded, Uint8Array.from(normalized.script).slice(start + length));
1653
- }
1654
- function buildSnapshotBootstrapScriptForState(artifact, state) {
1655
- const normalized = normalizeSilverScriptArtifact(artifact);
1656
- const encoded = encodeBootstrapState(state);
1657
- const start = normalized.state_layout?.start;
1658
- const length = normalized.state_layout?.len;
1659
- if (normalized.contract_name !== "KCC20SnapshotBootstrap" ||
1660
- !Number.isInteger(start) ||
1661
- !Number.isInteger(length) ||
1662
- encoded.length !== length) {
1663
- throw new Error("snapshot bootstrap artifact state layout is invalid");
1664
- }
1665
- return concatBytes(Uint8Array.from(normalized.script).slice(0, start), encoded, Uint8Array.from(normalized.script).slice(start + length));
1666
- }
1667
- function encodeBootstrapState(state) {
1668
- return concatBytes(pushData(state.migrationCommitment), pushData(state.manifestCommitment), pushData(state.holderExtensionCommitment), pushData(i64(state.totalSupply)), pushData(i64(state.claimNotBeforeDaaScore)), pushData(state.kcc20TemplateHash), pushData(i64(state.kcc20TemplatePrefixLen)), pushData(i64(state.kcc20TemplateSuffixLen)), pushData(i64(state.tokenCellKas)), pushData(i64(state.reserveCellKas)), pushData(i64(state.bootstrapCellKas)), pushData(state.approvalKey), pushData(i64(state.phase)), pushData(state.tokenId), pushData(state.shardPlanCommitment), pushData(state.activationDigest), pushData(i64(state.shardCount)));
1669
- }
1670
- function bootstrapStateReceipt(state) {
1671
- return {
1672
- migrationCommitment: bytesToHex(state.migrationCommitment),
1673
- manifestCommitment: bytesToHex(state.manifestCommitment),
1674
- holderExtensionCommitment: bytesToHex(state.holderExtensionCommitment),
1675
- totalSupply: state.totalSupply.toString(),
1676
- claimNotBeforeDaaScore: state.claimNotBeforeDaaScore.toString(),
1677
- kcc20TemplateHash: bytesToHex(state.kcc20TemplateHash),
1678
- kcc20TemplatePrefixLen: state.kcc20TemplatePrefixLen.toString(),
1679
- kcc20TemplateSuffixLen: state.kcc20TemplateSuffixLen.toString(),
1680
- tokenCellKas: state.tokenCellKas.toString(),
1681
- reserveCellKas: state.reserveCellKas.toString(),
1682
- bootstrapCellKas: state.bootstrapCellKas.toString(),
1683
- approvalKey: bytesToHex(state.approvalKey),
1684
- phase: state.phase.toString(),
1685
- tokenId: bytesToHex(state.tokenId),
1686
- shardPlanCommitment: bytesToHex(state.shardPlanCommitment),
1687
- activationDigest: bytesToHex(state.activationDigest),
1688
- shardCount: state.shardCount.toString(),
1689
- };
1690
- }
1691
- function bootstrapBaseState(params, template) {
1692
- const approvalKey = requireHex32(params.approvalKey ?? params.approvalKeyA, "approval key");
1693
- if (approvalKey === ZERO_HASH) {
1694
- throw new Error("bootstrap approval key must be nonzero");
1695
- }
1696
- const expectedTemplateHash = requireHex32(params.kcc20TemplateHash, "KCC20 template hash");
1697
- if (bytesToHex(template.hash) !== expectedTemplateHash) {
1698
- throw new Error("KCC20 template hash does not match the migration pin");
1699
- }
1700
- const claimNotBeforeDaaScore = positiveI64(params.claimNotBeforeDaaScore, "claim-not-before DAA score");
1701
- if (claimNotBeforeDaaScore >= 500000000000n) {
1702
- throw new Error("claim-not-before must use DAA-score locktime mode");
1703
- }
1704
- return {
1705
- migrationCommitment: hexToBytes(requireHex32(params.migrationId, "migration ID")),
1706
- manifestCommitment: hexToBytes(requireHex32(params.manifestCommitment, "manifest commitment")),
1707
- holderExtensionCommitment: hexToBytes(requireHex32(params.holderExtensionCommitment, "holder extension commitment")),
1708
- totalSupply: positiveI64(params.totalSupply, "total supply"),
1709
- claimNotBeforeDaaScore,
1710
- kcc20TemplateHash: hexToBytes(expectedTemplateHash),
1711
- kcc20TemplatePrefixLen: BigInt(template.prefix.length),
1712
- kcc20TemplateSuffixLen: BigInt(template.suffix.length),
1713
- tokenCellKas: minimumCell(params.tokenCellKas, "token cell KAS"),
1714
- reserveCellKas: minimumCell(params.reserveCellKas, "reserve cell KAS"),
1715
- bootstrapCellKas: minimumCell(params.bootstrapCellKas, "bootstrap cell KAS"),
1716
- approvalKey: hexToBytes(approvalKey),
1717
- };
1718
- }
1719
- function bootstrapStateArgs(state) {
1720
- return [
1721
- dataArg(state.migrationCommitment),
1722
- dataArg(state.manifestCommitment),
1723
- dataArg(state.holderExtensionCommitment),
1724
- i64Arg(state.totalSupply),
1725
- i64Arg(state.claimNotBeforeDaaScore),
1726
- dataArg(state.kcc20TemplateHash),
1727
- i64Arg(state.kcc20TemplatePrefixLen),
1728
- i64Arg(state.kcc20TemplateSuffixLen),
1729
- i64Arg(state.tokenCellKas),
1730
- i64Arg(state.reserveCellKas),
1731
- i64Arg(state.bootstrapCellKas),
1732
- dataArg(state.approvalKey),
1733
- i64Arg(state.phase),
1734
- dataArg(state.tokenId),
1735
- dataArg(state.shardPlanCommitment),
1736
- dataArg(state.activationDigest),
1737
- i64Arg(state.shardCount),
1738
- ];
1739
- }
1740
- function bootstrapBindArgs(artifacts, nextBootstrapState, tokenState) {
1741
- const template = templateParts(artifacts.kcc20);
1742
- return [
1743
- ...bootstrapStateArgs(nextBootstrapState),
1744
- i64Arg(1),
1745
- i64Arg(0),
1746
- i64Arg(1),
1747
- { type: "approval" },
1748
- dataArg(template.prefix),
1749
- dataArg(template.suffix),
1750
- ...kcc20StateArgs(tokenState),
1751
- dataArg(dispatchTagFor(artifacts.bootstrap, "bindToken")),
1752
- ];
1753
- }
1754
- function bootstrapSealArgs(artifacts, nextBootstrapState) {
1755
- return [
1756
- ...bootstrapStateArgs(nextBootstrapState),
1757
- i64Arg(0),
1758
- { type: "approval" },
1759
- dataArg(dispatchTagFor(artifacts.bootstrap, "seal")),
1760
- ];
1761
- }
1762
- function bootstrapCancellationArgs(artifacts, bound, sinkOutputIndex, sinkTokenState) {
1763
- return [
1764
- { type: "approval" },
1765
- i64Arg(sinkOutputIndex),
1766
- ...(bound
1767
- ? [
1768
- i64Arg(0),
1769
- dataArg(templateParts(artifacts.kcc20).prefix),
1770
- dataArg(templateParts(artifacts.kcc20).suffix),
1771
- ...kcc20StateArgs(sinkTokenState),
1772
- ]
1773
- : []),
1774
- dataArg(dispatchTagFor(artifacts.bootstrap, bound ? "cancelBound" : "cancelUnbound")),
1775
- ];
1776
- }
1777
- function bootstrapApprovalRecipes(scriptHex, args) {
1778
- const zeroSignature = "00".repeat(65);
1779
- const replace = (dynamicSlot) => args.map((arg) => {
1780
- if (arg.type === dynamicSlot)
1781
- return { type: "signature" };
1782
- if (arg.type === "approval") {
1783
- return { type: "data", hex: zeroSignature };
1784
- }
1785
- return arg;
1786
- });
1787
- const script = (normalizedArgs) => ({
1788
- inputIndex: 0,
1789
- scriptHex,
1790
- signatureScript: { mode: "ordered-args", args: normalizedArgs },
1791
- });
1792
- return {
1793
- placeholder: { args: replace("none") },
1794
- approval: script(replace("approval")),
1795
- };
1796
- }
1797
- function signatureScriptArgsBytes(args, signature = new Uint8Array(65)) {
1798
- const builder = new kaspaWasm.ScriptBuilder({
1799
- flags: { covenantsEnabled: true },
1800
- });
1801
- for (const arg of args || []) {
1802
- if (arg.type === "i64") {
1803
- builder.addI64(BigInt(arg.value));
1804
- }
1805
- else if (arg.type === "byte") {
1806
- builder.addData(Uint8Array.of(arg.value));
1807
- }
1808
- else if (arg.type === "data") {
1809
- builder.addData(hexToBytes(arg.hex));
1810
- }
1811
- else if (arg.type === "signature") {
1812
- const prefix = hexToBytes(arg.prefixHex || "");
1813
- builder.addData(concatBytes(prefix, signature));
1814
- }
1815
- else {
1816
- throw new Error(`unsupported snapshot signature argument ${arg.type}`);
1817
- }
1818
- }
1819
- return builder.drain();
1820
- }
1821
821
  function encodeControllerState(state) {
1822
822
  return concatBytes(pushData(state.tokenId), pushData(state.holderExtensionCommitment), pushData(state.manifestCommitment), pushData(state.snapshotContext), pushData(state.kcc20TemplateHash), pushData(i64(state.claimNotBeforeDaaScore)), pushData(i64(state.shardIndex)), pushData(i64(state.globalIndexStart)), pushData(i64(state.holderCount)), pushData(i64(state.treeDepth)), pushData(i64(state.kcc20TemplatePrefixLen)), pushData(i64(state.kcc20TemplateSuffixLen)), pushData(i64(state.controllerCellKas)), pushData(i64(state.reserveCellKas)), pushData(i64(state.recipientMinCellKas)), pushData(state.remainingRoot), pushData(i64(state.remainingAmount)), pushData(i64(state.claimsProcessed)));
1823
823
  }
@@ -1951,36 +951,6 @@ export function createKcc20SnapshotPsktBuilder(options) {
1951
951
  }
1952
952
  return normalized;
1953
953
  }
1954
- function reserveShards(values, totalSupply) {
1955
- if (!Array.isArray(values) || values.length < 1 || values.length > 8) {
1956
- throw new Error("atomic reserve handoff requires 1..8 shards");
1957
- }
1958
- const indexes = new Set();
1959
- const controllerIds = new Set();
1960
- const shards = values.map((value) => {
1961
- const shardIndex = unsignedInteger(value?.shardIndex, "shard index");
1962
- const controllerId = requireHex32(value?.controllerId, "controller id");
1963
- const allocationTotal = positiveI64(value?.allocationTotal, "shard allocation total");
1964
- if (indexes.has(shardIndex) || controllerIds.has(controllerId)) {
1965
- throw new Error("reserve handoff shard identities must be unique");
1966
- }
1967
- indexes.add(shardIndex);
1968
- controllerIds.add(controllerId);
1969
- return { shardIndex, controllerId, allocationTotal };
1970
- });
1971
- if (shards.reduce((sum, shard) => sum + shard.allocationTotal, 0n) !==
1972
- totalSupply) {
1973
- throw new Error("reserve handoff allocations do not equal total supply");
1974
- }
1975
- return shards.sort((left, right) => left.shardIndex - right.shardIndex);
1976
- }
1977
- function snapshotShardPlanCommitment({ migrationCommitment, manifestCommitment, tokenId, totalSupply, shards, }) {
1978
- return bytesToHex(blake2b(concatBytes(Uint8Array.of(0x20), hexToBytes(migrationCommitment), hexToBytes(manifestCommitment), hexToBytes(tokenId), i64(totalSupply), i64(BigInt(shards.length)), ...shards.flatMap((shard, index) => [
1979
- i64(BigInt(index)),
1980
- hexToBytes(shard.controllerId),
1981
- i64(shard.allocationTotal),
1982
- ])), { dkLen: 32 }));
1983
- }
1984
954
  function claimProof(value, shard) {
1985
955
  const proof = value || {};
1986
956
  const normalized = {
@@ -2199,41 +1169,6 @@ export function createKcc20SnapshotPsktBuilder(options) {
2199
1169
  }
2200
1170
  return value.toLowerCase();
2201
1171
  }
2202
- function controllerDeploymentPayload(definition, state) {
2203
- return bytesToHex(new TextEncoder().encode(JSON.stringify({
2204
- tn10: {
2205
- v: 1,
2206
- tmpl: "KCC20SnapshotController",
2207
- migrationId: definition.migrationId,
2208
- manifestCommitment: definition.manifestCommitment,
2209
- shardIndex: definition.shard.shardIndex,
2210
- args: [
2211
- {
2212
- name: "controllerState",
2213
- type: "object",
2214
- value: jsonControllerState(state),
2215
- },
2216
- ],
2217
- },
2218
- })));
2219
- }
2220
- function jsonControllerState(state) {
2221
- return Object.fromEntries(Object.entries(state).map(([key, value]) => [
2222
- key,
2223
- value instanceof Uint8Array
2224
- ? bytesToHex(value)
2225
- : controllerInteger(value, key),
2226
- ]));
2227
- }
2228
- function controllerInteger(value, key) {
2229
- if (typeof value !== "string" &&
2230
- typeof value !== "number" &&
2231
- typeof value !== "bigint" &&
2232
- typeof value !== "boolean") {
2233
- throw new Error(`controller state ${key} is not an integer`);
2234
- }
2235
- return BigInt(value).toString();
2236
- }
2237
1172
  function scriptAddress(script, network) {
2238
1173
  return kaspaWasm
2239
1174
  .addressFromScriptPublicKey(kaspaWasm.payToScriptHashScript(script), network)
@@ -2365,64 +1300,4 @@ export function createKcc20SnapshotPsktBuilder(options) {
2365
1300
  }
2366
1301
  return buildSnapshotMigrationPskt;
2367
1302
  }
2368
- /** Pure script constructors shared by browser verification and server projections. */
2369
- function buildSnapshotControllerScriptForState(artifact, state) {
2370
- const normalized = normalizeSilverScriptArtifact(artifact);
2371
- const encoded = encodePortableControllerState(state);
2372
- const start = normalized.state_layout?.start;
2373
- const length = normalized.state_layout?.len;
2374
- if (!Number.isInteger(start) ||
2375
- !Number.isInteger(length) ||
2376
- encoded.length !== length) {
2377
- throw new Error("snapshot controller artifact state layout is invalid");
2378
- }
2379
- return portableConcatBytes(Uint8Array.from(normalized.script).slice(0, start), encoded, Uint8Array.from(normalized.script).slice(start + length));
2380
- }
2381
- function buildSnapshotBootstrapScriptForState(artifact, state) {
2382
- const normalized = normalizeSilverScriptArtifact(artifact);
2383
- const encoded = encodePortableBootstrapState(state);
2384
- const start = normalized.state_layout?.start;
2385
- const length = normalized.state_layout?.len;
2386
- if (normalized.contract_name !== "KCC20SnapshotBootstrap" ||
2387
- !Number.isInteger(start) ||
2388
- !Number.isInteger(length) ||
2389
- encoded.length !== length) {
2390
- throw new Error("snapshot bootstrap artifact state layout is invalid");
2391
- }
2392
- return portableConcatBytes(Uint8Array.from(normalized.script).slice(0, start), encoded, Uint8Array.from(normalized.script).slice(start + length));
2393
- }
2394
- function encodePortableControllerState(state) {
2395
- return portableConcatBytes(portablePushData(state.tokenId), portablePushData(state.holderExtensionCommitment), portablePushData(state.manifestCommitment), portablePushData(state.snapshotContext), portablePushData(state.kcc20TemplateHash), portablePushData(portableI64(state.claimNotBeforeDaaScore)), portablePushData(portableI64(state.shardIndex)), portablePushData(portableI64(state.globalIndexStart)), portablePushData(portableI64(state.holderCount)), portablePushData(portableI64(state.treeDepth)), portablePushData(portableI64(state.kcc20TemplatePrefixLen)), portablePushData(portableI64(state.kcc20TemplateSuffixLen)), portablePushData(portableI64(state.controllerCellKas)), portablePushData(portableI64(state.reserveCellKas)), portablePushData(portableI64(state.recipientMinCellKas)), portablePushData(state.remainingRoot), portablePushData(portableI64(state.remainingAmount)), portablePushData(portableI64(state.claimsProcessed)));
2396
- }
2397
- function encodePortableBootstrapState(state) {
2398
- return portableConcatBytes(portablePushData(state.migrationCommitment), portablePushData(state.manifestCommitment), portablePushData(state.holderExtensionCommitment), portablePushData(portableI64(state.totalSupply)), portablePushData(portableI64(state.claimNotBeforeDaaScore)), portablePushData(state.kcc20TemplateHash), portablePushData(portableI64(state.kcc20TemplatePrefixLen)), portablePushData(portableI64(state.kcc20TemplateSuffixLen)), portablePushData(portableI64(state.tokenCellKas)), portablePushData(portableI64(state.reserveCellKas)), portablePushData(portableI64(state.bootstrapCellKas)), portablePushData(state.approvalKey ?? state.approvalKeyA), portablePushData(portableI64(state.phase)), portablePushData(state.tokenId), portablePushData(state.shardPlanCommitment), portablePushData(state.activationDigest), portablePushData(portableI64(state.shardCount)));
2399
- }
2400
- function portablePushData(value) {
2401
- const bytes = Uint8Array.from(value);
2402
- if (bytes.length > 75)
2403
- throw new Error("snapshot state push is too large");
2404
- return portableConcatBytes(Uint8Array.of(bytes.length), bytes);
2405
- }
2406
- function portableI64(value) {
2407
- let cursor = BigInt(value);
2408
- if (cursor < 0n || cursor > 9223372036854775807n) {
2409
- throw new Error("snapshot state integer is outside signed i64 range");
2410
- }
2411
- const bytes = new Uint8Array(8);
2412
- for (let index = 0; index < bytes.length; index += 1) {
2413
- bytes[index] = Number(cursor & 0xffn);
2414
- cursor >>= 8n;
2415
- }
2416
- return bytes;
2417
- }
2418
- function portableConcatBytes(...values) {
2419
- const arrays = values.map((value) => Uint8Array.from(value));
2420
- const output = new Uint8Array(arrays.reduce((sum, value) => sum + value.length, 0));
2421
- let offset = 0;
2422
- for (const value of arrays) {
2423
- output.set(value, offset);
2424
- offset += value.length;
2425
- }
2426
- return output;
2427
- }
2428
1303
  //# sourceMappingURL=snapshot-operation.js.map