@ghostspeak/sdk 2.0.6 → 2.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +295 -30
  2. package/dist/GhostSpeakClient-bnXwUPHI.d.ts +1011 -0
  3. package/dist/StakingModule-DunDShLq.d.ts +2446 -0
  4. package/dist/{agent-M74TCRON.js → agent-S42FIMR7.js} +4 -4
  5. package/dist/{agent-M74TCRON.js.map → agent-S42FIMR7.js.map} +1 -1
  6. package/dist/batch-operations-45CQFEID.js +4 -0
  7. package/dist/batch-operations-45CQFEID.js.map +1 -0
  8. package/dist/browser-CI5_6Gzk.d.ts +234 -0
  9. package/dist/browser.d.ts +6 -576
  10. package/dist/browser.js +15 -842
  11. package/dist/browser.js.map +1 -1
  12. package/dist/chunk-46QWY3MG.js +156 -0
  13. package/dist/chunk-46QWY3MG.js.map +1 -0
  14. package/dist/{chunk-F3DZMBUA.js → chunk-5QBSC4T4.js} +327 -493
  15. package/dist/chunk-5QBSC4T4.js.map +1 -0
  16. package/dist/chunk-5QZVFUXB.js +4176 -0
  17. package/dist/chunk-5QZVFUXB.js.map +1 -0
  18. package/dist/chunk-6XCCMJ6M.js +1865 -0
  19. package/dist/chunk-6XCCMJ6M.js.map +1 -0
  20. package/dist/chunk-A7ALCVUI.js +98 -0
  21. package/dist/chunk-A7ALCVUI.js.map +1 -0
  22. package/dist/chunk-AWMGX3OX.js +814 -0
  23. package/dist/chunk-AWMGX3OX.js.map +1 -0
  24. package/dist/chunk-BF3IQ35I.js +284 -0
  25. package/dist/chunk-BF3IQ35I.js.map +1 -0
  26. package/dist/chunk-BQDGRTVP.js +168 -0
  27. package/dist/chunk-BQDGRTVP.js.map +1 -0
  28. package/dist/chunk-IQM5RASO.js +8502 -0
  29. package/dist/chunk-IQM5RASO.js.map +1 -0
  30. package/dist/chunk-JYXSOXCP.js +3850 -0
  31. package/dist/chunk-JYXSOXCP.js.map +1 -0
  32. package/dist/chunk-OXA7MECJ.js +7787 -0
  33. package/dist/chunk-OXA7MECJ.js.map +1 -0
  34. package/dist/chunk-QLRWUHN2.js +231 -0
  35. package/dist/chunk-QLRWUHN2.js.map +1 -0
  36. package/dist/chunk-SKMJJ3Q6.js +125 -0
  37. package/dist/chunk-SKMJJ3Q6.js.map +1 -0
  38. package/dist/chunk-TTB4OS2D.js +69 -0
  39. package/dist/chunk-TTB4OS2D.js.map +1 -0
  40. package/dist/chunk-UP2VWCW5.js +33 -0
  41. package/dist/{chunk-NSBPE2FW.js.map → chunk-UP2VWCW5.js.map} +1 -1
  42. package/dist/{chunk-UJUGGLMT.js → chunk-VQZQCHUT.js} +5 -5
  43. package/dist/{chunk-UJUGGLMT.js.map → chunk-VQZQCHUT.js.map} +1 -1
  44. package/dist/client.d.ts +4 -4
  45. package/dist/client.js +11 -10
  46. package/dist/createAgentAuthorization-KGZNXZBT.js +5 -0
  47. package/dist/createAgentAuthorization-KGZNXZBT.js.map +1 -0
  48. package/dist/credentials.js +1 -1
  49. package/dist/crypto.js +2 -2
  50. package/dist/errors.js +1 -1
  51. package/dist/feature-flags-B1g0DCPe.d.ts +1181 -0
  52. package/dist/generated-QJREJQ2C.js +9 -0
  53. package/dist/{generated-VNLHMR6Y.js.map → generated-QJREJQ2C.js.map} +1 -1
  54. package/dist/{ghostspeak_wasm-SB2RPJ3D.js → ghostspeak_wasm-F227HOSM.js} +3 -3
  55. package/dist/{ghostspeak_wasm-SB2RPJ3D.js.map → ghostspeak_wasm-F227HOSM.js.map} +1 -1
  56. package/dist/index.d.ts +1179 -1498
  57. package/dist/index.js +356 -3578
  58. package/dist/index.js.map +1 -1
  59. package/dist/metafile-esm.json +1 -1
  60. package/dist/minimal/core-minimal.d.ts +2446 -1245
  61. package/dist/minimal/core-minimal.js +9 -9
  62. package/dist/minimal/core-minimal.js.map +1 -1
  63. package/dist/nacl-fast-W5BJ3KZ2.js +2229 -0
  64. package/dist/nacl-fast-W5BJ3KZ2.js.map +1 -0
  65. package/dist/pda-4KP7CURF.js +4 -0
  66. package/dist/pda-4KP7CURF.js.map +1 -0
  67. package/dist/pda-Ce7VYg4T.d.ts +25 -0
  68. package/dist/reputation-types-Yebf0Rm_.d.ts +1071 -0
  69. package/dist/revokeAuthorization-2ZRO6GUZ.js +5 -0
  70. package/dist/revokeAuthorization-2ZRO6GUZ.js.map +1 -0
  71. package/dist/signature-verification-DGxR4aYQ.d.ts +448 -0
  72. package/dist/types.js +1 -1
  73. package/dist/updateReputationWithAuth-PCEUOCFV.js +5 -0
  74. package/dist/updateReputationWithAuth-PCEUOCFV.js.map +1 -0
  75. package/dist/utils.d.ts +69 -203
  76. package/dist/utils.js +15 -153
  77. package/dist/utils.js.map +1 -1
  78. package/package.json +27 -34
  79. package/dist/.tsbuildinfo +0 -1
  80. package/dist/GhostSpeakClient-D_66Uzsf.d.ts +0 -707
  81. package/dist/GovernanceModule-DQYYys-H.d.ts +0 -1766
  82. package/dist/chunk-APCKGD23.js +0 -1328
  83. package/dist/chunk-APCKGD23.js.map +0 -1
  84. package/dist/chunk-ASQXX4IT.js +0 -572
  85. package/dist/chunk-ASQXX4IT.js.map +0 -1
  86. package/dist/chunk-COGZFWOT.js +0 -19657
  87. package/dist/chunk-COGZFWOT.js.map +0 -1
  88. package/dist/chunk-F3DZMBUA.js.map +0 -1
  89. package/dist/chunk-GMHIUK2R.js +0 -7526
  90. package/dist/chunk-GMHIUK2R.js.map +0 -1
  91. package/dist/chunk-IAWBZYPE.js +0 -356
  92. package/dist/chunk-IAWBZYPE.js.map +0 -1
  93. package/dist/chunk-NSBPE2FW.js +0 -15
  94. package/dist/chunk-OWYHJG6H.js +0 -13311
  95. package/dist/chunk-OWYHJG6H.js.map +0 -1
  96. package/dist/chunk-RDDPOFR5.js +0 -3
  97. package/dist/chunk-RDDPOFR5.js.map +0 -1
  98. package/dist/chunk-RERCHKZP.js +0 -35
  99. package/dist/chunk-RERCHKZP.js.map +0 -1
  100. package/dist/chunk-TVVGXYCI.js +0 -2887
  101. package/dist/chunk-TVVGXYCI.js.map +0 -1
  102. package/dist/chunk-ZGP5552B.js +0 -377
  103. package/dist/chunk-ZGP5552B.js.map +0 -1
  104. package/dist/chunk-ZWOYNHVK.js +0 -196
  105. package/dist/chunk-ZWOYNHVK.js.map +0 -1
  106. package/dist/dist/.tsbuildinfo +0 -1
  107. package/dist/elgamal-VZLWB3XK.js +0 -5
  108. package/dist/elgamal-VZLWB3XK.js.map +0 -1
  109. package/dist/feature-flags-V722ZuXO.d.ts +0 -3512
  110. package/dist/generated-VNLHMR6Y.js +0 -5
  111. package/dist/ipfs-types-BOt9ZNg4.d.ts +0 -592
  112. package/dist/multisigConfig-BzEhy6jy.d.ts +0 -58
  113. package/dist/pda-B_nS8SbD.d.ts +0 -114
  114. package/dist/pda-S4BFJVGE.js +0 -4
  115. package/dist/pda-S4BFJVGE.js.map +0 -1
  116. package/dist/system-addresses-BFNLEbFx.d.ts +0 -857
  117. package/dist/token-2022-rpc-RALH4RK7.js +0 -593
  118. package/dist/token-2022-rpc-RALH4RK7.js.map +0 -1
@@ -1,10 +1,10 @@
1
- import { encryptAmount, serializeCiphertext, generateRangeProof, generateValidityProof, generateEqualityProof, generateElGamalKeypair, decryptAmount } from './chunk-IAWBZYPE.js';
2
- import { TOKEN_PROGRAM_ADDRESS, ASSOCIATED_TOKEN_PROGRAM_ADDRESS, TOKEN_2022_PROGRAM_ADDRESS } from './chunk-OWYHJG6H.js';
3
- import { AGENT_DISCRIMINATOR } from './chunk-GMHIUK2R.js';
4
- import { __export } from './chunk-NSBPE2FW.js';
5
- import { fetchEncodedAccount, getAddressEncoder, getU64Encoder, getBytesEncoder, getUtf8Encoder, getProgramDerivedAddress } from '@solana/kit';
1
+ import { TOKEN_PROGRAM_ADDRESS, ASSOCIATED_TOKEN_PROGRAM_ADDRESS, TOKEN_2022_PROGRAM_ADDRESS } from './chunk-OXA7MECJ.js';
2
+ import { AGENT_DISCRIMINATOR } from './chunk-5QZVFUXB.js';
3
+ import { __export } from './chunk-UP2VWCW5.js';
4
+ import { fetchEncodedAccount, getProgramDerivedAddress, getBytesEncoder, getAddressEncoder } from '@solana/kit';
6
5
  import { sha256 } from '@noble/hashes/sha256';
7
- import { bytesToHex, randomBytes } from '@noble/curves/abstract/utils';
6
+ import { randomBytes, bytesToNumberLE, bytesToHex } from '@noble/curves/abstract/utils';
7
+ import { ed25519 } from '@noble/curves/ed25519';
8
8
 
9
9
  // src/utils/discriminator-validator.ts
10
10
  function validateAccountDiscriminator(accountData, expectedDiscriminator) {
@@ -72,7 +72,7 @@ function createDiscriminatorErrorMessage(validation, accountType, address) {
72
72
  }
73
73
  async function safeDecodeAgent(encodedAccount) {
74
74
  try {
75
- const { AGENT_DISCRIMINATOR: AGENT_DISCRIMINATOR2, getAgentDecoder } = await import('./agent-M74TCRON.js');
75
+ const { AGENT_DISCRIMINATOR: AGENT_DISCRIMINATOR2, getAgentDecoder } = await import('./agent-S42FIMR7.js');
76
76
  const validation = validateAccountDiscriminator(encodedAccount.data, AGENT_DISCRIMINATOR2);
77
77
  if (validation.canDecode) {
78
78
  try {
@@ -131,7 +131,7 @@ async function createMigrationPlan(encodedAccount, address) {
131
131
  plan.recommendations.push("Account does not exist - no migration needed");
132
132
  return plan;
133
133
  }
134
- const { AGENT_DISCRIMINATOR: AGENT_DISCRIMINATOR2 } = await import('./agent-M74TCRON.js');
134
+ const { AGENT_DISCRIMINATOR: AGENT_DISCRIMINATOR2 } = await import('./agent-S42FIMR7.js');
135
135
  const validation = validateAccountDiscriminator(encodedAccount.data, AGENT_DISCRIMINATOR2);
136
136
  const inspection = inspectAccountData(encodedAccount, address);
137
137
  if (validation.isValid) {
@@ -306,7 +306,7 @@ async function runAccountDiagnostics(encodedAccount, address) {
306
306
  const accountExists = "exists" in encodedAccount && encodedAccount.exists;
307
307
  let discriminatorValidation, inspection, migrationPlan, migrationSimulation;
308
308
  if (accountExists) {
309
- const { AGENT_DISCRIMINATOR: AGENT_DISCRIMINATOR2 } = await import('./agent-M74TCRON.js');
309
+ const { AGENT_DISCRIMINATOR: AGENT_DISCRIMINATOR2 } = await import('./agent-S42FIMR7.js');
310
310
  discriminatorValidation = validateAccountDiscriminator(encodedAccount.data, AGENT_DISCRIMINATOR2);
311
311
  inspection = inspectAccountData(encodedAccount, address);
312
312
  migrationPlan = await createMigrationPlan(encodedAccount, address);
@@ -680,71 +680,13 @@ async function getTokenProgramType(mint) {
680
680
  const isToken2022 = await isToken2022Mint(mint);
681
681
  return isToken2022 ? "token-2022" /* TOKEN_2022 */ : "spl-token" /* SPL_TOKEN */;
682
682
  }
683
- async function checkToken2022Extensions(mint, extensions, rpcEndpoint = "https://api.devnet.solana.com") {
684
- try {
685
- const { getMintWithExtensions } = await import('./token-2022-rpc-RALH4RK7.js');
686
- const { createSolanaRpc } = await import('@solana/kit');
687
- const rpc = createSolanaRpc(rpcEndpoint);
688
- const mintData = await getMintWithExtensions(rpc, mint, "confirmed");
689
- if (!mintData) {
690
- const result2 = {};
691
- for (const extension of extensions) {
692
- result2[extension] = false;
693
- }
694
- return result2;
695
- }
696
- const result = {};
697
- for (const extension of extensions) {
698
- switch (extension) {
699
- case 1 /* TRANSFER_FEE_CONFIG */:
700
- result[extension] = Boolean(mintData.extensions.transferFeeConfig);
701
- break;
702
- case 3 /* MINT_CLOSE_AUTHORITY */:
703
- result[extension] = Boolean(mintData.extensions.mintCloseAuthority);
704
- break;
705
- case 4 /* CONFIDENTIAL_TRANSFER_MINT */:
706
- result[extension] = Boolean(mintData.extensions.confidentialTransferMint);
707
- break;
708
- case 6 /* DEFAULT_ACCOUNT_STATE */:
709
- result[extension] = Boolean(mintData.extensions.defaultAccountState);
710
- break;
711
- case 9 /* NON_TRANSFERABLE */:
712
- result[extension] = Boolean(mintData.extensions.nonTransferable);
713
- break;
714
- case 10 /* INTEREST_BEARING_MINT */:
715
- result[extension] = Boolean(mintData.extensions.interestBearingConfig);
716
- break;
717
- case 12 /* PERMANENT_DELEGATE */:
718
- result[extension] = Boolean(mintData.extensions.permanentDelegate);
719
- break;
720
- case 14 /* TRANSFER_HOOK */:
721
- result[extension] = Boolean(mintData.extensions.transferHook);
722
- break;
723
- case 16 /* METADATA_POINTER */:
724
- result[extension] = Boolean(mintData.extensions.metadataPointer);
725
- break;
726
- case 17 /* TOKEN_METADATA */:
727
- result[extension] = Boolean(mintData.extensions.tokenMetadata);
728
- break;
729
- case 18 /* GROUP_POINTER */:
730
- result[extension] = Boolean(mintData.extensions.groupPointer);
731
- break;
732
- case 19 /* TOKEN_GROUP */:
733
- result[extension] = Boolean(mintData.extensions.tokenGroup);
734
- break;
735
- default:
736
- result[extension] = false;
737
- }
738
- }
739
- return result;
740
- } catch (error) {
741
- console.error(`Failed to check Token-2022 extensions for mint ${mint}:`, error);
742
- const result = {};
743
- for (const extension of extensions) {
744
- result[extension] = false;
745
- }
746
- return result;
683
+ async function checkToken2022Extensions(mint, extensions, _rpcEndpoint = "https://api.devnet.solana.com") {
684
+ console.warn(`Token-2022 extension checking is deprecated: mint ${mint}`);
685
+ const result = {};
686
+ for (const extension of extensions) {
687
+ result[extension] = false;
747
688
  }
689
+ return result;
748
690
  }
749
691
  async function hasTransferFeeExtension(mint, rpcEndpoint = "https://api.devnet.solana.com") {
750
692
  const result = await checkToken2022Extensions(
@@ -770,79 +712,17 @@ async function hasInterestBearingExtension(mint, rpcEndpoint = "https://api.devn
770
712
  );
771
713
  return result[10 /* INTEREST_BEARING_MINT */];
772
714
  }
773
- async function getTransferFeeConfig(mint, rpcEndpoint = "https://api.devnet.solana.com") {
774
- try {
775
- const { getMintWithExtensions } = await import('./token-2022-rpc-RALH4RK7.js');
776
- const { createSolanaRpc } = await import('@solana/kit');
777
- const rpc = createSolanaRpc(rpcEndpoint);
778
- const mintData = await getMintWithExtensions(rpc, mint, "confirmed");
779
- if (!mintData?.extensions.transferFeeConfig) {
780
- return null;
781
- }
782
- const config = mintData.extensions.transferFeeConfig;
783
- return {
784
- transferFeeBasisPoints: config.newerTransferFee.transferFeeBasisPoints,
785
- maximumFee: config.newerTransferFee.maximumFee,
786
- transferFeeConfigAuthority: config.transferFeeConfigAuthority,
787
- withdrawWithheldAuthority: config.withdrawWithheldAuthority,
788
- withheldAmount: BigInt(0),
789
- olderTransferFee: {
790
- epoch: config.olderTransferFee.epoch || BigInt(0),
791
- transferFeeBasisPoints: config.olderTransferFee.transferFeeBasisPoints || 0,
792
- maximumFee: config.olderTransferFee.maximumFee || BigInt(0)
793
- },
794
- newerTransferFee: {
795
- epoch: config.newerTransferFee.epoch,
796
- transferFeeBasisPoints: config.newerTransferFee.transferFeeBasisPoints,
797
- maximumFee: config.newerTransferFee.maximumFee
798
- }
799
- };
800
- } catch (error) {
801
- console.error(`Failed to get transfer fee config for mint ${mint}:`, error);
802
- return null;
803
- }
715
+ async function getTransferFeeConfig(mint, _rpcEndpoint = "https://api.devnet.solana.com") {
716
+ console.warn(`Token-2022 getTransferFeeConfig is deprecated: mint ${mint}`);
717
+ return null;
804
718
  }
805
- async function getConfidentialTransferConfig(mint, rpcEndpoint = "https://api.devnet.solana.com") {
806
- try {
807
- const { getMintWithExtensions } = await import('./token-2022-rpc-RALH4RK7.js');
808
- const { createSolanaRpc } = await import('@solana/kit');
809
- const rpc = createSolanaRpc(rpcEndpoint);
810
- const mintData = await getMintWithExtensions(rpc, mint, "confirmed");
811
- if (!mintData?.extensions.confidentialTransferMint) {
812
- return null;
813
- }
814
- const config = mintData.extensions.confidentialTransferMint;
815
- return {
816
- authority: config.authority,
817
- autoApproveNewAccounts: config.autoApproveNewAccounts,
818
- auditorElgamalPubkey: config.auditorElgamalPubkey
819
- };
820
- } catch (error) {
821
- console.error(`Failed to get confidential transfer config for mint ${mint}:`, error);
822
- return null;
823
- }
719
+ async function getConfidentialTransferConfig(mint, _rpcEndpoint = "https://api.devnet.solana.com") {
720
+ console.warn(`Token-2022 getConfidentialTransferConfig is deprecated: mint ${mint}`);
721
+ return null;
824
722
  }
825
- async function getInterestBearingConfig(mint, rpcEndpoint = "https://api.devnet.solana.com") {
826
- try {
827
- const { getMintWithExtensions } = await import('./token-2022-rpc-RALH4RK7.js');
828
- const { createSolanaRpc } = await import('@solana/kit');
829
- const rpc = createSolanaRpc(rpcEndpoint);
830
- const mintData = await getMintWithExtensions(rpc, mint, "confirmed");
831
- if (!mintData?.extensions.interestBearingConfig) {
832
- return null;
833
- }
834
- const config = mintData.extensions.interestBearingConfig;
835
- return {
836
- rateAuthority: config.rateAuthority,
837
- currentRate: config.currentRate,
838
- initializationTimestamp: config.initializationTimestamp || BigInt(Math.floor(Date.now() / 1e3)),
839
- lastUpdateTimestamp: config.lastUpdateTimestamp,
840
- preUpdateAverageRate: config.preUpdateAverageRate
841
- };
842
- } catch (error) {
843
- console.error(`Failed to get interest-bearing config for mint ${mint}:`, error);
844
- return null;
845
- }
723
+ async function getInterestBearingConfig(mint, _rpcEndpoint = "https://api.devnet.solana.com") {
724
+ console.warn(`Token-2022 getInterestBearingConfig is deprecated: mint ${mint}`);
725
+ return null;
846
726
  }
847
727
  async function getAllAssociatedTokenAddresses(owner, mint) {
848
728
  const [splToken, token2022] = await Promise.all([
@@ -898,373 +778,264 @@ function parseTokenAmount(formatted, decimals) {
898
778
  return BigInt(rawAmount);
899
779
  }
900
780
 
901
- // src/utils/token-2022-extensions.ts
902
- var token_2022_extensions_exports = {};
903
- __export(token_2022_extensions_exports, {
904
- TokenAccountState: () => TokenAccountState,
905
- basisPointsToPercentage: () => basisPointsToPercentage,
906
- calculateCompoundInterest: () => calculateCompoundInterest,
907
- calculateInterest: () => calculateInterest,
908
- calculateRequiredAmountForNetTransfer: () => calculateRequiredAmountForNetTransfer,
909
- calculateTransferFee: () => calculateTransferFee,
910
- canTransfer: () => canTransfer,
911
- createInterestBearingConfig: () => createInterestBearingConfig,
912
- createTransferFeeConfig: () => createTransferFeeConfig,
913
- createTransferHookInstruction: () => createTransferHookInstruction,
914
- deserializeTokenMetadata: () => deserializeTokenMetadata,
915
- estimateAccumulatedFees: () => estimateAccumulatedFees,
916
- estimateComputeUnits: () => estimateComputeUnits,
917
- formatBasisPoints: () => formatBasisPoints,
918
- generateConfidentialTransferProof: () => generateConfidentialTransferProof,
919
- getRequiredExtensions: () => getRequiredExtensions,
920
- parseTokenExtension: () => parseTokenExtension,
921
- percentageToBasisPoints: () => percentageToBasisPoints,
922
- serializeTokenMetadata: () => serializeTokenMetadata,
923
- validateTransferHookInstruction: () => validateTransferHookInstruction,
924
- verifyConfidentialTransferProof: () => verifyConfidentialTransferProof
781
+ // src/utils/governance-helpers.ts
782
+ var governance_helpers_exports = {};
783
+ __export(governance_helpers_exports, {
784
+ GovernanceAnalyticsUtils: () => GovernanceAnalyticsUtils,
785
+ PERMISSION_TEMPLATES: () => PERMISSION_TEMPLATES,
786
+ ProposalUtils: () => ProposalUtils,
787
+ ROLE_TEMPLATES: () => ROLE_TEMPLATES,
788
+ VotingUtils: () => VotingUtils,
789
+ deriveMultisigPda: () => deriveMultisigPda,
790
+ deriveProposalPda: () => deriveProposalPda,
791
+ deriveRbacPda: () => deriveRbacPda
925
792
  });
926
- function calculateTransferFee(transferAmount, feeConfig) {
927
- const { transferFeeBasisPoints, maximumFee } = feeConfig;
928
- const calculatedFee = transferAmount * BigInt(transferFeeBasisPoints) / 10000n;
929
- const feeAmount = calculatedFee > maximumFee ? maximumFee : calculatedFee;
930
- const wasFeeCapped = calculatedFee > maximumFee;
931
- const netAmount = transferAmount - feeAmount;
932
- return {
933
- transferAmount,
934
- feeAmount,
935
- netAmount,
936
- feeBasisPoints: transferFeeBasisPoints,
937
- wasFeeCapped
938
- };
793
+ async function deriveMultisigPda(programId, authority, multisigId) {
794
+ const [pda] = await getProgramDerivedAddress({
795
+ programAddress: programId,
796
+ seeds: [
797
+ getBytesEncoder().encode(new Uint8Array([109, 117, 108, 116, 105, 115, 105, 103])),
798
+ // 'multisig'
799
+ getAddressEncoder().encode(authority),
800
+ new Uint8Array(new BigUint64Array([multisigId]).buffer)
801
+ ]
802
+ });
803
+ return pda;
939
804
  }
940
- function calculateRequiredAmountForNetTransfer(desiredNetAmount, feeConfig) {
941
- const { transferFeeBasisPoints } = feeConfig;
942
- const grossAmount = desiredNetAmount * 10000n / (10000n - BigInt(transferFeeBasisPoints));
943
- return calculateTransferFee(grossAmount, feeConfig);
805
+ async function deriveProposalPda(programId, multisig, proposalId) {
806
+ const [pda] = await getProgramDerivedAddress({
807
+ programAddress: programId,
808
+ seeds: [
809
+ getBytesEncoder().encode(new Uint8Array([112, 114, 111, 112, 111, 115, 97, 108])),
810
+ // 'proposal'
811
+ getAddressEncoder().encode(multisig),
812
+ new Uint8Array(new BigUint64Array([proposalId]).buffer)
813
+ ]
814
+ });
815
+ return pda;
944
816
  }
945
- function estimateAccumulatedFees(transfers, feeConfig) {
946
- const feeBreakdown = [];
947
- let totalFees = 0n;
948
- for (const transferAmount of transfers) {
949
- const calculation = calculateTransferFee(transferAmount, feeConfig);
950
- feeBreakdown.push(calculation);
951
- totalFees += calculation.feeAmount;
952
- }
953
- return { totalFees, feeBreakdown };
817
+ async function deriveRbacPda(programId, admin) {
818
+ const [pda] = await getProgramDerivedAddress({
819
+ programAddress: programId,
820
+ seeds: [
821
+ getBytesEncoder().encode(new Uint8Array([114, 98, 97, 99])),
822
+ // 'rbac'
823
+ getAddressEncoder().encode(admin)
824
+ ]
825
+ });
826
+ return pda;
954
827
  }
955
- async function generateConfidentialTransferProof(amount, senderKeypair, recipientPubkey, auditorPubkey) {
956
- const recipientCiphertext = encryptAmount(amount, recipientPubkey);
957
- const encryptedAmount = serializeCiphertext(recipientCiphertext);
958
- const randomness = new Uint8Array(32);
959
- crypto.getRandomValues(randomness);
960
- const rangeProof = await generateRangeProof(
961
- amount,
962
- recipientCiphertext.commitment,
963
- randomness
964
- );
965
- const validityProof = await generateValidityProof(
966
- recipientCiphertext,
967
- recipientPubkey,
968
- randomness
969
- );
970
- let auditorProof;
971
- if (auditorPubkey) {
972
- const auditorCiphertext = encryptAmount(amount, auditorPubkey);
973
- const auditorRandomness = new Uint8Array(32);
974
- crypto.getRandomValues(auditorRandomness);
975
- const equalityProof = generateEqualityProof(
976
- recipientCiphertext,
977
- auditorCiphertext,
978
- randomness,
979
- auditorRandomness
980
- );
981
- auditorProof = new Uint8Array(160);
982
- auditorProof.set(serializeCiphertext(auditorCiphertext), 0);
983
- auditorProof.set(equalityProof.proof, 64);
828
+ var ProposalUtils = class {
829
+ /**
830
+ * Check if proposal is in voting period
831
+ */
832
+ static isVotingOpen(proposal) {
833
+ const now = BigInt(Math.floor(Date.now() / 1e3));
834
+ return proposal.status === 1 /* Active */ && now >= proposal.votingStartsAt && now <= proposal.votingEndsAt;
984
835
  }
985
- return {
986
- encryptedAmount,
987
- rangeProof: rangeProof.proof,
988
- validityProof: validityProof.proof,
989
- auditorProof
990
- };
991
- }
992
- async function verifyConfidentialTransferProof(proof, publicInputs) {
993
- try {
994
- if (proof.encryptedAmount.length !== 64) {
995
- return false;
996
- }
997
- if (proof.rangeProof.length < 128) {
998
- return false;
836
+ /**
837
+ * Check if proposal has expired
838
+ */
839
+ static hasExpired(proposal) {
840
+ const now = BigInt(Math.floor(Date.now() / 1e3));
841
+ return now > proposal.votingEndsAt;
842
+ }
843
+ /**
844
+ * Calculate time remaining for voting
845
+ */
846
+ static timeRemaining(proposal) {
847
+ const now = BigInt(Math.floor(Date.now() / 1e3));
848
+ if (now >= proposal.votingEndsAt) return 0n;
849
+ return proposal.votingEndsAt - now;
850
+ }
851
+ /**
852
+ * Format time remaining as human-readable string
853
+ */
854
+ static formatTimeRemaining(proposal) {
855
+ const remaining = this.timeRemaining(proposal);
856
+ if (remaining === 0n) return "Voting ended";
857
+ const seconds = Number(remaining);
858
+ const days = Math.floor(seconds / 86400);
859
+ const hours = Math.floor(seconds % 86400 / 3600);
860
+ const minutes = Math.floor(seconds % 3600 / 60);
861
+ if (days > 0) return `${days}d ${hours}h remaining`;
862
+ if (hours > 0) return `${hours}h ${minutes}m remaining`;
863
+ return `${minutes}m remaining`;
864
+ }
865
+ /**
866
+ * Calculate if proposal has reached quorum
867
+ */
868
+ static hasReachedQuorum(votingResults, quorumRequirements, totalEligibleVoters) {
869
+ const totalVotes = Number(votingResults.votesFor + votingResults.votesAgainst + votingResults.votesAbstain);
870
+ const participationRate = totalVotes / totalEligibleVoters * 100;
871
+ return participationRate >= quorumRequirements.minimumParticipation;
872
+ }
873
+ /**
874
+ * Calculate voting results summary
875
+ */
876
+ static calculateResults(votingResults) {
877
+ const total = Number(votingResults.votesFor + votingResults.votesAgainst + votingResults.votesAbstain);
878
+ if (total === 0) {
879
+ return {
880
+ total: 0,
881
+ forPercentage: 0,
882
+ againstPercentage: 0,
883
+ abstainPercentage: 0,
884
+ passed: false
885
+ };
999
886
  }
1000
- if (proof.validityProof.length < 64) {
1001
- return false;
887
+ const forPercentage = Number(votingResults.votesFor) / total * 100;
888
+ const againstPercentage = Number(votingResults.votesAgainst) / total * 100;
889
+ const abstainPercentage = Number(votingResults.votesAbstain) / total * 100;
890
+ const passed = votingResults.votesFor > votingResults.votesAgainst;
891
+ return {
892
+ total,
893
+ forPercentage,
894
+ againstPercentage,
895
+ abstainPercentage,
896
+ passed
897
+ };
898
+ }
899
+ /**
900
+ * Validate proposal
901
+ */
902
+ static validateProposal(proposal) {
903
+ if (!proposal.title || proposal.title.trim().length === 0) {
904
+ return { valid: false, error: "Title is required" };
1002
905
  }
1003
- if (publicInputs.auditorPubkey && !proof.auditorProof) {
1004
- return false;
906
+ if (proposal.title.length > 100) {
907
+ return { valid: false, error: "Title cannot exceed 100 characters" };
1005
908
  }
1006
- if (proof.auditorProof && proof.auditorProof.length !== 160) {
1007
- return false;
909
+ if (!proposal.description || proposal.description.trim().length === 0) {
910
+ return { valid: false, error: "Description is required" };
1008
911
  }
1009
- const {
1010
- verifyRangeProof,
1011
- verifyValidityProof,
1012
- verifyEqualityProof,
1013
- deserializeCiphertext
1014
- } = await import('./elgamal-VZLWB3XK.js');
1015
- const encryptedAmountCiphertext = deserializeCiphertext(proof.encryptedAmount);
1016
- const rangeProofValid = await verifyRangeProof(
1017
- { proof: proof.rangeProof, commitment: encryptedAmountCiphertext.commitment.commitment },
1018
- encryptedAmountCiphertext.commitment.commitment
1019
- );
1020
- if (!rangeProofValid) {
1021
- return false;
912
+ if (proposal.description.length > 5e3) {
913
+ return { valid: false, error: "Description cannot exceed 5000 characters" };
1022
914
  }
1023
- const validityProofValid = verifyValidityProof(
1024
- { proof: proof.validityProof },
1025
- encryptedAmountCiphertext,
1026
- publicInputs.recipientPubkey
1027
- );
1028
- if (!validityProofValid) {
1029
- return false;
915
+ return { valid: true };
916
+ }
917
+ };
918
+ var VotingUtils = class {
919
+ /**
920
+ * Calculate vote weight based on token holdings or other factors
921
+ */
922
+ static calculateVoteWeight(baseWeight, tokenBalance, stakeDuration) {
923
+ let weight = baseWeight;
924
+ if (tokenBalance) {
925
+ const tokenMultiplier = Math.min(Number(tokenBalance / 1000000n), 10);
926
+ weight *= tokenMultiplier;
1030
927
  }
1031
- if (proof.auditorProof && publicInputs.auditorPubkey) {
1032
- const auditorCiphertext = deserializeCiphertext(proof.auditorProof.slice(0, 64));
1033
- const equalityProofData = proof.auditorProof.slice(64);
1034
- const equalityProofValid = verifyEqualityProof(
1035
- { proof: equalityProofData },
1036
- encryptedAmountCiphertext,
1037
- auditorCiphertext
1038
- );
1039
- if (!equalityProofValid) {
1040
- return false;
1041
- }
928
+ if (stakeDuration) {
929
+ const daysStaked = Number(stakeDuration / 86400n);
930
+ const timeMultiplier = 1 + daysStaked / 365;
931
+ weight *= timeMultiplier;
1042
932
  }
1043
- return true;
1044
- } catch {
1045
- return false;
933
+ return Math.floor(weight);
1046
934
  }
1047
- }
1048
- function calculateInterest(principal, config, currentTimestamp) {
1049
- const timePeriodSeconds = currentTimestamp - config.lastUpdateTimestamp;
1050
- const secondsPerYear = 365n * 24n * 60n * 60n;
1051
- const rateBasisPoints = BigInt(config.currentRate);
1052
- const interestAmount = principal * rateBasisPoints * timePeriodSeconds / (10000n * secondsPerYear);
1053
- const newBalance = principal + interestAmount;
1054
- const yearFraction = Number(timePeriodSeconds) / Number(secondsPerYear);
1055
- const effectiveAnnualRate = config.currentRate / 100 * yearFraction;
1056
- return {
1057
- principal,
1058
- annualRateBasisPoints: config.currentRate,
1059
- timePeriodSeconds,
1060
- interestAmount,
1061
- newAmount: newBalance,
1062
- effectiveAnnualRate
1063
- };
1064
- }
1065
- function calculateCompoundInterest(principal, annualRateBasisPoints, compoundingPeriodsPerYear, years) {
1066
- const rate = annualRateBasisPoints / 1e4;
1067
- const n = compoundingPeriodsPerYear;
1068
- const compoundFactor = Math.pow(1 + rate / n, n * years);
1069
- const newBalanceFloat = Number(principal) * compoundFactor;
1070
- const newBalance = BigInt(Math.floor(newBalanceFloat));
1071
- const interestAmount = newBalance - principal;
1072
- const timePeriodSeconds = BigInt(Math.floor(years * 365 * 24 * 60 * 60));
1073
- return {
1074
- principal,
1075
- annualRateBasisPoints,
1076
- timePeriodSeconds,
1077
- interestAmount,
1078
- newAmount: newBalance,
1079
- effectiveAnnualRate: (compoundFactor - 1) * 100
1080
- };
1081
- }
1082
- function validateTransferHookInstruction(instruction) {
1083
- if (!instruction.programId) return false;
1084
- if (!Array.isArray(instruction.additionalAccounts)) return false;
1085
- return true;
1086
- }
1087
- function createTransferHookInstruction(hookProgramId, context) {
1088
- const instructionData = new Uint8Array([
1089
- ...getAddressEncoder().encode(context.source),
1090
- ...getAddressEncoder().encode(context.destination),
1091
- ...getAddressEncoder().encode(context.authority),
1092
- ...getU64Encoder().encode(context.amount),
1093
- ...getAddressEncoder().encode(context.mint),
1094
- ...getBytesEncoder().encode(context.contextData)
1095
- ]);
1096
- return {
1097
- programId: hookProgramId,
1098
- instructionData,
1099
- additionalAccounts: []
1100
- // Hook-specific accounts would be added here
1101
- };
1102
- }
1103
- function serializeTokenMetadata(metadata) {
1104
- const jsonString = JSON.stringify(metadata);
1105
- const encoded = getUtf8Encoder().encode(jsonString);
1106
- return new Uint8Array(encoded);
1107
- }
1108
- function deserializeTokenMetadata(data) {
1109
- const jsonString = new TextDecoder().decode(data);
1110
- return JSON.parse(jsonString);
1111
- }
1112
- var TokenAccountState = /* @__PURE__ */ ((TokenAccountState2) => {
1113
- TokenAccountState2[TokenAccountState2["UNINITIALIZED"] = 0] = "UNINITIALIZED";
1114
- TokenAccountState2[TokenAccountState2["INITIALIZED"] = 1] = "INITIALIZED";
1115
- TokenAccountState2[TokenAccountState2["FROZEN"] = 2] = "FROZEN";
1116
- return TokenAccountState2;
1117
- })(TokenAccountState || {});
1118
- function canTransfer(state, isNonTransferable = false, isFrozen = false) {
1119
- if (state !== 1 /* INITIALIZED */) return false;
1120
- if (isNonTransferable) return false;
1121
- if (isFrozen) return false;
1122
- return true;
1123
- }
1124
- function getRequiredExtensions(extensions) {
1125
- const required = /* @__PURE__ */ new Set();
1126
- for (const extension of extensions) {
1127
- required.add(extension);
1128
- switch (extension) {
1129
- case 2 /* TRANSFER_FEE_AMOUNT */:
1130
- required.add(1 /* TRANSFER_FEE_CONFIG */);
1131
- break;
1132
- case 5 /* CONFIDENTIAL_TRANSFER_ACCOUNT */:
1133
- required.add(4 /* CONFIDENTIAL_TRANSFER_MINT */);
1134
- break;
1135
- case 15 /* TRANSFER_HOOK_ACCOUNT */:
1136
- required.add(14 /* TRANSFER_HOOK */);
1137
- break;
935
+ /**
936
+ * Format vote choice as string
937
+ */
938
+ static formatVoteChoice(voteChoice) {
939
+ switch (voteChoice) {
940
+ case 0 /* For */:
941
+ return "\u2705 For";
942
+ case 1 /* Against */:
943
+ return "\u274C Against";
944
+ case 2 /* Abstain */:
945
+ return "\u{1F937} Abstain";
946
+ default:
947
+ return "Unknown";
1138
948
  }
1139
949
  }
1140
- return Array.from(required).sort((a, b) => a - b);
1141
- }
1142
- function basisPointsToPercentage(basisPoints) {
1143
- return basisPoints / 1e4;
1144
- }
1145
- function percentageToBasisPoints(percentage) {
1146
- return Math.round(percentage * 1e4);
1147
- }
1148
- function formatBasisPoints(basisPoints) {
1149
- const percentage = basisPointsToPercentage(basisPoints) * 100;
1150
- return `${percentage.toFixed(2)}%`;
1151
- }
1152
- function estimateComputeUnits(operation, extensions = []) {
1153
- let baseUnits = 0n;
1154
- switch (operation) {
1155
- case "transfer":
1156
- baseUnits = 15000n;
1157
- break;
1158
- case "create_account":
1159
- baseUnits = 25000n;
1160
- break;
1161
- case "mint":
1162
- baseUnits = 10000n;
1163
- break;
1164
- case "burn":
1165
- baseUnits = 10000n;
1166
- break;
950
+ /**
951
+ * Calculate if simple majority is reached
952
+ */
953
+ static hasSimpleMajority(votingResults) {
954
+ return votingResults.votesFor > votingResults.votesAgainst;
1167
955
  }
1168
- let extensionUnits = 0n;
1169
- for (const extension of extensions) {
1170
- switch (extension) {
1171
- case 1 /* TRANSFER_FEE_CONFIG */:
1172
- extensionUnits += 5000n;
1173
- break;
1174
- case 4 /* CONFIDENTIAL_TRANSFER_MINT */:
1175
- case 5 /* CONFIDENTIAL_TRANSFER_ACCOUNT */:
1176
- extensionUnits += 50000n;
1177
- break;
1178
- case 14 /* TRANSFER_HOOK */:
1179
- extensionUnits += 15000n;
1180
- break;
1181
- default:
1182
- extensionUnits += 2000n;
1183
- }
956
+ /**
957
+ * Calculate if supermajority is reached (2/3)
958
+ */
959
+ static hasSupermajority(votingResults) {
960
+ const totalVotes = votingResults.votesFor + votingResults.votesAgainst;
961
+ if (totalVotes === 0n) return false;
962
+ const forPercentage = Number(votingResults.votesFor) / Number(totalVotes);
963
+ return forPercentage >= 0.667;
1184
964
  }
1185
- return baseUnits + extensionUnits;
1186
- }
1187
- function createTransferFeeConfig(params) {
1188
- if (params.transferFeeBasisPoints > 1e4) {
1189
- throw new Error("Transfer fee basis points cannot exceed 10000");
965
+ };
966
+ var PERMISSION_TEMPLATES = {
967
+ // Admin permissions
968
+ ADMIN: {
969
+ CREATE_PROPOSAL: { action: "create", resource: "proposal" },
970
+ EXECUTE_PROPOSAL: { action: "execute", resource: "proposal" },
971
+ MANAGE_ROLES: { action: "manage", resource: "roles" },
972
+ MANAGE_TREASURY: { action: "manage", resource: "treasury" }
973
+ },
974
+ // Member permissions
975
+ MEMBER: {
976
+ VOTE: { action: "vote", resource: "proposal" },
977
+ VIEW: { action: "view", resource: "all" },
978
+ COMMENT: { action: "comment", resource: "proposal" }
979
+ },
980
+ // Moderator permissions
981
+ MODERATOR: {
982
+ CANCEL_PROPOSAL: { action: "cancel", resource: "proposal" },
983
+ MODERATE_COMMENTS: { action: "moderate", resource: "comments" },
984
+ VIEW_REPORTS: { action: "view", resource: "reports" }
1190
985
  }
1191
- return {
1192
- transferFeeBasisPoints: params.transferFeeBasisPoints,
1193
- maximumFee: params.maximumFee,
1194
- transferFeeConfigAuthority: params.transferFeeConfigAuthority,
1195
- withdrawWithheldAuthority: params.withdrawWithheldAuthority,
1196
- withheldAmount: BigInt(0),
1197
- olderTransferFee: {
1198
- epoch: BigInt(0),
1199
- transferFeeBasisPoints: 0,
1200
- maximumFee: BigInt(0)
1201
- },
1202
- newerTransferFee: {
1203
- epoch: BigInt(1),
1204
- transferFeeBasisPoints: params.transferFeeBasisPoints,
1205
- maximumFee: params.maximumFee
1206
- }
1207
- };
1208
- }
1209
- function createInterestBearingConfig(params) {
1210
- if (params.currentRate > 32767 || params.currentRate < -32768) {
1211
- throw new Error("Interest rate must be within i16 range");
986
+ };
987
+ var ROLE_TEMPLATES = {
988
+ ADMIN: {
989
+ name: "Administrator",
990
+ description: "Full administrative access",
991
+ permissions: Object.values(PERMISSION_TEMPLATES.ADMIN)
992
+ },
993
+ MEMBER: {
994
+ name: "Member",
995
+ description: "Standard member access",
996
+ permissions: Object.values(PERMISSION_TEMPLATES.MEMBER)
997
+ },
998
+ MODERATOR: {
999
+ name: "Moderator",
1000
+ description: "Content moderation access",
1001
+ permissions: [
1002
+ ...Object.values(PERMISSION_TEMPLATES.MEMBER),
1003
+ ...Object.values(PERMISSION_TEMPLATES.MODERATOR)
1004
+ ]
1212
1005
  }
1213
- const currentTimestamp = BigInt(Math.floor(Date.now() / 1e3));
1214
- return {
1215
- rateAuthority: params.rateAuthority,
1216
- initializationTimestamp: currentTimestamp,
1217
- preUpdateAverageRate: 0,
1218
- lastUpdateTimestamp: currentTimestamp,
1219
- currentRate: params.currentRate
1220
- };
1221
- }
1222
- function parseTokenExtension(extensionType, data) {
1223
- switch (extensionType) {
1224
- case "TransferFeeConfig": {
1225
- if (data.length < 108) {
1226
- throw new Error("Invalid extension data length");
1227
- }
1228
- const transferFeeBasisPoints = data[0] | data[1] << 8;
1229
- return {
1230
- transferFeeBasisPoints,
1231
- maximumFee: BigInt(0),
1232
- // Would parse from bytes 2-9
1233
- transferFeeConfigAuthority: null,
1234
- withdrawWithheldAuthority: null,
1235
- withheldAmount: BigInt(0),
1236
- olderTransferFee: {
1237
- epoch: BigInt(0),
1238
- transferFeeBasisPoints: 0,
1239
- maximumFee: BigInt(0)
1240
- },
1241
- newerTransferFee: {
1242
- epoch: BigInt(1),
1243
- transferFeeBasisPoints,
1244
- maximumFee: BigInt(0)
1245
- }
1246
- };
1247
- }
1248
- case "InterestBearingConfig": {
1249
- if (data.length < 40) {
1250
- throw new Error("Invalid extension data length");
1251
- }
1252
- let timestamp = 0n;
1253
- for (let i = 0; i < 8; i++) {
1254
- timestamp |= BigInt(data[i]) << BigInt(i * 8);
1255
- }
1256
- return {
1257
- rateAuthority: null,
1258
- initializationTimestamp: timestamp,
1259
- preUpdateAverageRate: 0,
1260
- lastUpdateTimestamp: timestamp,
1261
- currentRate: 0
1262
- };
1006
+ };
1007
+ var GovernanceAnalyticsUtils = class {
1008
+ /**
1009
+ * Calculate governance health score (0-100)
1010
+ */
1011
+ static calculateHealthScore(analytics) {
1012
+ let score = 0;
1013
+ score += Math.min(analytics.averageVoterTurnout * 0.4, 40);
1014
+ const totalCompleted = analytics.passedProposals + analytics.failedProposals;
1015
+ if (totalCompleted > 0) {
1016
+ const successRate = analytics.passedProposals / totalCompleted;
1017
+ score += successRate * 30;
1263
1018
  }
1264
- default:
1265
- throw new Error("Unknown extension type");
1019
+ const activityRatio = analytics.activeProposals / Math.max(analytics.totalProposals, 1);
1020
+ score += Math.min(activityRatio * 60, 30);
1021
+ return Math.round(score);
1266
1022
  }
1267
- }
1023
+ /**
1024
+ * Generate governance summary report
1025
+ */
1026
+ static generateSummaryReport(analytics) {
1027
+ const healthScore = this.calculateHealthScore(analytics);
1028
+ const successRate = analytics.totalProposals > 0 ? Math.round(analytics.passedProposals / analytics.totalProposals * 100) : 0;
1029
+ return `
1030
+ Governance Summary:
1031
+ - Total Proposals: ${analytics.totalProposals}
1032
+ - Active: ${analytics.activeProposals}
1033
+ - Success Rate: ${successRate}%
1034
+ - Avg Turnout: ${Math.round(analytics.averageVoterTurnout)}%
1035
+ - Health Score: ${healthScore}/100
1036
+ `.trim();
1037
+ }
1038
+ };
1268
1039
 
1269
1040
  // src/utils/feature-flags.ts
1270
1041
  var feature_flags_exports = {};
@@ -1405,6 +1176,69 @@ __export(client_encryption_exports, {
1405
1176
  generateLocalPrivacyProof: () => generateLocalPrivacyProof,
1406
1177
  verifyLocalPrivacyProof: () => verifyLocalPrivacyProof
1407
1178
  });
1179
+ var MAX_DECRYPTABLE_VALUE = 4294967295n;
1180
+ var G = ed25519.ExtendedPoint.BASE;
1181
+ var hash = (data) => sha256(data);
1182
+ function generateElGamalKeypair(seed) {
1183
+ const secretKey = seed ? hash(seed).slice(0, 32) : randomBytes(32);
1184
+ secretKey[0] &= 248;
1185
+ secretKey[31] &= 127;
1186
+ secretKey[31] |= 64;
1187
+ const scalarValue = bytesToNumberLE(secretKey) % ed25519.CURVE.n;
1188
+ const publicKey = G.multiply(scalarValue).toRawBytes();
1189
+ return { publicKey, secretKey };
1190
+ }
1191
+ function encryptAmount(amount, pubkey) {
1192
+ const result = encryptAmountWithRandomness(amount, pubkey);
1193
+ return result.ciphertext;
1194
+ }
1195
+ function encryptAmountWithRandomness(amount, pubkey, providedRandomness) {
1196
+ if (amount < 0n) {
1197
+ throw new Error("Amount must be non-negative");
1198
+ }
1199
+ if (amount > MAX_DECRYPTABLE_VALUE) {
1200
+ throw new Error(`Amount exceeds maximum decryptable value (${MAX_DECRYPTABLE_VALUE})`);
1201
+ }
1202
+ const randomness = randomBytes(32);
1203
+ randomness[0] &= 248;
1204
+ randomness[31] &= 127;
1205
+ randomness[31] |= 64;
1206
+ const r = bytesToNumberLE(randomness) % ed25519.CURVE.n;
1207
+ const pubkeyPoint = ed25519.ExtendedPoint.fromHex(bytesToHex(pubkey));
1208
+ const amountPoint = amount === 0n ? ed25519.ExtendedPoint.ZERO : G.multiply(amount);
1209
+ const maskedAmount = amountPoint.add(pubkeyPoint.multiply(r));
1210
+ const commitment = maskedAmount.toRawBytes();
1211
+ const handle = G.multiply(r).toRawBytes();
1212
+ return {
1213
+ ciphertext: {
1214
+ commitment: { commitment },
1215
+ handle: { handle }
1216
+ },
1217
+ randomness
1218
+ };
1219
+ }
1220
+ function decryptAmount(ciphertext, secretKey, maxValue = 65536n) {
1221
+ const C = ed25519.ExtendedPoint.fromHex(bytesToHex(ciphertext.commitment.commitment));
1222
+ const D = ed25519.ExtendedPoint.fromHex(bytesToHex(ciphertext.handle.handle));
1223
+ const sk = bytesToNumberLE(secretKey) % ed25519.CURVE.n;
1224
+ const decryptedPoint = C.subtract(D.multiply(sk));
1225
+ for (let i = 0n; i <= maxValue; i++) {
1226
+ const testPoint = i === 0n ? ed25519.ExtendedPoint.ZERO : G.multiply(i);
1227
+ if (testPoint.equals(decryptedPoint)) {
1228
+ return i;
1229
+ }
1230
+ }
1231
+ return null;
1232
+ }
1233
+ function getGeneratorH() {
1234
+ const hashInput = new TextEncoder().encode("ElGamal-Generator-H");
1235
+ const hashOutput = hash(hashInput);
1236
+ const scalar = bytesToNumberLE(hashOutput) % ed25519.CURVE.n;
1237
+ return G.multiply(scalar);
1238
+ }
1239
+ getGeneratorH();
1240
+
1241
+ // src/utils/client-encryption.ts
1408
1242
  var ClientEncryptionService = class {
1409
1243
  keypair;
1410
1244
  featureFlags = getFeatureFlags();
@@ -1567,6 +1401,6 @@ async function verifyLocalPrivacyProof(proof, publicInputs, encrypted) {
1567
1401
  return bytesToHex(proofCommitment) === bytesToHex(encrypted.commitment) && bytesToHex(inputCommitment) === bytesToHex(encrypted.commitment);
1568
1402
  }
1569
1403
 
1570
- export { ClientEncryptionService, FeatureFlagManager, TokenAccountState, TokenExtension, TokenProgram, account_diagnostics_exports, basisPointsToPercentage, calculateCompoundInterest, calculateInterest, calculateRequiredAmountForNetTransfer, calculateTransferFee, canTransfer, client_encryption_exports, createDiscriminatorErrorMessage, createMigrationPlan, createMigrationReport, createTransferHookInstruction, deriveAssociatedTokenAddress, deriveSplTokenAssociatedTokenAddress, deriveToken2022AssociatedTokenAddress, deserializeTokenMetadata, detectTokenProgram, diagnoseAccountFromChain, diagnoseBatchFromChain, estimateAccumulatedFees, estimateComputeUnits, exportDiagnosticReport, extractLegacyData, feature_flags_exports, formatBasisPoints, formatTokenAmount, generateConfidentialTransferProof, generateLocalPrivacyProof, getAllAssociatedTokenAddresses, getAssociatedTokenAccount, getConfidentialTransferConfig, getFeatureFlags, getInterestBearingConfig, getMigrationInstructions, getRequiredExtensions, getTokenProgramAddress, getTokenProgramFromAddress, getTokenProgramType, getTransferFeeConfig, hasConfidentialTransferExtension, hasInterestBearingExtension, hasTransferFeeExtension, inspectAccountData, isFeatureEnabled, isToken2022Mint, parseTokenAmount, percentageToBasisPoints, runAccountDiagnostics, runBatchDiagnostics, safeDecodeAgent, serializeTokenMetadata, simulateMigration, token_2022_extensions_exports, validateAccountDiscriminator, validateAssociatedTokenAddress, validateTransferHookInstruction, verifyConfidentialTransferProof, verifyLocalPrivacyProof };
1571
- //# sourceMappingURL=chunk-F3DZMBUA.js.map
1572
- //# sourceMappingURL=chunk-F3DZMBUA.js.map
1404
+ export { ClientEncryptionService, FeatureFlagManager, TokenExtension, TokenProgram, account_diagnostics_exports, client_encryption_exports, createDiscriminatorErrorMessage, createMigrationPlan, createMigrationReport, deriveAssociatedTokenAddress, deriveMultisigPda, deriveProposalPda, deriveSplTokenAssociatedTokenAddress, deriveToken2022AssociatedTokenAddress, detectTokenProgram, diagnoseAccountFromChain, diagnoseBatchFromChain, exportDiagnosticReport, extractLegacyData, feature_flags_exports, formatTokenAmount, generateLocalPrivacyProof, getAllAssociatedTokenAddresses, getAssociatedTokenAccount, getConfidentialTransferConfig, getFeatureFlags, getInterestBearingConfig, getMigrationInstructions, getTokenProgramAddress, getTokenProgramFromAddress, getTokenProgramType, getTransferFeeConfig, governance_helpers_exports, hasConfidentialTransferExtension, hasInterestBearingExtension, hasTransferFeeExtension, inspectAccountData, isFeatureEnabled, isToken2022Mint, parseTokenAmount, runAccountDiagnostics, runBatchDiagnostics, safeDecodeAgent, simulateMigration, validateAccountDiscriminator, validateAssociatedTokenAddress, verifyLocalPrivacyProof };
1405
+ //# sourceMappingURL=chunk-5QBSC4T4.js.map
1406
+ //# sourceMappingURL=chunk-5QBSC4T4.js.map