@ghostspeak/sdk 2.0.0 → 2.0.1

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 (102) hide show
  1. package/LICENSE +21 -0
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/GhostSpeakClient-CyeZ6Tyb.d.ts +2061 -0
  4. package/dist/client.d.ts +4 -3
  5. package/dist/crypto.d.ts +2 -2
  6. package/dist/{feature-flags-CEaxXgQQ.d.ts → feature-flags-3POmoO_Z.d.ts} +833 -1190
  7. package/dist/index.d.ts +206 -4543
  8. package/dist/ipfs-types-KJcvy9Qk.d.ts +553 -0
  9. package/dist/minimal/core-minimal.d.ts +2037 -82
  10. package/dist/utils.d.ts +4 -4
  11. package/package.json +5 -29
  12. package/dist/EscrowInstructions-4P3H6ETO.js +0 -2
  13. package/dist/EscrowInstructions-4P3H6ETO.js.map +0 -1
  14. package/dist/GhostSpeakClient-4SROinEf.d.ts +0 -503
  15. package/dist/accounts-IUZMPYVE.js +0 -2
  16. package/dist/accounts-IUZMPYVE.js.map +0 -1
  17. package/dist/agent-GZ2OES75.js +0 -2
  18. package/dist/agent-GZ2OES75.js.map +0 -1
  19. package/dist/auctionMarketplace-W4YM7HKU.js +0 -2
  20. package/dist/auctionMarketplace-W4YM7HKU.js.map +0 -1
  21. package/dist/chunk-2KOOI5BX.js +0 -2
  22. package/dist/chunk-2KOOI5BX.js.map +0 -1
  23. package/dist/chunk-32GWTXRJ.js +0 -3
  24. package/dist/chunk-32GWTXRJ.js.map +0 -1
  25. package/dist/chunk-B4WUFVLE.js +0 -2
  26. package/dist/chunk-B4WUFVLE.js.map +0 -1
  27. package/dist/chunk-C2OTQ5YS.js +0 -2
  28. package/dist/chunk-C2OTQ5YS.js.map +0 -1
  29. package/dist/chunk-CTC4ZJ26.js +0 -5
  30. package/dist/chunk-CTC4ZJ26.js.map +0 -1
  31. package/dist/chunk-DF7LLAMH.js +0 -2
  32. package/dist/chunk-DF7LLAMH.js.map +0 -1
  33. package/dist/chunk-DJ356OUX.js +0 -2
  34. package/dist/chunk-DJ356OUX.js.map +0 -1
  35. package/dist/chunk-DK5YDBXR.js +0 -2
  36. package/dist/chunk-DK5YDBXR.js.map +0 -1
  37. package/dist/chunk-DOTF5ECA.js +0 -4
  38. package/dist/chunk-DOTF5ECA.js.map +0 -1
  39. package/dist/chunk-FKEUXXZS.js +0 -30
  40. package/dist/chunk-FKEUXXZS.js.map +0 -1
  41. package/dist/chunk-GSHXEKBW.js +0 -2
  42. package/dist/chunk-GSHXEKBW.js.map +0 -1
  43. package/dist/chunk-IZDAEOLH.js +0 -2
  44. package/dist/chunk-IZDAEOLH.js.map +0 -1
  45. package/dist/chunk-JY554RGE.js +0 -3
  46. package/dist/chunk-JY554RGE.js.map +0 -1
  47. package/dist/chunk-KK3HV2RD.js +0 -3
  48. package/dist/chunk-KK3HV2RD.js.map +0 -1
  49. package/dist/chunk-PPOCDM6G.js +0 -2
  50. package/dist/chunk-PPOCDM6G.js.map +0 -1
  51. package/dist/chunk-PUI35LBF.js +0 -2
  52. package/dist/chunk-PUI35LBF.js.map +0 -1
  53. package/dist/chunk-Q34J6YDA.js +0 -11
  54. package/dist/chunk-Q34J6YDA.js.map +0 -1
  55. package/dist/chunk-QATBFZMM.js +0 -3
  56. package/dist/chunk-QATBFZMM.js.map +0 -1
  57. package/dist/chunk-QTKN3VZV.js +0 -2
  58. package/dist/chunk-QTKN3VZV.js.map +0 -1
  59. package/dist/chunk-RFBYMTTN.js +0 -2
  60. package/dist/chunk-RFBYMTTN.js.map +0 -1
  61. package/dist/chunk-RJJPOLCK.js +0 -22
  62. package/dist/chunk-RJJPOLCK.js.map +0 -1
  63. package/dist/chunk-RTWJTEND.js +0 -2
  64. package/dist/chunk-RTWJTEND.js.map +0 -1
  65. package/dist/chunk-SR3ZJCME.js +0 -2
  66. package/dist/chunk-SR3ZJCME.js.map +0 -1
  67. package/dist/chunk-TAWXH7KX.js +0 -2
  68. package/dist/chunk-TAWXH7KX.js.map +0 -1
  69. package/dist/client.js +0 -2
  70. package/dist/client.js.map +0 -1
  71. package/dist/confidential-transfer-manager-CGS3T5DG.js +0 -2
  72. package/dist/confidential-transfer-manager-CGS3T5DG.js.map +0 -1
  73. package/dist/crypto.js +0 -2
  74. package/dist/crypto.js.map +0 -1
  75. package/dist/elgamal-3ABOJSHC.js +0 -2
  76. package/dist/elgamal-3ABOJSHC.js.map +0 -1
  77. package/dist/enhanced-client-errors-W22U3LNH.js +0 -2
  78. package/dist/enhanced-client-errors-W22U3LNH.js.map +0 -1
  79. package/dist/errors.js +0 -2
  80. package/dist/errors.js.map +0 -1
  81. package/dist/generated-U3L4KUE4.js +0 -2
  82. package/dist/generated-U3L4KUE4.js.map +0 -1
  83. package/dist/ghostspeak_wasm-3KPNJTSS.js +0 -2
  84. package/dist/ghostspeak_wasm-3KPNJTSS.js.map +0 -1
  85. package/dist/index.js +0 -97
  86. package/dist/index.js.map +0 -1
  87. package/dist/ipfs-types-BlxtJ3q2.d.ts +0 -194
  88. package/dist/metafile-esm.json +0 -1
  89. package/dist/minimal/core-minimal.js +0 -12
  90. package/dist/minimal/core-minimal.js.map +0 -1
  91. package/dist/pda-2GUWRQ5G.js +0 -2
  92. package/dist/pda-2GUWRQ5G.js.map +0 -1
  93. package/dist/registerAgentCompressed-L6ACXD2Z.js +0 -2
  94. package/dist/registerAgentCompressed-L6ACXD2Z.js.map +0 -1
  95. package/dist/token-2022-rpc-SRHRFN5Y.js +0 -2
  96. package/dist/token-2022-rpc-SRHRFN5Y.js.map +0 -1
  97. package/dist/types.js +0 -2
  98. package/dist/types.js.map +0 -1
  99. package/dist/utils.js +0 -2
  100. package/dist/utils.js.map +0 -1
  101. package/dist/zk-proof-builder-GXZ42QZA.js +0 -2
  102. package/dist/zk-proof-builder-GXZ42QZA.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/zk-proof-instructions.ts","../src/utils/feature-gate-detector.ts","../src/utils/zk-proof-builder.ts"],"names":["createVerifyTransferProofInstruction","accounts","proofData","data","serializeTransferProofData","accountMetas","ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS","createVerifyRangeProofInstruction","commitment","rangeProof","getStructEncoder","getU8Encoder","fixEncoderSize","getBytesEncoder","PROOF_SIZES","createVerifyValidityProofInstruction","ciphertext","validityProof","encoder","FEATURE_GATES","PublicKey","CACHE_TTL_MS","MAX_CACHE_ENTRIES","FeatureGateCacheManager","featureId","cached","status","oldest","id","featureCache","checkFeatureGate","connection","featureGate","accountInfo","activationSlot","error","errorStatus","isZkProgramEnabled","getZkProgramFeatureStatus","clearFeatureGateCache","getZkProgramStatusDescription","G","ed25519","H_BYTES","sha256","H_SCALAR","bytesToNumberLE","H","zkProgramStatusCache","ZK_STATUS_CACHE_TTL","ProofMode","generateRangeProofWithCommitment","amount","randomness","options","mode","gamma","commitmentBytes","proof","createSimplifiedRangeProof","instruction","zkProgramEnabled","checkZkProgramStatus","offset","a0","g0","A","a1","g1","S","a2","g2","T1","a3","g3","T2","challenge","taux","mu","tx","scalarToBytes","remaining","innerProduct","randomBytes","verifyRangeProofLocal","_commitmentPoint","bytesToHex","generateValidityProofWithInstruction","pubkey","r","pubkeyPoint","k","z1","z2","generateTransferProofWithInstruction","sourceBalance","transferAmount","sourcePubkey","destPubkey","sourceRandomness","transferRandomness","destR","destPubkeyPoint","destCommitment","destHandle","destCiphertext","newSourceBalance","rangeProofResult","validityProofResult","equalityProof","b","i","transferProof","scalar","bytes","enabled","message","isZkProgramAvailable","getZkProgramStatus","getZkProgramAddress","clearZkProgramStatusCache"],"mappings":"oXAuEO,SAASA,EACdC,CAAAA,CACAC,CAAAA,CACc,CAEd,IAAMC,CAAAA,CAAOC,EAA2BF,CAAS,CAAA,CAG3CG,EAA+B,CACnC,CAAE,QAASJ,CAAAA,CAAS,YAAA,CAAc,KAAM,CAAE,CAC5C,EAEA,OAAIA,CAAAA,CAAS,eACXI,CAAAA,CAAa,IAAA,CAAK,C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,IAAA,CAAK,GAAA,GAAQA,CAAAA,CAAqB,WAAA,CAAcC,EAClD,OAAOD,CAAAA,CAAqB,OAAA,CAI9B,GAAI,CACF,IAAMmE,EAAU,MAAM9E,CAAAA,CAAmBN,CAAU,CAAA,CAC7CqF,CAAAA,CAAU,MAAM5E,CAAAA,CAA8BT,CAAU,EAG9D,OAAAiB,CAAAA,CAAuB,CACrB,OAAA,CAAAmE,CAAAA,CACA,YAAa,IAAA,CAAK,GAAA,GAClB,OAAA,CAAAC,CACF,EAEOD,CACT,CAAA,MAAShF,EAAO,CACd,OAAA,OAAA,CAAQ,KAAK,oCAAA,CAAsCA,CAAK,EAExDa,CAAAA,CAAuB,CACrB,QAAS,KAAA,CACT,WAAA,CAAa,KAAK,GAAA,EAAI,CACtB,QAAS,CAAA,gCAAA,EAAmCb,CAAAA,YAAiB,MAAQA,CAAAA,CAAM,OAAA,CAAU,eAAe,CAAA,CACtG,CAAA,CACO,KACT,CACF,CAKA,eAAsBkF,GAAqBtF,CAAAA,CAA2C,CACpF,OAAKA,CAAAA,CAGE+B,CAAAA,CAAqB/B,CAAU,CAAA,CAF7B,KAGX,CAKA,eAAsBuF,EAAAA,CAAmBvF,EAA0C,CACjF,OAAKA,EAKDiB,CAAAA,EACA,IAAA,CAAK,KAAI,CAAIA,CAAAA,CAAqB,YAAcC,CAAAA,CAC3CD,CAAAA,CAAqB,SAI9B,MAAMc,CAAAA,CAAqB/B,CAAU,CAAA,CAC9BiB,CAAAA,EAAsB,SAAW,2BAAA,CAAA,CAX/B,2CAYX,CAKO,SAASuE,EAAAA,EAAsB,CACpC,OAAOjH,CACT,CAKO,SAASkH,EAAAA,EAAkC,CAChDxE,CAAAA,CAAuB,KACzB","file":"chunk-PPOCDM6G.js","sourcesContent":["/**\n * ZK ElGamal Proof Program Instructions\n * \n * Instruction builders for interacting with Solana's native ZK ElGamal Proof Program.\n * These instructions enable on-chain verification of zero-knowledge proofs for\n * confidential transfers and other privacy-preserving operations.\n * \n * Account Role Mapping (from @solana/kit):\n * - 0: ReadonlyNonSigner\n * - 1: ReadonlySigner \n * - 2: WritableNonSigner\n * - 3: WritableSigner\n */\n\nimport { type Address, address } from '@solana/addresses'\nimport type { \n IInstruction, \n IAccountMeta, \n TransactionSigner\n} from '@solana/kit'\nimport {\n getStructEncoder,\n getU8Encoder,\n getBytesEncoder,\n fixEncoderSize,\n getAddressEncoder,\n getU32Encoder,\n getU64Encoder\n} from '@solana/kit'\nimport { sha256 } from '@noble/hashes/sha256'\nimport bs58 from 'bs58'\n\nimport {\n ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS,\n ProofInstruction,\n type TransferProofData,\n type WithdrawProofData,\n type TransferWithFeeProofData,\n PROOF_SIZES\n} from '../constants/zk-proof-program.js'\n\n// Re-export for convenience\nexport { ProofInstruction, PROOF_SIZES }\n\n/**\n * Account structure for proof verification instructions\n */\nexport interface ProofVerificationAccounts {\n /** The proof context account (must be writable) */\n proofContext: Address\n \n /** System program (for context account creation if needed) */\n systemProgram?: Address\n \n /** Authority that owns the proof context (optional) */\n authority?: TransactionSigner\n \n /** Rent sysvar (for legacy compatibility) */\n rentSysvar?: Address\n}\n\n/**\n * Create instruction to verify a transfer proof\n * \n * This instruction verifies range, validity, and equality proofs for a\n * confidential transfer operation.\n * \n * @param accounts - Required accounts for verification\n * @param proofData - The transfer proof data to verify\n * @returns Instruction for proof verification\n */\nexport function createVerifyTransferProofInstruction(\n accounts: ProofVerificationAccounts,\n proofData: TransferProofData\n): IInstruction {\n // Serialize proof data\n const data = serializeTransferProofData(proofData)\n \n // Account metas\n const accountMetas: IAccountMeta[] = [\n { address: accounts.proofContext, role: 2 },\n ]\n \n if (accounts.systemProgram) {\n accountMetas.push({ address: accounts.systemProgram, role: 0 })\n }\n \n return {\n programAddress: ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS,\n accounts: accountMetas,\n data\n }\n}\n\n/**\n * Create instruction to verify a withdraw proof\n * \n * This instruction verifies the proof that a withdrawal maintains\n * a valid (non-negative) remaining balance.\n * \n * @param accounts - Required accounts for verification\n * @param proofData - The withdraw proof data to verify\n * @returns Instruction for proof verification\n */\nexport function createVerifyWithdrawProofInstruction(\n accounts: ProofVerificationAccounts,\n proofData: WithdrawProofData\n): IInstruction {\n // Serialize proof data\n const data = serializeWithdrawProofData(proofData)\n \n // Account metas\n const accountMetas: IAccountMeta[] = [\n { address: accounts.proofContext, role: 2 },\n ]\n \n if (accounts.systemProgram) {\n accountMetas.push({ address: accounts.systemProgram, role: 0 })\n }\n \n return {\n programAddress: ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS,\n accounts: accountMetas,\n data\n }\n}\n\n/**\n * Create instruction to verify a range proof\n * \n * This instruction verifies that an encrypted value is within a valid range\n * (typically 0 to 2^64 - 1 for token amounts).\n * \n * @param accounts - Required accounts for verification\n * @param commitment - The Pedersen commitment to verify\n * @param rangeProof - The range proof data\n * @returns Instruction for proof verification\n */\nexport function createVerifyRangeProofInstruction(\n accounts: ProofVerificationAccounts,\n commitment: Uint8Array,\n rangeProof: Uint8Array\n): IInstruction {\n // Create encoder for the instruction data\n const encoder = getStructEncoder([\n ['instruction', getU8Encoder()],\n ['commitment', fixEncoderSize(getBytesEncoder(), PROOF_SIZES.COMMITMENT)],\n ['proof', getBytesEncoder()]\n ])\n \n const data = encoder.encode({\n instruction: ProofInstruction.VerifyRangeProof,\n commitment,\n proof: rangeProof\n })\n \n // Account metas\n const accountMetas: IAccountMeta[] = [\n { address: accounts.proofContext, role: 2 },\n ]\n \n return {\n programAddress: ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS,\n accounts: accountMetas,\n data\n }\n}\n\n/**\n * Create instruction to verify a validity proof\n * \n * This instruction verifies that an ElGamal ciphertext is well-formed\n * and encrypts a valid value.\n * \n * @param accounts - Required accounts for verification\n * @param ciphertext - The ElGamal ciphertext to verify\n * @param validityProof - The validity proof data\n * @returns Instruction for proof verification\n */\nexport function createVerifyValidityProofInstruction(\n accounts: ProofVerificationAccounts,\n ciphertext: Uint8Array,\n validityProof: Uint8Array\n): IInstruction {\n // Create encoder for the instruction data\n const encoder = getStructEncoder([\n ['instruction', getU8Encoder()],\n ['ciphertext', fixEncoderSize(getBytesEncoder(), PROOF_SIZES.CIPHERTEXT)],\n ['proof', fixEncoderSize(getBytesEncoder(), PROOF_SIZES.VALIDITY_PROOF)]\n ])\n \n const data = encoder.encode({\n instruction: ProofInstruction.VerifyValidityProof,\n ciphertext,\n proof: validityProof\n })\n \n // Account metas\n const accountMetas: IAccountMeta[] = [\n { address: accounts.proofContext, role: 2 },\n ]\n \n return {\n programAddress: ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS,\n accounts: accountMetas,\n data\n }\n}\n\n/**\n * Create instruction to verify an equality proof\n * \n * This instruction verifies that two ElGamal ciphertexts encrypt the same value\n * under potentially different public keys.\n * \n * @param accounts - Required accounts for verification\n * @param ciphertext1 - The first ElGamal ciphertext\n * @param ciphertext2 - The second ElGamal ciphertext\n * @param equalityProof - The equality proof data\n * @returns Instruction for proof verification\n */\nexport function createVerifyEqualityProofInstruction(\n accounts: ProofVerificationAccounts,\n ciphertext1: Uint8Array,\n ciphertext2: Uint8Array,\n equalityProof: Uint8Array\n): IInstruction {\n // Create encoder for the instruction data\n const encoder = getStructEncoder([\n ['instruction', getU8Encoder()],\n ['ciphertext1', fixEncoderSize(getBytesEncoder(), PROOF_SIZES.CIPHERTEXT)],\n ['ciphertext2', fixEncoderSize(getBytesEncoder(), PROOF_SIZES.CIPHERTEXT)],\n ['proof', fixEncoderSize(getBytesEncoder(), PROOF_SIZES.EQUALITY_PROOF)]\n ])\n \n const data = encoder.encode({\n instruction: ProofInstruction.VerifyEqualityProof,\n ciphertext1,\n ciphertext2,\n proof: equalityProof\n })\n \n // Account metas\n const accountMetas: IAccountMeta[] = [\n { address: accounts.proofContext, role: 2 },\n ]\n \n return {\n programAddress: ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS,\n accounts: accountMetas,\n data\n }\n}\n\n/**\n * Create instruction to verify a transfer with fee proof\n * \n * This instruction verifies all proofs required for a confidential transfer\n * that includes a transfer fee.\n * \n * @param accounts - Required accounts for verification\n * @param proofData - The transfer with fee proof data\n * @returns Instruction for proof verification\n */\nexport function createVerifyTransferWithFeeProofInstruction(\n accounts: ProofVerificationAccounts,\n proofData: TransferWithFeeProofData\n): IInstruction {\n // Serialize proof data\n const data = serializeTransferWithFeeProofData(proofData)\n \n // Account metas\n const accountMetas: IAccountMeta[] = [\n { address: accounts.proofContext, role: 2 },\n ]\n \n if (accounts.systemProgram) {\n accountMetas.push({ address: accounts.systemProgram, role: 0 })\n }\n \n return {\n programAddress: ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS,\n accounts: accountMetas,\n data\n }\n}\n\n/**\n * Create instruction to close a proof context account\n * \n * This instruction closes a proof context account and returns the rent\n * to the specified recipient.\n * \n * @param proofContext - The proof context account to close\n * @param authority - The authority that owns the context\n * @param rentRecipient - Account to receive the rent\n * @returns Instruction to close the context\n */\nexport function createCloseProofContextInstruction(\n proofContext: Address,\n authority: TransactionSigner,\n rentRecipient: Address\n): IInstruction {\n // Create encoder for the instruction data\n const encoder = getStructEncoder([\n ['instruction', getU8Encoder()]\n ])\n \n const data = encoder.encode({\n instruction: ProofInstruction.CloseContextState\n })\n \n // Account metas\n const accountMetas: IAccountMeta[] = [\n { address: proofContext, role: 2 }, // WritableNonSigner\n { address: authority.address, role: 3 }, // WritableSigner\n { address: rentRecipient, role: 2 }, // WritableNonSigner\n ]\n \n return {\n programAddress: ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS,\n accounts: accountMetas,\n data\n }\n}\n\n// =====================================================\n// SERIALIZATION HELPERS\n// =====================================================\n\n/**\n * Serialize transfer proof data for instruction\n */\nfunction serializeTransferProofData(proofData: TransferProofData): Uint8Array {\n const encoder = getStructEncoder([\n ['instruction', getU8Encoder()],\n ['encryptedTransferAmount', fixEncoderSize(getBytesEncoder(), PROOF_SIZES.CIPHERTEXT)],\n ['newSourceCommitment', fixEncoderSize(getBytesEncoder(), PROOF_SIZES.COMMITMENT)],\n ['equalityProof', fixEncoderSize(getBytesEncoder(), PROOF_SIZES.EQUALITY_PROOF)],\n ['validityProof', fixEncoderSize(getBytesEncoder(), PROOF_SIZES.VALIDITY_PROOF)],\n ['rangeProof', getBytesEncoder()]\n ])\n \n return new Uint8Array(encoder.encode({\n instruction: ProofInstruction.VerifyTransfer,\n ...proofData\n }))\n}\n\n/**\n * Serialize withdraw proof data for instruction\n */\nfunction serializeWithdrawProofData(proofData: WithdrawProofData): Uint8Array {\n const encoder = getStructEncoder([\n ['instruction', getU8Encoder()],\n ['encryptedWithdrawAmount', fixEncoderSize(getBytesEncoder(), PROOF_SIZES.CIPHERTEXT)],\n ['newSourceCommitment', fixEncoderSize(getBytesEncoder(), PROOF_SIZES.COMMITMENT)],\n ['equalityProof', fixEncoderSize(getBytesEncoder(), PROOF_SIZES.EQUALITY_PROOF)],\n ['rangeProof', getBytesEncoder()]\n ])\n \n return new Uint8Array(encoder.encode({\n instruction: ProofInstruction.VerifyWithdraw,\n ...proofData\n }))\n}\n\n/**\n * Serialize transfer with fee proof data for instruction\n */\nfunction serializeTransferWithFeeProofData(proofData: TransferWithFeeProofData): Uint8Array {\n // First serialize the base transfer proof\n const transferProofBytes = serializeTransferProofData(proofData.transferProof)\n \n // Then add the fee-specific data\n const feeEncoder = getStructEncoder([\n ['encryptedFeeAmount', fixEncoderSize(getBytesEncoder(), PROOF_SIZES.CIPHERTEXT)],\n ['feeCommitment', fixEncoderSize(getBytesEncoder(), PROOF_SIZES.COMMITMENT)],\n ['feeValidityProof', fixEncoderSize(getBytesEncoder(), PROOF_SIZES.VALIDITY_PROOF)]\n ])\n \n const feeBytes = feeEncoder.encode({\n encryptedFeeAmount: proofData.encryptedFeeAmount,\n feeCommitment: proofData.feeCommitment,\n feeValidityProof: proofData.feeValidityProof\n })\n \n // Combine all data with the correct instruction discriminator\n const instruction = new Uint8Array([ProofInstruction.VerifyTransferWithFee])\n const result = new Uint8Array(1 + transferProofBytes.length - 1 + feeBytes.length)\n \n result.set(instruction, 0)\n result.set(transferProofBytes.slice(1), 1) // Skip the instruction byte from transfer proof\n result.set(feeBytes, 1 + transferProofBytes.length - 1)\n \n return result\n}\n\n/**\n * Helper to create a batch of range proof verifications\n * \n * @param accounts - Required accounts for verification\n * @param proofs - Array of commitments and their range proofs\n * @returns Array of instructions for batch verification\n */\nexport function createBatchVerifyRangeProofInstructions(\n accounts: ProofVerificationAccounts,\n proofs: { commitment: Uint8Array; rangeProof: Uint8Array }[]\n): IInstruction[] {\n // Due to transaction size limits, we may need to split into multiple instructions\n const MAX_PROOFS_PER_INSTRUCTION = 4 // Conservative limit\n \n const instructions: IInstruction[] = []\n \n for (let i = 0; i < proofs.length; i += MAX_PROOFS_PER_INSTRUCTION) {\n const batch = proofs.slice(i, i + MAX_PROOFS_PER_INSTRUCTION)\n \n // Create encoder for batched data\n const encoder = getStructEncoder([\n ['instruction', getU8Encoder()],\n ['proofCount', getU8Encoder()],\n ['proofs', getBytesEncoder()]\n ])\n \n // Serialize all proofs in the batch\n const batchData: number[] = []\n for (const { commitment, rangeProof } of batch) {\n batchData.push(...Array.from(commitment))\n batchData.push(...Array.from(new Uint8Array([rangeProof.length & 0xff, (rangeProof.length >> 8) & 0xff])))\n batchData.push(...Array.from(rangeProof))\n }\n \n const data = encoder.encode({\n instruction: ProofInstruction.VerifyBatchedRangeProof,\n proofCount: batch.length,\n proofs: new Uint8Array(batchData)\n })\n \n instructions.push({\n programAddress: ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS,\n accounts: [\n { address: accounts.proofContext, role: 2 },\n ],\n data\n })\n }\n \n return instructions\n}\n\n/**\n * Helper to create a batch of validity proof verifications\n * \n * @param accounts - Required accounts for verification\n * @param proofs - Array of ciphertexts and their validity proofs\n * @returns Array of instructions for batch verification\n */\nexport function createBatchVerifyValidityProofInstructions(\n accounts: ProofVerificationAccounts,\n proofs: { ciphertext: Uint8Array; validityProof: Uint8Array }[]\n): IInstruction[] {\n // Due to transaction size limits, we may need to split into multiple instructions\n const MAX_PROOFS_PER_INSTRUCTION = 6 // Conservative limit for validity proofs\n \n const instructions: IInstruction[] = []\n \n for (let i = 0; i < proofs.length; i += MAX_PROOFS_PER_INSTRUCTION) {\n const batch = proofs.slice(i, i + MAX_PROOFS_PER_INSTRUCTION)\n \n // Create encoder for batched data\n const encoder = getStructEncoder([\n ['instruction', getU8Encoder()],\n ['proofCount', getU8Encoder()],\n ['proofs', getBytesEncoder()]\n ])\n \n // Serialize all proofs in the batch\n const batchData: number[] = []\n for (const { ciphertext, validityProof } of batch) {\n batchData.push(...Array.from(ciphertext))\n batchData.push(...Array.from(validityProof))\n }\n \n const data = encoder.encode({\n instruction: ProofInstruction.VerifyBatchedValidityProof,\n proofCount: batch.length,\n proofs: new Uint8Array(batchData)\n })\n \n instructions.push({\n programAddress: ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS,\n accounts: [\n { address: accounts.proofContext, role: 2 }, // WritableNonSigner\n ],\n data\n })\n }\n \n return instructions\n}\n\n/**\n * Helper to create a batch of equality proof verifications\n * \n * Note: Equality proofs are typically not batched due to their complexity,\n * but this function provides the capability for future optimization.\n * \n * @param accounts - Required accounts for verification\n * @param proofs - Array of ciphertext pairs and their equality proofs\n * @returns Array of instructions for verification\n */\nexport function createBatchVerifyEqualityProofInstructions(\n accounts: ProofVerificationAccounts,\n proofs: {\n ciphertext1: Uint8Array\n ciphertext2: Uint8Array\n equalityProof: Uint8Array\n }[]\n): IInstruction[] {\n // Equality proofs are complex, so we process them individually\n // but return as an array for consistency with other batch functions\n const instructions: IInstruction[] = []\n \n for (const { ciphertext1, ciphertext2, equalityProof } of proofs) {\n instructions.push(\n createVerifyEqualityProofInstruction(\n accounts,\n ciphertext1,\n ciphertext2,\n equalityProof\n )\n )\n }\n \n return instructions\n}\n\n// =====================================================\n// CONTEXT MANAGEMENT HELPERS\n// =====================================================\n\n/**\n * Options for creating a proof context account\n */\nexport interface ProofContextOptions {\n /** Authority that will own the context */\n authority: TransactionSigner\n \n /** Space required for the context (depends on proof type) */\n space: number\n \n /** Optional seed for deterministic address */\n seed?: string\n \n /** Optional payer (defaults to authority) */\n payer?: TransactionSigner\n}\n\n/**\n * Calculate the minimum space required for a proof context\n * \n * @param proofType - Type of proof being verified\n * @param batchSize - Number of proofs if batched\n * @returns Required space in bytes\n */\nexport function calculateProofContextSpace(\n proofType: ProofInstruction,\n batchSize = 1\n): number {\n const BASE_CONTEXT_SIZE = 32 + 8 + 1 // Authority + discriminator + state\n \n switch (proofType) {\n case ProofInstruction.VerifyTransfer:\n return BASE_CONTEXT_SIZE + PROOF_SIZES.CIPHERTEXT + PROOF_SIZES.COMMITMENT\n \n case ProofInstruction.VerifyWithdraw:\n return BASE_CONTEXT_SIZE + PROOF_SIZES.CIPHERTEXT + PROOF_SIZES.COMMITMENT\n \n case ProofInstruction.VerifyRangeProof:\n return BASE_CONTEXT_SIZE + PROOF_SIZES.COMMITMENT\n \n case ProofInstruction.VerifyValidityProof:\n return BASE_CONTEXT_SIZE + PROOF_SIZES.CIPHERTEXT\n \n case ProofInstruction.VerifyEqualityProof:\n return BASE_CONTEXT_SIZE + (PROOF_SIZES.CIPHERTEXT * 2)\n \n case ProofInstruction.VerifyBatchedRangeProof:\n return BASE_CONTEXT_SIZE + (PROOF_SIZES.COMMITMENT * batchSize) + 4\n \n case ProofInstruction.VerifyBatchedValidityProof:\n return BASE_CONTEXT_SIZE + (PROOF_SIZES.CIPHERTEXT * batchSize) + 4\n \n default:\n return BASE_CONTEXT_SIZE + 256 // Conservative default\n }\n}\n\n/**\n * Create instruction to initialize a proof context account\n * \n * This creates the account and prepares it for proof verification.\n * The account must be closed after verification to recover rent.\n * \n * @param context - The proof context account to create\n * @param options - Context creation options\n * @returns Instruction to create the context\n */\nexport function createInitializeProofContextInstruction(\n context: TransactionSigner,\n options: ProofContextOptions\n): IInstruction {\n const payer = options.payer ?? options.authority\n \n // Calculate rent exemption\n const lamports = 1_000_000 // Placeholder - should calculate actual rent\n \n // Create account instruction data\n const encoder = getStructEncoder([\n ['instruction', getU32Encoder()], // System program CreateAccount\n ['lamports', getU64Encoder()],\n ['space', getU64Encoder()],\n ['owner', fixEncoderSize(getAddressEncoder(), 32)]\n ])\n \n const data = encoder.encode({\n instruction: 0, // CreateAccount\n lamports: BigInt(lamports),\n space: BigInt(options.space),\n owner: ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS\n })\n \n return {\n programAddress: address('11111111111111111111111111111111'), // System program\n accounts: [\n { address: payer.address, role: 3 }, // WritableSigner\n { address: context.address, role: 3 }, // WritableSigner\n ],\n data\n }\n}\n\n/**\n * Helper to create a complete proof verification transaction\n * \n * This combines context creation, proof verification, and context closure\n * into a single transaction for efficiency.\n * \n * @param proofInstruction - The proof verification instruction\n * @param context - Proof context account\n * @param authority - Authority that owns the context\n * @param payer - Transaction fee payer\n * @returns Array of instructions for the complete flow\n */\nexport function createCompleteProofVerificationFlow(\n proofInstruction: IInstruction,\n context: TransactionSigner,\n authority: TransactionSigner,\n payer: TransactionSigner\n): IInstruction[] {\n const instructions: IInstruction[] = []\n \n // 1. Create context account\n const proofType = proofInstruction.data?.[0] as ProofInstruction\n const space = calculateProofContextSpace(proofType)\n \n instructions.push(\n createInitializeProofContextInstruction(context, {\n authority,\n space,\n payer\n })\n )\n \n // 2. Verify proof\n instructions.push(proofInstruction)\n \n // 3. Close context account\n instructions.push(\n createCloseProofContextInstruction(\n context.address,\n authority,\n payer.address\n )\n )\n \n return instructions\n}\n\n/**\n * Create a deterministic proof context address\n * \n * This allows reusing the same context address across multiple transactions\n * for the same authority and proof type.\n * \n * @param authority - Authority that owns the context\n * @param proofType - Type of proof being verified\n * @param nonce - Optional nonce for uniqueness\n * @returns Deterministic context address\n */\nexport function deriveProofContextAddress(\n authority: Address,\n proofType: ProofInstruction,\n nonce = 0\n): Address {\n const seeds = [\n Buffer.from('proof-context'),\n Buffer.from([proofType]),\n Buffer.from(new Uint8Array(4).fill(0).map((_, i) => (nonce >> (i * 8)) & 0xff))\n ]\n \n // This is a placeholder - actual PDA derivation would use findProgramAddress\n const hashInput = Buffer.concat([\n ...seeds,\n Buffer.from(authority),\n Buffer.from(ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS)\n ])\n const hash = sha256(hashInput)\n const encoded = bs58.encode(hash)\n \n return address(encoded.slice(0, 44))\n}\n\n","/**\n * Feature Gate Detector\n * \n * Runtime detection of Solana feature gates to determine which native\n * programs and features are available on the current network.\n * \n * This module specifically tracks the ZK ElGamal Proof Program feature gate\n * and provides caching to minimize RPC calls.\n */\n\nimport { type Connection, PublicKey } from '@solana/web3.js'\nimport { address } from '@solana/addresses'\nimport type { Address } from '@solana/kit'\n\n// =====================================================\n// CONSTANTS\n// =====================================================\n\n/**\n * Known feature gate addresses\n */\nexport const FEATURE_GATES = {\n /** ZK ElGamal Proof Program re-enablement */\n ZK_ELGAMAL_PROOF_REENABLED: new PublicKey('zkemPXcuM3G4wpMDZ36Cpw34EjUpvm1nuioiSGbGZPR'),\n \n /** Confidential transfers feature (placeholder) */\n CONFIDENTIAL_TRANSFERS: new PublicKey('11111111111111111111111111111111'),\n \n /** Token-2022 program (placeholder) */\n TOKEN_2022: new PublicKey('TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb'),\n} as const\n\n/**\n * Cache configuration\n */\nconst CACHE_TTL_MS = 5 * 60 * 1000 // 5 minutes\nconst MAX_CACHE_ENTRIES = 100\n\n// =====================================================\n// TYPES\n// =====================================================\n\nexport interface FeatureStatus {\n /** Whether the feature is activated */\n activated: boolean\n \n /** When the status was last checked */\n lastChecked: number\n \n /** Optional activation slot if known */\n activationSlot?: bigint\n \n /** Error if status check failed */\n error?: string\n}\n\nexport interface FeatureGateCache {\n [featureId: string]: FeatureStatus\n}\n\n// =====================================================\n// CACHE IMPLEMENTATION\n// =====================================================\n\nclass FeatureGateCacheManager {\n private cache: FeatureGateCache = {}\n private cacheOrder: string[] = []\n \n /**\n * Get cached feature status\n */\n get(featureId: string): FeatureStatus | null {\n const cached = this.cache[featureId]\n // Cache found, continue\n \n // Check if cache is expired\n if (Date.now() - cached.lastChecked > CACHE_TTL_MS) {\n this.remove(featureId)\n return null\n }\n \n return cached\n }\n \n /**\n * Set feature status in cache\n */\n set(featureId: string, status: FeatureStatus): void {\n // Remove if already exists to update order\n this.remove(featureId)\n \n // Add to cache\n this.cache[featureId] = status\n this.cacheOrder.push(featureId)\n \n // Enforce max cache size\n if (this.cacheOrder.length > MAX_CACHE_ENTRIES) {\n const oldest = this.cacheOrder.shift()\n if (oldest) {\n delete this.cache[oldest]\n }\n }\n }\n \n /**\n * Remove from cache\n */\n remove(featureId: string): void {\n delete this.cache[featureId]\n this.cacheOrder = this.cacheOrder.filter(id => id !== featureId)\n }\n \n /**\n * Clear entire cache\n */\n clear(): void {\n this.cache = {}\n this.cacheOrder = []\n }\n}\n\n// Global cache instance\nconst featureCache = new FeatureGateCacheManager()\n\n// =====================================================\n// FEATURE DETECTION\n// =====================================================\n\n/**\n * Check if a feature gate is activated on the current network\n * \n * @param connection - Solana connection\n * @param featureGate - Feature gate public key to check\n * @returns Feature activation status\n */\nexport async function checkFeatureGate(\n connection: Connection,\n featureGate: PublicKey\n): Promise<FeatureStatus> {\n const featureId = featureGate.toBase58()\n \n // Check cache first\n const cached = featureCache.get(featureId)\n if (cached) {\n return cached\n }\n \n try {\n // Check if the feature account exists\n const accountInfo = await connection.getAccountInfo(featureGate)\n \n // Feature gates are special accounts - if they exist, the feature is active\n const activated = accountInfo !== null\n \n const status: FeatureStatus = {\n activated,\n lastChecked: Date.now(),\n }\n \n // If activated, try to get activation slot from account data\n if (accountInfo) {\n try {\n // First 8 bytes of feature account data is the activation slot\n const activationSlot = BigInt(\n accountInfo.data.readBigUInt64LE(0)\n )\n status.activationSlot = activationSlot\n } catch {\n // Ignore parsing errors\n }\n }\n \n // Cache the result\n featureCache.set(featureId, status)\n \n return status\n } catch (error) {\n // Cache error state to avoid repeated failures\n const errorStatus: FeatureStatus = {\n activated: false,\n lastChecked: Date.now(),\n error: error instanceof Error ? error.message : 'Unknown error',\n }\n \n featureCache.set(featureId, errorStatus)\n \n return errorStatus\n }\n}\n\n/**\n * Check if the ZK ElGamal Proof Program is enabled\n * \n * @param connection - Solana connection\n * @returns Whether the ZK program is available\n */\nexport async function isZkProgramEnabled(\n connection: Connection\n): Promise<boolean> {\n const status = await checkFeatureGate(\n connection,\n FEATURE_GATES.ZK_ELGAMAL_PROOF_REENABLED\n )\n \n return status.activated\n}\n\n/**\n * Get detailed status of the ZK ElGamal Proof Program\n * \n * @param connection - Solana connection\n * @returns Detailed feature status\n */\nexport async function getZkProgramFeatureStatus(\n connection: Connection\n): Promise<FeatureStatus> {\n return checkFeatureGate(\n connection,\n FEATURE_GATES.ZK_ELGAMAL_PROOF_REENABLED\n )\n}\n\n/**\n * Check multiple feature gates in parallel\n * \n * @param connection - Solana connection\n * @param featureGates - Array of feature gates to check\n * @returns Map of feature gate to status\n */\nexport async function checkMultipleFeatureGates(\n connection: Connection,\n featureGates: PublicKey[]\n): Promise<Map<string, FeatureStatus>> {\n const results = await Promise.all(\n featureGates.map(gate => checkFeatureGate(connection, gate))\n )\n \n const statusMap = new Map<string, FeatureStatus>()\n featureGates.forEach((gate, index) => {\n statusMap.set(gate.toBase58(), results[index])\n })\n \n return statusMap\n}\n\n/**\n * Monitor a feature gate for activation changes\n * \n * @param connection - Solana connection\n * @param featureGate - Feature gate to monitor\n * @param callback - Callback when status changes\n * @param intervalMs - Check interval (default 30 seconds)\n * @returns Function to stop monitoring\n */\nexport function monitorFeatureGate(\n connection: Connection,\n featureGate: PublicKey,\n callback: (status: FeatureStatus) => void,\n intervalMs = 30_000\n): () => void {\n let lastStatus: FeatureStatus | null = null\n let intervalId: ReturnType<typeof setInterval> | null = null\n \n const check = async () => {\n try {\n const status = await checkFeatureGate(connection, featureGate)\n \n // Check if status changed\n if (!lastStatus || lastStatus.activated !== status.activated) {\n callback(status)\n lastStatus = status\n }\n } catch (error) {\n console.error('Error monitoring feature gate:', error)\n }\n }\n \n // Initial check\n void check()\n \n // Set up interval\n intervalId = setInterval(check, intervalMs)\n \n // Return cleanup function\n return () => {\n if (intervalId) {\n clearInterval(intervalId)\n intervalId = null\n }\n }\n}\n\n// =====================================================\n// UTILITY FUNCTIONS\n// =====================================================\n\n/**\n * Clear the feature gate cache\n * Useful for testing or forcing fresh checks\n */\nexport function clearFeatureGateCache(): void {\n featureCache.clear()\n}\n\n/**\n * Get a human-readable description of the ZK program status\n * \n * @param connection - Solana connection\n * @returns Status description\n */\nexport async function getZkProgramStatusDescription(\n connection: Connection\n): Promise<string> {\n const status = await getZkProgramFeatureStatus(connection)\n \n if (status.error) {\n return `ZK ElGamal Proof Program status unknown: ${status.error}`\n }\n \n if (status.activated) {\n const slotInfo = status.activationSlot \n ? ` (activated at slot ${status.activationSlot})` \n : ''\n return `ZK ElGamal Proof Program is ENABLED${slotInfo}`\n }\n \n return 'ZK ElGamal Proof Program is DISABLED pending security audit completion'\n}\n\n/**\n * Convert feature gate public key to Address type\n */\nexport function featureGateToAddress(featureGate: PublicKey): Address {\n return address(featureGate.toBase58())\n}\n\n// =====================================================\n// EXPORTS\n// =====================================================\n\nexport {\n FeatureGateCacheManager,\n featureCache as defaultFeatureCache,\n}","/**\n * ZK Proof Builder\n * \n * Unified proof generation and verification with support for both\n * Solana's ZK ElGamal Proof Program and fallback local verification.\n * \n * This module handles the current disabled state of the ZK program\n * by providing local verification as a fallback while preparing\n * for the program's re-enablement.\n */\n\nimport { ed25519 } from '@noble/curves/ed25519'\nimport { sha256 } from '@noble/hashes/sha256'\nimport { bytesToNumberLE, bytesToHex, randomBytes } from '@noble/curves/abstract/utils'\nimport type { IInstruction } from '@solana/kit'\nimport type { Connection } from '@solana/web3.js'\n\nimport {\n ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS,\n type TransferProofData,\n PROOF_SIZES\n} from '../constants/zk-proof-program.js'\n\nimport {\n createVerifyTransferProofInstruction,\n createVerifyRangeProofInstruction,\n createVerifyValidityProofInstruction,\n type ProofVerificationAccounts\n} from './zk-proof-instructions.js'\n\nimport type {\n ElGamalCiphertext,\n ElGamalPubkey\n} from './elgamal.js'\n\nimport {\n isZkProgramEnabled,\n getZkProgramStatusDescription\n} from './feature-gate-detector.js'\n\n// =====================================================\n// CONSTANTS\n// =====================================================\n\n// Standard generator G for curve25519\nconst G = ed25519.ExtendedPoint.BASE\n\n// Secondary generator H for Pedersen commitments\n// Must be consistent across all modules\nconst H_BYTES = sha256(G.toRawBytes())\nconst H_SCALAR = bytesToNumberLE(H_BYTES) % ed25519.CURVE.n\nconst H = G.multiply(H_SCALAR)\n\n// ZK program status cache\nlet zkProgramStatusCache: {\n enabled: boolean\n lastChecked: number\n message: string\n} | null = null\n\nconst ZK_STATUS_CACHE_TTL = 60_000 // 1 minute\n\n// =====================================================\n// TYPES\n// =====================================================\n\nexport interface ProofGenerationResult {\n proof: Uint8Array\n commitment?: Uint8Array\n instruction?: IInstruction\n requiresZkProgram: boolean\n}\n\nexport interface ProofVerificationResult {\n valid: boolean\n error?: string\n usedFallback: boolean\n}\n\nexport enum ProofMode {\n /** Use ZK program if available, error if not */\n ZK_PROGRAM_ONLY = 'zk_program_only',\n \n /** Use ZK program if available, fallback to local if not */\n ZK_PROGRAM_WITH_FALLBACK = 'zk_program_with_fallback',\n \n /** Always use local verification (for testing) */\n LOCAL_ONLY = 'local_only',\n \n /** Automatically detect based on network status */\n AUTO_DETECT = 'auto_detect'\n}\n\nexport interface ProofGenerationOptions {\n mode?: ProofMode\n connection?: Connection\n}\n\n// =====================================================\n// RANGE PROOF GENERATION\n// =====================================================\n\n/**\n * Generate a range proof with proper commitment handling\n * \n * This creates a Pedersen commitment and bulletproof that can be\n * verified either by the ZK program or locally.\n */\nexport async function generateRangeProofWithCommitment(\n amount: bigint,\n randomness: Uint8Array,\n options: ProofGenerationOptions = {}\n): Promise<ProofGenerationResult> {\n const mode = options.mode ?? ProofMode.AUTO_DETECT\n const connection = options.connection\n if (amount < 0n || amount >= (1n << 64n)) {\n throw new Error('Amount must be in range [0, 2^64)')\n }\n\n // Convert randomness to scalar\n const gamma = bytesToNumberLE(randomness) % ed25519.CURVE.n\n \n if (gamma === 0n) {\n throw new Error('Invalid randomness: gamma cannot be zero')\n }\n\n // Create Pedersen commitment: amount*G + gamma*H\n const commitment = G.multiply(amount).add(H.multiply(gamma))\n const commitmentBytes = commitment.toRawBytes()\n\n // For now, we'll use a simplified bulletproof structure\n // In production, this would use the actual bulletproof implementation\n const proof = createSimplifiedRangeProof(amount, gamma, commitment)\n\n // Check if we should create ZK program instruction\n let instruction: IInstruction | undefined\n let zkProgramEnabled = false\n \n if (mode !== ProofMode.LOCAL_ONLY) {\n // Check if ZK program is enabled\n zkProgramEnabled = await checkZkProgramStatus(connection)\n \n if (zkProgramEnabled || mode === ProofMode.ZK_PROGRAM_ONLY) {\n const accounts: ProofVerificationAccounts = {\n proofContext: ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS // Placeholder\n }\n instruction = createVerifyRangeProofInstruction(accounts, commitmentBytes, proof)\n }\n }\n\n return {\n proof,\n commitment: commitmentBytes,\n instruction,\n requiresZkProgram: mode === ProofMode.ZK_PROGRAM_ONLY && !zkProgramEnabled\n }\n}\n\n/**\n * Create a simplified range proof for testing\n * In production, this would be a full bulletproof\n */\nfunction createSimplifiedRangeProof(\n amount: bigint,\n gamma: bigint,\n commitment: typeof ed25519.ExtendedPoint.BASE\n): Uint8Array {\n // Create a proof structure that includes:\n // 1. Commitment to the bits of the amount\n // 2. Challenge response\n // 3. Inner product proof\n \n const proof = new Uint8Array(PROOF_SIZES.RANGE_PROOF_BULLETPROOF)\n let offset = 0\n\n // A commitment (32 bytes)\n const a0 = amount % 256n || 1n // Ensure non-zero\n const g0 = gamma % 256n || 1n\n const A = G.multiply(a0).add(H.multiply(g0))\n proof.set(A.toRawBytes(), offset)\n offset += 32\n\n // S commitment (32 bytes)\n const a1 = (amount >> 8n) % 256n || 1n\n const g1 = (gamma >> 8n) % 256n || 1n\n const S = G.multiply(a1).add(H.multiply(g1))\n proof.set(S.toRawBytes(), offset)\n offset += 32\n\n // T1 commitment (32 bytes)\n const a2 = (amount >> 16n) % 256n || 1n\n const g2 = (gamma >> 16n) % 256n || 1n\n const T1 = G.multiply(a2).add(H.multiply(g2))\n proof.set(T1.toRawBytes(), offset)\n offset += 32\n\n // T2 commitment (32 bytes)\n const a3 = (amount >> 24n) % 256n || 1n\n const g3 = (gamma >> 24n) % 256n || 1n\n const T2 = G.multiply(a3).add(H.multiply(g3))\n proof.set(T2.toRawBytes(), offset)\n offset += 32\n\n // Challenge responses (3 * 32 = 96 bytes)\n const challenge = bytesToNumberLE(sha256(commitment.toRawBytes())) % ed25519.CURVE.n\n const taux = (gamma * challenge) % ed25519.CURVE.n\n const mu = (amount * challenge) % ed25519.CURVE.n\n const tx = (amount + gamma * challenge) % ed25519.CURVE.n\n\n proof.set(scalarToBytes(taux), offset)\n offset += 32\n proof.set(scalarToBytes(mu), offset)\n offset += 32\n proof.set(scalarToBytes(tx), offset)\n offset += 32\n\n // Fill the rest with inner product proof simulation\n const remaining = PROOF_SIZES.RANGE_PROOF_BULLETPROOF - offset\n const innerProduct = randomBytes(remaining)\n proof.set(innerProduct, offset)\n\n return proof\n}\n\n/**\n * Verify a range proof locally\n */\nexport function verifyRangeProofLocal(\n proof: Uint8Array,\n commitment: Uint8Array\n): ProofVerificationResult {\n try {\n if (proof.length !== PROOF_SIZES.RANGE_PROOF_BULLETPROOF) {\n return {\n valid: false,\n error: 'Invalid proof size',\n usedFallback: true\n }\n }\n\n // Parse commitment point\n const _commitmentPoint = ed25519.ExtendedPoint.fromHex(bytesToHex(commitment))\n \n // For simplified proof, just check structure\n // In production, this would verify the actual bulletproof\n \n // Extract proof components\n const A = proof.slice(0, 32)\n const S = proof.slice(32, 64)\n const T1 = proof.slice(64, 96)\n const T2 = proof.slice(96, 128)\n \n // Basic validation - ensure points are valid\n try {\n ed25519.ExtendedPoint.fromHex(bytesToHex(A))\n ed25519.ExtendedPoint.fromHex(bytesToHex(S))\n ed25519.ExtendedPoint.fromHex(bytesToHex(T1))\n ed25519.ExtendedPoint.fromHex(bytesToHex(T2))\n } catch {\n return {\n valid: false,\n error: 'Invalid proof points',\n usedFallback: true\n }\n }\n\n // For now, accept valid structure as proof\n // Real implementation would verify the bulletproof equations\n return {\n valid: true,\n usedFallback: true\n }\n } catch (error) {\n return {\n valid: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n usedFallback: true\n }\n }\n}\n\n// =====================================================\n// VALIDITY PROOF GENERATION\n// =====================================================\n\n/**\n * Generate a validity proof for a ciphertext\n */\nexport async function generateValidityProofWithInstruction(\n ciphertext: ElGamalCiphertext,\n pubkey: ElGamalPubkey,\n amount: bigint,\n randomness: Uint8Array,\n options: ProofGenerationOptions = {}\n): Promise<ProofGenerationResult> {\n const mode = options.mode ?? ProofMode.AUTO_DETECT\n const connection = options.connection\n // Convert randomness to scalar\n const r = bytesToNumberLE(randomness) % ed25519.CURVE.n\n \n // Parse public key\n const pubkeyPoint = ed25519.ExtendedPoint.fromHex(bytesToHex(pubkey))\n \n // Generate Schnorr proof\n const k = bytesToNumberLE(randomBytes(32)) % ed25519.CURVE.n\n \n // Commitments for proof\n const A = G.multiply(k).add(pubkeyPoint.multiply(k))\n \n // Challenge\n const challenge = bytesToNumberLE(\n sha256(new Uint8Array([\n ...ciphertext.commitment.commitment,\n ...ciphertext.handle.handle,\n ...A.toRawBytes()\n ]))\n ) % ed25519.CURVE.n\n \n // Response\n const z1 = (k + challenge * amount) % ed25519.CURVE.n\n const z2 = (k + challenge * r) % ed25519.CURVE.n\n \n // Construct proof\n const proof = new Uint8Array(PROOF_SIZES.VALIDITY_PROOF)\n let offset = 0\n \n proof.set(A.toRawBytes(), offset)\n offset += 32\n proof.set(scalarToBytes(z1), offset)\n offset += 32\n proof.set(scalarToBytes(z2), offset)\n\n // Create instruction if needed\n let instruction: IInstruction | undefined\n let zkProgramEnabled = false\n \n if (mode !== ProofMode.LOCAL_ONLY) {\n zkProgramEnabled = await checkZkProgramStatus(connection)\n \n if (zkProgramEnabled || mode === ProofMode.ZK_PROGRAM_ONLY) {\n const accounts: ProofVerificationAccounts = {\n proofContext: ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS\n }\n instruction = createVerifyValidityProofInstruction(accounts, \n new Uint8Array([\n ...ciphertext.commitment.commitment,\n ...ciphertext.handle.handle\n ]), \n proof)\n }\n }\n\n return {\n proof,\n instruction,\n requiresZkProgram: mode === ProofMode.ZK_PROGRAM_ONLY && !zkProgramEnabled\n }\n}\n\n// =====================================================\n// TRANSFER PROOF GENERATION\n// =====================================================\n\n/**\n * Generate a complete transfer proof with all components\n */\nexport async function generateTransferProofWithInstruction(\n sourceBalance: ElGamalCiphertext,\n transferAmount: bigint,\n sourcePubkey: ElGamalPubkey,\n destPubkey: ElGamalPubkey,\n sourceRandomness: Uint8Array,\n options: ProofGenerationOptions = {}\n): Promise<{\n transferProof: TransferProofData\n newSourceBalance: ElGamalCiphertext\n destCiphertext: ElGamalCiphertext\n instruction?: IInstruction\n requiresZkProgram: boolean\n}> {\n const mode = options.mode ?? ProofMode.AUTO_DETECT\n const connection = options.connection\n // Generate transfer randomness\n const transferRandomness = randomBytes(32)\n transferRandomness[0] &= 248\n transferRandomness[31] &= 127\n transferRandomness[31] |= 64\n\n // Encrypt transfer amount for destination\n const destR = bytesToNumberLE(transferRandomness) % ed25519.CURVE.n\n const destPubkeyPoint = ed25519.ExtendedPoint.fromHex(bytesToHex(destPubkey))\n const destCommitment = G.multiply(transferAmount).add(destPubkeyPoint.multiply(destR))\n const destHandle = G.multiply(destR)\n \n const destCiphertext: ElGamalCiphertext = {\n commitment: { commitment: destCommitment.toRawBytes() },\n handle: { handle: destHandle.toRawBytes() }\n }\n\n // Calculate new source balance (simplified - in practice would use homomorphic subtraction)\n const newSourceBalance = sourceBalance // Placeholder\n\n // Generate proofs\n const rangeProofResult = await generateRangeProofWithCommitment(\n transferAmount, \n transferRandomness, \n { mode: ProofMode.LOCAL_ONLY }\n )\n const validityProofResult = await generateValidityProofWithInstruction(\n destCiphertext,\n destPubkey,\n transferAmount,\n transferRandomness,\n { mode: ProofMode.LOCAL_ONLY }\n )\n\n // Generate equality proof (simplified)\n const equalityProof = new Uint8Array(PROOF_SIZES.EQUALITY_PROOF)\n randomBytes(32).forEach((b, i) => equalityProof[i] = b)\n\n // Construct transfer proof data\n const transferProof: TransferProofData = {\n encryptedTransferAmount: new Uint8Array([\n ...destCiphertext.commitment.commitment,\n ...destCiphertext.handle.handle\n ]),\n newSourceCommitment: newSourceBalance.commitment.commitment,\n equalityProof,\n validityProof: validityProofResult.proof,\n rangeProof: rangeProofResult.proof\n }\n\n // Create instruction if needed\n let instruction: IInstruction | undefined\n let zkProgramEnabled = false\n \n if (mode !== ProofMode.LOCAL_ONLY) {\n zkProgramEnabled = await checkZkProgramStatus(connection)\n \n if (zkProgramEnabled || mode === ProofMode.ZK_PROGRAM_ONLY) {\n const accounts: ProofVerificationAccounts = {\n proofContext: ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS\n }\n instruction = createVerifyTransferProofInstruction(accounts, transferProof)\n }\n }\n\n return {\n transferProof,\n newSourceBalance,\n destCiphertext,\n instruction,\n requiresZkProgram: mode === ProofMode.ZK_PROGRAM_ONLY && !zkProgramEnabled\n }\n}\n\n// =====================================================\n// HELPERS\n// =====================================================\n\n/**\n * Convert scalar to bytes (little-endian)\n */\nfunction scalarToBytes(scalar: bigint): Uint8Array {\n const bytes = new Uint8Array(32)\n for (let i = 0; i < 32; i++) {\n bytes[i] = Number((scalar >> BigInt(i * 8)) & 0xffn)\n }\n return bytes\n}\n\n/**\n * Check ZK program status with caching\n */\nasync function checkZkProgramStatus(connection?: Connection): Promise<boolean> {\n // If no connection provided, assume disabled\n if (!connection) {\n return false\n }\n \n // Check cache\n if (zkProgramStatusCache && \n Date.now() - zkProgramStatusCache.lastChecked < ZK_STATUS_CACHE_TTL) {\n return zkProgramStatusCache.enabled\n }\n \n // Check feature gate\n try {\n const enabled = await isZkProgramEnabled(connection)\n const message = await getZkProgramStatusDescription(connection)\n \n // Update cache\n zkProgramStatusCache = {\n enabled,\n lastChecked: Date.now(),\n message\n }\n \n return enabled\n } catch (error) {\n console.warn('Failed to check ZK program status:', error)\n // Cache the error state\n zkProgramStatusCache = {\n enabled: false,\n lastChecked: Date.now(),\n message: `ZK program status check failed: ${error instanceof Error ? error.message : 'Unknown error'}`\n }\n return false\n }\n}\n\n/**\n * Check if ZK program is available\n */\nexport async function isZkProgramAvailable(connection?: Connection): Promise<boolean> {\n if (!connection) {\n return false\n }\n return checkZkProgramStatus(connection)\n}\n\n/**\n * Get ZK program status message\n */\nexport async function getZkProgramStatus(connection?: Connection): Promise<string> {\n if (!connection) {\n return 'No connection - ZK program status unknown'\n }\n \n // Check cache first\n if (zkProgramStatusCache && \n Date.now() - zkProgramStatusCache.lastChecked < ZK_STATUS_CACHE_TTL) {\n return zkProgramStatusCache.message\n }\n \n // Get fresh status\n await checkZkProgramStatus(connection)\n return zkProgramStatusCache?.message ?? 'ZK program status unknown'\n}\n\n/**\n * Get ZK program address\n */\nexport function getZkProgramAddress() {\n return ZK_ELGAMAL_PROOF_PROGRAM_ADDRESS\n}\n\n/**\n * Clear ZK program status cache (for testing)\n */\nexport function clearZkProgramStatusCache(): void {\n zkProgramStatusCache = null\n}"]}
@@ -1,2 +0,0 @@
1
- import {kb,gb,Pa,De,lb,hb,Qa,Ee}from'./chunk-B4WUFVLE.js';import {fixEncoderSize,getBytesEncoder,transformEncoder,getStructEncoder,getAddressEncoder,getU64Encoder,getBooleanEncoder,getOptionEncoder,getI64Encoder,getU32Encoder,getArrayEncoder,addEncoderSizePrefix,getU8Encoder,getUtf8Encoder,getStructDecoder,fixDecoderSize,getAddressDecoder,getU64Decoder,getBooleanDecoder,getOptionDecoder,getI64Decoder,getU32Decoder,getArrayDecoder,addDecoderSizePrefix,getU8Decoder,getBytesDecoder,getUtf8Decoder,combineCodec,decodeAccount,assertAccountExists,fetchEncodedAccount,assertAccountsExist,fetchEncodedAccounts}from'@solana/kit';var v=new Uint8Array([163,174,175,5,237,55,21,230]);function ee(){return fixEncoderSize(getBytesEncoder(),8).encode(v)}function V(){return transformEncoder(getStructEncoder([["discriminator",fixEncoderSize(getBytesEncoder(),8)],["auction",getAddressEncoder()],["agent",getAddressEncoder()],["creator",getAddressEncoder()],["auctionType",kb()],["startingPrice",getU64Encoder()],["reservePrice",getU64Encoder()],["isReserveHidden",getBooleanEncoder()],["reserveMet",getBooleanEncoder()],["currentPrice",getU64Encoder()],["currentWinner",getOptionEncoder(getAddressEncoder())],["winner",getOptionEncoder(getAddressEncoder())],["auctionEndTime",getI64Encoder()],["minimumBidIncrement",getU64Encoder()],["totalBids",getU32Encoder()],["status",gb()],["bids",getArrayEncoder(Pa())],["createdAt",getI64Encoder()],["endedAt",getOptionEncoder(getI64Encoder())],["metadataUri",addEncoderSizePrefix(getUtf8Encoder(),getU32Encoder())],["dutchConfig",getOptionEncoder(De())],["extensionCount",getU8Encoder()],["originalEndTime",getI64Encoder()],["reservePriceLocked",getBooleanEncoder()],["reserveShortfallNotified",getBooleanEncoder()],["bump",getU8Encoder()]]),e=>({...e,discriminator:v}))}function B(){return getStructDecoder([["discriminator",fixDecoderSize(getBytesDecoder(),8)],["auction",getAddressDecoder()],["agent",getAddressDecoder()],["creator",getAddressDecoder()],["auctionType",lb()],["startingPrice",getU64Decoder()],["reservePrice",getU64Decoder()],["isReserveHidden",getBooleanDecoder()],["reserveMet",getBooleanDecoder()],["currentPrice",getU64Decoder()],["currentWinner",getOptionDecoder(getAddressDecoder())],["winner",getOptionDecoder(getAddressDecoder())],["auctionEndTime",getI64Decoder()],["minimumBidIncrement",getU64Decoder()],["totalBids",getU32Decoder()],["status",hb()],["bids",getArrayDecoder(Qa())],["createdAt",getI64Decoder()],["endedAt",getOptionDecoder(getI64Decoder())],["metadataUri",addDecoderSizePrefix(getUtf8Decoder(),getU32Decoder())],["dutchConfig",getOptionDecoder(Ee())],["extensionCount",getU8Decoder()],["originalEndTime",getI64Decoder()],["reservePriceLocked",getBooleanDecoder()],["reserveShortfallNotified",getBooleanDecoder()],["bump",getU8Decoder()]])}function te(){return combineCodec(V(),B())}function O(e){return decodeAccount(e,B())}async function ne(e,n,r){let t=await X(e,n,r);return assertAccountExists(t),t}async function X(e,n,r){let t=await fetchEncodedAccount(e,n,r);return O(t)}async function re(e,n,r){let t=await Y(e,n,r);return assertAccountsExist(t),t}async function Y(e,n,r){return (await fetchEncodedAccounts(e,n,r)).map(S=>O(S))}export{v as a,ee as b,V as c,B as d,te as e,O as f,ne as g,X as h,re as i,Y as j};//# sourceMappingURL=chunk-PUI35LBF.js.map
2
- //# sourceMappingURL=chunk-PUI35LBF.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/generated/accounts/auctionMarketplace.ts"],"names":["AUCTION_MARKETPLACE_DISCRIMINATOR","getAuctionMarketplaceDiscriminatorBytes","fixEncoderSize","getBytesEncoder","getAuctionMarketplaceEncoder","transformEncoder","getStructEncoder","getAddressEncoder","getAuctionTypeEncoder","getU64Encoder","getBooleanEncoder","getOptionEncoder","getI64Encoder","getU32Encoder","getAuctionStatusEncoder","getArrayEncoder","getAuctionBidEncoder","addEncoderSizePrefix","getUtf8Encoder","getDutchAuctionConfigEncoder","getU8Encoder","value","getAuctionMarketplaceDecoder","getStructDecoder","fixDecoderSize","getBytesDecoder","getAddressDecoder","getAuctionTypeDecoder","getU64Decoder","getBooleanDecoder","getOptionDecoder","getI64Decoder","getU32Decoder","getAuctionStatusDecoder","getArrayDecoder","getAuctionBidDecoder","addDecoderSizePrefix","getUtf8Decoder","getDutchAuctionConfigDecoder","getU8Decoder","getAuctionMarketplaceCodec","combineCodec","decodeAuctionMarketplace","encodedAccount","decodeAccount","fetchAuctionMarketplace","rpc","address","config","maybeAccount","fetchMaybeAuctionMarketplace","assertAccountExists","fetchEncodedAccount","fetchAllAuctionMarketplace","addresses","maybeAccounts","fetchAllMaybeAuctionMarketplace","assertAccountsExist","fetchEncodedAccounts"],"mappings":"inBA2EO,IAAMA,CAAAA,CAAoC,IAAI,UAAA,CAAW,CAC9D,GAAA,CAAK,GAAA,CAAK,GAAA,CAAK,CAAA,CAAG,GAAA,CAAK,EAAA,CAAI,EAAA,CAAI,GACjC,CAAC,EAEM,SAASC,EAAAA,EAA0C,CACxD,OAAOC,cAAAA,CAAeC,eAAAA,EAAgB,CAAG,CAAC,CAAA,CAAE,MAAA,CAC1CH,CACF,CACF,CA2DO,SAASI,CAAAA,EAAgE,CAC9E,OAAOC,gBAAAA,CACLC,gBAAAA,CAAiB,CACf,CAAC,eAAA,CAAiBJ,cAAAA,CAAeC,eAAAA,EAAgB,CAAG,CAAC,CAAC,CAAA,CACtD,CAAC,SAAA,CAAWI,iBAAAA,EAAmB,CAAA,CAC/B,CAAC,OAAA,CAASA,iBAAAA,EAAmB,CAAA,CAC7B,CAAC,SAAA,CAAWA,iBAAAA,EAAmB,EAC/B,CAAC,aAAA,CAAeC,EAAAA,EAAuB,CAAA,CACvC,CAAC,eAAA,CAAiBC,aAAAA,EAAe,CAAA,CACjC,CAAC,cAAA,CAAgBA,aAAAA,EAAe,CAAA,CAChC,CAAC,iBAAA,CAAmBC,iBAAAA,EAAmB,CAAA,CACvC,CAAC,YAAA,CAAcA,iBAAAA,EAAmB,CAAA,CAClC,CAAC,cAAA,CAAgBD,aAAAA,EAAe,CAAA,CAChC,CAAC,eAAA,CAAiBE,gBAAAA,CAAiBJ,iBAAAA,EAAmB,CAAC,CAAA,CACvD,CAAC,QAAA,CAAUI,gBAAAA,CAAiBJ,iBAAAA,EAAmB,CAAC,CAAA,CAChD,CAAC,gBAAA,CAAkBK,aAAAA,EAAe,CAAA,CAClC,CAAC,qBAAA,CAAuBH,aAAAA,EAAe,CAAA,CACvC,CAAC,WAAA,CAAaI,aAAAA,EAAe,CAAA,CAC7B,CAAC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MC,CAAAA,CAA6BJ,CAAAA,CAAKC,EAASC,CAAM,CAAA,CAC5E,OAAAG,mBAAAA,CAAoBF,CAAY,CAAA,CACzBA,CACT,CAEA,eAAsBC,CAAAA,CAGpBJ,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACqD,CACrD,IAAMC,CAAAA,CAAe,MAAMG,mBAAAA,CAAoBN,CAAAA,CAAKC,CAAAA,CAASC,CAAM,CAAA,CACnE,OAAON,CAAAA,CAAyBO,CAAY,CAC9C,CAEA,eAAsBI,EAAAA,CACpBP,CAAAA,CACAQ,CAAAA,CACAN,CAAAA,CACwC,CACxC,IAAMO,CAAAA,CAAgB,MAAMC,CAAAA,CAC1BV,CAAAA,CACAQ,CAAAA,CACAN,CACF,CAAA,CACA,OAAAS,mBAAAA,CAAoBF,CAAa,CAAA,CAC1BA,CACT,CAEA,eAAsBC,CAAAA,CACpBV,CAAAA,CACAQ,CAAAA,CACAN,CAAAA,CAC6C,CAE7C,OAAA,CADsB,MAAMU,oBAAAA,CAAqBZ,CAAAA,CAAKQ,CAAAA,CAAWN,CAAM,CAAA,EAClD,GAAA,CAAKC,CAAAA,EACxBP,CAAAA,CAAyBO,CAAY,CACvC,CACF","file":"chunk-PUI35LBF.js","sourcesContent":["/**\n * This code was AUTOGENERATED using the codama library.\n * Please DO NOT EDIT THIS FILE, instead use visitors\n * to add features, then rerun codama to update it.\n *\n * @see https://github.com/codama-idl/codama\n */\n\nimport {\n addDecoderSizePrefix,\n addEncoderSizePrefix,\n assertAccountExists,\n assertAccountsExist,\n combineCodec,\n decodeAccount,\n fetchEncodedAccount,\n fetchEncodedAccounts,\n fixDecoderSize,\n fixEncoderSize,\n getAddressDecoder,\n getAddressEncoder,\n getArrayDecoder,\n getArrayEncoder,\n getBooleanDecoder,\n getBooleanEncoder,\n getBytesDecoder,\n getBytesEncoder,\n getI64Decoder,\n getI64Encoder,\n getOptionDecoder,\n getOptionEncoder,\n getStructDecoder,\n getStructEncoder,\n getU32Decoder,\n getU32Encoder,\n getU64Decoder,\n getU64Encoder,\n getU8Decoder,\n getU8Encoder,\n getUtf8Decoder,\n getUtf8Encoder,\n transformEncoder,\n type Account,\n type Address,\n type Codec,\n type Decoder,\n type EncodedAccount,\n type Encoder,\n type FetchAccountConfig,\n type FetchAccountsConfig,\n type MaybeAccount,\n type MaybeEncodedAccount,\n type Option,\n type OptionOrNullable,\n type ReadonlyUint8Array,\n} from '@solana/kit';\nimport {\n getAuctionBidDecoder,\n getAuctionBidEncoder,\n getAuctionStatusDecoder,\n getAuctionStatusEncoder,\n getAuctionTypeDecoder,\n getAuctionTypeEncoder,\n getDutchAuctionConfigDecoder,\n getDutchAuctionConfigEncoder,\n type AuctionBid,\n type AuctionBidArgs,\n type AuctionStatus,\n type AuctionStatusArgs,\n type AuctionType,\n type AuctionTypeArgs,\n type DutchAuctionConfig,\n type DutchAuctionConfigArgs,\n} from '../types';\n\nexport const AUCTION_MARKETPLACE_DISCRIMINATOR = new Uint8Array([\n 163, 174, 175, 5, 237, 55, 21, 230,\n]);\n\nexport function getAuctionMarketplaceDiscriminatorBytes() {\n return fixEncoderSize(getBytesEncoder(), 8).encode(\n AUCTION_MARKETPLACE_DISCRIMINATOR\n );\n}\n\nexport type AuctionMarketplace = {\n discriminator: ReadonlyUint8Array;\n auction: Address;\n agent: Address;\n creator: Address;\n auctionType: AuctionType;\n startingPrice: bigint;\n reservePrice: bigint;\n isReserveHidden: boolean;\n reserveMet: boolean;\n currentPrice: bigint;\n currentWinner: Option<Address>;\n winner: Option<Address>;\n auctionEndTime: bigint;\n minimumBidIncrement: bigint;\n totalBids: number;\n status: AuctionStatus;\n bids: Array<AuctionBid>;\n createdAt: bigint;\n endedAt: Option<bigint>;\n metadataUri: string;\n dutchConfig: Option<DutchAuctionConfig>;\n extensionCount: number;\n originalEndTime: bigint;\n reservePriceLocked: boolean;\n reserveShortfallNotified: boolean;\n bump: number;\n};\n\nexport type AuctionMarketplaceArgs = {\n auction: Address;\n agent: Address;\n creator: Address;\n auctionType: AuctionTypeArgs;\n startingPrice: number | bigint;\n reservePrice: number | bigint;\n isReserveHidden: boolean;\n reserveMet: boolean;\n currentPrice: number | bigint;\n currentWinner: OptionOrNullable<Address>;\n winner: OptionOrNullable<Address>;\n auctionEndTime: number | bigint;\n minimumBidIncrement: number | bigint;\n totalBids: number;\n status: AuctionStatusArgs;\n bids: Array<AuctionBidArgs>;\n createdAt: number | bigint;\n endedAt: OptionOrNullable<number | bigint>;\n metadataUri: string;\n dutchConfig: OptionOrNullable<DutchAuctionConfigArgs>;\n extensionCount: number;\n originalEndTime: number | bigint;\n reservePriceLocked: boolean;\n reserveShortfallNotified: boolean;\n bump: number;\n};\n\nexport function getAuctionMarketplaceEncoder(): Encoder<AuctionMarketplaceArgs> {\n return transformEncoder(\n getStructEncoder([\n ['discriminator', fixEncoderSize(getBytesEncoder(), 8)],\n ['auction', getAddressEncoder()],\n ['agent', getAddressEncoder()],\n ['creator', getAddressEncoder()],\n ['auctionType', getAuctionTypeEncoder()],\n ['startingPrice', getU64Encoder()],\n ['reservePrice', getU64Encoder()],\n ['isReserveHidden', getBooleanEncoder()],\n ['reserveMet', getBooleanEncoder()],\n ['currentPrice', getU64Encoder()],\n ['currentWinner', getOptionEncoder(getAddressEncoder())],\n ['winner', getOptionEncoder(getAddressEncoder())],\n ['auctionEndTime', getI64Encoder()],\n ['minimumBidIncrement', getU64Encoder()],\n ['totalBids', getU32Encoder()],\n ['status', getAuctionStatusEncoder()],\n ['bids', getArrayEncoder(getAuctionBidEncoder())],\n ['createdAt', getI64Encoder()],\n ['endedAt', getOptionEncoder(getI64Encoder())],\n ['metadataUri', addEncoderSizePrefix(getUtf8Encoder(), getU32Encoder())],\n ['dutchConfig', getOptionEncoder(getDutchAuctionConfigEncoder())],\n ['extensionCount', getU8Encoder()],\n ['originalEndTime', getI64Encoder()],\n ['reservePriceLocked', getBooleanEncoder()],\n ['reserveShortfallNotified', getBooleanEncoder()],\n ['bump', getU8Encoder()],\n ]),\n (value) => ({ ...value, discriminator: AUCTION_MARKETPLACE_DISCRIMINATOR })\n );\n}\n\nexport function getAuctionMarketplaceDecoder(): Decoder<AuctionMarketplace> {\n return getStructDecoder([\n ['discriminator', fixDecoderSize(getBytesDecoder(), 8)],\n ['auction', getAddressDecoder()],\n ['agent', getAddressDecoder()],\n ['creator', getAddressDecoder()],\n ['auctionType', getAuctionTypeDecoder()],\n ['startingPrice', getU64Decoder()],\n ['reservePrice', getU64Decoder()],\n ['isReserveHidden', getBooleanDecoder()],\n ['reserveMet', getBooleanDecoder()],\n ['currentPrice', getU64Decoder()],\n ['currentWinner', getOptionDecoder(getAddressDecoder())],\n ['winner', getOptionDecoder(getAddressDecoder())],\n ['auctionEndTime', getI64Decoder()],\n ['minimumBidIncrement', getU64Decoder()],\n ['totalBids', getU32Decoder()],\n ['status', getAuctionStatusDecoder()],\n ['bids', getArrayDecoder(getAuctionBidDecoder())],\n ['createdAt', getI64Decoder()],\n ['endedAt', getOptionDecoder(getI64Decoder())],\n ['metadataUri', addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],\n ['dutchConfig', getOptionDecoder(getDutchAuctionConfigDecoder())],\n ['extensionCount', getU8Decoder()],\n ['originalEndTime', getI64Decoder()],\n ['reservePriceLocked', getBooleanDecoder()],\n ['reserveShortfallNotified', getBooleanDecoder()],\n ['bump', getU8Decoder()],\n ]);\n}\n\nexport function getAuctionMarketplaceCodec(): Codec<\n AuctionMarketplaceArgs,\n AuctionMarketplace\n> {\n return combineCodec(\n getAuctionMarketplaceEncoder(),\n getAuctionMarketplaceDecoder()\n );\n}\n\nexport function decodeAuctionMarketplace<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress>\n): Account<AuctionMarketplace, TAddress>;\nexport function decodeAuctionMarketplace<TAddress extends string = string>(\n encodedAccount: MaybeEncodedAccount<TAddress>\n): MaybeAccount<AuctionMarketplace, TAddress>;\nexport function decodeAuctionMarketplace<TAddress extends string = string>(\n encodedAccount: EncodedAccount<TAddress> | MaybeEncodedAccount<TAddress>\n):\n | Account<AuctionMarketplace, TAddress>\n | MaybeAccount<AuctionMarketplace, TAddress> {\n return decodeAccount(\n encodedAccount as MaybeEncodedAccount<TAddress>,\n getAuctionMarketplaceDecoder()\n );\n}\n\nexport async function fetchAuctionMarketplace<TAddress extends string = string>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<Account<AuctionMarketplace, TAddress>> {\n const maybeAccount = await fetchMaybeAuctionMarketplace(rpc, address, config);\n assertAccountExists(maybeAccount);\n return maybeAccount;\n}\n\nexport async function fetchMaybeAuctionMarketplace<\n TAddress extends string = string,\n>(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address<TAddress>,\n config?: FetchAccountConfig\n): Promise<MaybeAccount<AuctionMarketplace, TAddress>> {\n const maybeAccount = await fetchEncodedAccount(rpc, address, config);\n return decodeAuctionMarketplace(maybeAccount);\n}\n\nexport async function fetchAllAuctionMarketplace(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<Account<AuctionMarketplace>[]> {\n const maybeAccounts = await fetchAllMaybeAuctionMarketplace(\n rpc,\n addresses,\n config\n );\n assertAccountsExist(maybeAccounts);\n return maybeAccounts;\n}\n\nexport async function fetchAllMaybeAuctionMarketplace(\n rpc: Parameters<typeof fetchEncodedAccounts>[0],\n addresses: Array<Address>,\n config?: FetchAccountsConfig\n): Promise<MaybeAccount<AuctionMarketplace>[]> {\n const maybeAccounts = await fetchEncodedAccounts(rpc, addresses, config);\n return maybeAccounts.map((maybeAccount) =>\n decodeAuctionMarketplace(maybeAccount)\n );\n}\n"]}
@@ -1,11 +0,0 @@
1
- import {a as a$1}from'./chunk-GSHXEKBW.js';import {a}from'./chunk-DJ356OUX.js';import {fetchEncodedAccount,getProgramDerivedAddress,getBytesEncoder,getAddressEncoder}from'@solana/kit';function d(r,e){if(r.length<e.length)return {isValid:false,expectedLength:e.length,actualLength:r.length,canDecode:false,needsMigration:true,errorMessage:`Account too small. Expected at least ${e.length} bytes, got ${r.length}`};let t=r.slice(0,e.length);if(t.every((a,o)=>a===e[o]))return {isValid:true,expectedLength:e.length,actualLength:t.length,canDecode:true,needsMigration:false};if(t.length>=2){let a=t.slice(0,2);if(a[0]!==0||a[1]!==0)return {isValid:false,expectedLength:e.length,actualLength:2,canDecode:false,needsMigration:true,errorMessage:"Legacy discriminator format detected. Account needs migration."}}return {isValid:false,expectedLength:e.length,actualLength:t.length,canDecode:false,needsMigration:true,errorMessage:`Discriminator mismatch. Expected [${Array.from(e).join(", ")}], got [${Array.from(t).join(", ")}]`}}async function U(r,e,t,n,a="account"){try{let i=await r.getAccountInfo(e,{encoding:"base64"}).send();if(!i.value)return {account:null,validation:{isValid:!1,expectedLength:n.length,actualLength:0,canDecode:!1,needsMigration:!1,errorMessage:`${a} account not found`},needsAttention:!1};let l=i.value.data[0];if(typeof l!="string")throw new Error("Expected base64 string from RPC response");let c=Buffer.from(l,"base64"),u=d(c,n);if(u.canDecode)try{return {account:t(c),validation:u,needsAttention:!1}}catch(s){return {account:null,validation:{...u,canDecode:!1,errorMessage:`Decoding failed: ${s instanceof Error?s.message:String(s)}`},needsAttention:!0}}return {account:null,validation:u,needsAttention:u.needsMigration}}catch(o){return {account:null,validation:{isValid:false,expectedLength:n.length,actualLength:0,canDecode:false,needsMigration:false,errorMessage:`Failed to fetch account: ${o instanceof Error?o.message:String(o)}`},needsAttention:true}}}function F(r,e,t){return r.needsMigration?[`\u26A0\uFE0F ${e} account needs attention: ${t}`,` Issue: ${r.errorMessage}`," Resolution: Account may need to be recreated with current program version",` Use 'ghost diagnose account ${t}' for detailed analysis`].join(`
2
- `):r.canDecode?`\u2705 ${e} account is valid: ${t}`:[`\u274C Failed to decode ${e} account: ${t}`,` Issue: ${r.errorMessage}`," This may indicate a corrupt or incompatible account"].join(`
3
- `)}async function q(r){try{let{AGENT_DISCRIMINATOR:e,getAgentDecoder:t}=await import('./agent-GZ2OES75.js');if(d(r.data,e).canDecode)try{return {exists:!0,data:t().decode(r.data)}}catch(a){return console.warn(`Failed to decode Agent account ${r.address}:`,a),{exists:!1}}return {exists:!1}}catch(e){return console.warn(`Safe decode failed for ${r.address}:`,e),null}}function p(r,e){if(!("exists"in r)||!r.exists)return {address:e,dataLength:0,discriminator:null,discriminatorLength:0,isAgentAccount:false,needsMigration:false,rawData:new Uint8Array(0)};let t="data"in r?r.data:new Uint8Array(0),n=Math.min(t.length,8),a=n>0?t.slice(0,n):null;return {address:e,dataLength:t.length,discriminator:a,discriminatorLength:n,isAgentAccount:false,needsMigration:n>0&&n<8,rawData:t}}async function f(r,e){let t={address:e,currentState:"not_exists",migrationType:"none",issues:[],recommendations:[],canAutoMigrate:false};if(!("exists"in r)||!r.exists)return t.recommendations.push("Account does not exist - no migration needed"),t;let{AGENT_DISCRIMINATOR:n}=await import('./agent-GZ2OES75.js'),a=d(r.data,n),o=p(r,e);return a.isValid?(t.currentState="valid",t.recommendations.push("Account is already in the correct format"),t):(a.needsMigration?(t.currentState="needs_migration",t.issues.push(`Discriminator length mismatch: expected 8 bytes, got ${a.actualLength} bytes`)):(t.currentState="invalid",t.issues.push("Account has invalid or corrupted discriminator")),o.discriminatorLength===2?(t.migrationType="recreate",t.issues.push("Account uses legacy 2-byte discriminator format"),t.recommendations.push("Recreate account using current register_agent instruction"),t.recommendations.push("Export existing data first if valuable")):o.discriminatorLength===0?(t.migrationType="unsupported",t.issues.push("Account has no discriminator - may not be an Agent account"),t.recommendations.push("Verify this is actually an Agent account")):o.discriminatorLength<8?(t.migrationType="unsupported",t.issues.push(`Partial discriminator detected (${o.discriminatorLength} bytes)`),t.recommendations.push("Account data may be corrupted - consider recreation")):(t.migrationType="data_conversion",t.issues.push("Discriminator has correct length but wrong values"),t.recommendations.push("May be from a different program version"),t.recommendations.push("Check if this account belongs to the correct program")),t.canAutoMigrate=t.migrationType==="recreate"&&o.dataLength>8,t)}function j(r){if(!("exists"in r)||!r.exists||!("data"in r)||r.data.length<2)return null;let e="data"in r?r.data:new Uint8Array(0);try{if(e.length>=2)return {discriminator:e.slice(0,2)}}catch(t){console.warn("Failed to extract legacy data:",t);}return null}async function H(r){let e=await Promise.all(r.map(({address:a,encodedAccount:o})=>f(o,a))),t={total:e.length,valid:e.filter(a=>a.currentState==="valid").length,needsMigration:e.filter(a=>a.currentState==="needs_migration").length,invalid:e.filter(a=>a.currentState==="invalid").length,canAutoMigrate:e.filter(a=>a.canAutoMigrate).length},n=[];return t.needsMigration>0&&n.push(`${t.needsMigration} accounts need migration`),t.canAutoMigrate>0&&n.push(`${t.canAutoMigrate} accounts can be auto-migrated`),t.invalid>0&&n.push(`${t.invalid} accounts have invalid data and should be investigated`),t.needsMigration===0&&t.invalid===0?n.push("All accounts are in the correct format"):(n.push("Consider running migration utilities to fix account format issues"),n.push("Backup important account data before migration")),{summary:t,plans:e,recommendations:n}}async function P(r,e){let t=await f(r,e),n={wouldSucceed:false,estimatedSteps:[],warnings:[],requiredActions:[]};if(t.currentState==="valid")return n.wouldSucceed=true,n.estimatedSteps.push("No migration needed - account is already valid"),{plan:t,simulation:n};switch(t.migrationType){case "recreate":n.estimatedSteps.push("1. Extract existing account data"),n.estimatedSteps.push("2. Create new account with correct format"),n.estimatedSteps.push("3. Transfer any salvageable data"),n.estimatedSteps.push("4. Close old account"),n.requiredActions.push("User must re-register the agent"),n.warnings.push("Some data may be lost during recreation"),n.wouldSucceed=t.canAutoMigrate;break;case "data_conversion":n.estimatedSteps.push("1. Analyze existing data format"),n.estimatedSteps.push("2. Convert to new format"),n.estimatedSteps.push("3. Update discriminator"),n.warnings.push("Data conversion is experimental"),n.requiredActions.push("Manual verification required"),n.wouldSucceed=false;break;case "unsupported":n.estimatedSteps.push("1. Manual investigation required"),n.estimatedSteps.push("2. Determine if account is recoverable"),n.warnings.push("Account may not be recoverable"),n.requiredActions.push("Manual inspection and possible recreation"),n.wouldSucceed=false;break;default:n.estimatedSteps.push("No migration strategy available"),n.wouldSucceed=false;}return {plan:t,simulation:n}}function R(r){let e=[];switch(r.migrationType){case "none":e.push("\u2705 No migration needed - your account is up to date");break;case "recreate":e.push("\u{1F504} Account Recreation Required:"),e.push("1. Use the CLI command: `ghost agent register` to create a new account"),e.push("2. Configure your agent with the same settings as before"),e.push("3. The old account will be automatically replaced"),e.push("\u26A0\uFE0F Note: You may need to re-verify your agent after recreation");break;case "data_conversion":e.push("\u{1F527} Data Conversion Required:"),e.push("1. Contact support for assistance with account conversion"),e.push("2. Manual intervention may be required"),e.push("3. Backup your account data before proceeding");break;case "unsupported":e.push("\u274C Migration Not Supported:"),e.push("1. This account cannot be automatically migrated"),e.push("2. Consider creating a new account"),e.push("3. Contact support if this account contains important data");break}return e}var L={};a(L,{diagnoseAccountFromChain:()=>T,diagnoseBatchFromChain:()=>V,exportDiagnosticReport:()=>C,runAccountDiagnostics:()=>h,runBatchDiagnostics:()=>D});async function h(r,e){let t=new Date().toISOString(),n="exists"in r&&r.exists,a,o,i,l;if(n){let{AGENT_DISCRIMINATOR:s}=await import('./agent-GZ2OES75.js');a=d(r.data,s),o=p(r,e),i=await f(r,e),l=await P(r,e);}else a={isValid:false,actualLength:0,expectedLength:8,canDecode:false,needsMigration:false,errorMessage:"Account does not exist"},o={address:e,dataLength:0,discriminator:null,discriminatorLength:0,isAgentAccount:false,needsMigration:false,rawData:new Uint8Array(0)},i={address:e,currentState:"not_exists",migrationType:"none",issues:["Account does not exist"],recommendations:["Create account using register_agent instruction"],canAutoMigrate:false},l={plan:i,simulation:{wouldSucceed:false,estimatedSteps:["Account must be created first"],warnings:[],requiredActions:["Use register_agent instruction"]}};let c=[];n?a.isValid?c.push("Account is valid - no action needed"):c.push(...R(i)):c.push("Account does not exist - create using register_agent");let u={expectedDiscriminator:Array.from(a$1),actualDiscriminator:o.discriminator?Array.from(o.discriminator):null,dataPreview:Array.from(o.rawData.slice(0,32)),programId:n&&"owner"in r?r.owner:void 0};return {address:e,timestamp:t,accountExists:n,discriminatorValidation:a,inspection:o,migrationPlan:i,migrationSimulation:l,recommendations:c,debugInfo:u}}async function D(r){let e=new Date().toISOString(),t=await Promise.all(r.map(({address:o,encodedAccount:i})=>h(i,o))),n={total:t.length,valid:t.filter(o=>o.accountExists&&o.discriminatorValidation.isValid).length,invalid:t.filter(o=>o.accountExists&&!o.discriminatorValidation.isValid).length,needsMigration:t.filter(o=>o.migrationPlan.currentState==="needs_migration").length,notExists:t.filter(o=>!o.accountExists).length},a=[];return n.notExists>0&&a.push(`${n.notExists} accounts need to be created`),n.needsMigration>0&&a.push(`${n.needsMigration} accounts need migration`),n.invalid>0&&a.push(`${n.invalid} accounts have data issues`),n.valid===n.total&&a.push("All accounts are healthy"),{summary:n,reports:t,globalRecommendations:a,timestamp:e}}async function T(r,e,t){try{let n=await fetchEncodedAccount(r,e),a=await h(n,e);return t?.logToConsole&&(console.group(`\u{1F50D} Account Diagnostics: ${e}`),console.log("Exists:",a.accountExists),console.log("Valid:",a.discriminatorValidation.isValid),console.log("Needs Migration:",a.migrationPlan.currentState==="needs_migration"),console.log("Recommendations:"),a.recommendations.forEach(o=>console.log(` - ${o}`)),a.discriminatorValidation.isValid||(console.log("Issues:"),Array.isArray(a.migrationPlan.issues)&&a.migrationPlan.issues.forEach(o=>console.log(` - ${o}`))),console.groupEnd()),a}catch(n){return console.error(`Failed to diagnose account ${e}:`,n),{address:e,timestamp:new Date().toISOString(),accountExists:false,discriminatorValidation:{isValid:false,actualLength:0,expectedLength:8,canDecode:false,needsMigration:false,errorMessage:`Failed to fetch account: ${n instanceof Error?n.message:String(n)}`},inspection:{address:e,dataLength:0,discriminator:null,discriminatorLength:0,isAgentAccount:false,needsMigration:false,rawData:new Uint8Array(0)},migrationPlan:{address:e,currentState:"invalid",migrationType:"unsupported",issues:[`Failed to fetch account: ${n instanceof Error?n.message:String(n)}`],recommendations:["Check network connection and account address"],canAutoMigrate:false},migrationSimulation:{plan:{address:e,currentState:"invalid",migrationType:"unsupported",issues:[`Failed to fetch account: ${n instanceof Error?n.message:String(n)}`],recommendations:["Check network connection and account address"],canAutoMigrate:false},simulation:{wouldSucceed:false,estimatedSteps:["Fix network connectivity issues"],warnings:["Account could not be fetched"],requiredActions:["Verify account address and network connection"]}},recommendations:["Check network connection and account address"],debugInfo:{expectedDiscriminator:Array.from(a$1),actualDiscriminator:null,dataPreview:[],programId:void 0}}}}async function V(r,e,t){let n=t?.maxConcurrent??10,a=[];for(let i=0;i<e.length;i+=n){let c=e.slice(i,i+n).map(s=>T(r,s,{logToConsole:false})),u=await Promise.allSettled(c);for(let s of u)s.status==="fulfilled"?a.push(s.value):(console.error("Failed to diagnose account:",s.reason),a.push({address:"unknown",timestamp:new Date().toISOString(),accountExists:false,discriminatorValidation:{isValid:false,actualLength:0,expectedLength:8,canDecode:false,needsMigration:false,errorMessage:"Failed to fetch account"},inspection:{address:"unknown",dataLength:0,discriminator:null,discriminatorLength:0,isAgentAccount:false,needsMigration:false,rawData:new Uint8Array(0)},migrationPlan:{address:"unknown",currentState:"invalid",migrationType:"unsupported",issues:["Failed to fetch account"],recommendations:["Check network connection"],canAutoMigrate:false},migrationSimulation:{plan:{address:"unknown",currentState:"invalid",migrationType:"unsupported",issues:["Failed to fetch account"],recommendations:["Check network connection"],canAutoMigrate:false},simulation:{wouldSucceed:false,estimatedSteps:["Fix fetch issues"],warnings:["Account could not be fetched"],requiredActions:["Check network"]}},recommendations:["Check network connection"],debugInfo:{expectedDiscriminator:Array.from(a$1),actualDiscriminator:null,dataPreview:[],programId:void 0}}));}let o=await D(a.map(i=>({address:i.address,encodedAccount:{exists:i.accountExists,data:i.inspection.rawData,address:i.address,owner:i.debugInfo.programId??"",executable:false,lamports:0n,programAddress:i.debugInfo.programId??"",space:i.inspection.rawData.length}})));return t?.logToConsole&&(console.group("\u{1F50D} Batch Diagnostics Summary"),console.log("Total accounts:",o.summary.total),console.log("Valid accounts:",o.summary.valid),console.log("Invalid accounts:",o.summary.invalid),console.log("Need migration:",o.summary.needsMigration),console.log("Do not exist:",o.summary.notExists),console.log("Global recommendations:"),o.globalRecommendations.forEach(i=>console.log(` - ${i}`)),console.groupEnd()),o}function C(r,e){let t=JSON.stringify(r,null,2);return e&&(console.log(`Diagnostic report would be saved as: ${e}`),console.log("Report data:",t)),t}var _={};a(_,{GovernanceAnalyticsUtils:()=>v,MultisigUtils:()=>A,PERMISSION_TEMPLATES:()=>g,ProposalUtils:()=>b,ROLE_TEMPLATES:()=>O,RbacUtils:()=>y,VotingUtils:()=>M,deriveMultisigPda:()=>$,deriveProposalPda:()=>k,deriveRbacPda:()=>N});async function $(r,e,t){let[n]=await getProgramDerivedAddress({programAddress:r,seeds:[getBytesEncoder().encode(new Uint8Array([109,117,108,116,105,115,105,103])),getAddressEncoder().encode(e),new Uint8Array(new BigUint64Array([t]).buffer)]});return n}async function k(r,e,t){let[n]=await getProgramDerivedAddress({programAddress:r,seeds:[getBytesEncoder().encode(new Uint8Array([112,114,111,112,111,115,97,108])),getAddressEncoder().encode(e),new Uint8Array(new BigUint64Array([t]).buffer)]});return n}async function N(r,e){let[t]=await getProgramDerivedAddress({programAddress:r,seeds:[getBytesEncoder().encode(new Uint8Array([114,98,97,99])),getAddressEncoder().encode(e)]});return t}var A=class{static hasReachedThreshold(e,t){return t>=e.threshold}static isSigner(e,t){return e.signers.some(n=>n===t)}static remainingSignatures(e,t){let n=e.threshold-t;return Math.max(0,n)}static validateConfiguration(e,t){return e.length===0?{valid:false,error:"At least one signer required"}:e.length>10?{valid:false,error:"Maximum 10 signers allowed"}:t===0?{valid:false,error:"Threshold must be at least 1"}:t>e.length?{valid:false,error:"Threshold cannot exceed number of signers"}:new Set(e).size!==e.length?{valid:false,error:"Duplicate signers not allowed"}:{valid:true}}static generateSummary(e){let t=e.signers.length,n=Math.round(e.threshold/t*100);return `${e.threshold}-of-${t} multisig (${n}% approval required)`}},b=class{static isVotingOpen(e){let t=BigInt(Math.floor(Date.now()/1e3));return e.status===1&&t>=e.votingStartsAt&&t<=e.votingEndsAt}static hasExpired(e){return BigInt(Math.floor(Date.now()/1e3))>e.votingEndsAt}static timeRemaining(e){let t=BigInt(Math.floor(Date.now()/1e3));return t>=e.votingEndsAt?0n:e.votingEndsAt-t}static formatTimeRemaining(e){let t=this.timeRemaining(e);if(t===0n)return "Voting ended";let n=Number(t),a=Math.floor(n/86400),o=Math.floor(n%86400/3600),i=Math.floor(n%3600/60);return a>0?`${a}d ${o}h remaining`:o>0?`${o}h ${i}m remaining`:`${i}m remaining`}static hasReachedQuorum(e,t,n){return Number(e.votesFor+e.votesAgainst+e.votesAbstain)/n*100>=t.minimumParticipation}static calculateResults(e){let t=Number(e.votesFor+e.votesAgainst+e.votesAbstain);if(t===0)return {total:0,forPercentage:0,againstPercentage:0,abstainPercentage:0,passed:false};let n=Number(e.votesFor)/t*100,a=Number(e.votesAgainst)/t*100,o=Number(e.votesAbstain)/t*100,i=e.votesFor>e.votesAgainst;return {total:t,forPercentage:n,againstPercentage:a,abstainPercentage:o,passed:i}}static validateProposal(e){return !e.title||e.title.trim().length===0?{valid:false,error:"Title is required"}:e.title.length>100?{valid:false,error:"Title cannot exceed 100 characters"}:!e.description||e.description.trim().length===0?{valid:false,error:"Description is required"}:e.description.length>5e3?{valid:false,error:"Description cannot exceed 5000 characters"}:{valid:true}}},y=class{static hasPermission(e,t,n){let a=this.getUserRole(e,t);return a?a.permissions.includes(n):false}static getUserRole(e,t){let n=e.accessPolicies.find(a=>a.policyId.includes(t)||a.name.includes(t));if(n){let a=e.roles.find(o=>o.roleId===n.policyId||o.name===n.name||n.scope.toString().includes(o.roleId));if(a)return a}return e.roles.find(a=>a.name==="default")??null}static isValidPermission(e){return e.length>0&&e.length<100}static validateRole(e){return !e.name||e.name.trim().length===0?{valid:false,error:"Role name is required"}:e.name.length>50?{valid:false,error:"Role name cannot exceed 50 characters"}:e.permissions.length===0?{valid:false,error:"Role must have at least one permission"}:e.permissions.length>20?{valid:false,error:"Role cannot have more than 20 permissions"}:{valid:true}}static generatePermissionSummary(e){return e.length===0?"No permissions":e.length===1?"1 permission":`${e.length} permissions`}},M=class{static calculateVoteWeight(e,t,n){let a=e;if(t){let o=Math.min(Number(t/1000000n),10);a*=o;}if(n){let i=1+Number(n/86400n)/365;a*=i;}return Math.floor(a)}static formatVoteChoice(e){switch(e){case 0:return "\u2705 For";case 1:return "\u274C Against";case 2:return "\u{1F937} Abstain";default:return "Unknown"}}static hasSimpleMajority(e){return e.votesFor>e.votesAgainst}static hasSupermajority(e){let t=e.votesFor+e.votesAgainst;return t===0n?false:Number(e.votesFor)/Number(t)>=.667}},g={ADMIN:{CREATE_PROPOSAL:{action:"create",resource:"proposal"},EXECUTE_PROPOSAL:{action:"execute",resource:"proposal"},MANAGE_ROLES:{action:"manage",resource:"roles"},MANAGE_TREASURY:{action:"manage",resource:"treasury"}},MEMBER:{VOTE:{action:"vote",resource:"proposal"},VIEW:{action:"view",resource:"all"},COMMENT:{action:"comment",resource:"proposal"}},MODERATOR:{CANCEL_PROPOSAL:{action:"cancel",resource:"proposal"},MODERATE_COMMENTS:{action:"moderate",resource:"comments"},VIEW_REPORTS:{action:"view",resource:"reports"}}},O={ADMIN:{name:"Administrator",description:"Full administrative access",permissions:Object.values(g.ADMIN)},MEMBER:{name:"Member",description:"Standard member access",permissions:Object.values(g.MEMBER)},MODERATOR:{name:"Moderator",description:"Content moderation access",permissions:[...Object.values(g.MEMBER),...Object.values(g.MODERATOR)]}},v=class{static calculateHealthScore(e){let t=0;t+=Math.min(e.averageVoterTurnout*.4,40);let n=e.passedProposals+e.failedProposals;if(n>0){let o=e.passedProposals/n;t+=o*30;}let a=e.activeProposals/Math.max(e.totalProposals,1);return t+=Math.min(a*60,30),Math.round(t)}static generateSummaryReport(e){let t=this.calculateHealthScore(e),n=e.totalProposals>0?Math.round(e.passedProposals/e.totalProposals*100):0;return `
4
- Governance Summary:
5
- - Total Proposals: ${e.totalProposals}
6
- - Active: ${e.activeProposals}
7
- - Success Rate: ${n}%
8
- - Avg Turnout: ${Math.round(e.averageVoterTurnout)}%
9
- - Health Score: ${t}/100
10
- `.trim()}};export{d as a,U as b,F as c,q as d,p as e,f,j as g,H as h,P as i,R as j,h as k,D as l,T as m,V as n,C as o,L as p,$ as q,k as r,_ as s};//# sourceMappingURL=chunk-Q34J6YDA.js.map
11
- //# sourceMappingURL=chunk-Q34J6YDA.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/discriminator-validator.ts","../src/utils/account-migration.ts","../src/utils/account-diagnostics.ts","../src/utils/governance-helpers.ts"],"names":["validateAccountDiscriminator","accountData","expectedDiscriminator","actualDiscriminator","byte","index","first2Bytes","safeDecodeAccount","rpc","address","decoder","accountType","response","rawData","validation","decodeError","error","createDiscriminatorErrorMessage","safeDecodeAgent","encodedAccount","AGENT_DISCRIMINATOR","getAgentDecoder","inspectAccountData","data","discriminatorLength","discriminator","createMigrationPlan","plan","inspection","extractLegacyData","createMigrationReport","accounts","plans","summary","p","recommendations","simulateMigration","simulation","getMigrationInstructions","instructions","account_diagnostics_exports","__export","diagnoseAccountFromChain","diagnoseBatchFromChain","exportDiagnosticReport","runAccountDiagnostics","runBatchDiagnostics","timestamp","accountExists","discriminatorValidation","migrationPlan","migrationSimulation","debugInfo","reports","r","globalRecommendations","options","fetchEncodedAccount","report","rec","issue","err","addresses","maxConcurrent","batchPromises","batchReports","result","batchReport","filename","json","governance_helpers_exports","GovernanceAnalyticsUtils","MultisigUtils","PERMISSION_TEMPLATES","ProposalUtils","ROLE_TEMPLATES","RbacUtils","VotingUtils","deriveMultisigPda","deriveProposalPda","deriveRbacPda","programId","authority","multisigId","pda","getProgramDerivedAddress","getBytesEncoder","getAddressEncoder","multisig","proposalId","admin","approvalCount","signer","currentApprovals","remaining","signers","threshold","signerCount","percentage","proposal","now","seconds","days","hours","minutes","votingResults","quorumRequirements","totalEligibleVoters","total","forPercentage","againstPercentage","abstainPercentage","passed","rbac","user","permission","userRole","userPolicy","policy","assignedRole","role","permissions","baseWeight","tokenBalance","stakeDuration","weight","tokenMultiplier","timeMultiplier","voteChoice","totalVotes","analytics","score","totalCompleted","successRate","activityRatio","healthScore"],"mappings":"wLAgDO,SAASA,EACdC,CAAAA,CACAC,CAAAA,CAC+B,CAE/B,GAAID,EAAY,MAAA,CAASC,CAAAA,CAAsB,MAAA,CAC7C,OAAO,CACL,OAAA,CAAS,KAAA,CACT,eAAgBA,CAAAA,CAAsB,MAAA,CACtC,aAAcD,CAAAA,CAAY,MAAA,CAC1B,SAAA,CAAW,KAAA,CACX,eAAgB,IAAA,CAChB,YAAA,CAAc,CAAA,qCAAA,EAAwCC,CAAAA,CAAsB,MAAM,CAAA,YAAA,EAAeD,CAAAA,CAAY,MAAM,CAAA,CACrH,EAIF,IAAME,CAAAA,CAAsBF,EAAY,KAAA,CAAM,CAAA,CAAGC,EAAsB,MAAM,CAAA,CAK7E,GAFgBC,CAAAA,CAAoB,MAAM,CAACC,CAAAA,CAAMC,CAAAA,GAAUD,CAAAA,GAASF,EAAsBG,CAAK,CAAC,CAAA,CAG9F,OAAO,CACL,OAAA,CAAS,IAAA,CACT,eAAgBH,CAAAA,CAAsB,MAAA,CACtC,aAAcC,CAAAA,CAAoB,MAAA,CAClC,SAAA,CAAW,IAAA,CACX,eAAgB,KAClB,CAAA,CAIF,GAAIA,CAAAA,CAAoB,QAAU,CAAA,CAAG,CACnC,IAAMG,CAAAA,CAAcH,EAAoB,KAAA,CAAM,CAAA,CAAG,CAAC,CAAA,CAElD,GAAIG,EAAY,CAAC,CAAA,GAAM,CAAA,EAAKA,CAAAA,CAAY,CAAC,CAAA,GAAM,CAAA,CAC7C,OAAO,CACL,QAAS,KAAA,CACT,cAAA,CAAgBJ,CAAAA,CAAsB,MAAA,CACtC,aAAc,CAAA,CACd,SAAA,CAAW,MACX,cAAA,CAAgB,IAAA,CAChB,aAAc,gEAChB,CAEJ,CAEA,OAAO,CACL,OAAA,CAAS,KAAA,CACT,cAAA,CAAgBA,CAAAA,CAAsB,OACtC,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A,CAAkBE,EAChDD,CAAAA,EAASE,CAAAA,CAAc,GACzB,CAGA,IAAMC,EAAgBJ,CAAAA,CAAU,eAAA,CAAkB,IAAA,CAAK,GAAA,CAAIA,EAAU,cAAA,CAAgB,CAAC,EACtF,OAAAC,CAAAA,EAAS,KAAK,GAAA,CAAIG,CAAAA,CAAgB,EAAA,CAAI,EAAE,EAEjC,IAAA,CAAK,KAAA,CAAMH,CAAK,CACzB,CAKA,OAAO,qBAAA,CAAsBD,CAAAA,CAAwC,CACnE,IAAMK,EAAc,IAAA,CAAK,oBAAA,CAAqBL,CAAS,CAAA,CACjDG,CAAAA,CAAcH,EAAU,cAAA,CAAiB,CAAA,CAC3C,IAAA,CAAK,KAAA,CAAOA,EAAU,eAAA,CAAkBA,CAAAA,CAAU,eAAkB,GAAG,CAAA,CACvE,EAEJ,OAAO;AAAA;AAAA,mBAAA,EAEUA,EAAU,cAAc;AAAA,UAAA,EACjCA,EAAU,eAAe;AAAA,gBAAA,EACnBG,CAAW,CAAA;AAAA,eAAA,EACZ,IAAA,CAAK,KAAA,CAAMH,CAAAA,CAAU,mBAAmB,CAAC,CAAA;AAAA,gBAAA,EACxCK,CAAW,CAAA;AAAA,IAAA,CAAA,CACvB,IAAA,EACJ,CACF,CAAA","file":"chunk-Q34J6YDA.js","sourcesContent":["/**\n * Discriminator Validation Utilities\n * \n * Handles discriminator validation and provides fallback mechanisms\n * for accounts with mismatched discriminators\n */\n\nimport type { Address } from '@solana/addresses'\nimport type { EncodedAccount, MaybeEncodedAccount } from '@solana/kit'\n\ninterface RpcResponse {\n value: {\n data: [string, string]\n executable: boolean\n lamports: number\n owner: string\n rentEpoch: number\n } | null\n}\n\ninterface RpcInterface {\n getAccountInfo: (address: Address, options: { encoding: string }) => {\n send: () => Promise<RpcResponse>\n }\n}\n\nexport interface DiscriminatorValidationResult {\n isValid: boolean\n expectedLength: number\n actualLength: number\n canDecode: boolean\n needsMigration: boolean\n errorMessage?: string\n}\n\nexport interface AccountInspectionResult {\n address: string\n dataLength: number\n discriminator: Uint8Array | null\n discriminatorLength: number\n isAgentAccount: boolean\n needsMigration: boolean\n rawData: Uint8Array\n}\n\n/**\n * Validates account discriminator before attempting to decode\n */\nexport function validateAccountDiscriminator(\n accountData: Uint8Array,\n expectedDiscriminator: Uint8Array\n): DiscriminatorValidationResult {\n // Check if we have enough data for a discriminator\n if (accountData.length < expectedDiscriminator.length) {\n return {\n isValid: false,\n expectedLength: expectedDiscriminator.length,\n actualLength: accountData.length,\n canDecode: false,\n needsMigration: true,\n errorMessage: `Account too small. Expected at least ${expectedDiscriminator.length} bytes, got ${accountData.length}`\n }\n }\n\n // Extract the discriminator from account data\n const actualDiscriminator = accountData.slice(0, expectedDiscriminator.length)\n\n // Check if discriminators match\n const isValid = actualDiscriminator.every((byte, index) => byte === expectedDiscriminator[index])\n\n if (isValid) {\n return {\n isValid: true,\n expectedLength: expectedDiscriminator.length,\n actualLength: actualDiscriminator.length,\n canDecode: true,\n needsMigration: false\n }\n }\n\n // Check for common legacy discriminator patterns\n if (actualDiscriminator.length >= 2) {\n const first2Bytes = actualDiscriminator.slice(0, 2)\n // If first 2 bytes are non-zero, might be legacy format\n if (first2Bytes[0] !== 0 || first2Bytes[1] !== 0) {\n return {\n isValid: false,\n expectedLength: expectedDiscriminator.length,\n actualLength: 2, // Legacy format\n canDecode: false,\n needsMigration: true,\n errorMessage: `Legacy discriminator format detected. Account needs migration.`\n }\n }\n }\n\n return {\n isValid: false,\n expectedLength: expectedDiscriminator.length,\n actualLength: actualDiscriminator.length,\n canDecode: false,\n needsMigration: true,\n errorMessage: `Discriminator mismatch. Expected [${Array.from(expectedDiscriminator).join(', ')}], got [${Array.from(actualDiscriminator).join(', ')}]`\n }\n}\n\n/**\n * Safe account decoding with discriminator validation\n */\nexport async function safeDecodeAccount<T>(\n rpc: unknown,\n address: Address,\n decoder: (data: Uint8Array) => T,\n expectedDiscriminator: Uint8Array,\n accountType = 'account'\n): Promise<{ account: T | null; validation: DiscriminatorValidationResult; needsAttention: boolean }> {\n try {\n // Fetch raw account data using compatible RPC interface\n const rpcClient = rpc as RpcInterface\n const response = await rpcClient.getAccountInfo(address, { encoding: 'base64' }).send()\n \n if (!response.value) {\n return {\n account: null,\n validation: {\n isValid: false,\n expectedLength: expectedDiscriminator.length,\n actualLength: 0,\n canDecode: false,\n needsMigration: false,\n errorMessage: `${accountType} account not found`\n },\n needsAttention: false\n }\n }\n\n // Decode base64 data\n const rawData = response.value.data[0]\n if (typeof rawData !== 'string') {\n throw new Error('Expected base64 string from RPC response')\n }\n const accountData = Buffer.from(rawData, 'base64')\n \n // Validate discriminator\n const validation = validateAccountDiscriminator(accountData, expectedDiscriminator)\n \n if (validation.canDecode) {\n // Try to decode the account\n try {\n const account = decoder(accountData)\n return { account, validation, needsAttention: false }\n } catch (decodeError) {\n return {\n account: null,\n validation: {\n ...validation,\n canDecode: false,\n errorMessage: `Decoding failed: ${decodeError instanceof Error ? decodeError.message : String(decodeError)}`\n },\n needsAttention: true\n }\n }\n }\n\n return {\n account: null,\n validation,\n needsAttention: validation.needsMigration\n }\n\n } catch (error) {\n return {\n account: null,\n validation: {\n isValid: false,\n expectedLength: expectedDiscriminator.length,\n actualLength: 0,\n canDecode: false,\n needsMigration: false,\n errorMessage: `Failed to fetch account: ${error instanceof Error ? error.message : String(error)}`\n },\n needsAttention: true\n }\n }\n}\n\n/**\n * Create user-friendly error message for discriminator issues\n */\nexport function createDiscriminatorErrorMessage(\n validation: DiscriminatorValidationResult,\n accountType: string,\n address: string\n): string {\n if (validation.needsMigration) {\n return [\n `⚠️ ${accountType} account needs attention: ${address}`,\n ` Issue: ${validation.errorMessage}`,\n ` Resolution: Account may need to be recreated with current program version`,\n ` Use 'ghost diagnose account ${address}' for detailed analysis`\n ].join('\\n')\n }\n\n if (!validation.canDecode) {\n return [\n `❌ Failed to decode ${accountType} account: ${address}`,\n ` Issue: ${validation.errorMessage}`,\n ` This may indicate a corrupt or incompatible account`\n ].join('\\n')\n }\n\n return `✅ ${accountType} account is valid: ${address}`\n}\n\n/**\n * Safe Agent account decoding with discriminator validation\n * Returns a compatibility result with exists property\n */\nexport async function safeDecodeAgent(\n encodedAccount: { address: Address; data: Uint8Array }\n): Promise<{ exists: boolean; data?: unknown } | null> {\n try {\n // Import Agent discriminator and decoder\n const { AGENT_DISCRIMINATOR, getAgentDecoder } = await import('../generated/accounts/agent.js')\n \n // Validate discriminator\n const validation = validateAccountDiscriminator(encodedAccount.data, AGENT_DISCRIMINATOR)\n \n if (validation.canDecode) {\n try {\n const decoder = getAgentDecoder()\n const data = decoder.decode(encodedAccount.data)\n return { exists: true, data }\n } catch (decodeError) {\n console.warn(`Failed to decode Agent account ${encodedAccount.address}:`, decodeError)\n return { exists: false }\n }\n }\n \n // Account exists but can't be decoded due to discriminator issues\n return { exists: false }\n } catch (error) {\n console.warn(`Safe decode failed for ${encodedAccount.address}:`, error)\n return null\n }\n}\n\n/**\n * Inspects account data and extracts useful information about discriminator\n */\nexport function inspectAccountData(\n encodedAccount: EncodedAccount | MaybeEncodedAccount,\n address: string\n): AccountInspectionResult {\n if (!('exists' in encodedAccount) || !encodedAccount.exists) {\n return {\n address,\n dataLength: 0,\n discriminator: null,\n discriminatorLength: 0,\n isAgentAccount: false,\n needsMigration: false,\n rawData: new Uint8Array(0)\n }\n }\n\n const data = 'data' in encodedAccount ? encodedAccount.data : new Uint8Array(0)\n \n // Extract discriminator (first 8 bytes if available)\n const discriminatorLength = Math.min(data.length, 8)\n const discriminator = discriminatorLength > 0 ? data.slice(0, discriminatorLength) : null\n\n return {\n address,\n dataLength: data.length,\n discriminator,\n discriminatorLength,\n isAgentAccount: false, // Would need more logic to determine this\n needsMigration: discriminatorLength > 0 && discriminatorLength < 8,\n rawData: data\n }\n}","/**\n * Account Migration Utility\n * \n * Handles migration of old Agent accounts that were created with\n * different discriminator formats to the current format.\n */\n\nimport type { EncodedAccount, MaybeEncodedAccount } from '@solana/kit';\nimport { \n validateAccountDiscriminator, \n inspectAccountData \n} from './discriminator-validator.js';\n\nexport interface MigrationPlan {\n address: string;\n currentState: 'valid' | 'needs_migration' | 'invalid' | 'not_exists';\n migrationType: 'none' | 'recreate' | 'data_conversion' | 'unsupported';\n issues: string[];\n recommendations: string[];\n canAutoMigrate: boolean;\n}\n\nexport interface MigrationResult {\n success: boolean;\n address: string;\n action: 'skipped' | 'migrated' | 'failed';\n error?: string;\n newAccountData?: Uint8Array;\n}\n\nexport interface LegacyAgentData {\n // Define potential old Agent format fields here\n // This would need to be updated based on actual legacy formats\n discriminator: Uint8Array;\n owner?: string;\n name?: string;\n // ... other legacy fields\n}\n\n/**\n * Analyzes an account and creates a migration plan\n */\nexport async function createMigrationPlan(\n encodedAccount: EncodedAccount | MaybeEncodedAccount,\n address: string\n): Promise<MigrationPlan> {\n const plan: MigrationPlan = {\n address,\n currentState: 'not_exists',\n migrationType: 'none',\n issues: [],\n recommendations: [],\n canAutoMigrate: false\n };\n\n if (!('exists' in encodedAccount) || !encodedAccount.exists) {\n plan.recommendations.push('Account does not exist - no migration needed');\n return plan;\n }\n\n // Import the discriminator\n const { AGENT_DISCRIMINATOR } = await import('../generated/accounts/agent.js');\n const validation = validateAccountDiscriminator(encodedAccount.data, AGENT_DISCRIMINATOR);\n const inspection = inspectAccountData(encodedAccount, address);\n\n // Determine current state\n if (validation.isValid) {\n plan.currentState = 'valid';\n plan.recommendations.push('Account is already in the correct format');\n return plan;\n }\n\n if (validation.needsMigration) {\n plan.currentState = 'needs_migration';\n plan.issues.push(`Discriminator length mismatch: expected 8 bytes, got ${validation.actualLength} bytes`);\n } else {\n plan.currentState = 'invalid';\n plan.issues.push('Account has invalid or corrupted discriminator');\n }\n\n // Determine migration type based on data analysis\n if (inspection.discriminatorLength === 2) {\n // This is likely an old format with 2-byte discriminator\n plan.migrationType = 'recreate';\n plan.issues.push('Account uses legacy 2-byte discriminator format');\n plan.recommendations.push('Recreate account using current register_agent instruction');\n plan.recommendations.push('Export existing data first if valuable');\n } else if (inspection.discriminatorLength === 0) {\n // Account has no discriminator\n plan.migrationType = 'unsupported';\n plan.issues.push('Account has no discriminator - may not be an Agent account');\n plan.recommendations.push('Verify this is actually an Agent account');\n } else if (inspection.discriminatorLength < 8) {\n // Partial discriminator\n plan.migrationType = 'unsupported';\n plan.issues.push(`Partial discriminator detected (${inspection.discriminatorLength} bytes)`);\n plan.recommendations.push('Account data may be corrupted - consider recreation');\n } else {\n // Full 8-byte discriminator but wrong values\n plan.migrationType = 'data_conversion';\n plan.issues.push('Discriminator has correct length but wrong values');\n plan.recommendations.push('May be from a different program version');\n plan.recommendations.push('Check if this account belongs to the correct program');\n }\n\n // Determine if auto-migration is possible\n plan.canAutoMigrate = plan.migrationType === 'recreate' && inspection.dataLength > 8;\n\n return plan;\n}\n\n/**\n * Attempts to extract meaningful data from a legacy account\n */\nexport function extractLegacyData(\n encodedAccount: EncodedAccount | MaybeEncodedAccount\n): LegacyAgentData | null {\n if (!('exists' in encodedAccount) || !encodedAccount.exists || !('data' in encodedAccount) || encodedAccount.data.length < 2) {\n return null;\n }\n\n const data = ('data' in encodedAccount) ? encodedAccount.data : new Uint8Array(0);\n \n try {\n // For accounts with 2-byte discriminator, try to extract what we can\n if (data.length >= 2) {\n return {\n discriminator: data.slice(0, 2),\n // Add more extraction logic here based on known legacy formats\n // This would need to be customized based on actual legacy account structures\n };\n }\n } catch (error) {\n console.warn('Failed to extract legacy data:', error);\n }\n\n return null;\n}\n\n/**\n * Creates a detailed migration report for multiple accounts\n */\nexport async function createMigrationReport(\n accounts: { address: string; encodedAccount: EncodedAccount | MaybeEncodedAccount }[]\n): Promise<{\n summary: {\n total: number;\n valid: number;\n needsMigration: number;\n invalid: number;\n canAutoMigrate: number;\n };\n plans: MigrationPlan[];\n recommendations: string[];\n}> {\n const plans = await Promise.all(accounts.map(({ address, encodedAccount }) => \n createMigrationPlan(encodedAccount, address)\n ));\n\n const summary = {\n total: plans.length,\n valid: plans.filter(p => p.currentState === 'valid').length,\n needsMigration: plans.filter(p => p.currentState === 'needs_migration').length,\n invalid: plans.filter(p => p.currentState === 'invalid').length,\n canAutoMigrate: plans.filter(p => p.canAutoMigrate).length\n };\n\n const recommendations: string[] = [];\n\n if (summary.needsMigration > 0) {\n recommendations.push(`${summary.needsMigration} accounts need migration`);\n }\n\n if (summary.canAutoMigrate > 0) {\n recommendations.push(`${summary.canAutoMigrate} accounts can be auto-migrated`);\n }\n\n if (summary.invalid > 0) {\n recommendations.push(`${summary.invalid} accounts have invalid data and should be investigated`);\n }\n\n if (summary.needsMigration === 0 && summary.invalid === 0) {\n recommendations.push('All accounts are in the correct format');\n } else {\n recommendations.push('Consider running migration utilities to fix account format issues');\n recommendations.push('Backup important account data before migration');\n }\n\n return {\n summary,\n plans,\n recommendations\n };\n}\n\n/**\n * Simulates migration without actually performing it\n */\nexport async function simulateMigration(\n encodedAccount: EncodedAccount | MaybeEncodedAccount,\n address: string\n): Promise<{\n plan: MigrationPlan;\n simulation: {\n wouldSucceed: boolean;\n estimatedSteps: string[];\n warnings: string[];\n requiredActions: string[];\n };\n}> {\n const plan = await createMigrationPlan(encodedAccount, address);\n \n const simulation = {\n wouldSucceed: false,\n estimatedSteps: [] as string[],\n warnings: [] as string[],\n requiredActions: [] as string[]\n };\n\n if (plan.currentState === 'valid') {\n simulation.wouldSucceed = true;\n simulation.estimatedSteps.push('No migration needed - account is already valid');\n return { plan, simulation };\n }\n\n switch (plan.migrationType) {\n case 'recreate':\n simulation.estimatedSteps.push('1. Extract existing account data');\n simulation.estimatedSteps.push('2. Create new account with correct format');\n simulation.estimatedSteps.push('3. Transfer any salvageable data');\n simulation.estimatedSteps.push('4. Close old account');\n simulation.requiredActions.push('User must re-register the agent');\n simulation.warnings.push('Some data may be lost during recreation');\n simulation.wouldSucceed = plan.canAutoMigrate;\n break;\n\n case 'data_conversion':\n simulation.estimatedSteps.push('1. Analyze existing data format');\n simulation.estimatedSteps.push('2. Convert to new format');\n simulation.estimatedSteps.push('3. Update discriminator');\n simulation.warnings.push('Data conversion is experimental');\n simulation.requiredActions.push('Manual verification required');\n simulation.wouldSucceed = false;\n break;\n\n case 'unsupported':\n simulation.estimatedSteps.push('1. Manual investigation required');\n simulation.estimatedSteps.push('2. Determine if account is recoverable');\n simulation.warnings.push('Account may not be recoverable');\n simulation.requiredActions.push('Manual inspection and possible recreation');\n simulation.wouldSucceed = false;\n break;\n\n default:\n simulation.estimatedSteps.push('No migration strategy available');\n simulation.wouldSucceed = false;\n }\n\n return { plan, simulation };\n}\n\n/**\n * Provides user-friendly migration instructions\n */\nexport function getMigrationInstructions(plan: MigrationPlan): string[] {\n const instructions: string[] = [];\n\n switch (plan.migrationType) {\n case 'none':\n instructions.push('✅ No migration needed - your account is up to date');\n break;\n\n case 'recreate':\n instructions.push('🔄 Account Recreation Required:');\n instructions.push('1. Use the CLI command: `ghost agent register` to create a new account');\n instructions.push('2. Configure your agent with the same settings as before');\n instructions.push('3. The old account will be automatically replaced');\n instructions.push('⚠️ Note: You may need to re-verify your agent after recreation');\n break;\n\n case 'data_conversion':\n instructions.push('🔧 Data Conversion Required:');\n instructions.push('1. Contact support for assistance with account conversion');\n instructions.push('2. Manual intervention may be required');\n instructions.push('3. Backup your account data before proceeding');\n break;\n\n case 'unsupported':\n instructions.push('❌ Migration Not Supported:');\n instructions.push('1. This account cannot be automatically migrated');\n instructions.push('2. Consider creating a new account');\n instructions.push('3. Contact support if this account contains important data');\n break;\n }\n\n return instructions;\n}","/**\n * Account Diagnostics Utility\n * \n * Comprehensive diagnostic tools for inspecting and debugging\n * account discriminator issues and data format problems.\n */\n\nimport type { \n Address, \n EncodedAccount, \n MaybeEncodedAccount\n} from '@solana/kit';\n\nimport { \n fetchEncodedAccount\n} from '@solana/kit';\nimport { \n validateAccountDiscriminator, \n inspectAccountData, \n type AccountInspectionResult \n} from './discriminator-validator.js';\nimport { \n createMigrationPlan, \n simulateMigration,\n getMigrationInstructions \n} from './account-migration.js';\nimport { AGENT_DISCRIMINATOR } from '../generated/accounts/agent.js';\n\nexport interface DiagnosticReport {\n address: string;\n timestamp: string;\n accountExists: boolean;\n discriminatorValidation: ReturnType<typeof validateAccountDiscriminator>;\n inspection: AccountInspectionResult;\n migrationPlan: Awaited<ReturnType<typeof createMigrationPlan>>;\n migrationSimulation: Awaited<ReturnType<typeof simulateMigration>>;\n recommendations: string[];\n debugInfo: {\n expectedDiscriminator: number[];\n actualDiscriminator: number[] | null;\n dataPreview: number[];\n programId?: string;\n };\n}\n\nexport interface BatchDiagnosticReport {\n summary: {\n total: number;\n valid: number;\n invalid: number;\n needsMigration: number;\n notExists: number;\n };\n reports: DiagnosticReport[];\n globalRecommendations: string[];\n timestamp: string;\n}\n\n/**\n * Runs comprehensive diagnostics on a single account\n */\nexport async function runAccountDiagnostics(\n encodedAccount: EncodedAccount | MaybeEncodedAccount,\n address: string\n): Promise<DiagnosticReport> {\n const timestamp = new Date().toISOString();\n const accountExists = ('exists' in encodedAccount) && encodedAccount.exists;\n \n let discriminatorValidation, inspection, migrationPlan, migrationSimulation;\n \n if (accountExists) {\n // Import the discriminator\n const { AGENT_DISCRIMINATOR } = await import('../generated/accounts/agent.js');\n discriminatorValidation = validateAccountDiscriminator(encodedAccount.data, AGENT_DISCRIMINATOR);\n inspection = inspectAccountData(encodedAccount, address);\n migrationPlan = await createMigrationPlan(encodedAccount, address);\n migrationSimulation = await simulateMigration(encodedAccount, address);\n } else {\n // Default values for non-existent accounts\n discriminatorValidation = {\n isValid: false,\n actualLength: 0,\n expectedLength: 8,\n canDecode: false,\n needsMigration: false,\n errorMessage: 'Account does not exist'\n };\n inspection = {\n address,\n dataLength: 0,\n discriminator: null,\n discriminatorLength: 0,\n isAgentAccount: false,\n needsMigration: false,\n rawData: new Uint8Array(0)\n };\n migrationPlan = {\n address,\n currentState: 'not_exists' as const,\n migrationType: 'none' as const,\n issues: ['Account does not exist'],\n recommendations: ['Create account using register_agent instruction'],\n canAutoMigrate: false\n };\n migrationSimulation = {\n plan: migrationPlan,\n simulation: {\n wouldSucceed: false,\n estimatedSteps: ['Account must be created first'],\n warnings: [],\n requiredActions: ['Use register_agent instruction']\n }\n };\n }\n\n // Generate recommendations\n const recommendations: string[] = [];\n \n if (!accountExists) {\n recommendations.push('Account does not exist - create using register_agent');\n } else if (discriminatorValidation.isValid) {\n recommendations.push('Account is valid - no action needed');\n } else {\n recommendations.push(...getMigrationInstructions(migrationPlan));\n }\n\n // Create debug info\n const debugInfo = {\n expectedDiscriminator: Array.from(AGENT_DISCRIMINATOR),\n actualDiscriminator: inspection.discriminator ? Array.from(inspection.discriminator) : null,\n dataPreview: Array.from(inspection.rawData.slice(0, 32)),\n programId: (accountExists && ('owner' in encodedAccount) ? encodedAccount.owner : undefined) as string | undefined\n };\n\n return {\n address,\n timestamp,\n accountExists,\n discriminatorValidation,\n inspection,\n migrationPlan,\n migrationSimulation,\n recommendations,\n debugInfo\n };\n}\n\n/**\n * Runs diagnostics on multiple accounts\n */\nexport async function runBatchDiagnostics(\n accounts: { address: string; encodedAccount: EncodedAccount | MaybeEncodedAccount }[]\n): Promise<BatchDiagnosticReport> {\n const timestamp = new Date().toISOString();\n const reports = await Promise.all(accounts.map(({ address, encodedAccount }) => \n runAccountDiagnostics(encodedAccount, address)\n ));\n\n const summary = {\n total: reports.length,\n valid: reports.filter(r => r.accountExists && r.discriminatorValidation.isValid).length,\n invalid: reports.filter(r => r.accountExists && !r.discriminatorValidation.isValid).length,\n needsMigration: reports.filter(r => r.migrationPlan.currentState === 'needs_migration').length,\n notExists: reports.filter(r => !r.accountExists).length\n };\n\n const globalRecommendations: string[] = [];\n \n if (summary.notExists > 0) {\n globalRecommendations.push(`${summary.notExists} accounts need to be created`);\n }\n if (summary.needsMigration > 0) {\n globalRecommendations.push(`${summary.needsMigration} accounts need migration`);\n }\n if (summary.invalid > 0) {\n globalRecommendations.push(`${summary.invalid} accounts have data issues`);\n }\n if (summary.valid === summary.total) {\n globalRecommendations.push('All accounts are healthy');\n }\n\n return {\n summary,\n reports,\n globalRecommendations,\n timestamp\n };\n}\n\n/**\n * Fetches and diagnoses an account directly from the blockchain\n */\nexport async function diagnoseAccountFromChain(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n address: Address,\n options?: { logToConsole?: boolean }\n): Promise<DiagnosticReport> {\n try {\n const encodedAccount = await fetchEncodedAccount(rpc, address);\n const report = await runAccountDiagnostics(encodedAccount, address);\n \n if (options?.logToConsole) {\n console.group(`🔍 Account Diagnostics: ${address}`);\n console.log('Exists:', report.accountExists);\n console.log('Valid:', report.discriminatorValidation.isValid);\n console.log('Needs Migration:', report.migrationPlan.currentState === 'needs_migration');\n console.log('Recommendations:');\n report.recommendations.forEach(rec => console.log(` - ${rec}`));\n \n if (!report.discriminatorValidation.isValid) {\n console.log('Issues:');\n if (Array.isArray(report.migrationPlan.issues)) {\n report.migrationPlan.issues.forEach((issue: string) => console.log(` - ${issue}`));\n }\n }\n \n console.groupEnd();\n }\n \n return report;\n } catch (err) {\n console.error(`Failed to diagnose account ${address}:`, err);\n \n // Return a diagnostic report for the error case\n return {\n address,\n timestamp: new Date().toISOString(),\n accountExists: false,\n discriminatorValidation: {\n isValid: false,\n actualLength: 0,\n expectedLength: 8,\n canDecode: false,\n needsMigration: false,\n errorMessage: `Failed to fetch account: ${err instanceof Error ? err.message : String(err)}`\n },\n inspection: {\n address,\n dataLength: 0,\n discriminator: null,\n discriminatorLength: 0,\n isAgentAccount: false,\n needsMigration: false,\n rawData: new Uint8Array(0)\n },\n migrationPlan: {\n address,\n currentState: 'invalid',\n migrationType: 'unsupported',\n issues: [`Failed to fetch account: ${err instanceof Error ? err.message : String(err)}`],\n recommendations: ['Check network connection and account address'],\n canAutoMigrate: false\n },\n migrationSimulation: {\n plan: {\n address,\n currentState: 'invalid',\n migrationType: 'unsupported',\n issues: [`Failed to fetch account: ${err instanceof Error ? err.message : String(err)}`],\n recommendations: ['Check network connection and account address'],\n canAutoMigrate: false\n },\n simulation: {\n wouldSucceed: false,\n estimatedSteps: ['Fix network connectivity issues'],\n warnings: ['Account could not be fetched'],\n requiredActions: ['Verify account address and network connection']\n }\n },\n recommendations: ['Check network connection and account address'],\n debugInfo: {\n expectedDiscriminator: Array.from(AGENT_DISCRIMINATOR),\n actualDiscriminator: null,\n dataPreview: [],\n programId: undefined\n }\n };\n }\n}\n\n/**\n * Fetches and diagnoses multiple accounts from the blockchain\n */\nexport async function diagnoseBatchFromChain(\n rpc: Parameters<typeof fetchEncodedAccount>[0],\n addresses: Address[],\n options?: { \n logToConsole?: boolean;\n maxConcurrent?: number;\n }\n): Promise<BatchDiagnosticReport> {\n const maxConcurrent = options?.maxConcurrent ?? 10;\n const reports: DiagnosticReport[] = [];\n \n // Process accounts in batches to avoid overwhelming the RPC\n for (let i = 0; i < addresses.length; i += maxConcurrent) {\n const batch = addresses.slice(i, i + maxConcurrent);\n const batchPromises = batch.map(address => \n diagnoseAccountFromChain(rpc, address, { logToConsole: false })\n );\n \n const batchReports = await Promise.allSettled(batchPromises);\n \n for (const result of batchReports) {\n if (result.status === 'fulfilled') {\n reports.push(result.value);\n } else {\n console.error('Failed to diagnose account:', result.reason);\n // Add a fallback report for failed fetches\n reports.push({\n address: 'unknown',\n timestamp: new Date().toISOString(),\n accountExists: false,\n discriminatorValidation: {\n isValid: false,\n actualLength: 0,\n expectedLength: 8,\n canDecode: false,\n needsMigration: false,\n errorMessage: 'Failed to fetch account'\n },\n inspection: {\n address: 'unknown',\n dataLength: 0,\n discriminator: null,\n discriminatorLength: 0,\n isAgentAccount: false,\n needsMigration: false,\n rawData: new Uint8Array(0)\n },\n migrationPlan: {\n address: 'unknown',\n currentState: 'invalid',\n migrationType: 'unsupported',\n issues: ['Failed to fetch account'],\n recommendations: ['Check network connection'],\n canAutoMigrate: false\n },\n migrationSimulation: {\n plan: {\n address: 'unknown',\n currentState: 'invalid' as const,\n migrationType: 'unsupported' as const,\n issues: ['Failed to fetch account'],\n recommendations: ['Check network connection'],\n canAutoMigrate: false\n },\n simulation: {\n wouldSucceed: false,\n estimatedSteps: ['Fix fetch issues'],\n warnings: ['Account could not be fetched'],\n requiredActions: ['Check network']\n }\n },\n recommendations: ['Check network connection'],\n debugInfo: {\n expectedDiscriminator: Array.from(AGENT_DISCRIMINATOR),\n actualDiscriminator: null,\n dataPreview: [],\n programId: undefined\n }\n });\n }\n }\n }\n\n const batchReport = await runBatchDiagnostics(\n reports.map(report => ({\n address: report.address,\n encodedAccount: {\n exists: report.accountExists,\n data: report.inspection.rawData,\n address: report.address,\n owner: report.debugInfo.programId ?? '',\n executable: false,\n lamports: 0n,\n programAddress: report.debugInfo.programId ?? '',\n space: report.inspection.rawData.length\n } as unknown as EncodedAccount\n }))\n );\n\n if (options?.logToConsole) {\n console.group('🔍 Batch Diagnostics Summary');\n console.log('Total accounts:', batchReport.summary.total);\n console.log('Valid accounts:', batchReport.summary.valid);\n console.log('Invalid accounts:', batchReport.summary.invalid);\n console.log('Need migration:', batchReport.summary.needsMigration);\n console.log('Do not exist:', batchReport.summary.notExists);\n console.log('Global recommendations:');\n batchReport.globalRecommendations.forEach(rec => console.log(` - ${rec}`));\n console.groupEnd();\n }\n\n return batchReport;\n}\n\n/**\n * Exports a diagnostic report as JSON\n */\nexport function exportDiagnosticReport(\n report: DiagnosticReport | BatchDiagnosticReport,\n filename?: string\n): string {\n const json = JSON.stringify(report, null, 2);\n \n if (filename) {\n // In a browser environment, you might want to trigger a download\n // In Node.js, you might want to write to file\n console.log(`Diagnostic report would be saved as: ${filename}`);\n console.log('Report data:', json);\n }\n \n return json;\n}","/**\n * Governance Helper Utilities\n * \n * Comprehensive utilities for RBAC management, multi-signature wallets,\n * proposal lifecycle, and voting mechanisms.\n */\n\nimport type { Address } from '@solana/kit'\nimport { getAddressEncoder, getProgramDerivedAddress, getBytesEncoder } from '@solana/kit'\nimport {\n ProposalStatus,\n VoteChoice,\n type Multisig,\n type GovernanceProposal,\n type RbacConfig,\n type Role,\n type Permission,\n type VotingResults,\n type QuorumRequirements\n} from '../generated/index.js'\n\n// =====================================================\n// PDA DERIVATION\n// =====================================================\n\n/**\n * Derive multisig account PDA\n */\nexport async function deriveMultisigPda(\n programId: Address,\n authority: Address,\n multisigId: bigint\n): Promise<Address> {\n const [pda] = await getProgramDerivedAddress({\n programAddress: programId,\n seeds: [\n getBytesEncoder().encode(new Uint8Array([109, 117, 108, 116, 105, 115, 105, 103])), // 'multisig'\n getAddressEncoder().encode(authority),\n new Uint8Array(new BigUint64Array([multisigId]).buffer)\n ]\n })\n return pda\n}\n\n/**\n * Derive proposal account PDA\n */\nexport async function deriveProposalPda(\n programId: Address,\n multisig: Address,\n proposalId: bigint\n): Promise<Address> {\n const [pda] = await getProgramDerivedAddress({\n programAddress: programId,\n seeds: [\n getBytesEncoder().encode(new Uint8Array([112, 114, 111, 112, 111, 115, 97, 108])), // 'proposal'\n getAddressEncoder().encode(multisig),\n new Uint8Array(new BigUint64Array([proposalId]).buffer)\n ]\n })\n return pda\n}\n\n/**\n * Derive RBAC account PDA\n */\nexport async function deriveRbacPda(\n programId: Address,\n admin: Address\n): Promise<Address> {\n const [pda] = await getProgramDerivedAddress({\n programAddress: programId,\n seeds: [\n getBytesEncoder().encode(new Uint8Array([114, 98, 97, 99])), // 'rbac'\n getAddressEncoder().encode(admin)\n ]\n })\n return pda\n}\n\n// =====================================================\n// MULTISIG UTILITIES\n// =====================================================\n\nexport class MultisigUtils {\n /**\n * Calculate if a multisig action has reached threshold\n */\n static hasReachedThreshold(\n multisig: Multisig,\n approvalCount: number\n ): boolean {\n return approvalCount >= multisig.threshold\n }\n\n /**\n * Check if an address is a signer on the multisig\n */\n static isSigner(multisig: Multisig, address: Address): boolean {\n return multisig.signers.some((signer: Address) => signer === address)\n }\n\n /**\n * Calculate remaining signatures needed\n */\n static remainingSignatures(\n multisig: Multisig,\n currentApprovals: number\n ): number {\n const remaining = multisig.threshold - currentApprovals\n return Math.max(0, remaining)\n }\n\n /**\n * Validate multisig configuration\n */\n static validateConfiguration(\n signers: Address[],\n threshold: number\n ): { valid: boolean; error?: string } {\n if (signers.length === 0) {\n return { valid: false, error: 'At least one signer required' }\n }\n\n if (signers.length > 10) {\n return { valid: false, error: 'Maximum 10 signers allowed' }\n }\n\n if (threshold === 0) {\n return { valid: false, error: 'Threshold must be at least 1' }\n }\n\n if (threshold > signers.length) {\n return { valid: false, error: 'Threshold cannot exceed number of signers' }\n }\n\n // Check for duplicate signers\n const uniqueSigners = new Set(signers)\n if (uniqueSigners.size !== signers.length) {\n return { valid: false, error: 'Duplicate signers not allowed' }\n }\n\n return { valid: true }\n }\n\n /**\n * Generate multisig configuration summary\n */\n static generateSummary(multisig: Multisig): string {\n const signerCount = multisig.signers.length\n const percentage = Math.round((multisig.threshold / signerCount) * 100)\n \n return `${multisig.threshold}-of-${signerCount} multisig (${percentage}% approval required)`\n }\n}\n\n// =====================================================\n// PROPOSAL UTILITIES\n// =====================================================\n\nexport class ProposalUtils {\n /**\n * Check if proposal is in voting period\n */\n static isVotingOpen(proposal: GovernanceProposal): boolean {\n const now = BigInt(Math.floor(Date.now() / 1000))\n return proposal.status === ProposalStatus.Active &&\n now >= proposal.votingStartsAt &&\n now <= proposal.votingEndsAt\n }\n\n /**\n * Check if proposal has expired\n */\n static hasExpired(proposal: GovernanceProposal): boolean {\n const now = BigInt(Math.floor(Date.now() / 1000))\n return now > proposal.votingEndsAt\n }\n\n /**\n * Calculate time remaining for voting\n */\n static timeRemaining(proposal: GovernanceProposal): bigint {\n const now = BigInt(Math.floor(Date.now() / 1000))\n if (now >= proposal.votingEndsAt) return 0n\n return proposal.votingEndsAt - now\n }\n\n /**\n * Format time remaining as human-readable string\n */\n static formatTimeRemaining(proposal: GovernanceProposal): string {\n const remaining = this.timeRemaining(proposal)\n if (remaining === 0n) return 'Voting ended'\n\n const seconds = Number(remaining)\n const days = Math.floor(seconds / 86400)\n const hours = Math.floor((seconds % 86400) / 3600)\n const minutes = Math.floor((seconds % 3600) / 60)\n\n if (days > 0) return `${days}d ${hours}h remaining`\n if (hours > 0) return `${hours}h ${minutes}m remaining`\n return `${minutes}m remaining`\n }\n\n /**\n * Calculate if proposal has reached quorum\n */\n static hasReachedQuorum(\n votingResults: VotingResults,\n quorumRequirements: QuorumRequirements,\n totalEligibleVoters: number\n ): boolean {\n const totalVotes = Number(votingResults.votesFor + votingResults.votesAgainst + votingResults.votesAbstain)\n const participationRate = (totalVotes / totalEligibleVoters) * 100\n \n return participationRate >= quorumRequirements.minimumParticipation\n }\n\n /**\n * Calculate voting results summary\n */\n static calculateResults(votingResults: VotingResults): {\n total: number\n forPercentage: number\n againstPercentage: number\n abstainPercentage: number\n passed: boolean\n } {\n const total = Number(votingResults.votesFor + votingResults.votesAgainst + votingResults.votesAbstain)\n \n if (total === 0) {\n return {\n total: 0,\n forPercentage: 0,\n againstPercentage: 0,\n abstainPercentage: 0,\n passed: false\n }\n }\n\n const forPercentage = (Number(votingResults.votesFor) / total) * 100\n const againstPercentage = (Number(votingResults.votesAgainst) / total) * 100\n const abstainPercentage = (Number(votingResults.votesAbstain) / total) * 100\n \n // Simple majority (>50% for votes)\n const passed = votingResults.votesFor > votingResults.votesAgainst\n\n return {\n total,\n forPercentage,\n againstPercentage,\n abstainPercentage,\n passed\n }\n }\n\n /**\n * Validate proposal\n */\n static validateProposal(proposal: GovernanceProposal): { valid: boolean; error?: string } {\n if (!proposal.title || proposal.title.trim().length === 0) {\n return { valid: false, error: 'Title is required' }\n }\n\n if (proposal.title.length > 100) {\n return { valid: false, error: 'Title cannot exceed 100 characters' }\n }\n\n if (!proposal.description || proposal.description.trim().length === 0) {\n return { valid: false, error: 'Description is required' }\n }\n\n if (proposal.description.length > 5000) {\n return { valid: false, error: 'Description cannot exceed 5000 characters' }\n }\n\n return { valid: true }\n }\n}\n\n// =====================================================\n// RBAC UTILITIES\n// =====================================================\n\nexport class RbacUtils {\n /**\n * Check if a user has a specific permission\n */\n static hasPermission(\n rbac: RbacConfig,\n user: Address,\n permission: string\n ): boolean {\n const userRole = this.getUserRole(rbac, user)\n if (!userRole) return false\n\n return userRole.permissions.includes(permission)\n }\n\n /**\n * Get user's role\n */\n static getUserRole(rbac: RbacConfig, user: Address): Role | null {\n // Find user's role assignment by checking access policies\n // Since Role doesn't have members field, we check access policies instead\n // We'll use the policy metadata to store user assignments\n const userPolicy = rbac.accessPolicies.find(policy => {\n // Check if policy metadata contains user information\n // This is a simplified implementation - in real usage, you'd have\n // a more structured way to associate users with policies\n return policy.policyId.includes(user) || policy.name.includes(user)\n })\n \n if (userPolicy) {\n // Find the role associated with this policy by checking policy scope\n // In a real implementation, you'd have a more structured relationship\n const assignedRole = rbac.roles.find(role => \n role.roleId === userPolicy.policyId || \n role.name === userPolicy.name ||\n userPolicy.scope.toString().includes(role.roleId)\n )\n \n if (assignedRole) {\n return assignedRole\n }\n }\n \n // If no specific role found, return default role (if exists)\n return rbac.roles.find(role => role.name === 'default') ?? null\n }\n\n /**\n * Check if permission string is valid\n */\n static isValidPermission(permission: string): boolean {\n // In production, validate against known permission strings\n return permission.length > 0 && permission.length < 100\n }\n\n /**\n * Validate role configuration\n */\n static validateRole(role: Role): { valid: boolean; error?: string } {\n if (!role.name || role.name.trim().length === 0) {\n return { valid: false, error: 'Role name is required' }\n }\n\n if (role.name.length > 50) {\n return { valid: false, error: 'Role name cannot exceed 50 characters' }\n }\n\n if (role.permissions.length === 0) {\n return { valid: false, error: 'Role must have at least one permission' }\n }\n\n if (role.permissions.length > 20) {\n return { valid: false, error: 'Role cannot have more than 20 permissions' }\n }\n\n return { valid: true }\n }\n\n /**\n * Generate permission summary\n */\n static generatePermissionSummary(permissions: Permission[]): string {\n if (permissions.length === 0) return 'No permissions'\n if (permissions.length === 1) return '1 permission'\n return `${permissions.length} permissions`\n }\n}\n\n// =====================================================\n// VOTING UTILITIES\n// =====================================================\n\nexport class VotingUtils {\n /**\n * Calculate vote weight based on token holdings or other factors\n */\n static calculateVoteWeight(\n baseWeight: number,\n tokenBalance?: bigint,\n stakeDuration?: bigint\n ): number {\n let weight = baseWeight\n\n // Apply token-based multiplier\n if (tokenBalance) {\n const tokenMultiplier = Math.min(Number(tokenBalance / 1000000n), 10) // Cap at 10x\n weight *= tokenMultiplier\n }\n\n // Apply time-based multiplier\n if (stakeDuration) {\n const daysStaked = Number(stakeDuration / 86400n)\n const timeMultiplier = 1 + (daysStaked / 365) // +100% per year\n weight *= timeMultiplier\n }\n\n return Math.floor(weight)\n }\n\n /**\n * Format vote choice as string\n */\n static formatVoteChoice(voteChoice: VoteChoice): string {\n switch (voteChoice) {\n case VoteChoice.For:\n return '✅ For'\n case VoteChoice.Against:\n return '❌ Against'\n case VoteChoice.Abstain:\n return '🤷 Abstain'\n default:\n return 'Unknown'\n }\n }\n\n /**\n * Calculate if simple majority is reached\n */\n static hasSimpleMajority(votingResults: VotingResults): boolean {\n return votingResults.votesFor > votingResults.votesAgainst\n }\n\n /**\n * Calculate if supermajority is reached (2/3)\n */\n static hasSupermajority(votingResults: VotingResults): boolean {\n const totalVotes = votingResults.votesFor + votingResults.votesAgainst\n if (totalVotes === 0n) return false\n \n const forPercentage = Number(votingResults.votesFor) / Number(totalVotes)\n return forPercentage >= 0.667\n }\n}\n\n// =====================================================\n// PERMISSION TEMPLATES\n// =====================================================\n\nexport const PERMISSION_TEMPLATES = {\n // Admin permissions\n ADMIN: {\n CREATE_PROPOSAL: { action: 'create', resource: 'proposal' },\n EXECUTE_PROPOSAL: { action: 'execute', resource: 'proposal' },\n MANAGE_ROLES: { action: 'manage', resource: 'roles' },\n MANAGE_TREASURY: { action: 'manage', resource: 'treasury' }\n },\n \n // Member permissions\n MEMBER: {\n VOTE: { action: 'vote', resource: 'proposal' },\n VIEW: { action: 'view', resource: 'all' },\n COMMENT: { action: 'comment', resource: 'proposal' }\n },\n \n // Moderator permissions\n MODERATOR: {\n CANCEL_PROPOSAL: { action: 'cancel', resource: 'proposal' },\n MODERATE_COMMENTS: { action: 'moderate', resource: 'comments' },\n VIEW_REPORTS: { action: 'view', resource: 'reports' }\n }\n}\n\n// =====================================================\n// ROLE TEMPLATES\n// =====================================================\n\nexport const ROLE_TEMPLATES = {\n ADMIN: {\n name: 'Administrator',\n description: 'Full administrative access',\n permissions: Object.values(PERMISSION_TEMPLATES.ADMIN)\n },\n \n MEMBER: {\n name: 'Member',\n description: 'Standard member access',\n permissions: Object.values(PERMISSION_TEMPLATES.MEMBER)\n },\n \n MODERATOR: {\n name: 'Moderator',\n description: 'Content moderation access',\n permissions: [\n ...Object.values(PERMISSION_TEMPLATES.MEMBER),\n ...Object.values(PERMISSION_TEMPLATES.MODERATOR)\n ]\n }\n}\n\n// =====================================================\n// GOVERNANCE ANALYTICS\n// =====================================================\n\nexport interface GovernanceAnalytics {\n totalProposals: number\n activeProposals: number\n passedProposals: number\n failedProposals: number\n averageVoterTurnout: number\n topVoters: { address: Address; voteCount: number }[]\n proposalCategories: { category: string; count: number }[]\n}\n\nexport class GovernanceAnalyticsUtils {\n /**\n * Calculate governance health score (0-100)\n */\n static calculateHealthScore(analytics: GovernanceAnalytics): number {\n let score = 0\n\n // Voter turnout (40 points max)\n score += Math.min(analytics.averageVoterTurnout * 0.4, 40)\n\n // Proposal success rate (30 points max)\n const totalCompleted = analytics.passedProposals + analytics.failedProposals\n if (totalCompleted > 0) {\n const successRate = analytics.passedProposals / totalCompleted\n score += successRate * 30\n }\n\n // Activity level (30 points max)\n const activityRatio = analytics.activeProposals / Math.max(analytics.totalProposals, 1)\n score += Math.min(activityRatio * 60, 30)\n\n return Math.round(score)\n }\n\n /**\n * Generate governance summary report\n */\n static generateSummaryReport(analytics: GovernanceAnalytics): string {\n const healthScore = this.calculateHealthScore(analytics)\n const successRate = analytics.totalProposals > 0\n ? Math.round((analytics.passedProposals / analytics.totalProposals) * 100)\n : 0\n\n return `\nGovernance Summary:\n- Total Proposals: ${analytics.totalProposals}\n- Active: ${analytics.activeProposals}\n- Success Rate: ${successRate}%\n- Avg Turnout: ${Math.round(analytics.averageVoterTurnout)}%\n- Health Score: ${healthScore}/100\n `.trim()\n }\n}"]}
@@ -1,3 +0,0 @@
1
- import {a,b as b$1,c}from'./chunk-DOTF5ECA.js';import {m,n,l,V,D}from'./chunk-32GWTXRJ.js';import {md,Pb,xk,Oa,za,Ui,wi,Kd,Ei,oi,gm,pj}from'./chunk-QTKN3VZV.js';import {address}from'@solana/addresses';import {sendAndConfirmTransactionFactory,pipe,createTransactionMessage,setTransactionMessageFeePayerSigner,setTransactionMessageLifetimeUsingBlockhash,appendTransactionMessageInstructions,signTransactionMessageWithSigners,getBase64EncodedWireTransaction,setTransactionMessageFeePayer,compileTransactionMessage,createSolanaRpc,createSolanaRpcSubscriptions}from'@solana/kit';var P=class{rpc;rpcSubscriptions;commitment;endpoint;constructor(e){this.endpoint=e.endpoint,this.rpc=createSolanaRpc(e.endpoint),this.commitment=e.commitment??"confirmed",e.wsEndpoint&&(this.rpcSubscriptions=createSolanaRpcSubscriptions(e.wsEndpoint));}async getAccountInfo(e,n){try{let t=await this.rpc.getAccountInfo(e,{commitment:n?.commitment??this.commitment,encoding:"base64"}).send();if(!t.value)return null;let o=t.value.data,r=Array.isArray(o)?o[0]:o;return {executable:t.value.executable,lamports:t.value.lamports,owner:t.value.owner,rentEpoch:t.value.rentEpoch,data:Buffer.from(r,"base64"),space:t.value.space}}catch(t){return console.warn(`Failed to get account info for ${e}:`,t),null}}async getMultipleAccounts(e,n){try{return (await this.rpc.getMultipleAccounts(e,{commitment:n?.commitment??this.commitment,encoding:"base64"}).send()).value.map(o=>o?this.parseAccountInfo(o):null)}catch(t){return console.warn("Failed to get multiple accounts:",t),e.map(()=>null)}}async getLatestBlockhash(){return (await this.rpc.getLatestBlockhash({commitment:this.commitment}).send()).value}async sendTransaction(e,n){try{console.log("\u{1F50D} Debug - Sending transaction to RPC:"),console.log(` Transaction length: ${e.length}`),console.log(` First 50 chars: ${e.substring(0,50)}...`),console.log(` Options: ${JSON.stringify(n)}`);let t={jsonrpc:"2.0",id:Math.floor(Math.random()*1e5),method:"sendTransaction",params:[e,{skipPreflight:n?.skipPreflight??!1,preflightCommitment:n?.preflightCommitment??this.commitment,encoding:"base64"}]};console.log("\u{1F50D} Debug - RPC request:"),console.log(` Method: ${t.method}`),console.log(` Transaction (first 50): ${e.substring(0,50)}...`),console.log(` Params count: ${t.params.length}`);let r=await(await globalThis.fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(r.error)throw console.error("\u{1F534} RPC error response:",r.error),new Error(`RPC Error: ${r.error.message}`);return r.result}catch(t){throw console.error("\u{1F534} RPC sendTransaction error:",t),t}}async getSignatureStatuses(e){return (await this.rpc.getSignatureStatuses(e).send()).value}async simulateTransaction(e,n){return this.rpc.simulateTransaction(e,{commitment:n?.commitment??this.commitment,replaceRecentBlockhash:n?.replaceRecentBlockhash??false,sigVerify:false,encoding:"base64"}).send()}async getFeeForMessage(e){let n=await this.rpc.getFeeForMessage(e).send();return Number(n.value??5e3)}async getProgramAccounts(e,n){try{console.log(`Getting program accounts for program: ${e}`),console.log(`Options: ${JSON.stringify(n)}`);let t={commitment:n?.commitment??this.commitment,encoding:"base64",...n?.filters&&{filters:n.filters}},o=e.toString();if(!o||o.includes("/")||o.length<32)throw new Error(`Invalid program ID format: ${o}. Expected base58 Solana address.`);let r={jsonrpc:"2.0",id:Math.floor(Math.random()*1e5),method:"getProgramAccounts",params:[o,t]},s=await globalThis.fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);let a=await s.json();if(a.error)throw new Error(`RPC Error: ${a.error.message}`);let c=a.result??[];return console.log(`Found ${c.length} program accounts`),c.map(i=>({pubkey:i.pubkey,account:this.parseAccountInfo(i.account)}))}catch(t){throw console.error("Failed to get program accounts:",t),new Error(`Failed to get program accounts: ${t instanceof Error?t.message:"Unknown error"}`)}}parseAccountInfo(e){let n=e,t=n.data,o=Array.isArray(t)?t[0]:t;return {executable:n.executable,lamports:BigInt(n.lamports),owner:n.owner,rentEpoch:n.rentEpoch,data:Buffer.from(o,"base64"),space:n.space}}};var b=class{config;_sendAndConfirmTransaction=null;_rpcClient=null;constructor(e){this.config=e;}get rpc(){return this.config.rpc}getRpcClient(){return this._rpcClient??=new P({endpoint:this.config.rpcEndpoint??"https://api.devnet.solana.com",wsEndpoint:(this.config.rpcSubscriptions,void 0),commitment:this.config.commitment??"confirmed"}),this._rpcClient}get rpcSubscriptions(){return this.config.rpcSubscriptions}get programId(){return this.config.programId}get commitment(){return this.config.commitment??"confirmed"}getSendAndConfirmTransaction(){if(!this._sendAndConfirmTransaction)if(this.rpcSubscriptions){let e={rpc:this.rpc,rpcSubscriptions:this.rpcSubscriptions};try{this._sendAndConfirmTransaction=sendAndConfirmTransactionFactory(e);}catch{this._sendAndConfirmTransaction=sendAndConfirmTransactionFactory({rpc:this.rpc,rpcSubscriptions:this.rpcSubscriptions});}}else this._sendAndConfirmTransaction=sendAndConfirmTransactionFactory({rpc:this.rpc,rpcSubscriptions:null});return this._sendAndConfirmTransaction}estimateTransactionSize(e){let n=64;for(let t of e)n+=32,n+=(t.accounts?.length??0)*32,n+=t.data?.length??0;return n}async sendTransaction(e,n){let t=this.estimateTransactionSize(e);return t>1232&&console.warn(`\u26A0\uFE0F Transaction size (${t} bytes) may exceed Solana limit (1232 bytes)`),this.sendTransactionWithDetails(e,n).then(o=>o.signature)}async sendTransactionWithDetails(e,n){try{for(let d=0;d<e.length;d++){let u=e[d];if(!u.programAddress)throw new Error(`Instruction at index ${d} has no programAddress`);if(!u.accounts)throw new Error(`Instruction at index ${d} has no accounts array`);if(!Array.isArray(u.accounts))throw new Error(`Instruction at index ${d} accounts is not an array`)}let t=this.getRpcClient(),o=await t.getLatestBlockhash(),r=pipe(createTransactionMessage({version:0}),d=>setTransactionMessageFeePayerSigner(n[0],d),d=>setTransactionMessageLifetimeUsingBlockhash(o,d),d=>appendTransactionMessageInstructions(e,d)),s=await signTransactionMessageWithSigners(r);console.log("\u{1F4DD} Debug - Instruction data:"),e.forEach((d,u)=>{if(console.log(` Instruction ${u}: data length = ${d.data?.length??0} bytes`),d.data){let w=Buffer.from(d.data).toString("hex").substring(0,100);console.log(` Data (hex): ${w}...`);}});let a$1,c$1;if(this.rpcSubscriptions)if(a$1=await this.getSendAndConfirmTransaction()(s,{commitment:this.commitment,skipPreflight:!1}),a$1&&typeof a$1=="object"&&"signature"in a$1)c$1=a$1.signature;else {let u=Object.values(s.signatures);if(u.length>0&&typeof u[0]=="string")c$1=u[0];else throw new Error("Unable to extract transaction signature")}else {let d=getBase64EncodedWireTransaction(s);console.log("\u{1F50D} Debug - Wire transaction:"),console.log(` Base64 length: ${d.length}`),console.log(` First 100 chars: ${d.substring(0,100)}`);let u=await t.sendTransaction(d,{skipPreflight:!1,preflightCommitment:this.commitment}),w=!1,A=0,y=30,k=1e3;for(;!w&&A<y;)try{let f=await t.getSignatureStatuses([u]);if(f[0]){let p=f[0].confirmationStatus,T=f[0].err;if(T)throw new Error(`Transaction failed: ${JSON.stringify(T)}`);if(p===this.commitment||this.commitment==="confirmed"&&p==="finalized"){w=!0,console.log("\u2705 Transaction confirmed!");break}}A++,console.log(`\u23F3 Waiting for confirmation... (${A}/${y})`),await new Promise(p=>setTimeout(p,k)),k=Math.min(k*1.5,5e3);}catch(f){let p=f instanceof Error?f.message:String(f);if(p.includes("Transaction failed"))throw f;A++,console.warn(`\u26A0\uFE0F Status check failed (${A}/${y}): ${p}`),await new Promise(T=>setTimeout(T,k*2));}if(!w)throw new Error(`Transaction confirmation timeout after ${y} attempts. Signature: ${u}`);c$1=u;}let i=this.config.cluster??(this.config.rpcEndpoint?a(this.config.rpcEndpoint):"devnet"),l=b$1(c$1,i,this.commitment);return c(l),l}catch(t){throw console.error("\u274C Transaction failed:",t),new Error(`Transaction failed: ${t instanceof Error?t.message:"Unknown error"}`)}}async estimateTransactionCost(e,n){try{console.log(`\u{1F4B0} Estimating REAL cost for ${e.length} instructions`);let t=this.getRpcClient(),o=await t.getLatestBlockhash(),r=pipe(createTransactionMessage({version:0}),i=>setTransactionMessageFeePayer(n??this.config.defaultFeePayer,i),i=>setTransactionMessageLifetimeUsingBlockhash(o,i),i=>appendTransactionMessageInstructions(e,i)),s=compileTransactionMessage(r),a=Buffer.from(s).toString("base64"),c=await t.getFeeForMessage(a);return console.log(`\u{1F4B3} Real estimated fee: ${c} lamports`),BigInt(c)}catch(t){return console.warn("\u26A0\uFE0F Real fee estimation failed, using fallback:",t),5000n+BigInt(e.length)*1000n}}async simulateTransaction(e,n){try{console.log(`\u{1F9EA} Running REAL simulation with ${e.length} instructions`);let t=this.getRpcClient(),o=await t.getLatestBlockhash(),r=pipe(createTransactionMessage({version:0}),i=>setTransactionMessageFeePayerSigner(n[0],i),i=>setTransactionMessageLifetimeUsingBlockhash(o,i),i=>appendTransactionMessageInstructions(e,i)),s=await signTransactionMessageWithSigners(r),a=getBase64EncodedWireTransaction(s),c=await t.simulateTransaction(a,{commitment:this.commitment,replaceRecentBlockhash:!0});return console.log("\u2705 Real simulation completed:"),console.log(` Success: ${!c.value.err}`),console.log(` Compute units: ${c.value.unitsConsumed??"N/A"}`),console.log(` Logs: ${c.value.logs?.length??0} entries`),c}catch(t){throw console.error("\u274C Real simulation failed:",t),new Error(`Simulation failed: ${t instanceof Error?t.message:"Unknown error"}`)}}async sendTransactionBatch(e,n){console.log(`\u{1F504} Sending REAL batch of ${e.length} transactions`);let t=[];for(let o=0;o<e.length;o++){console.log(`\u{1F4E4} Processing REAL transaction ${o+1}/${e.length}`);try{let r=await this.sendTransaction(e[o],n);t.push(r),console.log(`\u2705 Batch transaction ${o+1} confirmed: ${r}`);}catch(r){throw console.error(`\u274C Batch transaction ${o+1} failed:`,r),new Error(`Batch transaction ${o+1} failed: ${r instanceof Error?r.message:"Unknown error"}`)}}return console.log(`\u{1F389} REAL batch complete: ${t.length} transactions confirmed`),t}async buildTransactionMessage(e,n){console.log("\u{1F3D7}\uFE0F Building transaction message without sending...");let o=await this.getRpcClient().getLatestBlockhash(),r=pipe(createTransactionMessage({version:0}),s=>setTransactionMessageFeePayer(n,s),s=>setTransactionMessageLifetimeUsingBlockhash(o,s),s=>appendTransactionMessageInstructions(e,s));return console.log("\u2705 Transaction message built (not sent)"),r}logInstructionDetails(e){console.log("\u{1F4CB} Instruction Details:"),console.log(` Program: ${e.programAddress}`),console.log(` Accounts: ${e.accounts?.length??0}`),console.log(` Data size: ${e.data?.length??0} bytes`),e.accounts&&e.accounts.forEach((n,t)=>{console.log(` Account ${t}: ${JSON.stringify(n)}`);});}async getDecodedAccount(e,n,t=this.commitment){try{let r=(await import('./generated-U3L4KUE4.js'))[n];if(!r||typeof r!="function")return console.warn(`Decoder ${n} not found in generated decoders`),null;let a=await this.getRpcClient().getAccountInfo(e,{commitment:t});if(!a)return null;let c=r(),i=Buffer.isBuffer(a.data)||a.data instanceof Uint8Array?a.data:Buffer.from(a.data.data??a.data,"base64");return c.decode(i)}catch(o){if(o instanceof Error&&o.message.includes("expected 8 bytes, got"))throw o;return console.warn(`Failed to fetch account ${e}:`,o),null}}async getDecodedAccounts(e,n,t=this.commitment){try{let r=(await import('./generated-U3L4KUE4.js'))[n];if(!r||typeof r!="function")return console.warn(`Decoder ${n} not found in generated decoders`),e.map(()=>null);let a=await this.getRpcClient().getMultipleAccounts(e,{commitment:t}),c=r();return a.map(i=>{if(!i)return null;try{let l=Buffer.isBuffer(i.data)||i.data instanceof Uint8Array?i.data:Buffer.from(i.data.data??i.data,"base64");return c.decode(l)}catch{return null}})}catch(o){return console.warn("Failed to fetch multiple accounts:",o),e.map(()=>null)}}async getDecodedProgramAccounts(e,n=[],t=this.commitment){try{console.log(`Getting program accounts with decoder: ${e}`),console.log(`Filters: ${JSON.stringify(n)}`),console.log(`Commitment: ${t}`);let r=await this.getRpcClient().getProgramAccounts(this.config.programId,{commitment:t,filters:n});console.log(`Found ${Array.isArray(r)?r.length:0} program accounts`);try{let a=(await import('./generated-U3L4KUE4.js'))[e];if(!a||typeof a!="function")return console.warn(`Decoder ${e} not found in generated decoders`),[];let c=a(),i=[];for(let{pubkey:l,account:d}of r)try{let u=Buffer.isBuffer(d.data)||d.data instanceof Uint8Array?d.data:Buffer.from(d.data.data??d.data,"base64"),w=c.decode(u);i.push({address:l,data:w});}catch(u){console.warn(`Failed to decode account ${l}:`,u);}return console.log(`Successfully decoded ${i.length}/${r.length} program accounts`),i}catch(s){return console.warn(`Failed to load decoder ${e}:`,s),[]}}catch(o){throw console.error("Failed to get program accounts:",o),new Error(`Failed to get program accounts: ${o instanceof Error?o.message:"Unknown error"}`)}}async executeInstruction(e,n,t){try{let o=e();return await this.sendTransaction([o],[n])}catch(o){throw console.error(`\u274C Failed to execute ${t??"instruction execution"}:`,o),o}}async executeInstructionWithDetails(e,n,t){try{let o=e();return await this.sendTransactionWithDetails([o],[n])}catch(o){throw console.error(`\u274C Failed to execute ${t??"instruction execution"}:`,o),o}}async getRawAccount(e,n=this.commitment){try{let o=await this.getRpcClient().getAccountInfo(e,{commitment:n});if(!o)return null;let r=Buffer.isBuffer(o.data)||o.data instanceof Uint8Array?o.data:Buffer.from(o.data.data??o.data,"base64");return {exists:!0,address:e,data:new Uint8Array(r),owner:o.owner,executable:o.executable,lamports:BigInt(o.lamports),programAddress:o.owner,space:r.length}}catch(t){return console.warn(`Failed to fetch raw account ${e}:`,t),null}}async getAllProgramAccounts(e=this.commitment){try{return (await this.getRpcClient().getProgramAccounts(this.config.programId,{commitment:e})).map(({pubkey:o,account:r})=>({exists:!0,address:o,data:Buffer.isBuffer(r.data)||r.data instanceof Uint8Array?new Uint8Array(r.data):new Uint8Array(Buffer.from(r.data.data??r.data,"base64")),owner:r.owner,executable:r.executable,lamports:BigInt(r.lamports),programAddress:r.owner,space:Buffer.isBuffer(r.data)||r.data instanceof Uint8Array?r.data.length:Buffer.from(r.data.data??r.data,"base64").length}))}catch(n){return console.error("Failed to get all program accounts:",n),[]}}};var Q=class extends b{constructor(e){super(e);}async _resolveCreateParams(e){let n="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";return {title:e.title,description:e.description,amount:e.amount,orderId:e.orderId??BigInt(Date.now()),provider:e.provider,requirements:e.requirements??[],paymentToken:e.paymentToken??n,deadline:e.deadline,signer:e.signer,tokenMint:e.tokenMint??n,createdAt:e.createdAt??BigInt(Math.floor(Date.now()/1e3))}}async _resolvePaymentParams(e){let t=e.tokenMint??"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",o=await m(t),r=await n(t);console.log("\u{1F50D} Token Analysis:"),console.log(` Token mint: ${t}`),console.log(` Token program: ${o}`),console.log(` Is Token 2022: ${r}`);let s,a;return e.payerTokenAccount?s=e.payerTokenAccount:(s=(await l(e.signer.address,t,o)).address,console.log(` Derived payer ATA: ${s}`)),e.providerTokenAccount?a=e.providerTokenAccount:(a=(await l(e.providerAgent,t,o)).address,console.log(` Derived provider ATA: ${a}`)),console.log("\u{1F4B0} Payment Resolution:"),console.log(` Payer token account: ${s}`),console.log(` Provider token account: ${a}`),console.log(` Using confidential transfers: ${e.useConfidentialTransfer??false}`),{workOrderAddress:e.workOrderAddress,providerAgent:e.providerAgent,payerTokenAccount:s,providerTokenAccount:a,tokenMint:t,amount:e.amount,useConfidentialTransfer:e.useConfidentialTransfer??false,expectTransferFees:e.expectTransferFees??r,maxFeeSlippageBasisPoints:e.maxFeeSlippageBasisPoints??500,confidentialProof:e.confidentialProof??null,signer:e.signer}}async _resolveDeliveryParams(e){return {workOrderAddress:e.workOrderAddress,deliverables:e.deliverables??[],ipfsHash:e.ipfsHash??"",metadataUri:e.metadataUri??`https://ghostspeak.io/delivery/${Date.now()}`,signer:e.signer}}async createWorkOrder(e,n){let{deriveWorkOrderPda:t}=await import('./pda-2GUWRQ5G.js'),o=await t(this.config.programId,e.address,n.orderId),r="Work Order",s="Work order task",a=[];if(n.metadataUri.startsWith("data:application/json;base64,"))try{let i=n.metadataUri.split(",")[1],l=Buffer.from(i,"base64").toString(),d=JSON.parse(l);r=d.title??r,s=d.description??s,d.deliverables&&a.push(...d.deliverables);}catch(i){console.warn("Failed to parse metadata URI:",i);}let c=md({workOrder:o,client:e,orderId:n.orderId,provider:n.provider,title:r,description:s,requirements:a,paymentAmount:n.amount,paymentToken:address("So11111111111111111111111111111111111111112"),deadline:BigInt(n.deadline)});return await this.sendTransactionWithDetails([c],[e]),console.log(`\u2705 Work order created: ${o}`),o.toString()}async create(e){let n=await this._resolveCreateParams(e),{deriveWorkOrderPda:t}=await import('./pda-2GUWRQ5G.js'),o=await t(this.config.programId,n.signer.address,n.orderId),r=md({workOrder:o,client:n.signer,orderId:n.orderId,provider:n.provider,title:n.title,description:n.description,requirements:n.requirements,paymentAmount:n.amount,paymentToken:n.paymentToken,deadline:n.deadline}),s=await this.sendTransactionWithDetails([r],[n.signer]);return console.log(`\u2705 Escrow created with signature: ${s.signature}`),console.log(` Work order address: ${o.toString()}`),o.toString()}async createEscrow(e){console.log("\u{1F512} Creating real escrow with token custody:",e.taskId);let{findProgramDerivedAddress:n$1}=await import('./pda-2GUWRQ5G.js'),[t]=await n$1(["escrow",e.taskId],this.programId),[o]=await n$1(["reentrancy_guard"],this.programId),r=await m(e.paymentToken),s=await n(e.paymentToken);console.log("\u{1F4B0} Escrow Creation Setup:"),console.log(` Escrow address: ${t}`),console.log(` Client: ${e.signer.address}`),console.log(` Agent: ${e.agent}`),console.log(` Amount: ${e.amount}`),console.log(` Token: ${e.paymentToken}`),console.log(` Token program: ${r}`),console.log(` Is Token 2022: ${s}`);let a=await l(e.signer.address,e.paymentToken,r),c=await l(t,e.paymentToken,r);console.log(` Client token account: ${a.address}`),console.log(` Escrow token account: ${c.address}`);let i=Pb({escrow:t,reentrancyGuard:o,client:e.signer,agent:e.agent,clientTokenAccount:a.address,escrowTokenAccount:c.address,paymentToken:e.paymentToken,tokenProgram:r,taskId:e.taskId,amount:e.amount,expiresAt:e.expiresAt,transferHook:e.transferHook??null,isConfidential:e.isConfidential??false}),l$1=await this.sendTransactionWithDetails([i],[e.signer]);return console.log(`\u2705 Real escrow created with signature: ${l$1.signature}`),console.log(` Escrow address: ${t}`),console.log(` Tokens locked: ${e.amount}`),t.toString()}async release(e,n){let t=await this._resolveDeliveryParams(n),o=xk({workDelivery:e,workOrder:t.workOrderAddress,provider:t.signer,deliverables:t.deliverables,ipfsHash:t.ipfsHash,metadataUri:t.metadataUri});return (await this.sendTransactionWithDetails([o],[t.signer])).signature}async completeEscrow(e){console.log("\u2714\uFE0F Completing escrow:",e.escrowAddress);let n=await this.getEscrowAccount(e.escrowAddress);if(!n)throw new Error(`Escrow account not found: ${e.escrowAddress}`);if(e.signer.address!==n.agent)throw new Error(`Only the agent can complete the escrow. Expected: ${n.agent}, got: ${e.signer.address}`);let{findProgramDerivedAddress:t}=await import('./pda-2GUWRQ5G.js'),[o]=await t(["reentrancy_guard"],this.programId),[r]=await t(["agent",n.agent],this.programId),s=await m(n.paymentToken),a=await l(e.escrowAddress,n.paymentToken,s),c=await l(n.agent,n.paymentToken,s);console.log("\u{1F4CB} Escrow Completion Setup:"),console.log(` Escrow status: ${n.status}`),console.log(` Agent: ${n.agent}`),console.log(` Escrow token account: ${a.address}`),console.log(` Agent token account: ${c.address}`);let i=Oa({escrow:e.escrowAddress,reentrancyGuard:o,agent:r,escrowTokenAccount:a.address,agentTokenAccount:c.address,authority:e.signer,tokenProgram:s,resolutionNotes:e.resolutionNotes??null}),l$1=await this.sendTransactionWithDetails([i],[e.signer]);return console.log(`\u2705 Escrow marked as completed: ${l$1.signature}`),console.log(" Ready for payment processing"),l$1.signature}async cancel(e){console.log("\u{1F6AB} Cancelling escrow:",e.escrowAddress);let n$1=await this.getEscrowAccount(e.escrowAddress);if(!n$1)throw new Error(`Escrow account not found: ${e.escrowAddress}`);let{findProgramDerivedAddress:t}=await import('./pda-2GUWRQ5G.js'),[o]=await t(["reentrancy_guard"],this.programId),r=await m(e.paymentToken),s=await n(e.paymentToken);console.log(` Token program: ${r}, Is Token 2022: ${s}`);let a=await l(e.escrowAddress,e.paymentToken,r),c=await l(n$1.client,e.paymentToken,r);console.log("\u{1F4B0} Token Account Setup:"),console.log(` Escrow token account: ${a.address}`),console.log(` Client refund account: ${c.address}`);let i=za({escrow:e.escrowAddress,reentrancyGuard:o,escrowTokenAccount:a.address,clientRefundAccount:c.address,paymentToken:e.paymentToken,authority:e.signer,tokenProgram:r,cancellationReason:e.cancellationReason}),l$1=await this.sendTransactionWithDetails([i],[e.signer]);return console.log(`\u2705 Escrow cancelled successfully: ${l$1.signature}`),l$1.signature}async refundExpired(e){console.log("\u23F0 Refunding expired escrow:",e.escrowAddress);let n=await this.getEscrowAccount(e.escrowAddress);if(!n)throw new Error(`Escrow account not found: ${e.escrowAddress}`);let{findProgramDerivedAddress:t}=await import('./pda-2GUWRQ5G.js'),[o]=await t(["reentrancy_guard"],this.programId),r=await m(e.paymentToken),s=await l(e.escrowAddress,e.paymentToken,r),a=await l(n.client,e.paymentToken,r);console.log("\u{1F4B0} Expired Refund Setup:"),console.log(` Escrow token account: ${s.address}`),console.log(` Client refund account: ${a.address}`);let c=Ui({escrow:e.escrowAddress,reentrancyGuard:o,escrowTokenAccount:s.address,clientRefundAccount:a.address,paymentToken:e.paymentToken,caller:e.signer,tokenProgram:r}),i=await this.sendTransactionWithDetails([c],[e.signer]);return console.log(`\u2705 Expired escrow refund processed: ${i.signature}`),i.signature}async processPartialRefund(e){if(console.log("\u2696\uFE0F Processing partial refund for escrow:",e.escrowAddress),console.log(` Client refund percentage: ${e.clientRefundPercentage}%`),e.clientRefundPercentage<0||e.clientRefundPercentage>100)throw new Error("Client refund percentage must be between 0 and 100");let n=await this.getEscrowAccount(e.escrowAddress);if(!n)throw new Error(`Escrow account not found: ${e.escrowAddress}`);let{findProgramDerivedAddress:t}=await import('./pda-2GUWRQ5G.js'),[o]=await t(["reentrancy_guard"],this.programId),r=await m(e.paymentToken),s=await l(e.escrowAddress,e.paymentToken,r),a=await l(n.client,e.paymentToken,r),c=await l(n.agent,e.paymentToken,r);console.log("\u{1F4B0} Partial Refund Setup:"),console.log(` Escrow token account: ${s.address}`),console.log(` Client refund account: ${a.address}`),console.log(` Agent payment account: ${c.address}`);let i=wi({escrow:e.escrowAddress,reentrancyGuard:o,escrowTokenAccount:s.address,clientRefundAccount:a.address,agentPaymentAccount:c.address,paymentToken:e.paymentToken,authority:e.signer,tokenProgram:r,clientRefundPercentage:e.clientRefundPercentage}),l$1=await this.sendTransactionWithDetails([i],[e.signer]);return console.log(`\u2705 Partial refund processed successfully: ${l$1.signature}`),l$1.signature}async dispute(e){return console.warn("\u26A0\uFE0F Using deprecated dispute method. Please use disputeEscrow() instead."),this.disputeEscrow({...e,disputeReason:e.reason})}async disputeEscrow(e){console.log("\u2696\uFE0F Disputing escrow:",e.escrowAddress);let n=await this.getEscrowAccount(e.escrowAddress);if(!n)throw new Error(`Escrow account not found: ${e.escrowAddress}`);if(e.signer.address!==n.client&&e.signer.address!==n.agent)throw new Error("Only the client or agent can dispute the escrow");let{findProgramDerivedAddress:t}=await import('./pda-2GUWRQ5G.js'),[o]=await t(["reentrancy_guard"],this.programId);console.log("\u{1F4CB} Dispute Setup:"),console.log(` Escrow status: ${n.status}`),console.log(` Disputant: ${e.signer.address}`),console.log(` Reason: ${e.disputeReason}`);let r=Kd({escrow:e.escrowAddress,reentrancyGuard:o,authority:e.signer,disputeReason:e.disputeReason}),s=await this.sendTransactionWithDetails([r],[e.signer]);return console.log(`\u2705 Escrow disputed successfully: ${s.signature}`),console.log(" Escrow is now frozen pending resolution"),s.signature}async calculatePaymentFees(e,n$1){try{if(!await n(n$1))return null;let o=V({transferFeeBasisPoints:250,maximumFee:1000000n,transferFeeConfigAuthority:null,withdrawWithheldAuthority:null});console.log("\u{1F4B0} Calculating Token 2022 transfer fees:");let r=D(e,o);return console.log(` Transfer amount: ${e}`),console.log(` Fee amount: ${r.feeAmount}`),console.log(` Net amount: ${r.netAmount}`),console.log(` Fee rate: ${r.feeBasisPoints/100}%`),console.log(` Fee capped: ${r.wasFeeCapped}`),r}catch(t){return console.error("Failed to calculate payment fees:",t),null}}async processPaymentWithFees(e,n){let t=await this._resolvePaymentParams(n),o=await this.calculatePaymentFees(t.amount,t.tokenMint),r=t.amount;o&&t.expectTransferFees&&(r=o.transferAmount,console.log("\u{1F4CA} Payment amount adjusted for fees:"),console.log(` Requested net amount: ${t.amount}`),console.log(` Total amount with fees: ${r}`),console.log(` Transfer fees: ${o.feeAmount}`)),t.useConfidentialTransfer&&!t.confidentialProof&&(console.log("\u{1F510} Generating confidential transfer proof..."),console.warn("Confidential transfer proof generation requires ElGamal keypairs"));let s=Ei({payment:e,workOrder:t.workOrderAddress,providerAgent:t.providerAgent,payer:t.signer,payerTokenAccount:t.payerTokenAccount,providerTokenAccount:t.providerTokenAccount,tokenMint:t.tokenMint,amount:r,useConfidentialTransfer:t.useConfidentialTransfer});return {signature:(await this.sendTransactionWithDetails([s],[t.signer])).signature,feeCalculation:o??void 0}}async createEscrowTokenAccounts(e,n$1){console.log("\u{1F3E6} Creating escrow token accounts...");let t=await m(e),o=await n(e);console.log(` Token mint: ${e}`),console.log(` Token program: ${t}`),console.log(` Is Token 2022: ${o}`);let r=[];for(let s of n$1){let a=await l(s,e,t);r.push(a),console.log(` Created ATA for ${s}: ${a.address}`);}return r}async processEscrowPayment(e){console.log("\u{1F4B8} Processing escrow payment release:",e.escrowAddress);let n=await this.getEscrowAccount(e.escrowAddress);if(!n)throw new Error(`Escrow account not found: ${e.escrowAddress}`);let{EscrowStatus:t}=await import('./generated-U3L4KUE4.js');if(n.status!==t.Completed)throw new Error(`Escrow must be completed before payment. Current status: ${n.status}`);let{findProgramDerivedAddress:o}=await import('./pda-2GUWRQ5G.js'),[r]=await o(["payment",e.escrowAddress],this.programId),[s]=await o(["reentrancy_guard"],this.programId),a=await m(e.paymentToken),c=await l(e.escrowAddress,e.paymentToken,a),i=await l(n.agent,e.paymentToken,a);console.log("\u{1F4B0} Payment Processing Setup:"),console.log(` Payment address: ${r}`),console.log(` Escrow amount: ${n.amount}`),console.log(` Recipient (agent): ${n.agent}`),console.log(` Escrow token account: ${c.address}`),console.log(` Recipient token account: ${i.address}`);let l$1=oi({payment:r,escrow:e.escrowAddress,reentrancyGuard:s,escrowTokenAccount:c.address,recipientTokenAccount:i.address,recipient:n.agent,paymentToken:e.paymentToken,authority:e.signer,tokenProgram:a,workOrder:e.workOrder}),d=await this.sendTransactionWithDetails([l$1],[e.signer]);return console.log(`\u2705 Escrow payment processed: ${d.signature}`),console.log(` Tokens transferred to agent: ${n.amount}`),console.log(` Payment record created: ${r}`),d.signature}async processPayment(e,n){let t=await this._resolvePaymentParams(n),o=Ei({payment:e,workOrder:t.workOrderAddress,providerAgent:t.providerAgent,payer:t.signer,payerTokenAccount:t.payerTokenAccount,providerTokenAccount:t.providerTokenAccount,tokenMint:t.tokenMint,amount:t.amount,useConfidentialTransfer:t.useConfidentialTransfer});return (await this.sendTransactionWithDetails([o],[t.signer])).signature}async getAccount(e){return this.getDecodedAccount(e,"getWorkOrderDecoder")}async getEscrowAccount(e){return this.getDecodedAccount(e,"getEscrowDecoder")}async getEscrowsForUser(e){return (await this.getDecodedProgramAccounts("getWorkOrderDecoder")).map(({data:t})=>t).filter(t=>t.client===e||t.provider===e)}async getActiveEscrows(){let e=await this.getDecodedProgramAccounts("getWorkOrderDecoder");try{let{WorkOrderStatus:n}=await import('./generated-U3L4KUE4.js');return e.map(({data:t})=>t).filter(t=>t.status===n.Open||t.status===n.InProgress||t.status===n.Submitted)}catch(n){return console.warn("Failed to load WorkOrderStatus enum, returning all escrows:",n),e.map(({data:t})=>t)}}async verifyWorkDelivery(e){console.log("\u2705 Verifying work delivery:",e.workOrderAddress);let n=await this.getAccount(e.workOrderAddress);if(!n)throw new Error(`Work order not found: ${e.workOrderAddress}`);if(e.signer.address!==n.client)throw new Error("Only the client can verify work delivery");let{findProgramDerivedAddress:t}=await import('./pda-2GUWRQ5G.js'),[o]=await t(["work_delivery",e.workOrderAddress],this.programId);console.log("\u{1F4CB} Verification Setup:"),console.log(` Work order status: ${n.status}`),console.log(` Work delivery PDA: ${o}`),console.log(` Verification notes: ${e.verificationNotes??"None"}`);let r=gm({workOrder:e.workOrderAddress,workDelivery:o,client:e.signer,verificationNotes:e.verificationNotes??null}),s=await this.sendTransactionWithDetails([r],[e.signer]);return console.log(`\u2705 Work delivery verified successfully: ${s.signature}`),s.signature}async rejectWorkDelivery(e){console.log("\u274C Rejecting work delivery:",e.workOrderAddress);let n=await this.getAccount(e.workOrderAddress);if(!n)throw new Error(`Work order not found: ${e.workOrderAddress}`);if(e.signer.address!==n.client)throw new Error("Only the client can reject work delivery");if(!e.rejectionReason||e.rejectionReason.trim().length===0)throw new Error("Rejection reason is required");let{findProgramDerivedAddress:t}=await import('./pda-2GUWRQ5G.js'),[o]=await t(["work_delivery",e.workOrderAddress],this.programId);console.log("\u{1F4CB} Rejection Setup:"),console.log(` Work order status: ${n.status}`),console.log(` Rejection reason: ${e.rejectionReason}`),console.log(` Requested changes: ${e.requestedChanges?.length??0} items`);let r=pj({workOrder:e.workOrderAddress,workDelivery:o,client:e.signer,rejectionReason:e.rejectionReason,requestedChanges:e.requestedChanges??null}),s=await this.sendTransactionWithDetails([r],[e.signer]);return console.log(`\u274C Work delivery rejected: ${s.signature}`),s.signature}async getWorkDelivery(e){let{findProgramDerivedAddress:n}=await import('./pda-2GUWRQ5G.js'),[t]=await n(["work_delivery",e],this.programId);return this.getDecodedAccount(t,"getWorkDeliveryDecoder")}};
2
- export{b as a,Q as b};//# sourceMappingURL=chunk-QATBFZMM.js.map
3
- //# sourceMappingURL=chunk-QATBFZMM.js.map