@palliora.org/chainsdk 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +754 -238
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +658 -193
- package/dist/index.d.ts +658 -193
- package/dist/index.js +725 -209
- package/dist/index.js.map +1 -1
- package/package.json +12 -8
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/shivanshxyz/repos/labyrinth/manas/chainsdk/dist/index.cjs","../src/account/account.ts","../src/account/types.ts","../src/chain/spec.ts","../src/crypto/core.ts","../src/crypto/cipher.ts","../src/utils/assert.ts","../src/config.ts","../src/utils/helper.ts","../src/utils/token.ts","../src/chain/singleton.ts","../src/chain/wsProvider.ts","../src/chain/utils.ts","../src/guardian/active.ts","../src/guardian/group.ts","../src/guardian/join.ts","../src/chain/onchainfs.ts","../src/compute/agreement.ts","../src/compute/participants.ts","../src/crypto/random.ts","../src/da/register.ts","../src/da/submit.ts","../src/da/upload.ts","../src/stake/add.ts","../src/stake/idle.ts","../src/stake/new.ts","../src/stake/payout.ts","../src/stake/reduce.ts","../src/stake/remove.ts","../src/stake/withdraw.ts","../src/token/fund.ts","../src/token/transfer.ts","../src/validator/join.ts","../src/identity.ts","../src/rotateKeys.ts","../src/index.ts"],"names":["CryptoType","AccountSourceType","keyring"],"mappings":"AAAA;ACAA,0GAA0B;ADE1B;AACA;AEHA,IAAK,WAAA,kBAAL,CAAA,CAAKA,WAAAA,EAAAA,GAAL;AACE,EAAAA,WAAAA,CAAA,SAAA,EAAA,EAAU,SAAA;AACV,EAAAA,WAAAA,CAAA,SAAA,EAAA,EAAU,SAAA;AACV,EAAAA,WAAAA,CAAA,OAAA,EAAA,EAAQ,OAAA;AAHL,EAAA,OAAAA,WAAAA;AAAA,CAAA,CAAA,CAAA,WAAA,GAAA,CAAA,CAAA,CAAA;AAML,IAAK,k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;AAEA,EAAA;AAAS,iBAAA;AAET,EAAA;AACA,EAAA;AAEA,EAAA;AACF;A9B4/CA;AACA;A+B1gDA;AACE,EAAA;AAEA,EAAA;AAEA,EAAA;AAAS,+BAAA;AAET,EAAA;AACA,EAAA;AAEA,EAAA;AACF;A/BygDA;AACA;AgCrhDA;AACE,EAAA;AAEA,EAAA;AACA,EAAA;AAEA,EAAA;AACA,EAAA;AAEA,EAAA;AACF;AhCohDA;AACA;AiCliDA;AAIA;AACC,EAAA;AAEA,EAAA;AAEA,EAAA;AAAS,8BAAA;AAET,EAAA;AACA,EAAA;AAEA,EAAA;AACD;AjC8hDA;AACA;AkC7iDA;AAEA;AAEA;AACE,EAAA;AAEA,EAAA;AAEA,EAAA;AAEA,EAAA;AACA,EAAA;AAEA,EAAA;AACA,EAAA;AAEA,EAAA;AACF;AAEA;AACE,EAAA;AAEA,EAAA;AAEA,EAAA;AACA,EAAA;AACA,EAAA;AAEA,EAAA;AACF;AlCoiDA;AACA;AmCrjDA;AACA;AACA;AACA;AnCujDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/shivanshxyz/repos/labyrinth/manas/chainsdk/dist/index.cjs","sourcesContent":[null,"import { waitReady } from \"@polkadot/wasm-crypto\";\nimport { AccountSourceType, CryptoType } from \"./types\";\nimport { Keyring } from \"@polkadot/api\";\nimport { hexToU8a } from \"@polkadot/util\";\nimport { ed25519PairFromSecret, secp256k1PairFromSeed } from \"@polkadot/util-crypto\";\n\n/**\n * Creates a Substrate account from a private key, seed, or mnemonic.\n * @param input - The input string (private key hex, seed hex, or mnemonic phrase).\n * @param type - The type of input: 'privateKey', 'seed', or 'mnemonic'.\n * @param cryptoType - The crypto type: 'sr25519' | 'ed25519' | 'ecdsa' (default: 'sr25519').\n * @returns The keypair object.\n */\nexport async function createAccount(\n input: any,\n type: AccountSourceType,\n name: string = \"default\",\n cryptoType: CryptoType = CryptoType.SR25519\n): Promise<any> {\n await waitReady();\n const keyring = new Keyring({ type: cryptoType });\n\n switch (type) {\n case AccountSourceType.PRIVATE_KEY: {\n const pair = pairFromPrivateKeyHex(input, cryptoType);\n return keyring.addFromPair(pair, { name }, cryptoType);\n }\n case AccountSourceType.SEED: {\n const seed = hexToU8a(input);\n\n if (seed.length !== 32) {\n throw new Error(\n `Invalid ${cryptoType} seed length. Expected 32 bytes, got ${seed.length}`\n );\n }\n\n return keyring.addFromSeed(seed, { name }, cryptoType);\n }\n case AccountSourceType.MNEMONIC:\n // format: <mnemonic or mini-secret>[//hard-derivation][/soft-derivation][///password]\n // refer docs: https://polkadot.js.org/docs/keyring/start/suri/\n return keyring.createFromUri(input, { name }, cryptoType);\n case AccountSourceType.ADDRESS:\n const account = keyring.addFromAddress(\n input,\n { name },\n null,\n cryptoType\n );\n return account;\n default:\n throw new Error(\"Invalid input type\");\n }\n}\n\nexport function pairFromPrivateKeyHex(privateKeyHex: string, cryptoType: CryptoType) {\n const privateKey = hexToU8a(privateKeyHex);\n\n switch (cryptoType) {\n case CryptoType.ED25519:\n if (privateKey.length !== 64) {\n throw new Error(\n `Invalid ed25519 private key length. Expected 64 bytes, got ${privateKey.length}`\n );\n }\n return ed25519PairFromSecret(privateKey);\n case CryptoType.ECDSA:\n if (privateKey.length !== 32) {\n throw new Error(\n `Invalid ecdsa private key length. Expected 32 bytes, got ${privateKey.length}`\n );\n }\n return secp256k1PairFromSeed(privateKey);\n case CryptoType.SR25519:\n if (privateKey.length !== 96) {\n throw new Error(\n `Invalid sr25519 private key length. Expected 96 bytes (secret+public), got ${privateKey.length}`\n );\n }\n return {\n secretKey: privateKey.slice(0, 64),\n publicKey: privateKey.slice(64, 96),\n };\n default:\n throw new Error(`Unsupported crypto type: ${cryptoType}`);\n }\n}\n","enum CryptoType {\n SR25519 = \"sr25519\",\n ED25519 = \"ed25519\",\n ECDSA = \"ecdsa\",\n}\n\nenum AccountSourceType {\n PRIVATE_KEY = \"privateKey\",\n SEED = \"seed\",\n MNEMONIC = \"mnemonic\",\n DERIVED = \"derived\",\n ADDRESS = \"address\",\n}\n\nexport { CryptoType, AccountSourceType };\n","\nexport const API_RPC = {\n\tkate: {\n\t\tqueryRows: {\n\t\t\tdescription: \"\",\n\t\t\tparams: [\n\t\t\t\t{\n\t\t\t\t\tname: \"rows\",\n\t\t\t\t\ttype: \"Vec<u32>\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"at\",\n\t\t\t\t\ttype: \"Hash\",\n\t\t\t\t\tisOptional: true,\n\t\t\t\t},\n\t\t\t],\n\t\t\ttype: \"Vec<GRow>\",\n\t\t},\n\t\tqueryProof: {\n\t\t\tdescription: \"Generate the kate proof for the given `cells`\",\n\t\t\tparams: [\n\t\t\t\t{\n\t\t\t\t\tname: \"cells\",\n\t\t\t\t\ttype: \"Vec<Cell>\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"at\",\n\t\t\t\t\ttype: \"Hash\",\n\t\t\t\t\tisOptional: true,\n\t\t\t\t},\n\t\t\t],\n\t\t\ttype: \"Vec<GDataProof>\",\n\t\t},\n\t\tblockLength: {\n\t\t\tdescription: \"Get Block Length\",\n\t\t\tparams: [\n\t\t\t\t{\n\t\t\t\t\tname: \"at\",\n\t\t\t\t\ttype: \"Hash\",\n\t\t\t\t\tisOptional: true,\n\t\t\t\t},\n\t\t\t],\n\t\t\ttype: \"BlockLength\",\n\t\t},\n\t\tqueryDataProof: {\n\t\t\tdescription: \"Generate the data proof for the given `transaction_index`\",\n\t\t\tparams: [\n\t\t\t\t{\n\t\t\t\t\tname: \"transaction_index\",\n\t\t\t\t\ttype: \"u32\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"at\",\n\t\t\t\t\ttype: \"Hash\",\n\t\t\t\t\tisOptional: true,\n\t\t\t\t},\n\t\t\t],\n\t\t\ttype: \"ProofResponse\",\n\t\t},\n\t},\n\tguardian: {\n\t\truntimeInfo: {\n\t\t\tdescription: \"Fetch guardian runtime info\",\n\t\t\tparams: [\n\t\t\t\t{\n\t\t\t\t\tname: 'at',\n\t\t\t\t\ttype: 'Hash',\n\t\t\t\t\tisOptional: true\n\t\t\t\t}\n\t\t\t],\n\t\t\ttype: 'GuardianInfo'\n\t\t},\n\t\tguardianList: {\n\t\t\tdescription: \"Fetch guardian list\",\n\t\t\tparams: [],\n\t\t\ttype: 'Vec<String>'\n\t\t},\n\t\tguardianNwParams: {\n\t\t\tdescription: \"Fetch guardian network parameters\",\n\t\t\tparams: [],\n\t\t\ttype: 'GuardianNwParams'\n\t\t}\n\t},\n};\n\nexport const API_TYPES = {\n\tGuardianInfo: {\n\t\tactive: 'u32',\n\t\tmaximum: 'u32'\n\t},\n\tGuardianNwParams: {\n\t\tkzg: 'Vec<u8>',\n\t\tagg_key: 'Vec<u8>'\n\t},\n\tAppId: \"Compact<u32>\",\n\tDataLookupItem: {\n\t\tappId: \"AppId\",\n\t\tstart: \"Compact<u32>\",\n\t},\n\tCompactDataLookup: {\n\t\tsize: \"Compact<u32>\",\n\t\tindex: \"Vec<DataLookupItem>\",\n\t},\n\tKateCommitment: {\n\t\trows: \"Compact<u16>\",\n\t\tcols: \"Compact<u16>\",\n\t\tcommitment: \"Vec<u8>\",\n\t\tdataRoot: \"H256\",\n\t},\n\tV3HeaderExtension: {\n\t\tappLookup: \"CompactDataLookup\",\n\t\tcommitment: \"KateCommitment\",\n\t},\n\tHeaderExtension: {\n\t\t_enum: {\n\t\t\tV1: null,\n\t\t\tV2: null,\n\t\t\tV3: \"V3HeaderExtension\",\n\t\t},\n\t},\n\tDaHeader: {\n\t\tparentHash: \"Hash\",\n\t\tnumber: \"Compact<BlockNumber>\",\n\t\tstateRoot: \"Hash\",\n\t\textrinsicsRoot: \"Hash\",\n\t\tdigest: \"Digest\",\n\t\textension: \"HeaderExtension\",\n\t},\n\tHeader: \"DaHeader\",\n\tCheckAppIdExtra: {\n\t\tappId: \"AppId\",\n\t},\n\tCheckAppIdTypes: {},\n\tCheckAppId: {\n\t\textra: \"CheckAppIdExtra\",\n\t\ttypes: \"CheckAppIdTypes\",\n\t},\n ComputePayload: {\n da_type: \"u8\",\n agreement: \"Option<BoundedVec<[u8; 32], 10>>\",\n verification: \"u8\",\n compute: \"u8\",\n },\n\tBlockLengthColumns: \"Compact<u32>\",\n\tBlockLengthRows: \"Compact<u32>\",\n\tBlockLength: {\n\t\tmax: \"PerDispatchClass\",\n\t\tcols: \"BlockLengthColumns\",\n\t\trows: \"BlockLengthRows\",\n\t\tchunkSize: \"Compact<u32>\",\n\t},\n\tPerDispatchClass: {\n\t\tnormal: \"u32\",\n\t\toperational: \"u32\",\n\t\tmandatory: \"u32\",\n\t},\n\tTxDataRoots: {\n\t\tdataRoot: \"H256\",\n\t\tblobRoot: \"H256\",\n\t\tbridgeRoot: \"H256\",\n\t},\n\tDataProof: {\n\t\troots: \"TxDataRoots\",\n\t\tproof: \"Vec<H256>\",\n\t\tnumberOfLeaves: \"Compact<u32>\",\n\t\tleafIndex: \"Compact<u32>\",\n\t\tleaf: \"H256\",\n\t},\n\tProofResponse: {\n\t\tdataProof: \"DataProof\",\n\t\tmessage: \"Option<AddressedMessage>\",\n\t},\n\tAddressedMessage: {\n\t\tmessage: \"Message\",\n\t\tfrom: \"H256\",\n\t\tto: \"H256\",\n\t\toriginDomain: \"u32\",\n\t\tdestinationDomain: \"u32\",\n\t\tid: \"u64\",\n\t},\n\tMessage: {\n\t\t_enum: {\n\t\t\tArbitraryMessage: \"ArbitraryMessage\",\n\t\t\tFungibleToken: \"FungibleToken\",\n\t\t},\n\t},\n\tFungibleToken: {\n\t\tassetId: \"H256\",\n\t\tamount: \"u128\",\n\t},\n\tBoundedData: \"Vec<u8>\",\n\tArbitraryMessage: \"BoundedData\",\n\tCell: {\n\t\trow: \"u32\",\n\t\tcol: \"u32\",\n\t},\n\tGRawScalar: \"U256\",\n\tGProof: \"[u8; 48]\",\n\tGRow: \"Vec<GRawScalar>\",\n\tGDataProof: \"(GRawScalar, GProof)\",\n};\n\nexport const DEFAULT_COMPUTE_PAYLOAD = { compute: { da_type: 0, verification: 0, compute: 0 } };\nexport const DEFAULT_EMPTY_PAYLOAD = { compute: { da_type: 0, verification: 0, compute: 0, agreement: [] } };\n\nexport const API_EXTENSIONS = {\n\tCheckAppId: {\n\t\textrinsic: {\n\t\t\tappId: \"AppId\",\n\t\t},\n\t\tpayload: {},\n\t},\n\tCheckCompute: {\n\t\textrinsic: {\n\t\t\t\tcompute: \"ComputePayload\",\n\t\t},\n\t\tpayload: {},\n\t},\n};\n","// import { CurveType } from '@noble/curves/abstract/bls';\nimport { bls12_381 as bls } from \"@noble/curves/bls12-381\";\nimport type { ProjPointType } from \"@noble/curves/abstract/weierstrass\";\nimport type { Fp, Fp12, Fp2 } from \"@noble/curves/abstract/tower\";\n\n/**\n * Summary of porting the Silent Threshold encryption scheme from Rust to JavaScript.\n *\n * The Silent Threshold encryption scheme is a threshold encryption scheme that uses BLS12-381 as the underlying elliptic curve.\n * The scheme is based on the BLS signature scheme and uses the BLS pairing to encrypt and decrypt data.\n *\n * The types ported from the original Rust implementation are:\n * - E::ScalarField -> BigInt\n * - QuadExtField -> Fp2\n * - CubicExtField -> Fp6\n * - E::G1 -> ProjPointType<Fp>\n * - E::G2 -> ProjPointType<Fp2>\n * - PairingOutput -> ProjPointType<Fp12>\n */\n\n/**\n * @typedef {Object} PublicKey\n * @property {number} id - The identifier for the public key.\n * @property {ProjPointType<Fp>} bls_pk - The BLS public key.\n * @property {ProjPointType<Fp>} sk_li - The secret key component li.\n * @property {ProjPointType<Fp>} sk_li_minus0 - The secret key component li minus 0.\n * @property {ProjPointType<Fp>} sk_li_x - The secret key component li x.\n * @property {Array<ProjPointType<Fp>>} sk_li_lj_z - The secret key components li lj z.\n */\ntype PublicKey = {\n\tid: number;\n\tbls_pk: ProjPointType<Fp>;\n\tsk_li: ProjPointType<Fp>; //hint\n\tsk_li_minus0: ProjPointType<Fp>; //hint\n\tsk_li_lj_z: Array<ProjPointType<Fp>>; //hint\n\tsk_li_x: ProjPointType<Fp>; //hint\n};\n\n/**\n * @typedef {Object} LagrangePowers\n * @property {Array<CurveType>} li - The Lagrange coefficients li.\n * @property {Array<ProjPointType<Fp>>} li_minus0 - The Lagrange coefficients li minus 0.\n * @property {Array<ProjPointType<Fp>>} li_x - The Lagrange coefficients li x.\n * @property {Array<Array<ProjPointType<Fp>>>} li_lj_z - The Lagrange coefficients li lj z.\n */\ntype LagrangePowers = {\n\t// li: Array<CurveType>,\n\tli_minus0: Array<ProjPointType<Fp>>;\n\tli_x: Array<ProjPointType<Fp>>;\n\tli_lj_z: Array<Array<ProjPointType<Fp>>>;\n};\n\n/**\n * @typedef {ProjPointType<Fp12>} PairingOutput - The output of the pairing operation.\n */\ntype PairingOutput = ProjPointType<Fp12>;\n\n/**\n * @typedef {Object} AggregateKey\n * @property {Array<PublicKey>} pk - The array of public keys.\n * @property {Array<ProjPointType<Fp>>} agg_sk_li_lj_z - The aggregated secret key components li lj z.\n * @property {ProjPointType<Fp>} ask - The aggregated secret key.\n * @property {ProjPointType<Fp2>} z_g2 - The z_g2 component.\n * @property {ProjPointType<Fp2>} h_minus1 - The h_minus1 component.\n * @property {PairingOutput} e_gh - The preprocessed pairing output.\n */\ntype AggregateKey = {\n\tpk: Array<PublicKey>;\n\tagg_sk_li_lj_z: Array<ProjPointType<Fp>>;\n\task: ProjPointType<Fp>;\n\tz_g2: ProjPointType<Fp2>;\n\n\t//preprocessed values\n\th_minus1: ProjPointType<Fp2>;\n\te_gh: Fp12;\n};\n\n/**\n * @typedef {Object} Ciphertext\n * @property {ProjPointType<Fp2>} gamma_g2 - The gamma_g2 component.\n * @property {Array<ProjPointType<Fp>>} sa1 - The sa1 components (2 elements).\n * @property {Array<ProjPointType<Fp2>>} sa2 - The sa2 components (6 elements).\n * @property {PairingOutput} enc_key - The encryption key.\n * @property {number} t - The threshold value.\n */\ntype Ciphertext = {\n\tgamma_g2: ProjPointType<Fp2>;\n\tsa1: ProjPointType<Fp>[];\n\tsa2: ProjPointType<Fp2>[];\n\tenc_key: Fp12; // key to be used for encapsulation\n\tt: number; // threshold\n};\n\n/**\n * @typedef {Object} PowersOfTau\n * @property {ArrayLike<ProjPointType<Fp>>} powers_of_g - The powers of g.\n * @property {ArrayLike<ProjPointType<Fp2>>} powers_of_h - The powers of h.\n */\ntype PowersOfTau = {\n\tpowers_of_g: ArrayLike<ProjPointType<Fp>>;\n\tpowers_of_h: ArrayLike<ProjPointType<Fp2>>;\n};\n\n/**\n * Encrypts data using the provided parameters and aggregate public key.\n *\n * @param params - The PowersOfTau parameters containing powers of g and h.\n * @param apk - The AggregateKey containing the aggregated public key and preprocessed values.\n * @param t - The threshold value for encryption.\n * @returns A Ciphertext object containing the encrypted data.\n */\nconst encrypt = (params: PowersOfTau, apk: AggregateKey, t: number) => {\n\t// Initialize an ArrayBuffer (tau) from a fixed string\n\tconst gamma = bls.fields.Fr.create(\n\t\tBigInt(\n\t\t\t\"0x\" +\n\t\t\treverseEndianess(\n\t\t\t\t\"8660d3c2a2ab458dd6da04d3e7cb5cf6edb702dfa2fa0c952cd6f3bcdc0fdb1a\",\n\t\t\t),\n\t\t),\n\t);\n\t// console.log(gamma.toString(16));\n\t// const gamma = bls.G1.normPrivateKeyToScalar(bls.utils.randomPrivateKey());\n\tconst gamma_g2 = params.powers_of_h[0].multiply(gamma);\n\t// console.log(gamma_g2.toHex(true));\n\n\tlet g = params.powers_of_g[0];\n\tlet h = params.powers_of_h[0];\n\n\tlet sa1 = [bls.G1.ProjectivePoint.BASE, bls.G1.ProjectivePoint.BASE];\n\tlet sa2: ProjPointType<Fp2>[] = Array(6).fill(bls.G2.ProjectivePoint.BASE);\n\t// sa1.forEach((value, index) => {\n\t// console.log(`sa1[${index}]: ${value.toHex(true)}`);\n\t// });\n\t// sa2.forEach((value, index) => {\n\t// console.log(`sa2[${index}]: ${value.toHex(true)}`);\n\t// });\n\n\tconst hexValues = [\n\t\treverseEndianess(\n\t\t\t\"08ca6f2a35f8f6f9cad58e9d764d450af154c246fc04266151e2a5493ff02943\",\n\t\t),\n\t\treverseEndianess(\n\t\t\t\"8696a66087578b92e1b4b11c6b4c06d4694a9bed1f9468f0115e7f2648eb021d\",\n\t\t),\n\t\treverseEndianess(\n\t\t\t\"91e201cc83dc03cc47d63cfb8a9016e73ffd1a78fffd14e4dfcdf2cbb9a7245d\",\n\t\t),\n\t\treverseEndianess(\n\t\t\t\"a90598c6e0f25c3a104fc94632b1d58cf21bca3bbd7e41da07feb9c14e0fa60d\",\n\t\t),\n\t\treverseEndianess(\n\t\t\t\"d3f5a9fc8abfef02fb6095c08ba4f3445b36f0fb963579bc5112d34a02044567\",\n\t\t),\n\t];\n\n\t// let s = hexValues.map((hex) => bls.G1.normPrivateKeyToScalar(hex));\n\t// s.forEach((value, index) => {\n\t// console.log(`s[${index}]: ${value.toString(16)}`);\n\t// });\n\tconst s = Array.from({ length: 5 }, () => bls.G1.normPrivateKeyToScalar(bls.utils.randomPrivateKey()));\n\n\t// sa1[0] = s0*ask + s3*g^{tau^t} + s4*g\n\tsa1[0] = apk.ask\n\t\t.multiply(s[0])\n\t\t.add(params.powers_of_g[t].multiply(s[3]))\n\t\t.add(params.powers_of_g[0].multiply(s[4]));\n\n\t// sa1[1] = s2*g\n\tsa1[1] = g.multiply(s[2]);\n\n\t// sa2[0] = s0*h + s2*gamma_g2\n\tsa2[0] = h.multiply(s[0]).add(gamma_g2.multiply(s[2]));\n\n\t// sa2[1] = s0*z_g2\n\tsa2[1] = apk.z_g2.multiply(s[0]);\n\n\t// sa2[2] = s0*h^tau + s1*h^tau\n\tsa2[2] = params.powers_of_h[1]\n\t\t.multiply(s[0])\n\t\t.add(params.powers_of_h[1].multiply(s[1]));\n\n\t// sa2[3] = s1*h\n\tsa2[3] = h.multiply(s[1]);\n\n\t// sa2[4] = s3*h\n\tsa2[4] = h.multiply(s[3]);\n\n\t// sa2[5] = s4*h^{tau - omega^0}\n\tsa2[5] = params.powers_of_h[1].add(apk.h_minus1).multiply(s[4]);\n\n\t// enc_key = s4*e_gh\n\tconst enc_key = bls.fields.Fp12.pow(apk.e_gh, s[4]);\n\t// const enc_key = apk.e_gh.multiply(s[4]);\n\n\treturn { gamma_g2, sa1, sa2, enc_key, t };\n};\n\n/**\n * Decodes a hex string into a PowersOfTau object.\n *\n * @param input - The hex string to decode.\n * @returns A PowersOfTau object containing the decoded data.\n */\nconst decodePowersOfTau = (input: string): PowersOfTau => {\n\ttry {\n\t\t// Ensure input is properly formatted\n\t\tif (!input || input.length % 2 !== 0) {\n\t\t\tthrow new Error('Invalid input hex string');\n\t\t}\n\n\t\t// Convert hex string to Uint8Array\n\t\tconst hexArray = input.match(/.{1,2}/g) || [];\n\t\tconst buffer = new Uint8Array(hexArray.map(byte => parseInt(byte, 16)));\n\n\t\t// Create ArrayBuffer with the correct size\n\t\tconst arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);\n\t\tconst view = new DataView(arrayBuffer);\n\n\t\tconst powers_of_g: Array<ProjPointType<Fp>> = [];\n\t\tconst powers_of_h: Array<ProjPointType<Fp2>> = [];\n\n\t\tconst G1_POINT_SIZE = 48; // 96/2 bytes for G1 points\n\t\tconst G2_POINT_SIZE = 96; // 192/2 bytes for G2 points\n\n\t\tlet offset = 0;\n\n\t\t// Read count safely\n\t\tif (offset + 8 > buffer.length) {\n\t\t\tthrow new Error('Buffer too small to read count');\n\t\t}\n\t\tconst count = view.getBigUint64(offset, true);\n\t\toffset += 8;\n\n\t\t// Read powers_of_g\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tif (offset + G1_POINT_SIZE > buffer.length) {\n\t\t\t\tthrow new Error('Buffer too small to read G1 point');\n\t\t\t}\n\t\t\tconst pointBuffer = buffer.slice(offset, offset + G1_POINT_SIZE);\n\t\t\tconst point = bls.G1.ProjectivePoint.fromHex(pointBuffer);\n\t\t\tpowers_of_g.push(point);\n\t\t\toffset += G1_POINT_SIZE;\n\t\t}\n\n\t\t// Skip the second count\n\t\tif (offset + 8 > buffer.length) {\n\t\t\tthrow new Error('Buffer too small to read second count');\n\t\t}\n\t\toffset += 8;\n\n\t\t// Read powers_of_h\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tif (offset + G2_POINT_SIZE > buffer.length) {\n\t\t\t\tthrow new Error('Buffer too small to read G2 point');\n\t\t\t}\n\t\t\tconst pointBuffer = buffer.slice(offset, offset + G2_POINT_SIZE);\n\t\t\tconst point = bls.G2.ProjectivePoint.fromHex(pointBuffer);\n\t\t\tpowers_of_h.push(point);\n\t\t\toffset += G2_POINT_SIZE;\n\t\t}\n\n\t\treturn { powers_of_g, powers_of_h };\n\t} catch (error) {\n\t\tconsole.error('Error in decodePowersOfTau:', error);\n\t\tconsole.log('Input length:', input.length);\n\t\tconsole.log('Input preview:', input.slice(0, 100));\n\t\tthrow error;\n\t}\n};\n\n// Helper function to check if a hex string is valid\nconst isValidHex = (hex: string): boolean => {\n\treturn /^[0-9A-Fa-f]*$/.test(hex) && hex.length % 2 === 0;\n};\n\n// Helper function to safely create a DataView from a hex string\nconst createDataViewFromHex = (hex: string): { view: DataView, buffer: Uint8Array } => {\n\tif (!isValidHex(hex)) {\n\t\tthrow new Error('Invalid hex string');\n\t}\n\tconst buffer = new Uint8Array(hex.match(/.{1,2}/g)!.map(byte => parseInt(byte, 16)));\n\tconst arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);\n\treturn {\n\t\tview: new DataView(arrayBuffer),\n\t\tbuffer\n\t};\n};\n\n/**\n * Decodes a hex string into an AggregateKey object.\n *\n * @param input - The hex string to decode.\n * @returns An AggregateKey object containing the decoded data.\n */\nconst decodeAggregateKey = (input: string): AggregateKey => {\n\tconst buffer = new Uint8Array(input.match(/.{1,2}/g)?.map(byte => parseInt(byte, 16)) || []);\n\tlet offset = 0;\n\n\tconst view = new DataView(buffer.buffer);\n\tconst readBigUInt64LE = () => {\n\t\tconst value = view.getBigUint64(offset, true);\n\t\toffset += 8;\n\t\treturn value;\n\t};\n\n\tconst readProjPointTypeFp = (count: bigint) => {\n\t\tconst points: Array<ProjPointType<Fp>> = [];\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst pointBuffer = buffer.slice(offset, offset + 48);\n\t\t\tconst point = bls.G1.ProjectivePoint.fromHex(pointBuffer);\n\t\t\tpoints.push(point);\n\t\t\toffset += 48;\n\t\t}\n\t\treturn points;\n\t};\n\n\tconst readProjPointTypeFp2 = (count: bigint) => {\n\t\tconst points: Array<ProjPointType<Fp2>> = [];\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst pointBuffer = buffer.slice(offset, offset + 96);\n\t\t\tconst point = bls.G2.ProjectivePoint.fromHex(pointBuffer);\n\t\t\tpoints.push(point);\n\t\t\toffset += 96;\n\t\t}\n\t\treturn points;\n\t};\n\n\tconst readProjPointTypeFp12 = () => {\n\t\tconst points: Array<Fp> = [];\n\t\tfor (let i = 0; i < 12; i++) {\n\t\t\tconst pointBuffer = buffer.slice(offset, offset + 48);\n\t\t\t// Convert to hex and reverse for endianness\n\t\t\tconst hexValue = Array.from(pointBuffer)\n\t\t\t\t.reverse()\n\t\t\t\t.map(b => b.toString(16).padStart(2, '0'))\n\t\t\t\t.join('');\n\t\t\tconst point = BigInt(\"0x\" + hexValue);\n\t\t\tpoints.push(point);\n\t\t\toffset += 48;\n\t\t}\n\t\tif (points.length !== 12) {\n\t\t\tthrow new Error(\"Invalid number of points for Fp12\");\n\t\t}\n\t\treturn bls.fields.Fp12.create({\n\t\t\tc0: bls.fields.Fp6.create({\n\t\t\t\tc0: bls.fields.Fp2.create({ c0: points[0], c1: points[1] }),\n\t\t\t\tc1: bls.fields.Fp2.create({ c0: points[2], c1: points[3] }),\n\t\t\t\tc2: bls.fields.Fp2.create({ c0: points[4], c1: points[5] }),\n\t\t\t}),\n\t\t\tc1: bls.fields.Fp6.create({\n\t\t\t\tc0: bls.fields.Fp2.create({ c0: points[6], c1: points[7] }),\n\t\t\t\tc1: bls.fields.Fp2.create({ c0: points[8], c1: points[9] }),\n\t\t\t\tc2: bls.fields.Fp2.create({ c0: points[10], c1: points[11] }),\n\t\t\t}),\n\t\t});\n\t};\n\n\tconst pkCount = readBigUInt64LE();\n\tconst pk: Array<PublicKey> = [];\n\tfor (let i = 0; i < pkCount; i++) {\n\t\tconst id = Number(readBigUInt64LE());\n\t\tconst bls_pk = readProjPointTypeFp(BigInt(1))[0];\n\t\tconst sk_li = readProjPointTypeFp(BigInt(1))[0];\n\t\tconst sk_li_minus0 = readProjPointTypeFp(BigInt(1))[0];\n\t\tconst sk_li_lj_z = readProjPointTypeFp(readBigUInt64LE());\n\t\tconst sk_li_x = readProjPointTypeFp(BigInt(1))[0];\n\t\tpk.push({ id, bls_pk, sk_li, sk_li_minus0, sk_li_x, sk_li_lj_z });\n\t}\n\n\tconst agg_sk_li_lj_z = readProjPointTypeFp(readBigUInt64LE());\n\tconst ask = readProjPointTypeFp(BigInt(1))[0];\n\tconst z_g2 = readProjPointTypeFp2(BigInt(1))[0];\n\tconst h_minus1 = readProjPointTypeFp2(BigInt(1))[0];\n\tconst e_gh = readProjPointTypeFp12();\n\n\treturn { pk, agg_sk_li_lj_z, ask, z_g2, h_minus1, e_gh };\n};\n\n/**\n * Encode a Ciphertext object into a hex string.\n *\n * @param input - The Ciphertext object to encode.\n * @returns A hex string containing the encoded data.\n */\nconst encodeCiphertext = (input: Ciphertext): string => {\n\tconst writeProjPointTypeFp = (point: ProjPointType<Fp>) => {\n\t\tconst hex = point.toHex(true);\n\t\treturn new Uint8Array(hex.match(/.{1,2}/g)?.map(byte => parseInt(byte, 16)) || []);\n\t};\n\n\tconst writeProjPointTypeFp2 = (point: ProjPointType<Fp2>) => {\n\t\tconst hex = point.toHex(true);\n\t\treturn new Uint8Array(hex.match(/.{1,2}/g)?.map(byte => parseInt(byte, 16)) || []);\n\t};\n\n\tconst gamma_g2Buffer = writeProjPointTypeFp2(input.gamma_g2);\n\tconst sa1Buffer = new Uint8Array(input.sa1.flatMap(p => Array.from(writeProjPointTypeFp(p))));\n\tconst sa2Buffer = new Uint8Array(input.sa2.flatMap(p => Array.from(writeProjPointTypeFp2(p))));\n\tconst enc_keyBuffer = new Uint8Array(fp12ToHex(input.enc_key).match(/.{1,2}/g)?.map(byte => parseInt(byte, 16)) || []);\n\n\tconst tBuffer = new Uint8Array(8);\n\tnew DataView(tBuffer.buffer).setBigUint64(0, BigInt(input.t), true);\n\n\tconst totalLength = gamma_g2Buffer.length + sa1Buffer.length + sa2Buffer.length + enc_keyBuffer.length + tBuffer.length;\n\tconst resultBuffer = new Uint8Array(totalLength);\n\n\tlet offset = 0;\n\tresultBuffer.set(gamma_g2Buffer, offset);\n\toffset += gamma_g2Buffer.length;\n\tresultBuffer.set(sa1Buffer, offset);\n\toffset += sa1Buffer.length;\n\tresultBuffer.set(sa2Buffer, offset);\n\toffset += sa2Buffer.length;\n\tresultBuffer.set(enc_keyBuffer, offset);\n\toffset += enc_keyBuffer.length;\n\tresultBuffer.set(tBuffer, offset);\n\n\treturn Array.from(resultBuffer)\n\t\t.map(b => b.toString(16).padStart(2, '0'))\n\t\t.join('');\n};\n\nfunction demoFieldOperations() {\n\t// Create base points in G1 and G2\n\tconst g1Base = bls.G1.ProjectivePoint.BASE;\n\tconst g2Base = bls.G2.ProjectivePoint.BASE;\n\tconsole.log(\"G1 generator: \", g1Base.toHex(true));\n\tconsole.log(\"G2 generator: \", g2Base.toHex(true));\n\n\tconst scalar = bls.fields.Fr.create(\n\t\tBigInt(\n\t\t\t\"0x1d8a77a2bc0faf4c4c904eed119108ed9b375265f7d06cec6862a2a97c3adb27\",\n\t\t),\n\t);\n\tconsole.log(\"Scalar: \", scalar.toString(16));\n\n\tconst e_ghH = bls.pairing(g1Base, g2Base);\n\tconsole.log(fp12ToHex(e_ghH));\n\t// return\n\n\t// Perform G1 addition\n\tconst g1Sum = g1Base.add(g1Base);\n\tconsole.log(\"G1 generator doubled: \", g1Sum.toHex(true));\n\n\t// Perform G2 addition\n\tconst g2Sum = g2Base.add(g2Base);\n\tconsole.log(\"G2 generator doubled: \", g2Sum.toHex(true));\n\n\t// Create an Fp element and do multiplication\n\tconst fp_a = bls.fields.Fp.create(\n\t\tBigInt(\n\t\t\t\"0xa191b705ef18a6e4e5bd4cc56de0b8f94b1f3c908f3e3fcbd4d1dc12eb85059be7e7d801edc1856c8cfbe6d63a681c1f\",\n\t\t),\n\t);\n\tconst fp_b = bls.fields.Fp.create(\n\t\tBigInt(\n\t\t\t\"0x8e07730c0dceb35342bfa587940babad2ec7622aec96994179086a5d323c479e64c890939e47f9a46b427f063f71d4f4\",\n\t\t),\n\t);\n\tconst fpModified = bls.fields.Fp.addN(fp_a, fp_b);\n\tconsole.log(\"Fp a + b: \", fpModified.toString(16));\n\n\tconst g1_a = bls.G1.ProjectivePoint.fromHex(\n\t\t\"a191b705ef18a6e4e5bd4cc56de0b8f94b1f3c908f3e3fcbd4d1dc12eb85059be7e7d801edc1856c8cfbe6d63a681c1f\",\n\t);\n\tconst g1_b = bls.G1.ProjectivePoint.fromHex(\n\t\t\"8e07730c0dceb35342bfa587940babad2ec7622aec96994179086a5d323c479e64c890939e47f9a46b427f063f71d4f4\",\n\t);\n\tconst g1_zero = bls.G1.ProjectivePoint.ZERO;\n\tconsole.log(\"G1 a: \", g1_a.toHex(true));\n\tconsole.log(\"G1 b: \", g1_b.toHex(true));\n\tconsole.log(\"G1 zero: \", g1_zero.toHex(true));\n\n\tconst g1_sum = g1_a.add(g1_b);\n\tconst g1_sub = g1_a.subtract(g1_b);\n\tconst g1_neg = g1_a.negate();\n\tconst g1_dbl = g1_a.double();\n\tconst g1_scalar_mul = g1_a.multiply(scalar);\n\tconsole.log(\"G1 a + b: \", g1_sum.toHex(true));\n\tconsole.log(\"G1 a - b: \", g1_sub.toHex(true));\n\tconsole.log(\"G1 -a: \", g1_neg.toHex(true));\n\tconsole.log(\"G1 2a: \", g1_dbl.toHex(true));\n\tconsole.log(\"G1 scalar mul: \", g1_scalar_mul.toHex(true));\n\n\t// Create an Fp2 element and do multiplication\n\tconst fp2_a = bls.fields.Fp2.create({\n\t\tc0: BigInt(\n\t\t\t\"0x848e9f7ae435bd738c33ae1f11cefb472b29a090de5ce00740b8ec1bd30fdbb27eb7e65162eed68c55e0bb03bf749857\",\n\t\t),\n\t\tc1: BigInt(\n\t\t\t\"0x0f8faa02f0dd3225ca98d8306f8efa4e3f62a13efc342f3466d3e56be5144dae68cafab0f99ddf1f04a6659806b12235\",\n\t\t),\n\t});\n\tconst fp2_b = bls.fields.Fp2.create({\n\t\tc0: BigInt(\n\t\t\t\"0xa4d21fc0921dcca8f0666f3b7530b569c2309bc13d3303a6fc3d233c58275972879c415608b6774bbbb00e10a6e47ace\",\n\t\t),\n\t\tc1: BigInt(\n\t\t\t\"0x1046aa2e6208f5d1813de823e5e3dec638bb7b82247cebeebbc70a14f1f59b9c0738b0f08120cb81d8c876579bd2391f\",\n\t\t),\n\t});\n\tconst fp2Modified = bls.fields.Fp2.addN(fp2_a, fp2_b);\n\tconsole.log(\n\t\t\"Fp2 a + b: \",\n\t\tfp2Modified.c0.toString(16),\n\t\tfp2Modified.c1.toString(16),\n\t);\n\n\tconst g2_a = bls.G2.ProjectivePoint.fromHex(\n\t\t\"848e9f7ae435bd738c33ae1f11cefb472b29a090de5ce00740b8ec1bd30fdbb27eb7e65162eed68c55e0bb03bf7498570f8faa02f0dd3225ca98d8306f8efa4e3f62a13efc342f3466d3e56be5144dae68cafab0f99ddf1f04a6659806b12235\",\n\t);\n\tconst g2_b = bls.G2.ProjectivePoint.fromHex(\n\t\t\"a4d21fc0921dcca8f0666f3b7530b569c2309bc13d3303a6fc3d233c58275972879c415608b6774bbbb00e10a6e47ace1046aa2e6208f5d1813de823e5e3dec638bb7b82247cebeebbc70a14f1f59b9c0738b0f08120cb81d8c876579bd2391f\",\n\t);\n\tconst g2_zero = bls.G2.ProjectivePoint.ZERO;\n\tconsole.log(\"G2 a: \", g2_a.toHex(true));\n\tconsole.log(\"G2 b: \", g2_b.toHex(true));\n\tconsole.log(\"G2 zero: \", g2_zero.toHex(true));\n\n\tconst g2_sum = g2_a.add(g2_b);\n\tconst g2_sub = g2_a.subtract(g2_b);\n\tconst g2_neg = g2_a.negate();\n\tconst g2_dbl = g2_a.double();\n\tconst g2_scalar_mul = g2_a.multiply(scalar);\n\tconsole.log(\"G2 a + b: \", g2_sum.toHex(true));\n\tconsole.log(\"G2 a - b: \", g2_sub.toHex(true));\n\tconsole.log(\"G2 -a: \", g2_neg.toHex(true));\n\tconsole.log(\"G2 2a: \", g2_dbl.toHex(true));\n\tconsole.log(\"G2 scalar mul: \", g2_scalar_mul.toHex(true));\n\n\t// Create an Fp12 element and do squaring\n\tconst fp12_a = hexToFp12(\n\t\t\"7b41018107fbe009aeb2ae912921bb2145b658bff588daea81a2d53a8c4aee171935fcc96fb395398ae4e4b20d937e16967f5e6a543f14a6751a869bfd22c8d96857389065eb86aa6784483efafc422ddb530f3dd76b3ce620605f6e21ee8c13f0a6b6f84a6ab78fdc1167e447c4f3a1d7cc51cf686646b7b31199d3e453c009ca949eb79696bf3d64c68a92e66fcc1514605dea849d01626006d806aca856a641993f84d2c620e6c97f4d8773c7664baee35761c576f687d6a643c3c6257b07f1f07ec6b0eb29ebaa9cb4088b29db25d2612fa604c96b3d148f0f8a954a0777b6e21f4b51f69530401651d1d0c9480ff23d5c0c0d34ede48be9c08dd6bbee77015deddac23d10eebd64ff1ecbce86a696f051fabe6c26e15e3b946afcc2b613f0b3a2126b6533792284bc5fc90a899c4c3a05b2491ce6903a9b2d85f30d630f421324492cbbbaf174cdc1a29adc110bb4891940fa9e8ad79520296819a6b6a32a578f7283c44d9c45e0c2676e0bbb4522cbdc23baebfa3cb008f43700a67207d7eb10a9d82cc576cbe3e10bac5e23613d456c18a512180869f48b52117c8dd1de9ce4728737d3239cfe829ccea8740e42c737ff961d5cff8d9ca0da3434ed909a3d362411cdb5c8e1bc917913c3cd783c3974621309d255f81c06e46132e0076209171b0ffea3ed0541e03d78856c018912927c520c56af071062972d1cb07276d8dcea9746000dbca97f78060e1815d22f5f88652aa53ae1664e449457c2e700e65efdaff38ac0a7849f4966411153dfd1befa7bab0d1889cc643e82809911\",\n\t);\n\tconst fp12_b = hexToFp12(\n\t\t\"d9b0619e9e724685d2eb06d509523870f9dfe07c7d7fb623632fc8f3ef8acd66fd9ed31a79af676ac1c2adc48ff018066f12bda4c5b225652d002ccba86315d57ebf098d35f3987a0b79f4d989c09c0c6373e58ac42c24e5a3b16d3eafa3e91020f0bfea83f3f1736732e71aac76e40399ec881a62a93426306be1e9dfc6645f1649a1d26d7d1ada5aca07c57551250749995a15db818c0aa7acb4606e7f41b65375308abbd547f7b8d90f10e1a7bfba60924a451108c8b896efa7355e14af10c096bb64e70e0c055e27e79b3b7552aa0b36bd3eace4759e13a31eabaea322bf978d2815b287e7c4d31281c85898090b57af368ceefe8be408504a0d57c542ad8e73f44211df17c89a2fd099f25895615828c884d9c31e514819d63856841601cce68807457db323e23db4bbc9a80900fb19aafd655069700db1b5d5a5753adedab2bd556fdc1774a54f0733a51e3c18f16e700f87ade824f35dde86023a5b7d816031e0eac3c4d82a80637a777969815fbd3ddcfcaf77ed7d9ad7c8c886530414d76c34808efefd57b488b065319f573a4ac806eb5da273c4320301ca6de6c682cd844f0a08c9b5e86f29431c32830d1feedf4d8bcd5d5ca90ef15084fffb98abe683d36e9de474ed069e8f72f4cdc7043cd38cb59878acef0674d0b48b8f0b9a0df326c8c7e97a5f35dcc1377f2e68d2e6076afb792db5ad38cb01158571e0c8b644e77c8d1b574653dcd73941070cd34deac7afe916952d3b67b4ad3e8993b33308c282de58e37afb28ae2afbb44f8e56b2e3ef575b67c5bc3112ccfedd07\",\n\t);\n\tconst fp12_zero = bls.fields.Fp12.ZERO;\n\tconst fp12_one = bls.fields.Fp12.ONE;\n\tconst fp12_pairing = bls.pairing(g1_a, g2_b);\n\tconst fp12_scalar_mul = bls.fields.Fp12.pow(fp12_pairing, scalar);\n\n\tconsole.log(\"Fp12 a:\", fp12ToHex(fp12_a));\n\tconsole.log(\"Fp12 b:\", fp12ToHex(fp12_b));\n\tconsole.log(\"Fp12 zero:\", fp12ToHex(fp12_zero));\n\tconsole.log(\"Fp12 one:\", fp12ToHex(fp12_one));\n\tconsole.log(\"Fp12 pairing:\", fp12ToHex(fp12_pairing));\n\tconsole.log(\"Fp12 scalar mul:\", fp12ToHex(fp12_scalar_mul));\n\n\tconst fp12_add = bls.fields.Fp12.add(fp12_a, fp12_b);\n\tconst fp12_sub = bls.fields.Fp12.sub(fp12_a, fp12_b);\n\tconst fp12_neg = bls.fields.Fp12.neg(fp12_a);\n\tconst fp12_mul = bls.fields.Fp12.mul(fp12_a, fp12_b);\n\tconst fp12_inv = bls.fields.Fp12.inv(fp12_a);\n\n\tconsole.log(\"Fp12 add:\", fp12ToHex(fp12_add));\n\tconsole.log(\"Fp12 sub:\", fp12ToHex(fp12_sub));\n\tconsole.log(\"Fp12 neg:\", fp12ToHex(fp12_neg));\n\tconsole.log(\"Fp12 mul:\", fp12ToHex(fp12_mul));\n\tconsole.log(\"Fp12 inv:\", fp12ToHex(fp12_inv));\n}\n\nfunction hexToFp12(hex: string): any {\n\tconst c0 = bls.fields.Fp6.create({\n\t\tc0: bls.fields.Fp2.create({\n\t\t\tc0: BigInt(\"0x\" + reverseEndianess(hex.slice(0, 96))),\n\t\t\tc1: BigInt(\"0x\" + reverseEndianess(hex.slice(96, 192))),\n\t\t}),\n\t\tc1: bls.fields.Fp2.create({\n\t\t\tc0: BigInt(\"0x\" + reverseEndianess(hex.slice(192, 288))),\n\t\t\tc1: BigInt(\"0x\" + reverseEndianess(hex.slice(288, 384))),\n\t\t}),\n\t\tc2: bls.fields.Fp2.create({\n\t\t\tc0: BigInt(\"0x\" + reverseEndianess(hex.slice(384, 480))),\n\t\t\tc1: BigInt(\"0x\" + reverseEndianess(hex.slice(480, 576))),\n\t\t}),\n\t});\n\tconst c1 = bls.fields.Fp6.create({\n\t\tc0: bls.fields.Fp2.create({\n\t\t\tc0: BigInt(\"0x\" + reverseEndianess(hex.slice(576, 672))),\n\t\t\tc1: BigInt(\"0x\" + reverseEndianess(hex.slice(672, 768))),\n\t\t}),\n\t\tc1: bls.fields.Fp2.create({\n\t\t\tc0: BigInt(\"0x\" + reverseEndianess(hex.slice(768, 864))),\n\t\t\tc1: BigInt(\"0x\" + reverseEndianess(hex.slice(864, 960))),\n\t\t}),\n\t\tc2: bls.fields.Fp2.create({\n\t\t\tc0: BigInt(\"0x\" + reverseEndianess(hex.slice(960, 1056))),\n\t\t\tc1: BigInt(\"0x\" + reverseEndianess(hex.slice(1056, 1152))),\n\t\t}),\n\t});\n\treturn bls.fields.Fp12.create({ c0, c1 });\n}\n\nfunction convertToCyclotomic(fp12: any): any {\n\tconst p = BigInt(\n\t\t\"0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab\",\n\t); // BLS12-381 prime\n\tconst exponent = p ** BigInt(4) - p ** BigInt(2) + BigInt(1);\n\treturn bls.fields.Fp12.pow(fp12, exponent);\n}\n\nfunction fp12ToHex(fp12: any): string {\n\tconst c0 = fp12.c0;\n\tconst c1 = fp12.c1;\n\treturn [\n\t\tbigintToBigEndianHex(c0.c0.c0, 48),\n\t\tbigintToBigEndianHex(c0.c0.c1, 48),\n\t\tbigintToBigEndianHex(c0.c1.c0, 48),\n\t\tbigintToBigEndianHex(c0.c1.c1, 48),\n\t\tbigintToBigEndianHex(c0.c2.c0, 48),\n\t\tbigintToBigEndianHex(c0.c2.c1, 48),\n\t\tbigintToBigEndianHex(c1.c0.c0, 48),\n\t\tbigintToBigEndianHex(c1.c0.c1, 48),\n\t\tbigintToBigEndianHex(c1.c1.c0, 48),\n\t\tbigintToBigEndianHex(c1.c1.c1, 48),\n\t\tbigintToBigEndianHex(c1.c2.c0, 48),\n\t\tbigintToBigEndianHex(c1.c2.c1, 48),\n\t].join(\"\");\n}\n\nconst testCrypt = (\n\tkzg: string,\n\tagg_key: string,\n): { encoded: string; ikm: string; ciph: Ciphertext } => {\n\ttry {\n\t\t// Validate inputs\n\t\tif (!isValidHex(kzg) || !isValidHex(agg_key)) {\n\t\t\tthrow new Error('Invalid input hex strings');\n\t\t}\n\n\t\tconst powersOfTau = decodePowersOfTau(kzg);\n\t\tconst aggregateKey = decodeAggregateKey(agg_key);\n\n\t\tconst ciph = encrypt(powersOfTau, aggregateKey, 2);\n\t\tconst encoded = encodeCiphertext(ciph);\n\t\tconst ikm = fp12ToHex(ciph.enc_key);\n\n\t\treturn { encoded, ikm, ciph };\n\t} catch (error) {\n\t\tconsole.error('Error in testCrypt:', error);\n\t\tthrow error;\n\t}\n};\n\nfunction bigintToBigEndianHex(value: bigint, length: number): string {\n\t// Convert BigInt to hex string without the '0x' prefix\n\tlet hex = value.toString(16);\n\n\t// Ensure the hex string is padded to the desired length\n\tif (hex.length > length * 2) {\n\t\tthrow new Error(\"BigInt value is too large to fit in the specified length\");\n\t}\n\n\t// Pad the hex string with leading zeros\n\thex = hex.padStart(length * 2, \"0\");\n\n\t// Convert the hex string to a byte array\n\tconst byteArray =\n\t\thex.match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16)) || [];\n\n\t// Reverse the byte array to get big-endian format\n\tconst reversedByteArray = byteArray.reverse();\n\n\t// Convert the reversed byte array back to a hex string\n\tconst bigEndianHex = reversedByteArray\n\t\t.map((byte) => byte.toString(16).padStart(2, \"0\"))\n\t\t.join(\"\");\n\n\treturn bigEndianHex;\n}\n\nfunction reverseEndianess(hex: string): string {\n\tif (hex.length % 2 !== 0) {\n\t\tthrow new Error(\"Hex string must have an even length\");\n\t}\n\treturn hex.match(/.{1,2}/g)?.reverse().join('') || '';\n}\n\nexport {\n\tdecodeAggregateKey,\n\tdecodePowersOfTau,\n\tencodeCiphertext,\n\tencrypt as ecncryptTest,\n\ttestCrypt,\n};\n","import { edwardsToMontgomeryPriv, edwardsToMontgomeryPub, x25519 } from '@noble/curves/ed25519';\nimport { hkdf } from \"@noble/hashes/hkdf\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { ChaCha20Poly1305 } from \"@stablelib/chacha20poly1305\";\n\nexport const gen_stretched_key = (input: Uint8Array) => {\n const salt = new Uint8Array(32); // 32 bytes of zero\n const info = new TextEncoder().encode(\"aes_encryption\");\n return hkdf(sha256, input, salt, info, 32); // 32 bytes output key length\n};\n\nexport const gen_shared_key = (key: Uint8Array, pk: Uint8Array) => {\n const mg_key = edwardsToMontgomeryPriv(key);\n const mg_pk = edwardsToMontgomeryPub(pk);\n return x25519.getSharedSecret(mg_key, mg_pk);\n};\n\nexport const encrypt = (plaintext: Uint8Array, key: Uint8Array) => {\n const cipher = new ChaCha20Poly1305(key);\n const nonce = new Uint8Array(cipher.nonceLength);\n globalThis.crypto.getRandomValues(nonce);\n const ciphertext = cipher.seal(nonce, plaintext);\n return { ciphertext, nonce };\n};\n\nexport const decrypt = (ciphertext: Uint8Array, key: Uint8Array, nonce: Uint8Array) => {\n const cipher = new ChaCha20Poly1305(key);\n const res = cipher.open(nonce, ciphertext);\n return res;\n};\n","/**\n * Isomorphic assert utility that works in both Node.js and browser environments.\n * Replaces Node.js built-in assert for client-side compatibility.\n */\nexport function assert(\n condition: unknown,\n message?: string\n): asserts condition {\n if (!condition) {\n throw new Error(message ?? \"Assertion failed\");\n }\n}\n","const env = typeof process !== \"undefined\" && process.env ? process.env : {} as Record<string, string | undefined>;\n\nexport let PALLIORA_WS = env.PALLIORA_WS || \"wss://manas-rpc.palliora.org\";\nexport let PALLIORA_RPC_URL = env.PALLIORA_RPC_URL || \"wss://manas-rpc.palliora.org\";\n\nexport let DEBUG = env.DEBUG === \"true\" || false;\n\nexport let TX_WAIT_FINALIZATION = env.TX_WAIT_FINALIZATION === \"true\" || false;\n\nexport function configure(opts: {\n pallioraWs?: string;\n pallioraRpcUrl?: string;\n debug?: boolean;\n txWaitFinalization?: boolean;\n}) {\n if (opts.pallioraWs !== undefined) PALLIORA_WS = opts.pallioraWs;\n if (opts.pallioraRpcUrl !== undefined) PALLIORA_RPC_URL = opts.pallioraRpcUrl;\n if (opts.debug !== undefined) DEBUG = opts.debug;\n if (opts.txWaitFinalization !== undefined) TX_WAIT_FINALIZATION = opts.txWaitFinalization;\n}","import { DEBUG } from \"../config\";\nimport { Hex } from \"./types\";\n\n/**\n * Converts a token amount expressed in milliPALI into the smallest PALI denomination (10^-18 PALI) as a bigint.\n *\n * The function takes milliPALI denomination and returns the bigint value in the lowest denomination of the PALI token which is 10^-18.\n *\n * @param arg - The token amount to convert. Can be a string, number, or bigint representing an amount in milliPALI.\n * @returns The token amount converted to the smallest PALI unit (10^-18 PALI) as a bigint.\n *\n * @example\n * // 1 milliPALI => 10^15 lowest-denomination units\n * tokenToBigint(\"1\"); // => 1000000000000000n\n */\nexport const tokenToBigint = (arg: string | number | bigint): bigint => {\n const val = typeof arg === \"bigint\" ? arg : BigInt(arg);\n return val * 10n ** 15n;\n};\n \n/**\n * Converts a hex string into a Uint8Array.\n *\n * @param hex - A hex-encoded string (must contain only hexadecimal characters, without any 0x prefix).\n * @returns A Uint8Array containing the byte values represented by the hex string.\n * @throws {Error} If the provided hex string has an odd length (invalid hex string).\n *\n * @example\n * hexToUint8Array(\"ff00a1\"); // => Uint8Array [255, 0, 161]\n */\nexport function hexToUint8Array(hex: Hex) {\n if (hex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string\");\n }\n const arr = new Uint8Array(hex.length / 2);\n for (let i = 0; i < arr.length; i++) {\n arr[i] = parseInt(hex.substr(i * 2, 2), 16);\n }\n return arr;\n}\n \n/**\n * Encodes a Uint8Array into a Base64 string using the browser btoa API.\n *\n * Note: This implementation builds a binary string via String.fromCharCode for each byte and then calls btoa.\n * It is intended for browser environments where btoa is available. For very large arrays consider alternative approaches to avoid high memory usage.\n *\n * @param uint8Array - The bytes to encode as Base64.\n * @returns A Base64-encoded string representing the input bytes.\n *\n * @example\n * uint8ArrayToBase64(new Uint8Array([72, 101, 108, 108, 111])); // => \"SGVsbG8=\"\n */\nexport function uint8ArrayToBase64(uint8Array: Uint8Array) {\n let binary = \"\";\n for (let i = 0; i < uint8Array.length; i++) {\n binary += String.fromCharCode(uint8Array[i]);\n }\n return btoa(binary);\n}\n\n/**\n * Decodes a Base64 (or URL-safe Base64) string into a Uint8Array.\n *\n * This function normalizes URL-safe base64 by replacing '-' with '+' and '_' with '/', and it adds padding if missing\n * before decoding with atob. Works in browser environments where atob is available.\n *\n * @param base64 - A Base64 or URL-safe Base64 encoded string.\n * @returns The decoded bytes as a Uint8Array.\n *\n * @example\n * base64ToUint8Array(\"SGVsbG8=\"); // => Uint8Array [72, 101, 108, 108, 111]\n */\nexport const base64ToUint8Array = (base64: string): Uint8Array => {\n // Convert URL-safe base64 to standard base64.\n base64 = base64.replace(/-/g, \"+\").replace(/_/g, \"/\");\n // Add padding if missing.\n while (base64.length % 4) {\n base64 += \"=\";\n }\n const binaryString = atob(base64);\n const len = binaryString.length;\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n};\n\n/**\n * Decodes a Base64-encoded field into a Uint8Array and handles possible double-encoding.\n *\n * If expectedLength is provided and the decoded byte length does not match, this helper checks whether the decoded result\n * is exactly twice the expected length. If so, it treats the decoded bytes as a UTF-8 string containing another Base64 value,\n * decodes that second Base64 string, and returns it if it matches the expected length. Otherwise the initially decoded bytes are returned.\n *\n * @param field - The Base64 (or URL-safe Base64) encoded field to decode.\n * @param expectedLength - Optional expected length of the final decoded byte array. When provided, enables the double-decoding heuristic.\n * @returns The decoded bytes as a Uint8Array. If double-encoding is detected and validated, the inner decoded bytes are returned.\n *\n * @example\n * // Single-encoded\n * decodeField(\"SGVsbG8=\", 5); // => Uint8Array [72, 101, 108, 108, 111]\n *\n * @example\n * // Double-encoded: base64(base64(bytes))\n * decodeField(\"U0dWc2JHOGU=\", 5); // => Uint8Array [72, 101, 108, 108, 111]\n */\nexport const decodeField = (\n field: string,\n expectedLength?: number\n): Uint8Array => {\n const bytes = base64ToUint8Array(field);\n if (expectedLength && bytes.length !== expectedLength) {\n // If we got exactly twice as many bytes as expected, assume double-encoding.\n if (bytes.length === expectedLength * 2) {\n const intermediateStr = new TextDecoder().decode(bytes);\n const secondBytes = base64ToUint8Array(intermediateStr);\n if (secondBytes.length === expectedLength) {\n return secondBytes;\n }\n }\n }\n return bytes;\n};\n\n/**\n * Conditional debug logging utility.\n * Only logs when DEBUG flag is enabled in config.\n * \n * @param message - The message to log\n * @param optionalParams - Additional parameters to log\n */\nexport const debugLog = (message?: any, ...optionalParams: any[]) => {\n if (DEBUG) {\n console.log(message, ...optionalParams);\n }\n};\n","import { assert } from \"./assert\";\nimport { formatBalance } from \"@polkadot/util\";\nimport { getApi } from \"../chain\";\n\ninterface TokenProperties {\n symbol: string;\n decimals: number;\n}\n\nlet tokenCache: TokenProperties | null = null;\n\n/**\n * Fetch token name and decimals from RPC system properties\n * Results are cached for subsequent calls\n * @param rpc - RPC provider instance with system.properties method\n * @returns Promise<TokenProperties> with symbol and decimals\n */\nexport async function fetchTokenProperties(): Promise<TokenProperties> {\n // Return cached value if available\n if (tokenCache) {\n return tokenCache;\n }\n\n try {\n const systemProperties = (await (await getApi())?.rpc.system.properties())?.toHuman();\n\n assert(systemProperties, \"Failed to fetch system properties from RPC\");\n\n const tokenProperties: TokenProperties = {\n symbol: (systemProperties?.tokenSymbol as string[] || [\"UNIT\"])[0],\n decimals: Number((systemProperties?.tokenDecimals as string[] || ['18'])[0]),\n };\n\n // Store in cache\n tokenCache = tokenProperties;\n\n return tokenProperties;\n } catch (error) {\n console.error(\"Failed to fetch token properties:\", error);\n throw error;\n }\n}\n\n/**\n * Get cached token properties without making an RPC call\n * @returns TokenProperties or null if not yet cached\n */\nexport function getCachedTokenProperties(): TokenProperties | null {\n return tokenCache;\n}\n\n/**\n * Clear the token properties cache\n */\nexport function clearTokenCache(): void {\n tokenCache = null;\n}\n\n/**\n * Format balance using cached token properties\n * @param balance - The balance value to format\n * @returns Formatted balance string\n */\nexport async function formatBalanceWithTokenProperties(balance: string | number): Promise<string> {\n const tokenProperties = await fetchTokenProperties();\n \n if (!tokenProperties) {\n throw new Error(\n \"Token properties not yet cached. Call fetchTokenProperties first.\",\n );\n }\n\n return formatBalance(balance, {\n decimals: tokenProperties.decimals,\n withSi: true,\n withUnit: tokenProperties.symbol,\n });\n}\n","/**\n * Module providing singleton access to Polkadot API, WebSocket provider, and keyring.\n *\n * This module ensures that only one instance of the WsProvider, ApiPromise and Keyring\n * are created and reused across the application. It exposes a class-based wrapper\n * (RpcApi) for managed connect/disconnect flows and convenience functions for directly\n * obtaining the singleton instances.\n *\n * Notes:\n * - The API is created with custom RPC, types and signed extensions provided by\n * {@link API_RPC}, {@link API_TYPES} and {@link API_EXTENSIONS}.\n * - In non-test environments, the module attaches fatal handlers to the API that call\n * `process.exit(0)` on error/disconnect to allow an external supervisor to restart\n * the process.\n * - The keyring is created for `sr25519` keys. The convenience getter populates a\n * default development account derived from the well-known dev URI `//Bob`\n * (named \"Bob default\"). This is a development-only seed and MUST NOT be used\n * in production.\n */\nimport { ApiPromise, Keyring, WsProvider } from \"@polkadot/api\";\nimport { API_EXTENSIONS, API_RPC, API_TYPES } from \"./spec\";\nimport { provider } from \"./wsProvider\";\nimport { waitReady } from \"@polkadot/wasm-crypto\";\n\n// Create singleton instances\nlet wsProvider: WsProvider | null = null;\nlet api: ApiPromise | null = null;\nlet keyring: Keyring | null = null;\n// Separate keyring instance intended for encryption-related keys/usages.\nlet encKeyring: Keyring | null = null;\n\n/**\n * Lightweight manager that holds and controls the lifecycle of the singleton\n * WsProvider, ApiPromise and Keyring instances.\n *\n * @remarks\n * - Instances are created lazily when {@link RpcApi.connect} is called.\n * - The class maintains simple connection state via `isConnected`, `isConnecting`,\n * and `error` fields so callers can inspect the status without directly\n * interrogating the underlying API/provider.\n * - Event handlers are attached to both the provider and the API to update `error`\n * and `isConnected` appropriately when runtime errors or disconnects occur.\n *\n * @example\n * const rpc = getRpcApi();\n * await rpc.connect(\"wss://example.com\");\n * const { api, keyring } = await rpc.getApi();\n *\n * @public\n */\nexport class RpcApi {\n isConnected: boolean;\n isConnecting: boolean;\n error: string | null;\n \n constructor() {\n this.isConnected = false;\n this.isConnecting = false;\n this.error = null;\n }\n\n /**\n * Establishes a connection to a node at `endpoint` and returns the singleton\n * API and Keyring instances.\n *\n * @param endpoint - WebSocket endpoint URL to connect to (e.g. \"wss://...\").\n * @returns A promise resolving to an object containing the singleton {@link ApiPromise}\n * instance and the singleton {@link Keyring} instance.\n *\n * @remarks\n * - If a connection already exists (`isConnected === true`) the method returns\n * the already-initialized instances without recreating them.\n * - The method sets `isConnecting` to true while establishing the connection and\n * clears it in a `finally` block.\n * - Provider and API event listeners update the instance `error` and `isConnected`\n * fields on runtime errors and disconnects.\n * - The Keyring created here uses `sr25519` keys. If the standalone `getKeyring`\n * helper is used elsewhere, it will additionally add a default development\n * account derived from the well-known dev URI `//Bob` (named \"Bob default\").\n *\n * @throws Will re-throw underlying errors encountered while creating the provider\n * or API. In that case `error` will contain the textual error message.\n */\n async connect(endpoint: string) {\n try {\n if (this.isConnected) {\n return { api, keyring };\n }\n\n this.isConnecting = true;\n this.error = null;\n\n // Create WsProvider only if it doesn't exist\n if (!wsProvider) {\n wsProvider = new WsProvider(endpoint);\n\n // Handle provider events\n wsProvider.on(\"error\", (err) => {\n console.error(\"WsProvider error:\", err);\n this.error = \"WebSocket connection error\";\n this.isConnected = false;\n });\n\n wsProvider.on(\"disconnected\", () => {\n console.log(\"WsProvider disconnected\");\n this.isConnected = false;\n });\n }\n\n // Create API only if it doesn't exist\n if (!api) {\n api = await ApiPromise.create({\n provider: wsProvider,\n rpc: API_RPC,\n types: API_TYPES,\n signedExtensions: API_EXTENSIONS,\n });\n\n // Handle API events\n api.on(\"error\", (err) => {\n console.error(\"API error:\", err);\n this.error = \"API error occurred\";\n });\n\n api.on(\"disconnected\", () => {\n this.isConnected = false;\n });\n }\n\n // Create Keyring only if it doesn't exist\n if (!keyring) {\n keyring = new Keyring({ type: \"sr25519\" });\n }\n\n // Create encryption keyring only if it doesn't exist\n if (!encKeyring) {\n encKeyring = new Keyring({ type: \"ed25519\" });\n }\n\n await api.isReady;\n\n this.isConnected = true;\n return { api, keyring };\n } catch (err) {\n console.error(\"Failed to connect to Polkadot:\", err);\n this.error = err instanceof Error ? err.message : \"Failed to connect to Polkadot\";\n throw err;\n } finally {\n this.isConnecting = false;\n }\n }\n\n /**\n * Gracefully disconnects and nullifies the singleton API, provider and keyring\n * instances managed by this RpcApi instance.\n *\n * @remarks\n * - The method calls `api.disconnect()` and `wsProvider.disconnect()` if they\n * exist, then sets the internal singletons to `null` and `isConnected` to false.\n * - Any error during disconnect is captured in `error`.\n */\n async disconnect() {\n try {\n if (api) {\n await api.disconnect();\n api = null;\n }\n if (wsProvider) {\n await wsProvider.disconnect();\n wsProvider = null;\n }\n keyring = null;\n this.isConnected = false;\n } catch (err) {\n console.error(\"Error disconnecting:\", err);\n this.error = err instanceof Error ? err.message : \"Failed to disconnect\";\n }\n }\n\n getApi() {\n return api;\n }\n\n getKeyring() {\n return keyring;\n }\n\n getEncKeyring() {\n return encKeyring;\n }\n}\n\n/**\n * getApi()\n *\n * Returns the singleton {@link ApiPromise} instance, creating it if necessary.\n *\n * @remarks\n * - If no underlying `provider` is configured (the module-level `provider`\n * imported from \"./wsProvider\"), this function returns `undefined`.\n * - When creating the API, the configured `rpc`, `types` and `signedExtensions`\n * are applied.\n * - In non-test environments, top-level API `error` and `disconnected` events\n * cause the process to exit so that an external supervisor can restart the\n * process.\n *\n * @returns The singleton {@link ApiPromise} instance (or `undefined` if no provider).\n */\nexport async function getApi() {\n if (!provider) return;\n console.debug(provider.endpoint);\n\n if (!api) {\n api = await ApiPromise.create({\n provider,\n rpc: API_RPC,\n types: API_TYPES,\n signedExtensions: API_EXTENSIONS,\n });\n }\n const isNode = typeof process !== \"undefined\" && typeof process.exit === \"function\";\n const isTest = typeof process !== \"undefined\" && process.env?.NODE_ENV === \"test\";\n if (isNode && !isTest) {\n api.on(\"error\", (err) => {\n console.error(\"api error, will restart:\", err);\n process.exit(0);\n });\n api.on(\"disconnected\", () => {\n console.error(\"api disconnected, will restart.\");\n process.exit(0);\n });\n }\n return api;\n}\n\n/**\n * getKeyring()\n *\n * Returns the singleton {@link Keyring} instance, creating it if necessary.\n *\n * @remarks\n * - Ensures {@link waitReady} has resolved before constructing the keyring so\n * that WASM crypto is initialized.\n * - The keyring is created with `type: \"sr25519\"`.\n * - The function also adds a default development account from the dev seed URI\n * `//Bob` and labels it \"Bob default\".\n *\n * @important\n * The seed URI `//Bob` is a well-known development seed. It is convenient for\n * local testing but is insecure for any real funds or production use. Replace\n * or remove this default account when deploying to production.\n *\n * @returns The singleton {@link Keyring} instance.\n */\nexport async function getKeyring() {\n if (!keyring) {\n await waitReady();\n keyring = new Keyring({ type: \"sr25519\" });\n keyring.addFromUri('//Bob', { name: 'Bob default' });\n }\n return keyring;\n}\n\n/**\n * getEncKeyring()\n *\n * Returns the singleton encryption-focused {@link Keyring} instance, creating it\n * if necessary.\n *\n * @remarks\n * - Ensures {@link waitReady} has resolved before constructing the keyring so\n * that WASM crypto is initialized.\n * - The keyring is created with `type: \"sr25519\"` and a development default\n * account derived from the dev seed URI `//Bob` is added and labeled\n * \"Bob default (enc)\".\n *\n * @important\n * The seed URI `//Bob` is a well-known development seed and MUST NOT be used\n * in production for real funds. Replace or remove this default when deploying\n * to production.\n *\n * @returns The singleton {@link Keyring} instance used for encryption keys.\n */\nexport async function getEncKeyring() {\n if (!encKeyring) {\n await waitReady();\n encKeyring = new Keyring({ type: \"ed25519\" });\n encKeyring.addFromUri('//Bob', { name: 'Bob default (enc)' });\n }\n return encKeyring;\n}\n\n// Singleton instance\nlet apiInstance: RpcApi | null = null;\n\n/**\n * Returns the singleton {@link RpcApi} manager instance, creating it on first use.\n *\n * @returns The singleton {@link RpcApi}.\n */\nexport function getRpcApi(): RpcApi {\n if (!apiInstance) {\n apiInstance = new RpcApi();\n }\n return apiInstance;\n}\n","import { WsProvider } from \"@polkadot/api\";\nimport { PALLIORA_WS } from \"../config\";\n\nexport const provider = new WsProvider(PALLIORA_WS, 10000);\n","import { TX_WAIT_FINALIZATION } from \"../config\";\nimport { getApi } from \"./singleton\";\nimport { isFunction } from \"@polkadot/util\";\nimport { DEFAULT_COMPUTE_PAYLOAD } from \"./spec\";\nimport bs58 from \"bs58\";\nimport { getGuardianList } from \"../guardian\";\nimport { assert } from \"../utils\";\n\nexport const signAndSend = async (request: any, account: any, opts = DEFAULT_COMPUTE_PAYLOAD) => {\n const tx_result: any = await new Promise((res, err) => {\n request.signAndSend(account, opts, (result: any) => {\n // console.trace(result.toHuman());\n if (result.isFinalized) {\n res(result);\n }\n if (!TX_WAIT_FINALIZATION && result.isInBlock) {\n res(result);\n }\n if (result.isError) err(result);\n });\n });\n // console.trace(tx_result.toHuman());\n\n if (tx_result.isError) {\n throw new Error(`Transaction failed with error: ${tx_result.error}`);\n }\n\n if (tx_result.dispatchError) {\n throw new Error(\n `Transaction dispatched with error: ${tx_result.dispatchError}`\n );\n }\n\n console.debug(\n `Transaction ${tx_result.txHash.toHex()} included in timepoint ${\n tx_result.blockNumber\n }-${tx_result.txIndex}`\n );\n\n return {\n blockNumber: tx_result?.blockNumber?.toNumber(),\n index: tx_result?.txIndex,\n hash: tx_result.txHash.toHex(),\n tx_result,\n };\n};\n\nexport const getFileMetadataCall = async (\n api: any,\n metadataRef: [number, number]\n) => {\n const block = await getBlock(api, metadataRef[0]);\n const call = block.block.extrinsics[metadataRef[1]];\n return call.method;\n};\n\nconst getBlock = async (api: any, blockNumber: number) => {\n const blockHash = await api.rpc.chain.getBlockHash(blockNumber);\n return await api.rpc.chain.getBlock(blockHash);\n};\n\nexport const getGuardianAddress = async () => {\n const api = await getApi();\n\n if (!api) throw new Error(\"API not initialized\");\n assert(\n isFunction(api.query[\"guardian\"]?.[\"worker\"]),\n `api.query.guardian.worker does not exist`,\n );\n\n const list = await getGuardianList();\n\n const addresses = await Promise.all(\n list.map(async (item) => {\n const peerid = bs58.decode(item).slice(0, 32);\n return ((await api.query[\"guardian\"][\"worker\"](peerid)).toString());\n })\n );\n\n return list.map((peerid, index) => ({ peerid, address: addresses[index] }));\n};\n\nexport const getGuardianNwParams = async () => {\n try {\n const api = await getApi();\n if (!api) throw new Error(\"API not initialized\");\n\n const rpc = api.rpc as unknown as Record<\n string,\n Record<string, (...params: unknown[]) => Promise<unknown>>\n >;\n const section = \"guardian\";\n const method = \"guardianNwParams\";\n\n assert(\n isFunction(rpc[section]?.[method]),\n `api.rpc.${section}.guardianNwParams does not exist`\n );\n\n const guardianNwParams = (await rpc[section][method]()) as Record<\n string,\n unknown\n >;\n if (\n typeof guardianNwParams === \"object\" &&\n guardianNwParams !== null &&\n \"kzg\" in guardianNwParams\n ) {\n return (guardianNwParams.kzg as any).toHex().slice(2);\n } else {\n throw new Error(`Invalid ${guardianNwParams} format`);\n }\n } catch (error) {\n console.error({ error });\n throw error;\n }\n};\n","import { getApi } from \"../chain\";\nimport { isFunction } from \"@polkadot/util\";\nimport { assert } from \"../utils\";\n\nexport const getGuardianList = async () => {\n const api = await getApi();\n if (!api) throw new Error(\"API not initialized\");\n\n const rpc = api.rpc as unknown as Record<\n string,\n Record<string, (...params: unknown[]) => Promise<unknown>>\n >;\n const section = \"guardian\";\n const method = \"guardianList\";\n\n assert(\n isFunction(rpc[section]?.[method]),\n `api.rpc.${section}.${method} does not exist`,\n );\n\n const list = ((await rpc[section][\"guardianList\"]()) as Array<Text>)\n .map((item) => [item.toString()])\n .flat(1);\n\n return list;\n};\n","import { getApi, getGuardianNwParams, signAndSend } from \"../chain\";\nimport { hexToUint8Array, debugLog, assert } from \"../utils\";\n\nexport const createGuardianGroup = async (account: any, selectedGuardians: any) => {\n try {\n const api = await getApi();\n\n assert(selectedGuardians.length >= 3, \"Not enough guardians available to create a group\");\n assert(account, \"Failed to load account\");\n assert(api, \"Failed to initialize API\");\n\n const tau_params = await getGuardianNwParams();\n assert(tau_params && tau_params !== \"\", \"Failed to retrieve guardian network parameters\");\n\n // For simplicity, select the first 3 guardians\n debugLog(`Selected guardians: ${selectedGuardians.join(\", \")} and tau_params: ${tau_params}`);\n\n // Create and send the transaction\n const tx = api.tx.dataAvailability.daccGuardianGroup(\n selectedGuardians,\n Array.from(hexToUint8Array(tau_params)) // Use the new helper function\n );\n const result = await signAndSend(tx, account);\n\n debugLog(\"Guardian group created:\", result);\n } catch (error) {\n console.error(\"Error creating guardian group:\", error);\n throw new Error(`Failed to create guardian group: ${error instanceof Error ? error.message : error}`);\n }\n};\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\n\nexport async function joinGuardian(account: any, prefs: any) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n const computeOpts =\n (prefs.compute as string | undefined)\n ?.split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0) || undefined;\n\n const guardianPrefs = {\n pubKey: account.publicKey,\n guardian: prefs.standard,\n verifier: prefs.verifier,\n compute: prefs.compute ? true : false,\n computePrefs: {\n trusted: computeOpts?.includes(\"trusted\") || false,\n tee: computeOpts?.includes(\"tee\") || false,\n mpc: computeOpts?.includes(\"mpc\") || false,\n fhe: computeOpts?.includes(\"fhe\") || false,\n zkp: computeOpts?.includes(\"zkp\") || false,\n },\n };\n\n debugLog(\n account.address,\n \"joining as guardian with preferences:\",\n guardianPrefs\n );\n\n const guardTx = api.tx.staking.guard(guardianPrefs);\n const hash = await signAndSend(guardTx, account);\n\n debugLog(\"Guardian join tx sent with hash:\", hash.hash);\n}\n","\nimport { ApiPromise } from \"@polkadot/api\";\nimport { testCrypt } from \"../crypto/core\";\nimport { encrypt, gen_stretched_key } from \"../crypto/cipher\";\nimport { hexToUint8Array, uint8ArrayToBase64 } from \"../utils\";\nimport type { Hex } from \"viem\";\nimport { signAndSend } from \"./utils\";\n\ntype OnChainFileOptions = {\n\tfile: File;\n\tfilePath: string,\n\tfileName: string;\n\tdescription: string;\n\tbaseCost: bigint;\n\townerL2Address: string;\n\tguardianInfo: any;\n}\n\nconst getBlock = async (api: ApiPromise, blockNumber: number) => {\n\tconst blockHash = await api.rpc.chain.getBlockHash(blockNumber);\n\treturn await api.rpc.chain.getBlock(blockHash);\n};\nconst getFileMetadataCall = async (api: ApiPromise, metadataRef: any) => {\n\tconst block = await getBlock(api, metadataRef[0]);\n\tconst call = block.block.extrinsics[metadataRef[1]];\n\treturn call.method;\n};\n\nconst getFileMetadata = async (api: ApiPromise, metadataRef: any) => {\n\tconst call = await getFileMetadataCall(api, metadataRef);\n\n\t// @ts-expect-error\n\tconst name = new TextDecoder().decode(call.args[0]);\n\t// @ts-expect-error\n\tconst description = new TextDecoder().decode(call.args[1]);\n\t// @ts-expect-error\n\tconst startRef = [call.args[2][0].toNumber(), call.args[2][1].toNumber()];\n\n\treturn {\n\t\tname,\n\t\tdescription,\n\t\tstartRef,\n\t};\n};\n\nasync function getFileSHA256(file: File): Promise<string> {\n\tconst buffer = new Array(12).fill(8);\n\t// const hashBuffer = await crypto.subtle.digest(\"SHA-256\", buffer);\n\tconst hashArray = Array.from(new Uint8Array(buffer));\n\tconst hashHex = hashArray.map(b => b.toString(16).padStart(2, \"0\")).join(\"\");\n\treturn hashHex;\n\n}\n\nconst readDataFromChain = async (api: ApiPromise, dataRef: any) => {\n\tconst call = await getFileMetadataCall(api, dataRef);\n\treturn call.args[0].toU8a();\n};\n\nclass MCryptFs {\n\t_api;\n\t_init;\n\t_metaRef;\n\t_metadata;\n\t_chunkRefs: any;\n\t_startRef: any;\n\n\tconstructor(mcryptApi: any, metadataRef: any, metadata: any) {\n\t\tthis._api = mcryptApi;\n\t\tthis._metaRef = metadataRef;\n\t\tthis._metadata = metadata;\n\t\tthis._init = true;\n\t}\n\n\tstatic dummyInstance(mcryptApi: any) {\n\t\treturn new MCryptFs(mcryptApi, null, {\n\t\t\tname: \"on-chain-file-name.txt\",\n\t\t\tdescription: \"File uploaded using mcrypt-onchain-fs\",\n\t\t});\n\t}\n\n\tisValid() {\n\t\tif (!this._metaRef) {\n\t\t\tthrow new Error(\"Metadata reference not set\");\n\t\t}\n\n\t\tif (\n\t\t\t!this._metadata ||\n\t\t\t!this._metadata.name ||\n\t\t\t!this._metadata.description ||\n\t\t\t!this._metadata.startRef\n\t\t) {\n\t\t\tthrow new Error(\"Metadata not set properly\");\n\t\t}\n\t}\n\n\tgetMetadata() {\n\t\tthis.isValid();\n\t\treturn this._metadata;\n\t}\n}\n\nclass MCryptFsWriter {\n\t_file;\n\t_filePath;\n\t_description;\n\t_chunkSize;\n\t_fileKey: string;\n\t_fileName: string;\n\t_baseCost;\n\t_ownerL2Address;\n\t_guardianInfo: any;\n\t_api;\n\t_account: any;\n\t_chunkRefs: any[];\n\t_blockNumber;\n\t_extrinsicIndex;\n\t_progress;\n\t_error: any;\n\n\tconstructor(fileOptions: OnChainFileOptions, chunkSize = 500, mcryptApi: any, account: any) {\n\t\tconst {\n\t\t\tfile: iFile,\n\t\t\tfilePath,\n\t\t\tfileName,\n\t\t\tdescription,\n\t\t\tbaseCost,\n\t\t\townerL2Address,\n\t\t\tguardianInfo,\n\t\t} = fileOptions;\n\n\t\tthis._file = iFile;\n\t\tthis._filePath = filePath;\n\t\tthis._description = description;\n\t\tthis._fileName = fileName;\n\t\tthis._baseCost = baseCost;\n\t\tthis._fileKey = \"\";\n\t\tthis._ownerL2Address = ownerL2Address;\n\t\tthis._guardianInfo = guardianInfo;\n\t\tthis._chunkSize = chunkSize * 1024;\n\t\tthis._api = mcryptApi;\n\t\tthis._account = account;\n\n\t\tthis._chunkRefs = [];\n\t\tthis._blockNumber = 0;\n\t\tthis._extrinsicIndex = 0;\n\n\t\tthis._progress = {\n\t\t\tiFileSize: iFile.size,\n\t\t\tiBlocksWritten: 0,\n\t\t};\n\n\t\tthis._error = null;\n\t}\n\n\tprependMetadata(chunk: any) {\n\t\tconst blockNumberBuffer = new ArrayBuffer(4);\n\t\tconst blockView = new DataView(blockNumberBuffer);\n\t\tblockView.setUint32(0, this._blockNumber, false);\n\n\t\tconst extIndexBuffer = new ArrayBuffer(4);\n\t\tconst extView = new DataView(extIndexBuffer);\n\t\textView.setUint32(0, this._extrinsicIndex, false);\n\n\t\treturn new Blob([blockNumberBuffer, extIndexBuffer, chunk]);\n\t}\n\n\tasync writeChunk(chunk: any) {\n\t\tconst request = this._api.tx.dataAvailability.submitData(\n\t\t\tArray.from(new Uint8Array(await chunk.arrayBuffer()))\n\t\t);\n\t\tconsole.log(\"account: \", this._account);\n\t\treturn new Promise((resolve) => {\n\t\t\trequest.signAndSend(this._account, { app_id: 1 }, (result: any) => {\n\t\t\t\tif (result.isInBlock || result.isFinalized || result.isError) {\n\t\t\t\t\tresolve({\n\t\t\t\t\t\tblockNumber: result.blockNumber?.toNumber(),\n\t\t\t\t\t\tindex: result.txIndex,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\tasync submitKey(account: any, data: any) {\n\t\tconst { encoded: encryptedKey, ikm } = testCrypt(this._guardianInfo.tauParams, this._guardianInfo.aggKey);\n\n\t\tconst td_params = uint8ArrayToBase64(hexToUint8Array(encryptedKey as Hex));\n\t\tconst shared_key = gen_stretched_key(\n\t\t\thexToUint8Array(ikm as Hex),\n\t\t);\n\t\tconst { ciphertext, nonce } = encrypt(\n\t\t\tnew Uint8Array(Uint8Array.from(data)),\n\t\t\tshared_key\n\t\t);\n\t\tconst blobRef = this._chunkRefs[this._chunkRefs.length - 1];\n\n\t\tconst modelSubmit = JSON.stringify({\n\t\t\tnonce: uint8ArrayToBase64(Uint8Array.from(nonce)),\n\t\t\tciphertext: uint8ArrayToBase64(Uint8Array.from(ciphertext)),\n\t\t\ttd_params,\n\t\t\tgroup_pk: this._guardianInfo.groupPk,\n\t\t\ttau_params: this._guardianInfo.tau_params,\n\t\t\tchosen_guardians: this._guardianInfo.guardians,\n\t\t\tblobRef: [blobRef.blockNumber, blobRef.extrinsicIndex],\n\t\t});\n\n\t\tconst request = this._api.tx.dataAvailability.submitData(modelSubmit);\n\t\treturn await signAndSend(request, account);\n\t}\n\n\tasync writeMetadata() {\n\n\t\tconst encoder = new TextEncoder();\n\t\tconst fileName = this._fileName;\n\t\tconst datasetRef = await this.submitKey(this._account, this._fileKey);\n\t\tconst keyRef = [datasetRef.blockNumber, datasetRef.index];\n\t\tconst request = this._api.tx.dataAvailability.daccRegisterData(\n\t\t\tArray.from(new TextEncoder().encode(fileName)),\n\t\t\tArray.from(new TextEncoder().encode(this._description)),\n\t\t\tkeyRef,\n\t\t\tthis._baseCost,\n\t\t\t0,\n\t\t\tArray.from(encoder.encode(this._ownerL2Address)),\n\t\t\tthis._guardianInfo.groupId,\n\t\t);\n\n\t\treturn await signAndSend(request, this._account);\n\t}\n\n\tasync writeFile() {\n\t\tconst chunks = [];\n\t\tlet offset = 0;\n\n\t\twhile (offset < this._file.size) {\n\t\t\tconst chunk = this._file.slice(offset, offset + this._chunkSize);\n\t\t\tconst prependedChunk = this.prependMetadata(chunk);\n\t\t\tconst blockInfo = await this.writeChunk(prependedChunk);\n\n\t\t\tthis._blockNumber = (blockInfo as any).blockNumber;\n\t\t\tthis._extrinsicIndex = (blockInfo as any).index;\n\t\t\tthis._progress.iBlocksWritten += chunk.size;\n\t\t\tthis._chunkRefs.push({\n\t\t\t\tblockNumber: this._blockNumber,\n\t\t\t\textrinsicIndex: this._extrinsicIndex,\n\t\t\t});\n\n\t\t\toffset += this._chunkSize;\n\t\t}\n\n\t\tthis._fileKey = (await getFileSHA256(this._file)) as string;\n\t\tconst metadataRef = await this.writeMetadata();\n\t\treturn await FileFromMetadataRef(this._api, [\n\t\t\t(metadataRef as any).blockNumber,\n\t\t\t(metadataRef as any).index,\n\t\t]);\n\t}\n}\n\nclass MCryptFsReader {\n\t_filename;\n\t_api;\n\t_onChainFile;\n\n\tconstructor(filename: string, mcryptApi: any, onChainFile: any) {\n\t\tthis._filename = filename;\n\t\tthis._api = mcryptApi;\n\t\tthis._onChainFile = onChainFile;\n\t}\n\n\tasync downloadFile() {\n\t\tconst chunks = [];\n\n\t\tlet _blockNumber = this._onChainFile._metadata.startRef[0];\n\t\tlet _extIndex = this._onChainFile._metadata.startRef[1];\n\n\t\twhile (_blockNumber !== 0) {\n\t\t\tconst prependedChunk = await readDataFromChain(this._api, [\n\t\t\t\t_blockNumber,\n\t\t\t\t_extIndex,\n\t\t\t]);\n\t\t\tconst chunk = prependedChunk.slice(12);\n\t\t\tchunks.push(chunk);\n\n\t\t\tconst view = new DataView(new Uint8Array(prependedChunk).buffer);\n\t\t\t_blockNumber = view.getUint32(4);\n\t\t\t_extIndex = view.getUint32(8);\n\t\t}\n\n\t\t// Combine all chunks into a single blob\n\t\tconst blob = new Blob(chunks.reverse());\n\n\t\t// Create download link\n\t\tconst url = URL.createObjectURL(blob);\n\t\tconst a = document.createElement(\"a\");\n\t\ta.href = url;\n\t\ta.download = this._filename;\n\t\tdocument.body.appendChild(a);\n\t\ta.click();\n\t\tdocument.body.removeChild(a);\n\t\tURL.revokeObjectURL(url);\n\n\t\treturn blob;\n\t}\n}\n\nconst FileFromMetadataRef = async (mcryptApi: any, metadataRef: any) => {\n\tconst metadata = await getFileMetadata(mcryptApi, metadataRef);\n\treturn new MCryptFs(mcryptApi, metadataRef, metadata);\n};\n\nexport { MCryptFs, MCryptFsWriter, MCryptFsReader, FileFromMetadataRef };\n","import bs58 from \"bs58\";\nimport { getApi, getKeyring, signAndSend } from \"../chain\";\nimport { getGuardianList } from \"../guardian\";\nimport { assert, debugLog } from \"../utils\";\n\nexport async function createAgreement() {\n const api = await getApi();\n if (!api) throw new Error(\"Api not initialized\");\n\n const tx = (api.tx as any).compute.agreement();\n const guardians = await getGuardianList();\n const agreement = guardians\n .slice(0, 3)\n .map((g) => bs58.decode(g).subarray(6));\n assert(agreement.length === 3, \"Not enough guardians to create agreement\");\n\n const keyring = await getKeyring();\n const account = keyring.getPairs()[0];\n\n const { tx_result } = await signAndSend(tx, account, {\n compute: { da_type: 1, agreement, verification: 0, compute: 1 },\n } as any);\n\n if (!tx_result.isError) {\n const agreementCreatedEvent = tx_result.events.find((event: any) => {\n return (\n event.event.section === \"compute\" &&\n event.event.method === \"AgreementCreated\"\n );\n });\n\n if (agreementCreatedEvent) {\n debugLog(\n \"Agreement data:\",\n agreementCreatedEvent.event.data.toString(),\n );\n } else {\n debugLog(\"AgreementCreated event not found\");\n }\n }\n}\n\nexport default createAgreement;\n","import bs58 from 'bs58';\nimport { getApi } from '../chain';\n\nexport async function getGuardianParticipants(): Promise<any> {\n\tconst api = await getApi();\n\tif (!api) throw new Error('Api not initialized');\n\n\ttry {\n\t\tconst guardians = await api.query.guardian.guardians();\n\t\tconst nextGuardians = await api.query.guardian.nextGuardians();\n\t\tconst currentEra = await api.query.staking.currentEra();\n\t\tconst currentIndex = await api.query.guardian.currentIndex();\n\t\tconst peerid = await api.rpc.system.localPeerId();\n\t\tconst _peerid = bs58.decode((peerid || '').toString());\n\t\tconst account = await api.query.guardian.worker(_peerid.slice(0, 32));\n\t\tconst nextIndex = currentIndex ? Number(currentIndex) + 1 : 1;\n\n\t\tconst guardiansList = (guardians?.toJSON() || []) as any[];\n\t\tconst nextGuardiansList = (nextGuardians?.toJSON() || []) as any[];\n\n\t\tconst buildDetails = async (list: any[]) => {\n\t\t\treturn Promise.all(\n\t\t\t\tlist.map(async (guardian: any) => {\n\t\t\t\t\tconst guardianPrefs = await api.query.staking.guardians(guardian);\n\t\t\t\t\tconst ledger = await api.query.staking.ledger(guardian);\n\t\t\t\t\tconst bonded = await api.query.staking.bonded(guardian);\n\t\t\t\t\tconst payee = await api.query.staking.payee(guardian);\n\t\t\t\t\tconst stakersOverview = await api.query.staking.erasStakersOverview(\n\t\t\t\t\t\tcurrentEra?.toPrimitive(),\n\t\t\t\t\t\tguardian,\n\t\t\t\t\t);\n\t\t\t\t\tconst guardianErasPrefs = await api.query.staking.erasGuardianPrefs(\n\t\t\t\t\t\tcurrentEra?.toPrimitive(),\n\t\t\t\t\t\tguardian,\n\t\t\t\t\t);\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tguardian,\n\t\t\t\t\t\trewardDestination: payee?.toHuman ? payee.toHuman() : null,\n\t\t\t\t\t\tcurrentPreferences: (guardianErasPrefs?.toHuman ? guardianErasPrefs.toHuman() : null),\n\t\t\t\t\t\tupcomingPreferences: (guardianPrefs?.toHuman ? guardianPrefs.toHuman() : null),\n\t\t\t\t\t\tstash: bonded?.toHuman ? bonded.toHuman() : null,\n\t\t\t\t\t\tcurrentStakeOverview: stakersOverview?.toHuman ? stakersOverview.toHuman() : null,\n\t\t\t\t\t\tupcomingStakeOverview: ledger?.toHuman ? ledger.toHuman() : null,\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t);\n\t\t};\n\n\t\tconst currentGuardians = await buildDetails(guardiansList);\n\t\tconst upcomingGuardians = await buildDetails(nextGuardiansList);\n\n\t\treturn {\n nwState: {\n localPeerId: peerid?.toString(),\n worker: account?.toHuman ? account.toHuman() : null,\n currentEra: currentEra?.toHuman ? currentEra.toHuman() : null,\n guardians: JSON.stringify(guardians?.toHuman ? guardians.toHuman() : null, null, 2),\n nextGuardians: JSON.stringify(nextGuardians?.toHuman ? nextGuardians.toHuman() : null, null, 2),\n currentIndex: currentIndex?.toHuman ? currentIndex.toHuman() : null,\n nextIndex,\n },\n\t\t\tcurrentGuardians,\n\t\t\tupcomingGuardians,\n\t\t};\n\t} finally {\n\t\tapi.disconnect();\n\t}\n}\n\nexport default getGuardianParticipants;\n\n","/**\n * Generates random bytes of the specified length.\n * Uses Web Crypto API (crypto.getRandomValues) - available in all modern browsers\n * and Node.js 18+.\n *\n * @param length Number of bytes.\n * @returns Uint8Array containing random bytes.\n */\nexport function generateRandomBytes(length: number = 32): Uint8Array {\n const bytes = new Uint8Array(length);\n const cr = globalThis.crypto;\n if (!cr || typeof cr.getRandomValues !== \"function\") {\n throw new Error(\n \"crypto.getRandomValues is not available. Ensure you're running in a supported environment (browser or Node.js 18+).\"\n );\n }\n cr.getRandomValues(bytes);\n return bytes;\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\nimport { OnChainRef } from \"./types\";\n\nexport async function writeMetadata(\n account: any,\n name: string,\n description: string,\n ref: OnChainRef,\n price: bigint,\n dataType: number,\n l2Owner: string,\n groupId: string,\n) {\n const blobRef = [ref.blockNumber, ref.index];\n const encoder = new TextEncoder();\n const nameBytes = Array.from(encoder.encode(name));\n const descriptionBytes = Array.from(encoder.encode(description));\n const ownerBytes = Array.from(encoder.encode(l2Owner));\n\n const api = await getApi();\n assert(api, \"Failed to get API connection\");\n\n const request = api.tx.dataAvailability.daccRegisterData(\n nameBytes,\n descriptionBytes,\n blobRef,\n price,\n dataType,\n ownerBytes,\n groupId,\n );\n\n const hash = await signAndSend(request, account);\n\n debugLog(`Metadata registration transaction sent with hash: ${hash.hash}`);\n\n return hash;\n}\n","import { DEFAULT_EMPTY_PAYLOAD, getApi, signAndSend } from \"../chain\";\nimport { encrypt, gen_stretched_key, testCrypt } from \"../crypto\";\nimport {\n assert,\n debugLog,\n Hex,\n hexToUint8Array,\n uint8ArrayToBase64,\n} from \"../utils\";\nimport { OnChainRef } from \"./types\";\n\nexport async function submitData(account: any, data: string) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n\n debugLog(`\\nSubmitting data with content length: ${data.length}`);\n\n const tx = api.tx.dataAvailability.submitData(data);\n const hash = await signAndSend(tx, account, DEFAULT_EMPTY_PAYLOAD);\n\n debugLog(`Data availability transaction sent with hash: ${hash.hash}`);\n}\n\nexport async function submitTEData(\n account: any,\n data: string,\n chosenGuardians: any[],\n tau_params: string,\n agg_key: string,\n group_pk: string,\n): Promise<OnChainRef> {\n const { encoded: encryptedKey, ikm } = testCrypt(tau_params, agg_key);\n const td_params = uint8ArrayToBase64(hexToUint8Array(encryptedKey as Hex));\n const shared_key = gen_stretched_key(hexToUint8Array(ikm as Hex));\n\n const encoder = new TextEncoder();\n const dataUint8Array = encoder.encode(data);\n const { ciphertext, nonce } = encrypt(dataUint8Array, shared_key);\n\n const modelSubmit = JSON.stringify({\n nonce: uint8ArrayToBase64(nonce),\n ciphertext: uint8ArrayToBase64(ciphertext),\n td_params,\n group_pk: Array.from(new Uint8Array(hexToUint8Array(group_pk as Hex))),\n tau_params: Array.from(new Uint8Array(hexToUint8Array(tau_params as Hex))),\n chosen_guardians: chosenGuardians,\n });\n\n const api = await getApi();\n assert(api, \"Failed to get API connection\");\n\n const request = await api.tx.dataAvailability.submitData(modelSubmit);\n const hash = await signAndSend(request, account, DEFAULT_EMPTY_PAYLOAD);\n\n debugLog(`TE data availability transaction sent with hash: ${hash.hash}`);\n\n return hash;\n}\n","import fs from \"fs\";\nimport path from \"path\";\nimport { getApi, getKeyring, MCryptFsWriter } from \"../chain\";\nimport { assert } from \"../utils\";\nimport { UploadOptions } from \"./types\";\nimport { submitTEData } from \"./submit\";\nimport { writeMetadata } from \"./register\";\n\nexport async function uploadData(options: UploadOptions) {\n const { name, description, price, type, guardianGroupInfo, ref, filePath } =\n options;\n\n assert(\n guardianGroupInfo.guardians &&\n guardianGroupInfo.tauParams &&\n guardianGroupInfo.aggKey &&\n guardianGroupInfo.groupPk,\n \"Guardian group info is missing required properties\",\n );\n\n const account = (await getKeyring()).pairs[0];\n const ethAddress = \"\";\n\n if (type === \"dataset\" && filePath) {\n const fileContent = fs.readFileSync(filePath);\n const selectedFile = new File([fileContent], path.basename(filePath), {\n type: \"application/octet-stream\",\n lastModified: Date.now(),\n });\n\n const msCryptFsWriter = new MCryptFsWriter(\n {\n file: selectedFile,\n fileName: selectedFile.name,\n filePath: \"\",\n description,\n baseCost: BigInt(Number(price) * 10 ** 18),\n ownerL2Address: ethAddress,\n guardianInfo: guardianGroupInfo,\n },\n 500,\n await getApi(),\n account,\n );\n\n await msCryptFsWriter.writeFile();\n } else {\n const dataRef = await submitTEData(\n account,\n ref || \"\",\n guardianGroupInfo.guardians,\n guardianGroupInfo.tauParams,\n guardianGroupInfo.aggKey,\n guardianGroupInfo.groupPk,\n );\n\n const dtype = type === \"model\" ? 1 : type === \"agent\" ? 2 : 0;\n await writeMetadata(\n account,\n name,\n description,\n dataRef,\n BigInt(Number(price) * 10 ** 18),\n dtype,\n ethAddress,\n guardianGroupInfo.groupId,\n );\n }\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\n\nexport async function addStake(account: any, amount: bigint) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n debugLog(\"Using account:\", account.address);\n\n const stakeTx = api.tx.staking.bondExtra(amount);\n const hash = await signAndSend(stakeTx, account);\n\n debugLog(`Stake transaction sent with hash: ${hash.hash}`);\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\n\nexport async function joinIdleStaker(account: any) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n const chillTx = api.tx.staking.chill();\n const hash = await signAndSend(chillTx, account);\n\n debugLog(\"Idle staker chill tx sent with hash:\", hash.hash);\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\n\nexport async function newStake(\n account: any,\n amount: bigint,\n rewardDestination: string = \"Staked\"\n) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n debugLog(\n `Staking amount: ${amount} for account: ${account.address} with reward destination: ${rewardDestination}`\n );\n\n const stakeTx = api.tx.staking.bond(amount, rewardDestination);\n const hash = await signAndSend(stakeTx, account);\n\n debugLog(`Stake transaction sent with hash: ${hash.hash}`);\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\n\nexport async function payoutStake(account: any, eras: Array<number>, address?: string) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n for (const era of eras) {\n debugLog(\"Paying account: \", address || account.address, \" for era \", era);\n }\n\n const unstakeTxs = eras.map((era) =>\n api.tx.staking.payoutStakers(address || account.address, era)\n );\n const batchTx = api.tx.utility.batch(unstakeTxs);\n const hash = await signAndSend(batchTx, account);\n\n debugLog(`Batch payout transaction sent with hash: ${hash.hash}`);\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\n\nexport async function reduceStake(account: any, amount: bigint) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n debugLog(\"Using account:\", account.address);\n\n const unstakeTx = api.tx.staking.unbond(amount);\n const hash = await signAndSend(unstakeTx, account);\n\n debugLog(`Unstake transaction sent with hash: ${hash.hash}`);\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\n\nexport async function removeStake(account: any) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n const stakeAmount: any = (await api.query.staking.ledger(account.address))?.toPrimitive();\n\n debugLog(\"Removing entire stake amount:\", stakeAmount?.active || 0n);\n\n const unstakeTx = api.tx.staking.unbond(stakeAmount?.active || 0n);\n const hash = await signAndSend(unstakeTx, account);\n\n debugLog(`Unstake transaction sent with hash: ${hash.hash}`);\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\n\nexport async function withdrawStake(account: any) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n const unstakeTx = api.tx.staking.withdrawUnbonded(0);\n const hash = await signAndSend(unstakeTx, account);\n\n debugLog(`Unstake transaction sent with hash: ${hash.hash}`);\n}\n","import { getApi, getKeyring, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\n\nexport async function fundAccount(account: any, amount: bigint, address?: string) {\n const addr = address ? address : account.address;\n const keyring = await getKeyring();\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n\n debugLog(`\\nFunding account: ${addr} with amount: ${amount}`);\n\n const tx = api.tx.balances.transferKeepAlive(addr, amount);\n const hash = await signAndSend(tx, keyring.getPairs()[0]);\n\n debugLog(`Fund transaction sent with hash: ${hash.hash}`);\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\n\nexport async function transfer(account: any, amount: bigint, address: string) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n\n debugLog(`\\nTransferring funds to account: ${address} with amount: ${amount}`);\n\n const tx = api.tx.balances.transferKeepAlive(address, amount);\n const hash = await signAndSend(tx, account);\n\n debugLog(`Transfer transaction sent with hash: ${hash.hash}`);\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\n\nexport async function joinValidator(account: any, commission: number) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n const validateTx = api.tx.staking.validate({commission, blocked: true});\n const hash = await signAndSend(validateTx, account);\n\n debugLog(\"Validator join tx sent with hash:\", hash.hash);\n}\n","import assert from \"assert\";\nimport { getApi, signAndSend } from \"./chain\";\nimport { debugLog } from \"./utils/helper\";\n\nexport async function setIdentity(account: any, {display = undefined}: any) {\n\tconst api = await getApi();\n\n\tassert(api, \"API not initialized\");\n\n\tdebugLog(`\\nSetting identity for account: ${account.address} as ${display}`);\n\n\tconst tx = api.tx.identity.setIdentity({display: {Raw: display}});\n\tconst hash = await signAndSend(tx, account);\n\n\tdebugLog(`Set identity transaction sent with hash: ${hash.hash}`);\n}\n\n","import { getApi, provider, signAndSend } from \"./chain\";\nimport bs58 from 'bs58';\nimport { debugLog } from \"./utils/helper\";\nimport assert from \"assert\";\n\nexport async function rotateAndSetKeys(account: any) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n\n debugLog(`Rotating session keys for ${account.meta.name} on ${provider.endpoint}`);\n\n const newKeys = await api.rpc.author.rotateKeys();\n debugLog(`${account.meta.name} rotated keys on ${provider.endpoint}:`, newKeys?.toHex?.() ?? newKeys);\n\n const setKeysTx = api.tx.session.setKeys(newKeys, []);\n const hash = await signAndSend(setKeysTx, account);\n\n debugLog(`Rotate session transaction sent with hash: ${hash.hash}`);\n}\n\nexport async function setWorker(account: any) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n\n const peerid = bs58.decode((await api.rpc.system.localPeerId()).toString());\n const setWorkerTx = api.tx.guardian.setWorker(peerid.slice(0, 32));\n const hash = await signAndSend(setWorkerTx, account);\n\n debugLog(`Set worker id transaction sent with hash: ${hash.hash}`);\n}","export * from \"./account\";\nexport * from \"./chain\";\nexport * from \"./compute\";\nexport * from \"./crypto\";\nexport * from \"./da\";\nexport * from \"./guardian\";\nexport * from \"./stake\";\nexport * from \"./token\";\nexport * from \"./utils/helper\";\nexport * from \"./utils/token\";\nexport * from \"./validator\";\nexport * from \"./config\";\nexport * from \"./identity\";\nexport * from \"./rotateKeys\";\n\nexport * from \"@polkadot/util\";\nexport * as utilCrypto from \"@polkadot/util-crypto\";\nexport * as wasmCrypto from \"@polkadot/wasm-crypto\";\nexport { ApiPromise, WsProvider, HttpProvider } from \"@polkadot/api\";\n"]}
|
|
1
|
+
{"version":3,"sources":["/Users/shivanshxyz/repos/labyrinth/manas/palliora-sdk/dist/index.cjs","../src/account/account.ts","../src/account/types.ts","../src/chain/spec.ts","../src/crypto/core.ts","../src/crypto/cipher.ts","../src/utils/assert.ts","../src/config.ts","../src/utils/helper.ts","../src/utils/token.ts","../src/chain/singleton.ts","../src/chain/wsProvider.ts","../src/chain/utils.ts","../src/guardian/active.ts","../src/guardian/group.ts","../src/guardian/join.ts","../src/chain/onchainfs.ts","../src/compute/agreement.ts","../src/compute/data.ts","../src/compute/inference.ts","../src/compute/participants.ts","../src/compute/simple.ts","../src/crypto/random.ts","../src/da/register.ts","../src/da/runAgent.ts","../src/da/submit.ts","../src/da/upload.ts","../src/stake/add.ts","../src/stake/idle.ts","../src/stake/new.ts","../src/stake/payout.ts","../src/stake/reduce.ts","../src/stake/remove.ts","../src/stake/withdraw.ts","../src/token/fund.ts","../src/token/transfer.ts","../src/validator/join.ts","../src/identity.ts","../src/rotateKeys.ts","../src/index.ts"],"names":["CryptoType","AccountSourceType","keyring"],"mappings":"AAAA;ACAA,0GAA0B;ADE1B;AACA;AEHA,IAAK,WAAA,kBAAL,CAAA,CAAKA,WAAAA,EAAAA,GAAL;AACE,EAAAA,WAAAA,CAAA,SAAA,EAAA,EAAU,SAAA;AACV,EAAAA,WAAAA,CAAA,SAAA,EAAA,EAAU,SAAA;AACV,EAAAA,WAAAA,CAAA,OAAA,EAAA,EAAQ,OAAA;AAHL,EAAA,OAAAA,WAAAA;AAAA,CAAA,CAAA,CAAA,WAAA,GAAA,CAAA,CAAA,CAAA;AAML,IAAK,kBAAA,kBAAL,CAAA,CAAKC,kBAAAA,EAAAA,GAAL;AACE,EAAAA,kBAAAA,CAAA,aAAA,EAAA,EAAc,YAAA;AACd,EAAAA,kBAAAA,CAAA,MAAA,EAAA,EAAO,MAAA;AACP,EAAAA,kBAAAA,CAAA,UAAA,EAAA,EAAW,UAAA;AACX,EAAAA,kBAAAA,CAAA,SAAA,EAAA,EAAU,SAAA;AACV,EAAAA,kBAAAA,CAAA,SAAA,EAAA,EAAU,SAAA;AALP,EAAA,OAAAA,kBAAAA;AAAA,CAAA,CAAA,CAAA,kBAAA,GAAA,CAAA,CAAA,CAAA;AFYL;AACA;ACjBA,qCAAwB;AACxB,gEAAyB;AACzB,0GAA6D;AAU7D,MAAA,SAAsB,aAAA,CACpB,KAAA,EACA,I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ACA,EAAA;AAEA,EAAA;AACF;A/B48DA;AACA;AgCz9DA;AACE,EAAA;AAEA,EAAA;AACA,EAAA;AAEA,EAAA;AAEA,EAAA;AAEA,EAAA;AACA,EAAA;AAEA,EAAA;AACF;AhCs9DA;AACA;AiCt+DA;AACE,EAAA;AAEA,EAAA;AACA,EAAA;AAEA,EAAA;AACA,EAAA;AAEA,EAAA;AACF;AjCq+DA;AACA;AkC/+DA;AACE,EAAA;AACA,EAAA;AACA,EAAA;AAEA,EAAA;AAEA,EAAA;AAAS,iBAAA;AAET,EAAA;AACA,EAAA;AAEA,EAAA;AACF;AlC8+DA;AACA;AmC5/DA;AACE,EAAA;AAEA,EAAA;AAEA,EAAA;AAAS,+BAAA;AAET,EAAA;AACA,EAAA;AAEA,EAAA;AACF;AnC2/DA;AACA;AoCxgEA;AACE,EAAA;AAEA,EAAA;AACA,EAAA;AAEA,EAAA;AACA,EAAA;AAEA,EAAA;AACF;ApCugEA;AACA;AqCthEA;AASA;AACC,EAAA;AAEA,EAAA;AAEA,EAAA;AAAS,8BAAA;AAET,EAAA;AACA,EAAA;AAEA,EAAA;AACD;ArC6gEA;AACA;AsCjiEA;AAEA;AAGA;AACE,EAAA;AAEA,EAAA;AAEA,EAAA;AAEA,EAAA;AACA,EAAA;AAEA,EAAA;AACA,EAAA;AAEA,EAAA;AACF;AAEA;AACE,EAAA;AAEA,EAAA;AAEA,EAAA;AACA,EAAA;AACA,EAAA;AAEA,EAAA;AACF;AtCuhEA;AACA;AuCziEA;AACA;AACA;AACA;AvC2iEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/shivanshxyz/repos/labyrinth/manas/palliora-sdk/dist/index.cjs","sourcesContent":[null,"import { waitReady } from \"@polkadot/wasm-crypto\";\nimport { AccountSourceType, CryptoType } from \"./types\";\nimport { Keyring } from \"@polkadot/api\";\nimport { hexToU8a } from \"@polkadot/util\";\nimport { ed25519PairFromSecret, secp256k1PairFromSeed } from \"@polkadot/util-crypto\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\n\n/**\n * Creates a Substrate account from a private key, seed, or mnemonic.\n * @param input - The input string (private key hex, seed hex, or mnemonic phrase).\n * @param type - The type of input: 'privateKey', 'seed', or 'mnemonic'.\n * @param cryptoType - The crypto type: 'sr25519' | 'ed25519' | 'ecdsa' (default: 'sr25519').\n * @returns The keypair object.\n */\nexport async function createAccount(\n input: string,\n type: AccountSourceType,\n name: string = \"default\",\n cryptoType: CryptoType = CryptoType.SR25519\n): Promise<KeyringPair> {\n await waitReady();\n const keyring = new Keyring({ type: cryptoType });\n\n switch (type) {\n case AccountSourceType.PRIVATE_KEY: {\n const pair = pairFromPrivateKeyHex(input, cryptoType);\n return keyring.addFromPair(pair, { name }, cryptoType);\n }\n case AccountSourceType.SEED: {\n const seed = hexToU8a(input);\n\n if (seed.length !== 32) {\n throw new Error(\n `Invalid ${cryptoType} seed length. Expected 32 bytes, got ${seed.length}`\n );\n }\n\n return keyring.addFromSeed(seed, { name }, cryptoType);\n }\n case AccountSourceType.MNEMONIC:\n // format: <mnemonic or mini-secret>[//hard-derivation][/soft-derivation][///password]\n // refer docs: https://polkadot.js.org/docs/keyring/start/suri/\n return keyring.createFromUri(input, { name }, cryptoType);\n case AccountSourceType.ADDRESS:\n const account = keyring.addFromAddress(\n input,\n { name },\n null,\n cryptoType\n );\n return account;\n default:\n throw new Error(\"Invalid input type\");\n }\n}\n\nexport function pairFromPrivateKeyHex(privateKeyHex: string, cryptoType: CryptoType) {\n const privateKey = hexToU8a(privateKeyHex);\n\n switch (cryptoType) {\n case CryptoType.ED25519:\n if (privateKey.length !== 64) {\n throw new Error(\n `Invalid ed25519 private key length. Expected 64 bytes, got ${privateKey.length}`\n );\n }\n return ed25519PairFromSecret(privateKey);\n case CryptoType.ECDSA:\n if (privateKey.length !== 32) {\n throw new Error(\n `Invalid ecdsa private key length. Expected 32 bytes, got ${privateKey.length}`\n );\n }\n return secp256k1PairFromSeed(privateKey);\n case CryptoType.SR25519:\n if (privateKey.length !== 96) {\n throw new Error(\n `Invalid sr25519 private key length. Expected 96 bytes (secret+public), got ${privateKey.length}`\n );\n }\n return {\n secretKey: privateKey.slice(0, 64),\n publicKey: privateKey.slice(64, 96),\n };\n default:\n throw new Error(`Unsupported crypto type: ${cryptoType}`);\n }\n}\n","enum CryptoType {\n SR25519 = \"sr25519\",\n ED25519 = \"ed25519\",\n ECDSA = \"ecdsa\",\n}\n\nenum AccountSourceType {\n PRIVATE_KEY = \"privateKey\",\n SEED = \"seed\",\n MNEMONIC = \"mnemonic\",\n DERIVED = \"derived\",\n ADDRESS = \"address\",\n}\n\nexport { CryptoType, AccountSourceType };\n","\nexport const API_RPC = {\n\tkate: {\n\t\tqueryRows: {\n\t\t\tdescription: \"\",\n\t\t\tparams: [\n\t\t\t\t{\n\t\t\t\t\tname: \"rows\",\n\t\t\t\t\ttype: \"Vec<u32>\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"at\",\n\t\t\t\t\ttype: \"Hash\",\n\t\t\t\t\tisOptional: true,\n\t\t\t\t},\n\t\t\t],\n\t\t\ttype: \"Vec<GRow>\",\n\t\t},\n\t\tqueryProof: {\n\t\t\tdescription: \"Generate the kate proof for the given `cells`\",\n\t\t\tparams: [\n\t\t\t\t{\n\t\t\t\t\tname: \"cells\",\n\t\t\t\t\ttype: \"Vec<Cell>\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"at\",\n\t\t\t\t\ttype: \"Hash\",\n\t\t\t\t\tisOptional: true,\n\t\t\t\t},\n\t\t\t],\n\t\t\ttype: \"Vec<GDataProof>\",\n\t\t},\n\t\tblockLength: {\n\t\t\tdescription: \"Get Block Length\",\n\t\t\tparams: [\n\t\t\t\t{\n\t\t\t\t\tname: \"at\",\n\t\t\t\t\ttype: \"Hash\",\n\t\t\t\t\tisOptional: true,\n\t\t\t\t},\n\t\t\t],\n\t\t\ttype: \"BlockLength\",\n\t\t},\n\t\tqueryDataProof: {\n\t\t\tdescription: \"Generate the data proof for the given `transaction_index`\",\n\t\t\tparams: [\n\t\t\t\t{\n\t\t\t\t\tname: \"transaction_index\",\n\t\t\t\t\ttype: \"u32\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"at\",\n\t\t\t\t\ttype: \"Hash\",\n\t\t\t\t\tisOptional: true,\n\t\t\t\t},\n\t\t\t],\n\t\t\ttype: \"ProofResponse\",\n\t\t},\n\t},\n\tguardian: {\n\t\truntimeInfo: {\n\t\t\tdescription: \"Fetch guardian runtime info\",\n\t\t\tparams: [\n\t\t\t\t{\n\t\t\t\t\tname: 'at',\n\t\t\t\t\ttype: 'Hash',\n\t\t\t\t\tisOptional: true\n\t\t\t\t}\n\t\t\t],\n\t\t\ttype: 'GuardianInfo'\n\t\t},\n\t\tguardianList: {\n\t\t\tdescription: \"Fetch guardian list\",\n\t\t\tparams: [],\n\t\t\ttype: 'Vec<String>'\n\t\t},\n\t\tguardianNwParams: {\n\t\t\tdescription: \"Fetch guardian network parameters\",\n\t\t\tparams: [],\n\t\t\ttype: 'GuardianNwParams'\n\t\t}\n\t},\n};\n\nexport const API_TYPES = {\n\tGuardianInfo: {\n\t\tactive: 'u32',\n\t\tmaximum: 'u32'\n\t},\n\tGuardianNwParams: {\n\t\tkzg: 'Vec<u8>',\n\t\tagg_key: 'Vec<u8>'\n\t},\n\tAppId: \"Compact<u32>\",\n\tDataLookupItem: {\n\t\tappId: \"AppId\",\n\t\tstart: \"Compact<u32>\",\n\t},\n\tCompactDataLookup: {\n\t\tsize: \"Compact<u32>\",\n\t\tindex: \"Vec<DataLookupItem>\",\n\t},\n\tKateCommitment: {\n\t\trows: \"Compact<u16>\",\n\t\tcols: \"Compact<u16>\",\n\t\tcommitment: \"Vec<u8>\",\n\t\tdataRoot: \"H256\",\n\t},\n\tV3HeaderExtension: {\n\t\tappLookup: \"CompactDataLookup\",\n\t\tcommitment: \"KateCommitment\",\n\t},\n\tHeaderExtension: {\n\t\t_enum: {\n\t\t\tV1: null,\n\t\t\tV2: null,\n\t\t\tV3: \"V3HeaderExtension\",\n\t\t},\n\t},\n\tDaHeader: {\n\t\tparentHash: \"Hash\",\n\t\tnumber: \"Compact<BlockNumber>\",\n\t\tstateRoot: \"Hash\",\n\t\textrinsicsRoot: \"Hash\",\n\t\tdigest: \"Digest\",\n\t\textension: \"HeaderExtension\",\n\t},\n\tHeader: \"DaHeader\",\n\tCheckAppIdExtra: {\n\t\tappId: \"AppId\",\n\t},\n\tCheckAppIdTypes: {},\n\tCheckAppId: {\n\t\textra: \"CheckAppIdExtra\",\n\t\ttypes: \"CheckAppIdTypes\",\n\t},\n\tFeePayload: {\n\t\tcompute: \"u128\",\n\t\tguardian: \"u128\",\n\t\tverifier: \"u128\",\n\t},\n\tSilentThresholdParams: {\n\t\ttd_params: 'Vec<u8>',\n\t\tpk_bytes: 'Vec<u8>',\n\t\ttau_params: 'Vec<u8>'\n\t},\n\tThresholdParams: {\n\t\t_enum: {\n\t\tSilentThreshold: 'SilentThresholdParams'\n\t\t}\n\t},\n\tChaCha20Poly1305Params: {\n\t\tnonce: '[u8; 12]'\n\t},\n\tAes256GcmParams: {\n\t\tnonce: '[u8; 12]'\n\t},\n\tSymmetricParams: {\n\t\t_enum: {\n\t\tChaCha20Poly1305: 'ChaCha20Poly1305Params',\n\t\tAes256Gcm: 'Aes256GcmParams'\n\t\t}\n\t},\n\tKdfParams: {\n\t\t_enum: {\n\t\tHkdfSha256: 'Null',\n\t\tHkdfSha512: 'Null'\n\t\t}\n\t},\n\tSecp256k1Params: {\n\t\trecipient_public_key: 'Vec<u8>',\n\t\tephemeral_public_key: 'Option<Vec<u8>>',\n\t\tcompressed: 'bool',\n\t\tkdf: 'KdfParams',\n\t\tsalt: 'Option<Vec<u8>>',\n\t\tinfo: 'Option<Vec<u8>>'\n\t},\n\tEd25519Params: {\n\t\trecipient_public_key: 'Vec<u8>',\n\t\tephemeral_public_key: 'Option<Vec<u8>>',\n\t\tkdf: 'KdfParams',\n\t\tsalt: 'Option<Vec<u8>>',\n\t\tinfo: 'Option<Vec<u8>>'\n\t},\n\tAsymmetricParams: {\n\t\t_enum: {\n\t\tSecp256k1: 'Secp256k1Params',\n\t\tEd25519: 'Ed25519Params'\n\t\t}\n\t},\n\tThresholdHybridParams: {\n\t\tthreshold_params: 'ThresholdParams',\n\t\tsymmetric_params: 'SymmetricParams'\n\t},\n\tAsymmetricHybridParams: {\n\t\tasymmetric_params: 'AsymmetricParams',\n\t\tsymmetric_params: 'SymmetricParams'\n\t},\n\tCipherSuite: {\n\t\t_enum: {\n\t\tPlaintext: 'Null',\n\t\tThresholdHybrid: 'ThresholdHybridParams',\n\t\tAsymmetricHybrid: 'AsymmetricHybridParams'\n\t\t}\n\t},\n\tConfidentialityLevel: {\n\t\t_enum: {\n\t\tTrusted: 'u32',\n\t\tTEE: 'Null',\n\t\tFHE: 'Null',\n\t\tSMPC: 'Null'\n\t\t}\n\t},\n\tNativeExecuteDA: {\n\t\t_enum: ['Inference']\n\t},\n\tNativeDataDA: {\n\t\t_enum: ['DaFalse', 'DaTrue']\n\t},\n\tDAInputInline: {\n\t\tdata: 'Vec<u8>'\n\t},\n\tDAInputChainTransaction: {\n\t\tblock_number: 'u64',\n\t\textrinsic_index: 'u32'\n\t},\n\tDAInputIpfs: {\n\t\tcid: 'Vec<u8>',\n\t\tsize: 'u64'\n\t},\n\tDAInputUrl: {\n\t\turl: 'Vec<u8>',\n\t\tsize: 'u64',\n\t\thash: 'Option<Vec<u8>>'\n\t},\n\tDAInput: {\n\t\t_enum: {\n\t\tNull: 'Null',\n\t\tInline: 'DAInputInline',\n\t\tChainTransaction: 'DAInputChainTransaction',\n\t\tIpfs: 'DAInputIpfs',\n\t\tUrl: 'DAInputUrl',\n\t\tNativeExecute: 'NativeExecuteDA',\n\t\tNativeData: 'NativeDataDA'\n\t\t}\n\t},\n\tContractType: {\n\t\t_enum: {\n\t\tDormant: 'Null',\n\t\tActive: 'Null'\n\t\t}\n\t},\n\tStoreType: {\n\t\t_enum: {\n\t\tDataset: 'Null',\n\t\tModel: 'Null',\n\t\tAgent: 'Null',\n\t\tOther: 'Null'\n\t\t}\n\t},\n\tComputeMetadata: {\n\t\tname: 'Vec<u8>',\n\t\tdescription: 'Vec<u8>',\n\t\tstore_type: 'StoreType',\n\t\tgroup_id: 'H256',\n\t},\n\tComputeInfo: {\n\t\tcipher: 'CipherSuite',\n\t\tcomputer_indices: 'Vec<u32>',\n\t\tfees: 'u128',\n\t\tdeadline: 'u64',\n\t\tconfidentiality: 'ConfidentialityLevel',\n\t\tfee_function: 'Option<u8>',\n\t\tprogram_env: 'Option<Vec<u8>>',\n\t\tinput: 'DAInput',\n\t\tprogram: 'DAInput',\n\t\tmetadata: 'Option<ComputeMetadata>',\n\t},\n\tContract: {\n\t\tcontract_type: 'ContractType',\n\t\tguardians: 'Vec<AccountId>',\n\t\tpre_check: 'Option<ComputeInfo>',\n\t\tcompute: 'ComputeInfo',\n\t\tpost_check: 'Option<ComputeInfo>',\n\t\tresult_cipher: 'CipherSuite'\n\t},\n\tAgreementInfo: {\n\t\tstatus: 'AgreementStatus',\n\t\tcreator: 'AccountId',\n\t\tindex: 'u32'\n\t},\n ComputePayload: {\n\t\tda_type: \"u8\",\n\t\tagreement: \"Option<BoundedVec<[u8; 32], 10>>\",\n\t\tverification: \"u8\",\n\t\tcompute: \"u8\",\n },\n\tComputePrefs: {\n\t\ttrusted: \"bool\",\n\t\ttee: \"bool\",\n\t\tmpc: \"bool\",\n\t\tfhe: \"bool\",\n\t\tzkp: \"bool\",\n\t},\n\tGuardianPrefs: {\n\t\tpubKey: \"[u8; 32]\",\n\t\tguardian: \"bool\",\n\t\tverifier: \"bool\",\n\t\tcompute: \"bool\",\n\t\tcomputePrefs: \"Option<ComputePrefs>\",\n\t\tfeeThreshold: \"u128\",\n\t},\n\tBlockLengthColumns: \"Compact<u32>\",\n\tBlockLengthRows: \"Compact<u32>\",\n\tBlockLength: {\n\t\tmax: \"PerDispatchClass\",\n\t\tcols: \"BlockLengthColumns\",\n\t\trows: \"BlockLengthRows\",\n\t\tchunkSize: \"Compact<u32>\",\n\t},\n\tPerDispatchClass: {\n\t\tnormal: \"u32\",\n\t\toperational: \"u32\",\n\t\tmandatory: \"u32\",\n\t},\n\tTxDataRoots: {\n\t\tdataRoot: \"H256\",\n\t\tblobRoot: \"H256\",\n\t\tbridgeRoot: \"H256\",\n\t},\n\tDataProof: {\n\t\troots: \"TxDataRoots\",\n\t\tproof: \"Vec<H256>\",\n\t\tnumberOfLeaves: \"Compact<u32>\",\n\t\tleafIndex: \"Compact<u32>\",\n\t\tleaf: \"H256\",\n\t},\n\tProofResponse: {\n\t\tdataProof: \"DataProof\",\n\t\tmessage: \"Option<AddressedMessage>\",\n\t},\n\tAddressedMessage: {\n\t\tmessage: \"Message\",\n\t\tfrom: \"H256\",\n\t\tto: \"H256\",\n\t\toriginDomain: \"u32\",\n\t\tdestinationDomain: \"u32\",\n\t\tid: \"u64\",\n\t},\n\tMessage: {\n\t\t_enum: {\n\t\t\tArbitraryMessage: \"ArbitraryMessage\",\n\t\t\tFungibleToken: \"FungibleToken\",\n\t\t},\n\t},\n\tFungibleToken: {\n\t\tassetId: \"H256\",\n\t\tamount: \"u128\",\n\t},\n\tBoundedData: \"Vec<u8>\",\n\tArbitraryMessage: \"BoundedData\",\n\tCell: {\n\t\trow: \"u32\",\n\t\tcol: \"u32\",\n\t},\n\tGRawScalar: \"U256\",\n\tGProof: \"[u8; 48]\",\n\tGRow: \"Vec<GRawScalar>\",\n\tGDataProof: \"(GRawScalar, GProof)\",\n};\n\nexport const DEFAULT_COMPUTE_PAYLOAD = { compute: { da_type: 0, verification: 0, compute: 0 } };\nexport const DEFAULT_EMPTY_PAYLOAD = { compute: { da_type: 0, verification: 0, compute: 0, agreement: [] } };\n\nexport const API_EXTENSIONS = {\n\tCheckAppId: {\n\t\textrinsic: {\n\t\t\tappId: \"AppId\",\n\t\t},\n\t\tpayload: {},\n\t},\n\tCheckCompute: {\n\t\textrinsic: {\n\t\t\t\tcompute: \"ComputePayload\",\n\t\t},\n\t\tpayload: {},\n\t},\n};\n","// import { CurveType } from '@noble/curves/abstract/bls';\nimport { bls12_381 as bls } from \"@noble/curves/bls12-381\";\nimport type { ProjPointType } from \"@noble/curves/abstract/weierstrass\";\nimport type { Fp, Fp12, Fp2 } from \"@noble/curves/abstract/tower\";\n\n/**\n * Summary of porting the Silent Threshold encryption scheme from Rust to JavaScript.\n *\n * The Silent Threshold encryption scheme is a threshold encryption scheme that uses BLS12-381 as the underlying elliptic curve.\n * The scheme is based on the BLS signature scheme and uses the BLS pairing to encrypt and decrypt data.\n *\n * The types ported from the original Rust implementation are:\n * - E::ScalarField -> BigInt\n * - QuadExtField -> Fp2\n * - CubicExtField -> Fp6\n * - E::G1 -> ProjPointType<Fp>\n * - E::G2 -> ProjPointType<Fp2>\n * - PairingOutput -> ProjPointType<Fp12>\n */\n\n/**\n * @typedef {Object} PublicKey\n * @property {number} id - The identifier for the public key.\n * @property {ProjPointType<Fp>} bls_pk - The BLS public key.\n * @property {ProjPointType<Fp>} sk_li - The secret key component li.\n * @property {ProjPointType<Fp>} sk_li_minus0 - The secret key component li minus 0.\n * @property {ProjPointType<Fp>} sk_li_x - The secret key component li x.\n * @property {Array<ProjPointType<Fp>>} sk_li_lj_z - The secret key components li lj z.\n */\ntype PublicKey = {\n\tid: number;\n\tbls_pk: ProjPointType<Fp>;\n\tsk_li: ProjPointType<Fp>; //hint\n\tsk_li_minus0: ProjPointType<Fp>; //hint\n\tsk_li_lj_z: Array<ProjPointType<Fp>>; //hint\n\tsk_li_x: ProjPointType<Fp>; //hint\n};\n\n/**\n * @typedef {Object} LagrangePowers\n * @property {Array<CurveType>} li - The Lagrange coefficients li.\n * @property {Array<ProjPointType<Fp>>} li_minus0 - The Lagrange coefficients li minus 0.\n * @property {Array<ProjPointType<Fp>>} li_x - The Lagrange coefficients li x.\n * @property {Array<Array<ProjPointType<Fp>>>} li_lj_z - The Lagrange coefficients li lj z.\n */\ntype LagrangePowers = {\n\t// li: Array<CurveType>,\n\tli_minus0: Array<ProjPointType<Fp>>;\n\tli_x: Array<ProjPointType<Fp>>;\n\tli_lj_z: Array<Array<ProjPointType<Fp>>>;\n};\n\n/**\n * @typedef {ProjPointType<Fp12>} PairingOutput - The output of the pairing operation.\n */\ntype PairingOutput = ProjPointType<Fp12>;\n\n/**\n * @typedef {Object} AggregateKey\n * @property {Array<PublicKey>} pk - The array of public keys.\n * @property {Array<ProjPointType<Fp>>} agg_sk_li_lj_z - The aggregated secret key components li lj z.\n * @property {ProjPointType<Fp>} ask - The aggregated secret key.\n * @property {ProjPointType<Fp2>} z_g2 - The z_g2 component.\n * @property {ProjPointType<Fp2>} h_minus1 - The h_minus1 component.\n * @property {PairingOutput} e_gh - The preprocessed pairing output.\n */\ntype AggregateKey = {\n\tpk: Array<PublicKey>;\n\tagg_sk_li_lj_z: Array<ProjPointType<Fp>>;\n\task: ProjPointType<Fp>;\n\tz_g2: ProjPointType<Fp2>;\n\n\t//preprocessed values\n\th_minus1: ProjPointType<Fp2>;\n\te_gh: Fp12;\n};\n\n/**\n * @typedef {Object} Ciphertext\n * @property {ProjPointType<Fp2>} gamma_g2 - The gamma_g2 component.\n * @property {Array<ProjPointType<Fp>>} sa1 - The sa1 components (2 elements).\n * @property {Array<ProjPointType<Fp2>>} sa2 - The sa2 components (6 elements).\n * @property {PairingOutput} enc_key - The encryption key.\n * @property {number} t - The threshold value.\n */\ntype Ciphertext = {\n\tgamma_g2: ProjPointType<Fp2>;\n\tsa1: ProjPointType<Fp>[];\n\tsa2: ProjPointType<Fp2>[];\n\tenc_key: Fp12; // key to be used for encapsulation\n\tt: number; // threshold\n};\n\n/**\n * @typedef {Object} PowersOfTau\n * @property {ArrayLike<ProjPointType<Fp>>} powers_of_g - The powers of g.\n * @property {ArrayLike<ProjPointType<Fp2>>} powers_of_h - The powers of h.\n */\ntype PowersOfTau = {\n\tpowers_of_g: ArrayLike<ProjPointType<Fp>>;\n\tpowers_of_h: ArrayLike<ProjPointType<Fp2>>;\n};\n\n/**\n * Encrypts data using the provided parameters and aggregate public key.\n *\n * @param params - The PowersOfTau parameters containing powers of g and h.\n * @param apk - The AggregateKey containing the aggregated public key and preprocessed values.\n * @param t - The threshold value for encryption.\n * @returns A Ciphertext object containing the encrypted data.\n */\nconst encrypt = (params: PowersOfTau, apk: AggregateKey, t: number) => {\n\t// Initialize an ArrayBuffer (tau) from a fixed string\n\tconst gamma = bls.fields.Fr.create(\n\t\tBigInt(\n\t\t\t\"0x\" +\n\t\t\treverseEndianess(\n\t\t\t\t\"8660d3c2a2ab458dd6da04d3e7cb5cf6edb702dfa2fa0c952cd6f3bcdc0fdb1a\",\n\t\t\t),\n\t\t),\n\t);\n\t// console.log(gamma.toString(16));\n\t// const gamma = bls.G1.normPrivateKeyToScalar(bls.utils.randomPrivateKey());\n\tconst gamma_g2 = params.powers_of_h[0].multiply(gamma);\n\t// console.log(gamma_g2.toHex(true));\n\n\tlet g = params.powers_of_g[0];\n\tlet h = params.powers_of_h[0];\n\n\tlet sa1 = [bls.G1.ProjectivePoint.BASE, bls.G1.ProjectivePoint.BASE];\n\tlet sa2: ProjPointType<Fp2>[] = Array(6).fill(bls.G2.ProjectivePoint.BASE);\n\t// sa1.forEach((value, index) => {\n\t// console.log(`sa1[${index}]: ${value.toHex(true)}`);\n\t// });\n\t// sa2.forEach((value, index) => {\n\t// console.log(`sa2[${index}]: ${value.toHex(true)}`);\n\t// });\n\n\tconst hexValues = [\n\t\treverseEndianess(\n\t\t\t\"08ca6f2a35f8f6f9cad58e9d764d450af154c246fc04266151e2a5493ff02943\",\n\t\t),\n\t\treverseEndianess(\n\t\t\t\"8696a66087578b92e1b4b11c6b4c06d4694a9bed1f9468f0115e7f2648eb021d\",\n\t\t),\n\t\treverseEndianess(\n\t\t\t\"91e201cc83dc03cc47d63cfb8a9016e73ffd1a78fffd14e4dfcdf2cbb9a7245d\",\n\t\t),\n\t\treverseEndianess(\n\t\t\t\"a90598c6e0f25c3a104fc94632b1d58cf21bca3bbd7e41da07feb9c14e0fa60d\",\n\t\t),\n\t\treverseEndianess(\n\t\t\t\"d3f5a9fc8abfef02fb6095c08ba4f3445b36f0fb963579bc5112d34a02044567\",\n\t\t),\n\t];\n\n\t// let s = hexValues.map((hex) => bls.G1.normPrivateKeyToScalar(hex));\n\t// s.forEach((value, index) => {\n\t// console.log(`s[${index}]: ${value.toString(16)}`);\n\t// });\n\tconst s = Array.from({ length: 5 }, () => bls.G1.normPrivateKeyToScalar(bls.utils.randomPrivateKey()));\n\n\t// sa1[0] = s0*ask + s3*g^{tau^t} + s4*g\n\tsa1[0] = apk.ask\n\t\t.multiply(s[0])\n\t\t.add(params.powers_of_g[t].multiply(s[3]))\n\t\t.add(params.powers_of_g[0].multiply(s[4]));\n\n\t// sa1[1] = s2*g\n\tsa1[1] = g.multiply(s[2]);\n\n\t// sa2[0] = s0*h + s2*gamma_g2\n\tsa2[0] = h.multiply(s[0]).add(gamma_g2.multiply(s[2]));\n\n\t// sa2[1] = s0*z_g2\n\tsa2[1] = apk.z_g2.multiply(s[0]);\n\n\t// sa2[2] = s0*h^tau + s1*h^tau\n\tsa2[2] = params.powers_of_h[1]\n\t\t.multiply(s[0])\n\t\t.add(params.powers_of_h[1].multiply(s[1]));\n\n\t// sa2[3] = s1*h\n\tsa2[3] = h.multiply(s[1]);\n\n\t// sa2[4] = s3*h\n\tsa2[4] = h.multiply(s[3]);\n\n\t// sa2[5] = s4*h^{tau - omega^0}\n\tsa2[5] = params.powers_of_h[1].add(apk.h_minus1).multiply(s[4]);\n\n\t// enc_key = s4*e_gh\n\tconst enc_key = bls.fields.Fp12.pow(apk.e_gh, s[4]);\n\t// const enc_key = apk.e_gh.multiply(s[4]);\n\n\treturn { gamma_g2, sa1, sa2, enc_key, t };\n};\n\n/**\n * Decodes a hex string into a PowersOfTau object.\n *\n * @param input - The hex string to decode.\n * @returns A PowersOfTau object containing the decoded data.\n */\nconst decodePowersOfTau = (input: string): PowersOfTau => {\n\ttry {\n\t\t// Ensure input is properly formatted\n\t\tif (!input || input.length % 2 !== 0) {\n\t\t\tthrow new Error('Invalid input hex string');\n\t\t}\n\n\t\t// Convert hex string to Uint8Array\n\t\tconst hexArray = input.match(/.{1,2}/g) || [];\n\t\tconst buffer = new Uint8Array(hexArray.map(byte => parseInt(byte, 16)));\n\n\t\t// Create ArrayBuffer with the correct size\n\t\tconst arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);\n\t\tconst view = new DataView(arrayBuffer);\n\n\t\tconst powers_of_g: Array<ProjPointType<Fp>> = [];\n\t\tconst powers_of_h: Array<ProjPointType<Fp2>> = [];\n\n\t\tconst G1_POINT_SIZE = 48; // 96/2 bytes for G1 points\n\t\tconst G2_POINT_SIZE = 96; // 192/2 bytes for G2 points\n\n\t\tlet offset = 0;\n\n\t\t// Read count safely\n\t\tif (offset + 8 > buffer.length) {\n\t\t\tthrow new Error('Buffer too small to read count');\n\t\t}\n\t\tconst count = view.getBigUint64(offset, true);\n\t\toffset += 8;\n\n\t\t// Read powers_of_g\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tif (offset + G1_POINT_SIZE > buffer.length) {\n\t\t\t\tthrow new Error('Buffer too small to read G1 point');\n\t\t\t}\n\t\t\tconst pointBuffer = buffer.slice(offset, offset + G1_POINT_SIZE);\n\t\t\tconst point = bls.G1.ProjectivePoint.fromHex(pointBuffer);\n\t\t\tpowers_of_g.push(point);\n\t\t\toffset += G1_POINT_SIZE;\n\t\t}\n\n\t\t// Skip the second count\n\t\tif (offset + 8 > buffer.length) {\n\t\t\tthrow new Error('Buffer too small to read second count');\n\t\t}\n\t\toffset += 8;\n\n\t\t// Read powers_of_h\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tif (offset + G2_POINT_SIZE > buffer.length) {\n\t\t\t\tthrow new Error('Buffer too small to read G2 point');\n\t\t\t}\n\t\t\tconst pointBuffer = buffer.slice(offset, offset + G2_POINT_SIZE);\n\t\t\tconst point = bls.G2.ProjectivePoint.fromHex(pointBuffer);\n\t\t\tpowers_of_h.push(point);\n\t\t\toffset += G2_POINT_SIZE;\n\t\t}\n\n\t\treturn { powers_of_g, powers_of_h };\n\t} catch (error) {\n\t\tconsole.error('Error in decodePowersOfTau:', error);\n\t\tconsole.log('Input length:', input.length);\n\t\tconsole.log('Input preview:', input.slice(0, 100));\n\t\tthrow error;\n\t}\n};\n\n// Helper function to check if a hex string is valid\nconst isValidHex = (hex: string): boolean => {\n\treturn /^[0-9A-Fa-f]*$/.test(hex) && hex.length % 2 === 0;\n};\n\n// Helper function to safely create a DataView from a hex string\nconst createDataViewFromHex = (hex: string): { view: DataView, buffer: Uint8Array } => {\n\tif (!isValidHex(hex)) {\n\t\tthrow new Error('Invalid hex string');\n\t}\n\tconst buffer = new Uint8Array(hex.match(/.{1,2}/g)!.map(byte => parseInt(byte, 16)));\n\tconst arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);\n\treturn {\n\t\tview: new DataView(arrayBuffer),\n\t\tbuffer\n\t};\n};\n\n/**\n * Decodes a hex string into an AggregateKey object.\n *\n * @param input - The hex string to decode.\n * @returns An AggregateKey object containing the decoded data.\n */\nconst decodeAggregateKey = (input: string): AggregateKey => {\n\tconst buffer = new Uint8Array(input.match(/.{1,2}/g)?.map(byte => parseInt(byte, 16)) || []);\n\tlet offset = 0;\n\n\tconst view = new DataView(buffer.buffer);\n\tconst readBigUInt64LE = () => {\n\t\tconst value = view.getBigUint64(offset, true);\n\t\toffset += 8;\n\t\treturn value;\n\t};\n\n\tconst readProjPointTypeFp = (count: bigint) => {\n\t\tconst points: Array<ProjPointType<Fp>> = [];\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst pointBuffer = buffer.slice(offset, offset + 48);\n\t\t\tconst point = bls.G1.ProjectivePoint.fromHex(pointBuffer);\n\t\t\tpoints.push(point);\n\t\t\toffset += 48;\n\t\t}\n\t\treturn points;\n\t};\n\n\tconst readProjPointTypeFp2 = (count: bigint) => {\n\t\tconst points: Array<ProjPointType<Fp2>> = [];\n\t\tfor (let i = 0; i < count; i++) {\n\t\t\tconst pointBuffer = buffer.slice(offset, offset + 96);\n\t\t\tconst point = bls.G2.ProjectivePoint.fromHex(pointBuffer);\n\t\t\tpoints.push(point);\n\t\t\toffset += 96;\n\t\t}\n\t\treturn points;\n\t};\n\n\tconst readProjPointTypeFp12 = () => {\n\t\tconst points: Array<Fp> = [];\n\t\tfor (let i = 0; i < 12; i++) {\n\t\t\tconst pointBuffer = buffer.slice(offset, offset + 48);\n\t\t\t// Convert to hex and reverse for endianness\n\t\t\tconst hexValue = Array.from(pointBuffer)\n\t\t\t\t.reverse()\n\t\t\t\t.map(b => b.toString(16).padStart(2, '0'))\n\t\t\t\t.join('');\n\t\t\tconst point = BigInt(\"0x\" + hexValue);\n\t\t\tpoints.push(point);\n\t\t\toffset += 48;\n\t\t}\n\t\tif (points.length !== 12) {\n\t\t\tthrow new Error(\"Invalid number of points for Fp12\");\n\t\t}\n\t\treturn bls.fields.Fp12.create({\n\t\t\tc0: bls.fields.Fp6.create({\n\t\t\t\tc0: bls.fields.Fp2.create({ c0: points[0], c1: points[1] }),\n\t\t\t\tc1: bls.fields.Fp2.create({ c0: points[2], c1: points[3] }),\n\t\t\t\tc2: bls.fields.Fp2.create({ c0: points[4], c1: points[5] }),\n\t\t\t}),\n\t\t\tc1: bls.fields.Fp6.create({\n\t\t\t\tc0: bls.fields.Fp2.create({ c0: points[6], c1: points[7] }),\n\t\t\t\tc1: bls.fields.Fp2.create({ c0: points[8], c1: points[9] }),\n\t\t\t\tc2: bls.fields.Fp2.create({ c0: points[10], c1: points[11] }),\n\t\t\t}),\n\t\t});\n\t};\n\n\tconst pkCount = readBigUInt64LE();\n\tconst pk: Array<PublicKey> = [];\n\tfor (let i = 0; i < pkCount; i++) {\n\t\tconst id = Number(readBigUInt64LE());\n\t\tconst bls_pk = readProjPointTypeFp(BigInt(1))[0];\n\t\tconst sk_li = readProjPointTypeFp(BigInt(1))[0];\n\t\tconst sk_li_minus0 = readProjPointTypeFp(BigInt(1))[0];\n\t\tconst sk_li_lj_z = readProjPointTypeFp(readBigUInt64LE());\n\t\tconst sk_li_x = readProjPointTypeFp(BigInt(1))[0];\n\t\tpk.push({ id, bls_pk, sk_li, sk_li_minus0, sk_li_x, sk_li_lj_z });\n\t}\n\n\tconst agg_sk_li_lj_z = readProjPointTypeFp(readBigUInt64LE());\n\tconst ask = readProjPointTypeFp(BigInt(1))[0];\n\tconst z_g2 = readProjPointTypeFp2(BigInt(1))[0];\n\tconst h_minus1 = readProjPointTypeFp2(BigInt(1))[0];\n\tconst e_gh = readProjPointTypeFp12();\n\n\treturn { pk, agg_sk_li_lj_z, ask, z_g2, h_minus1, e_gh };\n};\n\n/**\n * Encode a Ciphertext object into a hex string.\n *\n * @param input - The Ciphertext object to encode.\n * @returns A hex string containing the encoded data.\n */\nconst encodeCiphertext = (input: Ciphertext): string => {\n\tconst writeProjPointTypeFp = (point: ProjPointType<Fp>) => {\n\t\tconst hex = point.toHex(true);\n\t\treturn new Uint8Array(hex.match(/.{1,2}/g)?.map(byte => parseInt(byte, 16)) || []);\n\t};\n\n\tconst writeProjPointTypeFp2 = (point: ProjPointType<Fp2>) => {\n\t\tconst hex = point.toHex(true);\n\t\treturn new Uint8Array(hex.match(/.{1,2}/g)?.map(byte => parseInt(byte, 16)) || []);\n\t};\n\n\tconst gamma_g2Buffer = writeProjPointTypeFp2(input.gamma_g2);\n\tconst sa1Buffer = new Uint8Array(input.sa1.flatMap(p => Array.from(writeProjPointTypeFp(p))));\n\tconst sa2Buffer = new Uint8Array(input.sa2.flatMap(p => Array.from(writeProjPointTypeFp2(p))));\n\tconst enc_keyBuffer = new Uint8Array(fp12ToHex(input.enc_key).match(/.{1,2}/g)?.map(byte => parseInt(byte, 16)) || []);\n\n\tconst tBuffer = new Uint8Array(8);\n\tnew DataView(tBuffer.buffer).setBigUint64(0, BigInt(input.t), true);\n\n\tconst totalLength = gamma_g2Buffer.length + sa1Buffer.length + sa2Buffer.length + enc_keyBuffer.length + tBuffer.length;\n\tconst resultBuffer = new Uint8Array(totalLength);\n\n\tlet offset = 0;\n\tresultBuffer.set(gamma_g2Buffer, offset);\n\toffset += gamma_g2Buffer.length;\n\tresultBuffer.set(sa1Buffer, offset);\n\toffset += sa1Buffer.length;\n\tresultBuffer.set(sa2Buffer, offset);\n\toffset += sa2Buffer.length;\n\tresultBuffer.set(enc_keyBuffer, offset);\n\toffset += enc_keyBuffer.length;\n\tresultBuffer.set(tBuffer, offset);\n\n\treturn Array.from(resultBuffer)\n\t\t.map(b => b.toString(16).padStart(2, '0'))\n\t\t.join('');\n};\n\nfunction demoFieldOperations() {\n\t// Create base points in G1 and G2\n\tconst g1Base = bls.G1.ProjectivePoint.BASE;\n\tconst g2Base = bls.G2.ProjectivePoint.BASE;\n\tconsole.log(\"G1 generator: \", g1Base.toHex(true));\n\tconsole.log(\"G2 generator: \", g2Base.toHex(true));\n\n\tconst scalar = bls.fields.Fr.create(\n\t\tBigInt(\n\t\t\t\"0x1d8a77a2bc0faf4c4c904eed119108ed9b375265f7d06cec6862a2a97c3adb27\",\n\t\t),\n\t);\n\tconsole.log(\"Scalar: \", scalar.toString(16));\n\n\tconst e_ghH = bls.pairing(g1Base, g2Base);\n\tconsole.log(fp12ToHex(e_ghH));\n\t// return\n\n\t// Perform G1 addition\n\tconst g1Sum = g1Base.add(g1Base);\n\tconsole.log(\"G1 generator doubled: \", g1Sum.toHex(true));\n\n\t// Perform G2 addition\n\tconst g2Sum = g2Base.add(g2Base);\n\tconsole.log(\"G2 generator doubled: \", g2Sum.toHex(true));\n\n\t// Create an Fp element and do multiplication\n\tconst fp_a = bls.fields.Fp.create(\n\t\tBigInt(\n\t\t\t\"0xa191b705ef18a6e4e5bd4cc56de0b8f94b1f3c908f3e3fcbd4d1dc12eb85059be7e7d801edc1856c8cfbe6d63a681c1f\",\n\t\t),\n\t);\n\tconst fp_b = bls.fields.Fp.create(\n\t\tBigInt(\n\t\t\t\"0x8e07730c0dceb35342bfa587940babad2ec7622aec96994179086a5d323c479e64c890939e47f9a46b427f063f71d4f4\",\n\t\t),\n\t);\n\tconst fpModified = bls.fields.Fp.addN(fp_a, fp_b);\n\tconsole.log(\"Fp a + b: \", fpModified.toString(16));\n\n\tconst g1_a = bls.G1.ProjectivePoint.fromHex(\n\t\t\"a191b705ef18a6e4e5bd4cc56de0b8f94b1f3c908f3e3fcbd4d1dc12eb85059be7e7d801edc1856c8cfbe6d63a681c1f\",\n\t);\n\tconst g1_b = bls.G1.ProjectivePoint.fromHex(\n\t\t\"8e07730c0dceb35342bfa587940babad2ec7622aec96994179086a5d323c479e64c890939e47f9a46b427f063f71d4f4\",\n\t);\n\tconst g1_zero = bls.G1.ProjectivePoint.ZERO;\n\tconsole.log(\"G1 a: \", g1_a.toHex(true));\n\tconsole.log(\"G1 b: \", g1_b.toHex(true));\n\tconsole.log(\"G1 zero: \", g1_zero.toHex(true));\n\n\tconst g1_sum = g1_a.add(g1_b);\n\tconst g1_sub = g1_a.subtract(g1_b);\n\tconst g1_neg = g1_a.negate();\n\tconst g1_dbl = g1_a.double();\n\tconst g1_scalar_mul = g1_a.multiply(scalar);\n\tconsole.log(\"G1 a + b: \", g1_sum.toHex(true));\n\tconsole.log(\"G1 a - b: \", g1_sub.toHex(true));\n\tconsole.log(\"G1 -a: \", g1_neg.toHex(true));\n\tconsole.log(\"G1 2a: \", g1_dbl.toHex(true));\n\tconsole.log(\"G1 scalar mul: \", g1_scalar_mul.toHex(true));\n\n\t// Create an Fp2 element and do multiplication\n\tconst fp2_a = bls.fields.Fp2.create({\n\t\tc0: BigInt(\n\t\t\t\"0x848e9f7ae435bd738c33ae1f11cefb472b29a090de5ce00740b8ec1bd30fdbb27eb7e65162eed68c55e0bb03bf749857\",\n\t\t),\n\t\tc1: BigInt(\n\t\t\t\"0x0f8faa02f0dd3225ca98d8306f8efa4e3f62a13efc342f3466d3e56be5144dae68cafab0f99ddf1f04a6659806b12235\",\n\t\t),\n\t});\n\tconst fp2_b = bls.fields.Fp2.create({\n\t\tc0: BigInt(\n\t\t\t\"0xa4d21fc0921dcca8f0666f3b7530b569c2309bc13d3303a6fc3d233c58275972879c415608b6774bbbb00e10a6e47ace\",\n\t\t),\n\t\tc1: BigInt(\n\t\t\t\"0x1046aa2e6208f5d1813de823e5e3dec638bb7b82247cebeebbc70a14f1f59b9c0738b0f08120cb81d8c876579bd2391f\",\n\t\t),\n\t});\n\tconst fp2Modified = bls.fields.Fp2.addN(fp2_a, fp2_b);\n\tconsole.log(\n\t\t\"Fp2 a + b: \",\n\t\tfp2Modified.c0.toString(16),\n\t\tfp2Modified.c1.toString(16),\n\t);\n\n\tconst g2_a = bls.G2.ProjectivePoint.fromHex(\n\t\t\"848e9f7ae435bd738c33ae1f11cefb472b29a090de5ce00740b8ec1bd30fdbb27eb7e65162eed68c55e0bb03bf7498570f8faa02f0dd3225ca98d8306f8efa4e3f62a13efc342f3466d3e56be5144dae68cafab0f99ddf1f04a6659806b12235\",\n\t);\n\tconst g2_b = bls.G2.ProjectivePoint.fromHex(\n\t\t\"a4d21fc0921dcca8f0666f3b7530b569c2309bc13d3303a6fc3d233c58275972879c415608b6774bbbb00e10a6e47ace1046aa2e6208f5d1813de823e5e3dec638bb7b82247cebeebbc70a14f1f59b9c0738b0f08120cb81d8c876579bd2391f\",\n\t);\n\tconst g2_zero = bls.G2.ProjectivePoint.ZERO;\n\tconsole.log(\"G2 a: \", g2_a.toHex(true));\n\tconsole.log(\"G2 b: \", g2_b.toHex(true));\n\tconsole.log(\"G2 zero: \", g2_zero.toHex(true));\n\n\tconst g2_sum = g2_a.add(g2_b);\n\tconst g2_sub = g2_a.subtract(g2_b);\n\tconst g2_neg = g2_a.negate();\n\tconst g2_dbl = g2_a.double();\n\tconst g2_scalar_mul = g2_a.multiply(scalar);\n\tconsole.log(\"G2 a + b: \", g2_sum.toHex(true));\n\tconsole.log(\"G2 a - b: \", g2_sub.toHex(true));\n\tconsole.log(\"G2 -a: \", g2_neg.toHex(true));\n\tconsole.log(\"G2 2a: \", g2_dbl.toHex(true));\n\tconsole.log(\"G2 scalar mul: \", g2_scalar_mul.toHex(true));\n\n\t// Create an Fp12 element and do squaring\n\tconst fp12_a = hexToFp12(\n\t\t\"7b41018107fbe009aeb2ae912921bb2145b658bff588daea81a2d53a8c4aee171935fcc96fb395398ae4e4b20d937e16967f5e6a543f14a6751a869bfd22c8d96857389065eb86aa6784483efafc422ddb530f3dd76b3ce620605f6e21ee8c13f0a6b6f84a6ab78fdc1167e447c4f3a1d7cc51cf686646b7b31199d3e453c009ca949eb79696bf3d64c68a92e66fcc1514605dea849d01626006d806aca856a641993f84d2c620e6c97f4d8773c7664baee35761c576f687d6a643c3c6257b07f1f07ec6b0eb29ebaa9cb4088b29db25d2612fa604c96b3d148f0f8a954a0777b6e21f4b51f69530401651d1d0c9480ff23d5c0c0d34ede48be9c08dd6bbee77015deddac23d10eebd64ff1ecbce86a696f051fabe6c26e15e3b946afcc2b613f0b3a2126b6533792284bc5fc90a899c4c3a05b2491ce6903a9b2d85f30d630f421324492cbbbaf174cdc1a29adc110bb4891940fa9e8ad79520296819a6b6a32a578f7283c44d9c45e0c2676e0bbb4522cbdc23baebfa3cb008f43700a67207d7eb10a9d82cc576cbe3e10bac5e23613d456c18a512180869f48b52117c8dd1de9ce4728737d3239cfe829ccea8740e42c737ff961d5cff8d9ca0da3434ed909a3d362411cdb5c8e1bc917913c3cd783c3974621309d255f81c06e46132e0076209171b0ffea3ed0541e03d78856c018912927c520c56af071062972d1cb07276d8dcea9746000dbca97f78060e1815d22f5f88652aa53ae1664e449457c2e700e65efdaff38ac0a7849f4966411153dfd1befa7bab0d1889cc643e82809911\",\n\t);\n\tconst fp12_b = hexToFp12(\n\t\t\"d9b0619e9e724685d2eb06d509523870f9dfe07c7d7fb623632fc8f3ef8acd66fd9ed31a79af676ac1c2adc48ff018066f12bda4c5b225652d002ccba86315d57ebf098d35f3987a0b79f4d989c09c0c6373e58ac42c24e5a3b16d3eafa3e91020f0bfea83f3f1736732e71aac76e40399ec881a62a93426306be1e9dfc6645f1649a1d26d7d1ada5aca07c57551250749995a15db818c0aa7acb4606e7f41b65375308abbd547f7b8d90f10e1a7bfba60924a451108c8b896efa7355e14af10c096bb64e70e0c055e27e79b3b7552aa0b36bd3eace4759e13a31eabaea322bf978d2815b287e7c4d31281c85898090b57af368ceefe8be408504a0d57c542ad8e73f44211df17c89a2fd099f25895615828c884d9c31e514819d63856841601cce68807457db323e23db4bbc9a80900fb19aafd655069700db1b5d5a5753adedab2bd556fdc1774a54f0733a51e3c18f16e700f87ade824f35dde86023a5b7d816031e0eac3c4d82a80637a777969815fbd3ddcfcaf77ed7d9ad7c8c886530414d76c34808efefd57b488b065319f573a4ac806eb5da273c4320301ca6de6c682cd844f0a08c9b5e86f29431c32830d1feedf4d8bcd5d5ca90ef15084fffb98abe683d36e9de474ed069e8f72f4cdc7043cd38cb59878acef0674d0b48b8f0b9a0df326c8c7e97a5f35dcc1377f2e68d2e6076afb792db5ad38cb01158571e0c8b644e77c8d1b574653dcd73941070cd34deac7afe916952d3b67b4ad3e8993b33308c282de58e37afb28ae2afbb44f8e56b2e3ef575b67c5bc3112ccfedd07\",\n\t);\n\tconst fp12_zero = bls.fields.Fp12.ZERO;\n\tconst fp12_one = bls.fields.Fp12.ONE;\n\tconst fp12_pairing = bls.pairing(g1_a, g2_b);\n\tconst fp12_scalar_mul = bls.fields.Fp12.pow(fp12_pairing, scalar);\n\n\tconsole.log(\"Fp12 a:\", fp12ToHex(fp12_a));\n\tconsole.log(\"Fp12 b:\", fp12ToHex(fp12_b));\n\tconsole.log(\"Fp12 zero:\", fp12ToHex(fp12_zero));\n\tconsole.log(\"Fp12 one:\", fp12ToHex(fp12_one));\n\tconsole.log(\"Fp12 pairing:\", fp12ToHex(fp12_pairing));\n\tconsole.log(\"Fp12 scalar mul:\", fp12ToHex(fp12_scalar_mul));\n\n\tconst fp12_add = bls.fields.Fp12.add(fp12_a, fp12_b);\n\tconst fp12_sub = bls.fields.Fp12.sub(fp12_a, fp12_b);\n\tconst fp12_neg = bls.fields.Fp12.neg(fp12_a);\n\tconst fp12_mul = bls.fields.Fp12.mul(fp12_a, fp12_b);\n\tconst fp12_inv = bls.fields.Fp12.inv(fp12_a);\n\n\tconsole.log(\"Fp12 add:\", fp12ToHex(fp12_add));\n\tconsole.log(\"Fp12 sub:\", fp12ToHex(fp12_sub));\n\tconsole.log(\"Fp12 neg:\", fp12ToHex(fp12_neg));\n\tconsole.log(\"Fp12 mul:\", fp12ToHex(fp12_mul));\n\tconsole.log(\"Fp12 inv:\", fp12ToHex(fp12_inv));\n}\n\nfunction hexToFp12(hex: string): Fp12 {\n\tconst c0 = bls.fields.Fp6.create({\n\t\tc0: bls.fields.Fp2.create({\n\t\t\tc0: BigInt(\"0x\" + reverseEndianess(hex.slice(0, 96))),\n\t\t\tc1: BigInt(\"0x\" + reverseEndianess(hex.slice(96, 192))),\n\t\t}),\n\t\tc1: bls.fields.Fp2.create({\n\t\t\tc0: BigInt(\"0x\" + reverseEndianess(hex.slice(192, 288))),\n\t\t\tc1: BigInt(\"0x\" + reverseEndianess(hex.slice(288, 384))),\n\t\t}),\n\t\tc2: bls.fields.Fp2.create({\n\t\t\tc0: BigInt(\"0x\" + reverseEndianess(hex.slice(384, 480))),\n\t\t\tc1: BigInt(\"0x\" + reverseEndianess(hex.slice(480, 576))),\n\t\t}),\n\t});\n\tconst c1 = bls.fields.Fp6.create({\n\t\tc0: bls.fields.Fp2.create({\n\t\t\tc0: BigInt(\"0x\" + reverseEndianess(hex.slice(576, 672))),\n\t\t\tc1: BigInt(\"0x\" + reverseEndianess(hex.slice(672, 768))),\n\t\t}),\n\t\tc1: bls.fields.Fp2.create({\n\t\t\tc0: BigInt(\"0x\" + reverseEndianess(hex.slice(768, 864))),\n\t\t\tc1: BigInt(\"0x\" + reverseEndianess(hex.slice(864, 960))),\n\t\t}),\n\t\tc2: bls.fields.Fp2.create({\n\t\t\tc0: BigInt(\"0x\" + reverseEndianess(hex.slice(960, 1056))),\n\t\t\tc1: BigInt(\"0x\" + reverseEndianess(hex.slice(1056, 1152))),\n\t\t}),\n\t});\n\treturn bls.fields.Fp12.create({ c0, c1 });\n}\n\nfunction convertToCyclotomic(fp12: Fp12): Fp12 {\n\tconst p = BigInt(\n\t\t\"0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab\",\n\t); // BLS12-381 prime\n\tconst exponent = p ** BigInt(4) - p ** BigInt(2) + BigInt(1);\n\treturn bls.fields.Fp12.pow(fp12, exponent);\n}\n\nfunction fp12ToHex(fp12: Fp12): string {\n\tconst c0 = fp12.c0;\n\tconst c1 = fp12.c1;\n\treturn [\n\t\tbigintToBigEndianHex(c0.c0.c0, 48),\n\t\tbigintToBigEndianHex(c0.c0.c1, 48),\n\t\tbigintToBigEndianHex(c0.c1.c0, 48),\n\t\tbigintToBigEndianHex(c0.c1.c1, 48),\n\t\tbigintToBigEndianHex(c0.c2.c0, 48),\n\t\tbigintToBigEndianHex(c0.c2.c1, 48),\n\t\tbigintToBigEndianHex(c1.c0.c0, 48),\n\t\tbigintToBigEndianHex(c1.c0.c1, 48),\n\t\tbigintToBigEndianHex(c1.c1.c0, 48),\n\t\tbigintToBigEndianHex(c1.c1.c1, 48),\n\t\tbigintToBigEndianHex(c1.c2.c0, 48),\n\t\tbigintToBigEndianHex(c1.c2.c1, 48),\n\t].join(\"\");\n}\n\nconst testCrypt = (\n\tkzg: string,\n\tagg_key: string,\n): { encoded: string; ikm: string; ciph: Ciphertext } => {\n\ttry {\n\t\t// Validate inputs\n\t\tif (!isValidHex(kzg) || !isValidHex(agg_key)) {\n\t\t\tthrow new Error('Invalid input hex strings');\n\t\t}\n\n\t\tconst powersOfTau = decodePowersOfTau(kzg);\n\t\tconst aggregateKey = decodeAggregateKey(agg_key);\n\n\t\tconst ciph = encrypt(powersOfTau, aggregateKey, 2);\n\t\tconst encoded = encodeCiphertext(ciph);\n\t\tconst ikm = fp12ToHex(ciph.enc_key);\n\n\t\treturn { encoded, ikm, ciph };\n\t} catch (error) {\n\t\tconsole.error('Error in testCrypt:', error);\n\t\tthrow error;\n\t}\n};\n\nfunction bigintToBigEndianHex(value: bigint, length: number): string {\n\t// Convert BigInt to hex string without the '0x' prefix\n\tlet hex = value.toString(16);\n\n\t// Ensure the hex string is padded to the desired length\n\tif (hex.length > length * 2) {\n\t\tthrow new Error(\"BigInt value is too large to fit in the specified length\");\n\t}\n\n\t// Pad the hex string with leading zeros\n\thex = hex.padStart(length * 2, \"0\");\n\n\t// Convert the hex string to a byte array\n\tconst byteArray =\n\t\thex.match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16)) || [];\n\n\t// Reverse the byte array to get big-endian format\n\tconst reversedByteArray = byteArray.reverse();\n\n\t// Convert the reversed byte array back to a hex string\n\tconst bigEndianHex = reversedByteArray\n\t\t.map((byte) => byte.toString(16).padStart(2, \"0\"))\n\t\t.join(\"\");\n\n\treturn bigEndianHex;\n}\n\nfunction reverseEndianess(hex: string): string {\n\tif (hex.length % 2 !== 0) {\n\t\tthrow new Error(\"Hex string must have an even length\");\n\t}\n\treturn hex.match(/.{1,2}/g)?.reverse().join('') || '';\n}\n\nexport {\n\tdecodeAggregateKey,\n\tdecodePowersOfTau,\n\tencodeCiphertext,\n\tencrypt as ecncryptTest,\n\ttestCrypt,\n};\n","import { edwardsToMontgomeryPriv, edwardsToMontgomeryPub, x25519 } from '@noble/curves/ed25519';\nimport { hkdf } from \"@noble/hashes/hkdf\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { ChaCha20Poly1305 } from \"@stablelib/chacha20poly1305\";\n\nexport const gen_stretched_key = (input: Uint8Array) => {\n const salt = new Uint8Array(32); // 32 bytes of zero\n const info = new TextEncoder().encode(\"aes_encryption\");\n return hkdf(sha256, input, salt, info, 32); // 32 bytes output key length\n};\n\nexport const gen_shared_key = (key: Uint8Array, pk: Uint8Array) => {\n const mg_key = edwardsToMontgomeryPriv(key);\n const mg_pk = edwardsToMontgomeryPub(pk);\n return x25519.getSharedSecret(mg_key, mg_pk);\n};\n\nexport const encrypt = (plaintext: Uint8Array, key: Uint8Array) => {\n const cipher = new ChaCha20Poly1305(key);\n const nonce = new Uint8Array(cipher.nonceLength);\n globalThis.crypto.getRandomValues(nonce);\n const ciphertext = cipher.seal(nonce, plaintext);\n return { ciphertext, nonce };\n};\n\nexport const decrypt = (ciphertext: Uint8Array, key: Uint8Array, nonce: Uint8Array) => {\n const cipher = new ChaCha20Poly1305(key);\n const res = cipher.open(nonce, ciphertext);\n return res;\n};\n","/**\n * Isomorphic assert utility that works in both Node.js and browser environments.\n * Replaces Node.js built-in assert for client-side compatibility.\n */\nexport function assert(\n condition: unknown,\n message?: string\n): asserts condition {\n if (!condition) {\n throw new Error(message ?? \"Assertion failed\");\n }\n}\n","const env = typeof process !== \"undefined\" && process.env ? process.env : {} as Record<string, string | undefined>;\n\nexport let PALLIORA_WS = env.PALLIORA_WS || \"wss://manas-rpc.palliora.org\";\nexport let PALLIORA_RPC_URL = env.PALLIORA_RPC_URL || \"wss://manas-rpc.palliora.org\";\n\nexport let DEBUG = env.DEBUG === \"true\" || false;\n\nexport let TX_WAIT_FINALIZATION = env.TX_WAIT_FINALIZATION === \"true\" || false;\n\nexport function configure(opts: {\n pallioraWs?: string;\n pallioraRpcUrl?: string;\n debug?: boolean;\n txWaitFinalization?: boolean;\n}) {\n if (opts.pallioraWs !== undefined) PALLIORA_WS = opts.pallioraWs;\n if (opts.pallioraRpcUrl !== undefined) PALLIORA_RPC_URL = opts.pallioraRpcUrl;\n if (opts.debug !== undefined) DEBUG = opts.debug;\n if (opts.txWaitFinalization !== undefined) TX_WAIT_FINALIZATION = opts.txWaitFinalization;\n}","import { DEBUG } from \"../config\";\nimport { Hex } from \"./types\";\n \n/**\n * Converts a hex string into a Uint8Array.\n *\n * @param hex - A hex-encoded string (must contain only hexadecimal characters, without any 0x prefix).\n * @returns A Uint8Array containing the byte values represented by the hex string.\n * @throws {Error} If the provided hex string has an odd length (invalid hex string).\n *\n * @example\n * hexToUint8Array(\"ff00a1\"); // => Uint8Array [255, 0, 161]\n */\nexport function hexToUint8Array(hex: Hex) {\n if (hex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string\");\n }\n const arr = new Uint8Array(hex.length / 2);\n for (let i = 0; i < arr.length; i++) {\n arr[i] = parseInt(hex.substr(i * 2, 2), 16);\n }\n return arr;\n}\n \n/**\n * Encodes a Uint8Array into a Base64 string using the browser btoa API.\n *\n * Note: This implementation builds a binary string via String.fromCharCode for each byte and then calls btoa.\n * It is intended for browser environments where btoa is available. For very large arrays consider alternative approaches to avoid high memory usage.\n *\n * @param uint8Array - The bytes to encode as Base64.\n * @returns A Base64-encoded string representing the input bytes.\n *\n * @example\n * uint8ArrayToBase64(new Uint8Array([72, 101, 108, 108, 111])); // => \"SGVsbG8=\"\n */\nexport function uint8ArrayToBase64(uint8Array: Uint8Array) {\n let binary = \"\";\n for (let i = 0; i < uint8Array.length; i++) {\n binary += String.fromCharCode(uint8Array[i]);\n }\n return btoa(binary);\n}\n\n/**\n * Decodes a Base64 (or URL-safe Base64) string into a Uint8Array.\n *\n * This function normalizes URL-safe base64 by replacing '-' with '+' and '_' with '/', and it adds padding if missing\n * before decoding with atob. Works in browser environments where atob is available.\n *\n * @param base64 - A Base64 or URL-safe Base64 encoded string.\n * @returns The decoded bytes as a Uint8Array.\n *\n * @example\n * base64ToUint8Array(\"SGVsbG8=\"); // => Uint8Array [72, 101, 108, 108, 111]\n */\nexport const base64ToUint8Array = (base64: string): Uint8Array => {\n // Convert URL-safe base64 to standard base64.\n base64 = base64.replace(/-/g, \"+\").replace(/_/g, \"/\");\n // Add padding if missing.\n while (base64.length % 4) {\n base64 += \"=\";\n }\n const binaryString = atob(base64);\n const len = binaryString.length;\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n};\n\n/**\n * Decodes a Base64-encoded field into a Uint8Array and handles possible double-encoding.\n *\n * If expectedLength is provided and the decoded byte length does not match, this helper checks whether the decoded result\n * is exactly twice the expected length. If so, it treats the decoded bytes as a UTF-8 string containing another Base64 value,\n * decodes that second Base64 string, and returns it if it matches the expected length. Otherwise the initially decoded bytes are returned.\n *\n * @param field - The Base64 (or URL-safe Base64) encoded field to decode.\n * @param expectedLength - Optional expected length of the final decoded byte array. When provided, enables the double-decoding heuristic.\n * @returns The decoded bytes as a Uint8Array. If double-encoding is detected and validated, the inner decoded bytes are returned.\n *\n * @example\n * // Single-encoded\n * decodeField(\"SGVsbG8=\", 5); // => Uint8Array [72, 101, 108, 108, 111]\n *\n * @example\n * // Double-encoded: base64(base64(bytes))\n * decodeField(\"U0dWc2JHOGU=\", 5); // => Uint8Array [72, 101, 108, 108, 111]\n */\nexport const decodeField = (\n field: string,\n expectedLength?: number\n): Uint8Array => {\n const bytes = base64ToUint8Array(field);\n if (expectedLength && bytes.length !== expectedLength) {\n // If we got exactly twice as many bytes as expected, assume double-encoding.\n if (bytes.length === expectedLength * 2) {\n const intermediateStr = new TextDecoder().decode(bytes);\n const secondBytes = base64ToUint8Array(intermediateStr);\n if (secondBytes.length === expectedLength) {\n return secondBytes;\n }\n }\n }\n return bytes;\n};\n\n/**\n * Conditional debug logging utility.\n * Only logs when DEBUG flag is enabled in config.\n * \n * @param message - The message to log\n * @param optionalParams - Additional parameters to log\n */\nexport const debugLog = (message?: any, ...optionalParams: any[]) => {\n if (DEBUG) {\n console.log(message, ...optionalParams);\n }\n};\n","import { assert } from \"./assert\";\nimport { formatUnits, parseUnits } from \"viem\";\nimport { getApi } from \"../chain\";\n\nexport const PALI_SYMBOL = \"PALI\";\nexport const PALI_DECIMALS = 18;\n\ninterface TokenProperties {\n symbol: string;\n decimals: number;\n}\n\nexport type PaliAmountInput = string | number;\nexport type AtomicPaliAmount = bigint;\n\nlet tokenCache: TokenProperties | null = null;\n\nexport const toAtomicPaliAmount = (amount: PaliAmountInput): AtomicPaliAmount => {\n const normalizedAmount = String(amount).trim();\n\n if (!normalizedAmount) {\n throw new Error(\"Token amount cannot be empty\");\n }\n\n return parseUnits(normalizedAmount, PALI_DECIMALS);\n};\n\nexport const fromAtomicPaliAmount = (amount: bigint): string => {\n return formatUnits(amount, PALI_DECIMALS);\n};\n\nexport const formatPaliAmount = (amount: bigint, symbol: string = PALI_SYMBOL): string => {\n return `${fromAtomicPaliAmount(amount)} ${symbol}`;\n};\n\n/**\n * Fetch token name and decimals from RPC system properties\n * Results are cached for subsequent calls\n * @param rpc - RPC provider instance with system.properties method\n * @returns Promise<TokenProperties> with symbol and decimals\n */\nexport async function fetchTokenProperties(): Promise<TokenProperties> {\n // Return cached value if available\n if (tokenCache) {\n return tokenCache;\n }\n\n try {\n const systemProperties = (await (await getApi())?.rpc.system.properties())?.toHuman();\n\n assert(systemProperties, \"Failed to fetch system properties from RPC\");\n\n const tokenProperties: TokenProperties = {\n symbol: (systemProperties?.tokenSymbol as string[] || [PALI_SYMBOL])[0],\n decimals: Number((systemProperties?.tokenDecimals as string[] || [String(PALI_DECIMALS)])[0]),\n };\n\n // Store in cache\n tokenCache = tokenProperties;\n\n return tokenProperties;\n } catch (error) {\n throw error;\n }\n}\n\n/**\n * Get cached token properties without making an RPC call\n * @returns TokenProperties or null if not yet cached\n */\nexport function getCachedTokenProperties(): TokenProperties | null {\n return tokenCache;\n}\n\n/**\n * Clear the token properties cache\n */\nexport function clearTokenCache(): void {\n tokenCache = null;\n}\n\n/**\n * Format balance using cached token properties\n * @param balance - The balance value to format\n * @returns Formatted balance string\n */\nexport async function formatBalanceWithTokenProperties(balance: string | number | bigint): Promise<string> {\n const tokenProperties = await fetchTokenProperties();\n\n return `${formatUnits(typeof balance === \"bigint\" ? balance : BigInt(balance), tokenProperties.decimals)} ${tokenProperties.symbol}`;\n}\n\nexport const tokenToBigint = toAtomicPaliAmount;\n","/**\n * Module providing singleton access to Polkadot API, WebSocket provider, and keyring.\n *\n * This module ensures that only one instance of the WsProvider, ApiPromise and Keyring\n * are created and reused across the application. It exposes a class-based wrapper\n * (RpcApi) for managed connect/disconnect flows and convenience functions for directly\n * obtaining the singleton instances.\n *\n * Notes:\n * - The API is created with custom RPC, types and signed extensions provided by\n * {@link API_RPC}, {@link API_TYPES} and {@link API_EXTENSIONS}.\n * - In non-test environments, the module attaches fatal handlers to the API that call\n * `process.exit(0)` on error/disconnect to allow an external supervisor to restart\n * the process.\n * - The keyring is created for `sr25519` keys. The convenience getter populates a\n * default development account derived from the well-known dev URI `//Bob`\n * (named \"Bob default\"). This is a development-only seed and MUST NOT be used\n * in production.\n */\nimport { ApiPromise, Keyring, WsProvider } from \"@polkadot/api\";\nimport { API_EXTENSIONS, API_RPC, API_TYPES } from \"./spec\";\nimport { provider } from \"./wsProvider\";\nimport { waitReady } from \"@polkadot/wasm-crypto\";\n\n// Create singleton instances\nlet wsProvider: WsProvider | null = null;\nlet api: ApiPromise | null = null;\nlet keyring: Keyring | null = null;\n// Separate keyring instance intended for encryption-related keys/usages.\nlet encKeyring: Keyring | null = null;\nlet apiListenersAttached = false;\nlet apiTeardownInProgress = false;\n\n/**\n * getApi()\n *\n * Returns the singleton {@link ApiPromise} instance, creating it if necessary.\n *\n * @remarks\n * - If no underlying `provider` is configured (the module-level `provider`\n * imported from \"./wsProvider\"), this function returns `undefined`.\n * - When creating the API, the configured `rpc`, `types` and `signedExtensions`\n * are applied.\n * - In non-test environments, top-level API `error` and `disconnected` events\n * cause the process to exit so that an external supervisor can restart the\n * process.\n *\n * @param cb - Optional callback function to attach to the \"disconnected\" event.\n *\n * @returns The singleton {@link ApiPromise} instance (or `undefined` if no provider).\n */\nexport async function getApi(cb?: () => void) {\n if (!provider) return;\n\n if (!api) {\n api = await ApiPromise.create({\n provider,\n rpc: API_RPC,\n types: API_TYPES,\n signedExtensions: API_EXTENSIONS,\n });\n }\n const isNode = typeof process !== \"undefined\" && typeof process.exit === \"function\";\n const isTest = typeof process !== \"undefined\" && process.env?.NODE_ENV === \"test\";\n if (isNode && !isTest && api && !apiListenersAttached) {\n apiListenersAttached = true;\n api.on(\"error\", (err) => {\n if (apiTeardownInProgress) return;\n apiTeardownInProgress = true;\n apiListenersAttached = false;\n\n const currentApi = api;\n api = null;\n\n void currentApi?.disconnect().catch((disconnectErr) => {\n apiTeardownInProgress = false;\n console.error(\"api disconnect after error failed:\", disconnectErr);\n });\n });\n api.on(\"disconnected\", () => {\n api = null;\n apiListenersAttached = false;\n apiTeardownInProgress = false;\n if (cb) cb();\n });\n }\n return api;\n}\n\n/**\n * getKeyring()\n *\n * Returns the singleton {@link Keyring} instance, creating it if necessary.\n *\n * @remarks\n * - Ensures {@link waitReady} has resolved before constructing the keyring so\n * that WASM crypto is initialized.\n * - The keyring is created with `type: \"sr25519\"`.\n * - The function also adds a default development account from the dev seed URI\n * `//Bob` and labels it \"Bob default\".\n *\n * @important\n * The seed URI `//Bob` is a well-known development seed. It is convenient for\n * local testing but is insecure for any real funds or production use. Replace\n * or remove this default account when deploying to production.\n *\n * @returns The singleton {@link Keyring} instance.\n */\nexport async function getKeyring() {\n if (!keyring) {\n await waitReady();\n keyring = new Keyring({ type: \"sr25519\" });\n keyring.addFromUri('//Bob', { name: 'Bob default' });\n }\n return keyring;\n}\n\n/**\n * getEncKeyring()\n *\n * Returns the singleton encryption-focused {@link Keyring} instance, creating it\n * if necessary.\n *\n * @remarks\n * - Ensures {@link waitReady} has resolved before constructing the keyring so\n * that WASM crypto is initialized.\n * - The keyring is created with `type: \"sr25519\"` and a development default\n * account derived from the dev seed URI `//Bob` is added and labeled\n * \"Bob default (enc)\".\n *\n * @important\n * The seed URI `//Bob` is a well-known development seed and MUST NOT be used\n * in production for real funds. Replace or remove this default when deploying\n * to production.\n *\n * @returns The singleton {@link Keyring} instance used for encryption keys.\n */\nexport async function getEncKeyring() {\n if (!encKeyring) {\n await waitReady();\n encKeyring = new Keyring({ type: \"ed25519\" });\n encKeyring.addFromUri('//Bob', { name: 'Bob default (enc)' });\n }\n return encKeyring;\n}\n","import { WsProvider } from \"@polkadot/api\";\nimport { PALLIORA_WS } from \"../config\";\n\nexport const provider = new WsProvider(PALLIORA_WS, 10000);\n","import { TX_WAIT_FINALIZATION } from \"../config\";\nimport { getApi } from \"./singleton\";\nimport { isFunction } from \"@polkadot/util\";\nimport { DEFAULT_COMPUTE_PAYLOAD } from \"./spec\";\nimport bs58 from \"bs58\";\nimport { getGuardianList } from \"../guardian\";\nimport { assert, debugLog } from \"../utils\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\nimport type { SubmittableExtrinsic } from \"@polkadot/api/types\";\nimport type { ISubmittableResult } from \"@polkadot/types/types\";\nimport type { EventRecord } from \"@polkadot/types/interfaces\";\nimport type { ApiPromise } from \"@polkadot/api\";\nimport type { Header, SignedBlock } from \"@polkadot/types/interfaces\";\nimport { SubmissionReceipt } from \"./types\";\n\n/** ISubmittableResult extended with the concrete blockNumber present after finalization */\ninterface SubmittableResultExtended extends ISubmittableResult {\n readonly blockNumber?: { toNumber(): number };\n}\n\nexport const signAndSend = async (request: SubmittableExtrinsic<'promise'>, account: KeyringPair, opts: Record<string, unknown> = DEFAULT_COMPUTE_PAYLOAD) => {\n const tx_result: SubmittableResultExtended = await new Promise((res, err) => {\n // opts contains custom chain-specific fields (da_type, compute, etc.) that extend SignerOptions\n request.signAndSend(account, opts as Parameters<typeof request.signAndSend>[1], (result: SubmittableResultExtended) => {\n // console.trace(result.toHuman());\n if (result.isFinalized) {\n res(result);\n }\n if (!TX_WAIT_FINALIZATION && result.isInBlock) {\n res(result);\n }\n if (result.isError) err(result);\n });\n });\n // console.trace(tx_result.toHuman());\n\n if (tx_result.isError) {\n throw new Error(`Transaction failed with error: ${tx_result.dispatchError}`);\n }\n\n if (tx_result.dispatchError) {\n throw new Error(\n `Transaction dispatched with error: ${tx_result.dispatchError}`\n );\n }\n\n console.debug(\n `Transaction ${tx_result.txHash.toHex()} included in timepoint ${\n tx_result.blockNumber\n }-${tx_result.txIndex}`\n );\n\n return {\n blockNumber: tx_result.blockNumber?.toNumber() ?? 0,\n index: tx_result.txIndex ?? 0,\n hash: tx_result.txHash.toHex(),\n tx_result: tx_result as ISubmittableResult,\n };\n};\n\nexport const getFileMetadataCall = async (\n api: ApiPromise,\n metadataRef: [number, number]\n) => {\n const block = await getBlock(api, metadataRef[0]);\n const call = block.block.extrinsics[metadataRef[1]];\n return call.method;\n};\n\nconst getBlock = async (api: ApiPromise, blockNumber: number) => {\n const blockHash = await api.rpc.chain.getBlockHash(blockNumber);\n return await api.rpc.chain.getBlock(blockHash);\n};\n\nexport const getGuardianAddress = async () => {\n const api = await getApi();\n\n if (!api) throw new Error(\"API not initialized\");\n assert(\n isFunction(api.query[\"guardian\"]?.[\"workerByKey\"]),\n `api.query.guardian.workerByKey does not exist`,\n );\n\n const list = await getGuardianList();\n\n const addresses = await Promise.all(\n list.map(async (item) => {\n const peerid = bs58.decode(item).slice(6, 38);\n return ((await api.query[\"guardian\"][\"workerByKey\"](peerid)).toString());\n })\n );\n\n return list.map((peerid, index) => ({ peerid, address: addresses[index] }));\n};\n\nexport const getGuardianNwParams = async () => {\n try {\n const api = await getApi();\n if (!api) throw new Error(\"API not initialized\");\n\n const rpc = api.rpc as unknown as Record<\n string,\n Record<string, (...params: unknown[]) => Promise<unknown>>\n >;\n const section = \"guardian\";\n const method = \"guardianNwParams\";\n\n assert(\n isFunction(rpc[section]?.[method]),\n `api.rpc.${section}.guardianNwParams does not exist`\n );\n\n const guardianNwParams = (await rpc[section][method]()) as Record<\n string,\n unknown\n >;\n if (\n typeof guardianNwParams === \"object\" &&\n guardianNwParams !== null &&\n \"kzg\" in guardianNwParams\n ) {\n return (guardianNwParams.kzg as { toHex(): string }).toHex().slice(2);\n } else {\n throw new Error(`Invalid ${guardianNwParams} format`);\n }\n } catch (error) {\n console.error({ error });\n throw error;\n }\n};\n\n/**\n * Fetches the block at `blockHeight`, extracts the extrinsic at\n * `extrinsicIndex`, and returns both the raw codec object and its human-readable\n * decoded form.\n *\n * Throws if the block cannot be found or the index is out of range.\n */\nexport async function fetchAndDecodeExtrinsic(\n blockHeight: number,\n extrinsicIndex: number,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Promise<{ raw: any; decoded: Record<string, unknown> }> {\n const api = await getApi();\n if (!api) throw new Error(\"API not initialized\");\n\n const blockHash = await api.rpc.chain.getBlockHash(blockHeight);\n const signedBlock = await api.rpc.chain.getBlock(blockHash);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const extrinsics: any[] = signedBlock.block.extrinsics;\n if (extrinsicIndex >= extrinsics.length) {\n throw new Error(\n `extrinsic index ${extrinsicIndex} out of range — ` +\n `block ${blockHeight} has ${extrinsics.length} extrinsics`,\n );\n }\n\n const raw = extrinsics[extrinsicIndex];\n const decoded = raw.toHuman() as Record<string, unknown>;\n\n return { raw, decoded };\n}\n\nexport type BlockScanFilter =\n | {\n /** Pallet name, e.g. \"dataAvailability\" (case-insensitive) */\n section: string;\n /** Event name, e.g. \"DaccGuardianGroup\" (case-insensitive) */\n method: string;\n predicate?: never;\n }\n | {\n /**\n * Custom predicate called for every event record in each scanned block.\n * The full signed block is pre-fetched before any predicate call.\n * Return true to accept the match and resolve, false to skip and keep scanning.\n */\n predicate: (block: SignedBlock, event: EventRecord['event'], phase: EventRecord['phase']) => boolean | Promise<boolean>;\n section?: never;\n method?: never;\n };\n\nexport type BlockScanResult = {\n blockHash: string;\n blockNumber: number;\n /** Index of the extrinsic that emitted the event, or null for inherents */\n extrinsicIndex: number | null;\n /** Returns the full signed block; cached when predicate mode was used */\n block: () => Promise<SignedBlock>;\n /** All event records for this block */\n events: EventRecord[];\n};\n\n/**\n * Subscribes to new block headers and resolves with a match descriptor as soon\n * as a qualifying event is found.\n *\n * Supply exactly one of:\n * - `section` + `method` — lightweight name match, no block fetch\n * - `predicate(block, event, phase)` — full control; block is pre-fetched\n *\n * @param api Connected ApiPromise instance\n * @param filter Either a name filter or a predicate (mutually exclusive)\n * @param startBlock Ignore blocks with a number strictly below this value\n * @param maxBlocks Reject after scanning this many blocks; pass 0 to wait indefinitely (default 20)\n */\nexport const scanForBlockEvent = (\n api: ApiPromise,\n filter: BlockScanFilter,\n startBlock?: number,\n maxBlocks = 20\n): Promise<BlockScanResult> => {\n const hasPredicate = \"predicate\" in filter;\n let blocksScanned = 0;\n let done = false;\n\n return new Promise((resolve, reject) => {\n const unsubPromise: Promise<() => void> = api.rpc.chain.subscribeNewHeads(\n async (header: Header) => {\n if (done) return;\n\n const currentBlock: number = header.number.toNumber();\n if (startBlock !== undefined && currentBlock < startBlock) return;\n\n blocksScanned++;\n if (maxBlocks > 0 && blocksScanned > maxBlocks) {\n done = true;\n unsubPromise.then((unsub) => unsub());\n reject(new Error(`No matching event found within ${maxBlocks} blocks`));\n return;\n }\n\n try {\n const blockHash = await api.rpc.chain.getBlockHash(currentBlock);\n\n // Pre-fetch block when using predicate so the caller can inspect extrinsics\n const eventsResult = await api.query.system.events.at(blockHash);\n const events = eventsResult as unknown as EventRecord[];\n const blockData: SignedBlock | null = await (hasPredicate ? api.rpc.chain.getBlock(blockHash) : Promise.resolve(null));\n\n for (const record of events) {\n const { event, phase } = record;\n\n const matched: boolean = hasPredicate\n ? await (filter as { predicate: Function }).predicate(blockData, event, phase)\n : event.section.toLowerCase() === (filter as { section: string; method: string }).section.toLowerCase() &&\n event.method.toLowerCase() === (filter as { section: string; method: string }).method.toLowerCase();\n\n if (!matched) continue;\n\n done = true;\n unsubPromise.then((unsub) => unsub());\n resolve({\n blockHash: blockHash.toHex(),\n blockNumber: currentBlock,\n extrinsicIndex: phase.isApplyExtrinsic ? phase.asApplyExtrinsic.toNumber() : null,\n block: blockData ? () => Promise.resolve(blockData) : () => api.rpc.chain.getBlock(blockHash),\n events,\n });\n return;\n }\n } catch (err) {\n debugLog(`scanForBlockEvent: error scanning block ${currentBlock}: ${err}`);\n }\n }\n );\n });\n};\n\n/**\n * Subscribes to new block headers and scans each block's extrinsics until a\n * `compute.result` extrinsic matching `requestId` is found. Resolves with the\n * {@link SubmissionReceipt} (extrinsic hash, block height, and extrinsic index).\n *\n * The result-relay submits the extrinsic asynchronously, so this watcher may\n * need to observe several blocks before the tx lands.\n *\n * @param requestId - The hex-encoded request ID to match (e.g. \"0xabc123…\").\n * @param timeoutMs - Milliseconds to wait before giving up (default: 10 min).\n */\nexport async function watchForSubmissionReceipt(\n requestId: string,\n timeoutMs = 10 * 60 * 1_000,\n): Promise<SubmissionReceipt> {\n const api = await getApi();\n if (!api) throw new Error(\"API not initialized\");\n\n return new Promise<SubmissionReceipt>((resolve, reject) => {\n let unsubFn: (() => void) | undefined;\n let settled = false;\n\n const cleanup = (settleFn: () => void) => {\n if (settled) return;\n settled = true;\n unsubFn?.();\n settleFn();\n };\n\n const timer = setTimeout(\n () => cleanup(() => reject(new Error(`receipt watch timed out for requestId=${requestId}`))),\n timeoutMs,\n );\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n api.rpc.chain.subscribeNewHeads(async (header: any) => {\n if (settled) return;\n try {\n const blockNumber: number = header.number.toNumber();\n const blockHash = header.hash;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const signedBlock: any = await api.rpc.chain.getBlock(blockHash);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const extrinsics: any[] = signedBlock.block.extrinsics;\n\n for (let i = 0; i < extrinsics.length; i++) {\n const ext = extrinsics[i];\n const decoded = ext.toHuman() as Record<string, unknown>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const method = decoded?.method as any;\n\n if (\n String(method?.section ?? '').toLowerCase() === 'compute' &&\n String(method?.method ?? '').toLowerCase() === 'result'\n ) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const args = method?.args as any;\n // The first argument to compute.result is the request ID.\n const onChainId = String(args?.request_id ?? args?.requestId ?? args?.[0] ?? '');\n\n if (onChainId === requestId) {\n clearTimeout(timer);\n cleanup(() =>\n resolve({\n extrinsicHash: (ext.hash as { toHex(): string }).toHex(),\n blockHeight: blockNumber,\n extrinsicIndex: i,\n }),\n );\n return;\n }\n }\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.warn(`[watchReceipt] block check failed requestId=${requestId}: ${msg}`);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }).then((fn: any) => {\n if (settled) {\n // Already resolved/rejected before the subscribe promise returned — unsub now.\n (fn as () => void)();\n } else {\n unsubFn = fn as () => void;\n }\n }).catch((err: unknown) => {\n clearTimeout(timer);\n cleanup(() => reject(err));\n });\n });\n}\n\n/**\n * Fetches block events at `blockHeight` and returns the request ID from the\n * `compute.AgreementCreated` event emitted by the extrinsic at `extrinsicIndex`.\n * Returns `null` if no matching event is found for that extrinsic.\n */\nexport async function getAgreementCreatedRequestId(\n blockHeight: number,\n extrinsicIndex: number,\n): Promise<string | null> {\n const api = await getApi();\n if (!api) throw new Error(\"API not initialized\");\n\n const blockHash = await api.rpc.chain.getBlockHash(blockHeight);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const apiAt = await api.at(blockHash);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const allEvents = (await apiAt.query.system.events()) as unknown as EventRecord[];\n\n for (const record of allEvents) {\n const { phase, event } = record;\n\n // Only consider events produced by the extrinsic at our index.\n if (!phase.isApplyExtrinsic || phase.asApplyExtrinsic.toNumber() !== extrinsicIndex) {\n continue;\n }\n\n if (\n String(event.section ?? '').toLowerCase() !== 'compute' ||\n String(event.method ?? '').toLowerCase() !== 'agreementcreated'\n ) {\n continue;\n }\n\n // Decode event data and extract the request ID.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const dataHuman = event.data.toHuman() as Record<string, unknown> | unknown[];\n if (Array.isArray(dataHuman)) {\n const first = dataHuman[0];\n if (first != null) return String(first);\n } else if (dataHuman !== null && typeof dataHuman === 'object') {\n const id = dataHuman['requestId'] ?? dataHuman['request_id'] ?? dataHuman['id'];\n if (id != null) return String(id);\n }\n }\n\n return null;\n}\n","import { getApi } from \"../chain\";\nimport { isFunction } from \"@polkadot/util\";\nimport { assert } from \"../utils\";\n\nexport const getGuardianList = async () => {\n const api = await getApi();\n if (!api) throw new Error(\"API not initialized\");\n\n const rpc = api.rpc as unknown as Record<\n string,\n Record<string, (...params: unknown[]) => Promise<unknown>>\n >;\n const section = \"guardian\";\n const method = \"guardianList\";\n\n assert(\n isFunction(rpc[section]?.[method]),\n `api.rpc.${section}.${method} does not exist`,\n );\n\n const list = ((await rpc[section][\"guardianList\"]()) as Array<Text>)\n .map((item) => [item.toString()])\n .flat(1);\n\n return list;\n};\n","import { getApi, getGuardianNwParams, signAndSend, scanForBlockEvent } from \"../chain\";\nimport { GuardianGroupInfo } from \"..\";\nimport { hexToUint8Array, debugLog, assert } from \"../utils\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\nimport type { GuardianAddress } from \"../da/types\";\n\nexport const createGuardianGroup = async (account: KeyringPair, selectedGuardians: GuardianAddress[]) => {\n try {\n const api = await getApi();\n\n assert(selectedGuardians.length >= 3, \"Not enough guardians available to create a group\");\n assert(account, \"Failed to load account\");\n assert(api, \"Failed to initialize API\");\n\n const tau_params = await getGuardianNwParams();\n assert(tau_params && tau_params !== \"\", \"Failed to retrieve guardian network parameters\");\n\n // For simplicity, select the first 3 guardians\n debugLog(`Selected guardians: ${selectedGuardians.join(\", \")} and tau_params: ${tau_params}`);\n\n // Create and send the transaction\n const tx = api.tx.dataAvailability.daccGuardianGroup(\n selectedGuardians,\n Array.from(hexToUint8Array(tau_params as `0x${string}`)) // Use the new helper function\n );\n const result = await signAndSend(tx, account);\n\n debugLog(\"Guardian group created:\", result);\n return result;\n } catch (error) {\n console.error(\"Error creating guardian group:\", error);\n throw new Error(`Failed to create guardian group: ${error instanceof Error ? error.message : error}`);\n }\n};\n\n/**\n * Creates a guardian group with exactly 3 guardians, waits for tx confirmation,\n * then watches incoming blocks for the `DaccGuardianGroup` event (emitted by a\n * subsequent `daccGuardianGroupInfo` extrinsic) and returns the decoded args.\n *\n * @param account Signing account\n * @param guardians Exactly 3 guardian addresses / peer-ids\n * @param maxBlocks Give up waiting for the event after this many blocks; 0 = indefinite (default 20)\n */\nexport const createGuardianGroupAndWatch = async (\n account: KeyringPair,\n guardians: GuardianAddress[],\n maxBlocks = 20\n): Promise<GuardianGroupInfo> => {\n assert(guardians.length === 3, \"Exactly 3 guardians are required\");\n assert(account, \"Failed to load account\");\n\n const api = await getApi();\n assert(api, \"Failed to initialize API\");\n\n debugLog(`Submitting guardian group creation...`);\n // daccGuardianGroup emits DaccGuardianGroup with empty group_pk/tau_params/agg_key.\n // Start listening from the next block so we only catch the DaccGuardianGroup event\n // emitted by the subsequent daccGuardianGroupInfo extrinsic.\n const creationResult = await createGuardianGroup(account, guardians);\n const startBlock: number = (creationResult?.blockNumber ?? 0) + 1;\n debugLog(`Group creation tx confirmed at block ${startBlock - 1}. Listening for DaccGuardianGroup event from block ${startBlock}...`);\n\n const match = await scanForBlockEvent(\n api,\n {\n predicate: async (block, event, phase) => {\n if (\n event.section.toLowerCase() !== \"dataavailability\" ||\n event.method.toLowerCase() !== \"daccguardiangroup\"\n ) return false;\n if (!phase.isApplyExtrinsic) return false;\n const ext = block.block.extrinsics[phase.asApplyExtrinsic.toNumber()];\n return (\n ext?.method?.section?.toLowerCase() === \"dataavailability\" &&\n ext?.method?.method?.toLowerCase() === \"daccguardiangroupinfo\"\n );\n },\n },\n startBlock,\n maxBlocks\n );\n\n // Block is pre-fetched by scanForBlockEvent when using predicate mode\n assert(match.extrinsicIndex !== null, \"DaccGuardianGroup event was not emitted by an extrinsic\");\n debugLog(`DaccGuardianGroup event found at block ${match.blockNumber}, extrinsic index ${match.extrinsicIndex}. Decoding args...`);\n\n const block = await match.block();\n const ext = block.block.extrinsics[match.extrinsicIndex];\n\n // daccGuardianGroupInfo(group_id: H256, group_pk: AppData, tau_params: AppData, agg_key: AppData)\n const [group_id, group_pk, tau_params, agg_key] = ext.method.args;\n debugLog(`Guardian group parameters decoded: group_id=${group_id.toHex()}`);\n\n return {\n groupId: group_id.toHex(),\n groupPk: group_pk.toHex(),\n tauParams: tau_params.toHex(),\n aggKey: agg_key.toHex(),\n guardians,\n };\n};\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\nimport { formatPaliAmount } from \"../utils/token\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\n\nexport interface GuardianJoinPrefs {\n compute?: string;\n fee?: bigint | string | number;\n standard?: boolean;\n verifier?: boolean;\n}\n\nexport async function joinGuardian(account: KeyringPair, prefs: GuardianJoinPrefs) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n const computeOpts =\n (prefs.compute as string | undefined)\n ?.split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0) || undefined;\n\n const feeThreshold =\n typeof prefs.fee === \"bigint\" ? prefs.fee : BigInt(prefs.fee || \"0\");\n\n const guardianPrefs = {\n pubKey: account.publicKey,\n guardian: prefs.standard,\n verifier: prefs.verifier,\n compute: prefs.compute ? true : false,\n computePrefs: {\n trusted: computeOpts?.includes(\"trusted\") || false,\n tee: computeOpts?.includes(\"tee\") || false,\n mpc: computeOpts?.includes(\"mpc\") || false,\n fhe: computeOpts?.includes(\"fhe\") || false,\n zkp: computeOpts?.includes(\"zkp\") || false,\n },\n feeThreshold,\n };\n\n debugLog(\n account.address,\n \"joining as guardian with preferences:\",\n { ...guardianPrefs, feeThreshold: formatPaliAmount(feeThreshold) }\n );\n\n const guardTx = api.tx.staking.guard(guardianPrefs);\n const hash = await signAndSend(guardTx, account);\n\n debugLog(\"Guardian join tx sent with hash:\", hash.hash);\n}\n","\nimport { ApiPromise } from \"@polkadot/api\";\nimport { testCrypt } from \"../crypto/core\";\nimport { encrypt, gen_stretched_key } from \"../crypto/cipher\";\nimport { hexToUint8Array, uint8ArrayToBase64 } from \"../utils\";\nimport type { Hex } from \"viem\";\nimport { signAndSend } from \"./utils\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\nimport type { GuardianGroupInfo } from \"../da/types\";\n\ntype OnChainFileOptions = {\n\tfile: File;\n\tfilePath: string,\n\tfileName: string;\n\tdescription: string;\n\tbaseCost: bigint;\n\townerL2Address: string;\n\tguardianInfo: GuardianGroupInfo;\n}\n\ntype ChunkRef = { blockNumber: number; extrinsicIndex: number };\n\ntype FileMetadata = {\n\tname: string;\n\tdescription: string;\n\tstartRef: [number, number];\n};\n\nconst getBlock = async (api: ApiPromise, blockNumber: number) => {\n\tconst blockHash = await api.rpc.chain.getBlockHash(blockNumber);\n\treturn await api.rpc.chain.getBlock(blockHash);\n};\nconst getFileMetadataCall = async (api: ApiPromise, metadataRef: [number, number]) => {\n\tconst block = await getBlock(api, metadataRef[0]);\n\tconst call = block.block.extrinsics[metadataRef[1]];\n\treturn call.method;\n};\n\nconst getFileMetadata = async (api: ApiPromise, metadataRef: [number, number]): Promise<FileMetadata> => {\n\tconst call = await getFileMetadataCall(api, metadataRef);\n\n\t// @ts-expect-error\n\tconst name = new TextDecoder().decode(call.args[0]);\n\t// @ts-expect-error\n\tconst description = new TextDecoder().decode(call.args[1]);\n\t// @ts-expect-error\n\tconst startRef = [call.args[2][0].toNumber(), call.args[2][1].toNumber()] as [number, number];\n\n\treturn {\n\t\tname,\n\t\tdescription,\n\t\tstartRef,\n\t};\n};\n\nasync function getFileSHA256(file: File): Promise<string> {\n\tconst buffer = new Array(12).fill(8);\n\t// const hashBuffer = await crypto.subtle.digest(\"SHA-256\", buffer);\n\tconst hashArray = Array.from(new Uint8Array(buffer));\n\tconst hashHex = hashArray.map(b => b.toString(16).padStart(2, \"0\")).join(\"\");\n\treturn hashHex;\n\n}\n\nconst readDataFromChain = async (api: ApiPromise, dataRef: [number, number]) => {\n\tconst call = await getFileMetadataCall(api, dataRef);\n\treturn call.args[0].toU8a();\n};\n\nclass MCryptFs {\n\t_api;\n\t_init;\n\t_metaRef: [number, number] | null;\n\t_metadata: FileMetadata | null;\n\t_chunkRefs: ChunkRef[];\n\n\tconstructor(mcryptApi: any, metadataRef: [number, number] | null, metadata: FileMetadata | null) {\n\t\tthis._api = mcryptApi;\n\t\tthis._metaRef = metadataRef;\n\t\tthis._metadata = metadata;\n\t\tthis._init = true;\n\t\tthis._chunkRefs = [];\n\t}\n\n\tstatic dummyInstance(mcryptApi: any) {\n\t\treturn new MCryptFs(mcryptApi, null, null);\n\t}\n\n\tisValid() {\n\t\tif (!this._metaRef) {\n\t\t\tthrow new Error(\"Metadata reference not set\");\n\t\t}\n\n\t\tif (\n\t\t\t!this._metadata ||\n\t\t\t!this._metadata.name ||\n\t\t\t!this._metadata.description ||\n\t\t\t!this._metadata.startRef\n\t\t) {\n\t\t\tthrow new Error(\"Metadata not set properly\");\n\t\t}\n\t}\n\n\tgetMetadata() {\n\t\tthis.isValid();\n\t\treturn this._metadata;\n\t}\n}\n\nclass MCryptFsWriter {\n\t_file;\n\t_filePath;\n\t_description;\n\t_chunkSize;\n\t_fileKey: string;\n\t_fileName: string;\n\t_baseCost;\n\t_ownerL2Address;\n\t_guardianInfo: GuardianGroupInfo;\n\t_api;\n\t_account: KeyringPair;\n\t_chunkRefs: ChunkRef[];\n\t_blockNumber;\n\t_extrinsicIndex;\n\t_progress;\n\t_error: Error | null;\n\n\tconstructor(fileOptions: OnChainFileOptions, chunkSize = 500, mcryptApi: any, account: KeyringPair) {\n\t\tconst {\n\t\t\tfile: iFile,\n\t\t\tfilePath,\n\t\t\tfileName,\n\t\t\tdescription,\n\t\t\tbaseCost,\n\t\t\townerL2Address,\n\t\t\tguardianInfo,\n\t\t} = fileOptions;\n\n\t\tthis._file = iFile;\n\t\tthis._filePath = filePath;\n\t\tthis._description = description;\n\t\tthis._fileName = fileName;\n\t\tthis._baseCost = baseCost;\n\t\tthis._fileKey = \"\";\n\t\tthis._ownerL2Address = ownerL2Address;\n\t\tthis._guardianInfo = guardianInfo;\n\t\tthis._chunkSize = chunkSize * 1024;\n\t\tthis._api = mcryptApi;\n\t\tthis._account = account;\n\n\t\tthis._chunkRefs = [];\n\t\tthis._blockNumber = 0;\n\t\tthis._extrinsicIndex = 0;\n\n\t\tthis._progress = {\n\t\t\tiFileSize: iFile.size,\n\t\t\tiBlocksWritten: 0,\n\t\t};\n\n\t\tthis._error = null;\n\t}\n\n\tprependMetadata(chunk: Blob) {\n\t\tconst blockNumberBuffer = new ArrayBuffer(4);\n\t\tconst blockView = new DataView(blockNumberBuffer);\n\t\tblockView.setUint32(0, this._blockNumber, false);\n\n\t\tconst extIndexBuffer = new ArrayBuffer(4);\n\t\tconst extView = new DataView(extIndexBuffer);\n\t\textView.setUint32(0, this._extrinsicIndex, false);\n\n\t\treturn new Blob([blockNumberBuffer, extIndexBuffer, chunk]);\n\t}\n\n\tasync writeChunk(chunk: Blob): Promise<{ blockNumber: number; index: number }> {\n\t\tconst request = this._api.tx.dataAvailability.submitData(\n\t\t\tArray.from(new Uint8Array(await chunk.arrayBuffer()))\n\t\t);\n\t\tconsole.log(\"account: \", this._account);\n\t\treturn new Promise<{ blockNumber: number; index: number }>((resolve) => {\n\t\t\trequest.signAndSend(this._account, { app_id: 1 }, (result: { isInBlock: boolean; isFinalized: boolean; isError: boolean; blockNumber?: { toNumber(): number }; txIndex?: number }) => {\n\t\t\t\tif (result.isInBlock || result.isFinalized || result.isError) {\n\t\t\t\t\tresolve({\n\t\t\t\t\t\tblockNumber: result.blockNumber?.toNumber() ?? 0,\n\t\t\t\t\t\tindex: result.txIndex ?? 0,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\tasync submitKey(account: KeyringPair, data: string) {\n\t\tconst { encoded: encryptedKey, ikm } = testCrypt(this._guardianInfo.tauParams, this._guardianInfo.aggKey);\n\n\t\tconst td_params = uint8ArrayToBase64(hexToUint8Array(encryptedKey as Hex));\n\t\tconst shared_key = gen_stretched_key(\n\t\t\thexToUint8Array(ikm as Hex),\n\t\t);\n\t\tconst { ciphertext, nonce } = encrypt(\n\t\t\tnew Uint8Array(Uint8Array.from(data)),\n\t\t\tshared_key\n\t\t);\n\t\tconst blobRef = this._chunkRefs[this._chunkRefs.length - 1];\n\n\t\tconst modelSubmit = JSON.stringify({\n\t\t\tnonce: uint8ArrayToBase64(Uint8Array.from(nonce)),\n\t\t\tciphertext: uint8ArrayToBase64(Uint8Array.from(ciphertext)),\n\t\t\ttd_params,\n\t\t\tgroup_pk: this._guardianInfo.groupPk,\n\t\t\ttau_params: this._guardianInfo.tauParams,\n\t\t\tchosen_guardians: this._guardianInfo.guardians,\n\t\t\tblobRef: [blobRef.blockNumber, blobRef.extrinsicIndex],\n\t\t});\n\n\t\tconst request = this._api.tx.dataAvailability.submitData(modelSubmit);\n\t\treturn await signAndSend(request, account);\n\t}\n\n\tasync writeMetadata() {\n\n\t\tconst encoder = new TextEncoder();\n\t\tconst fileName = this._fileName;\n\t\tconst datasetRef = await this.submitKey(this._account, this._fileKey);\n\t\tconst keyRef = [datasetRef.blockNumber, datasetRef.index];\n\t\tconst request = this._api.tx.dataAvailability.daccRegisterData(\n\t\t\tArray.from(new TextEncoder().encode(fileName)),\n\t\t\tArray.from(new TextEncoder().encode(this._description)),\n\t\t\tkeyRef,\n\t\t\tthis._baseCost,\n\t\t\t0,\n\t\t\tArray.from(encoder.encode(this._ownerL2Address)),\n\t\t\tthis._guardianInfo.groupId,\n\t\t);\n\n\t\treturn await signAndSend(request, this._account);\n\t}\n\n\tasync writeFile() {\n\t\tconst chunks = [];\n\t\tlet offset = 0;\n\n\t\twhile (offset < this._file.size) {\n\t\t\tconst chunk = this._file.slice(offset, offset + this._chunkSize);\n\t\t\tconst prependedChunk = this.prependMetadata(chunk);\n\t\t\tconst blockInfo = await this.writeChunk(prependedChunk);\n\n\t\t\tthis._blockNumber = blockInfo.blockNumber;\n\t\t\tthis._extrinsicIndex = blockInfo.index;\n\t\t\tthis._progress.iBlocksWritten += chunk.size;\n\t\t\tthis._chunkRefs.push({\n\t\t\t\tblockNumber: this._blockNumber,\n\t\t\t\textrinsicIndex: this._extrinsicIndex,\n\t\t\t});\n\n\t\t\toffset += this._chunkSize;\n\t\t}\n\n\t\tthis._fileKey = (await getFileSHA256(this._file)) as string;\n\t\tconst metadataRef = await this.writeMetadata();\n\t\treturn await FileFromMetadataRef(this._api, [\n\t\t\tmetadataRef.blockNumber,\n\t\t\tmetadataRef.index ?? 0,\n\t\t]);\n\t}\n}\n\nclass MCryptFsReader {\n\t_filename;\n\t_api;\n\t_onChainFile: MCryptFs;\n\n\tconstructor(filename: string, mcryptApi: any, onChainFile: MCryptFs) {\n\t\tthis._filename = filename;\n\t\tthis._api = mcryptApi;\n\t\tthis._onChainFile = onChainFile;\n\t}\n\n\tasync downloadFile() {\n\t\tconst chunks = [];\n\n\t\tif (!this._onChainFile._metadata) {\n\t\t\tthrow new Error(\"Metadata not loaded\");\n\t\t}\n\n\t\tlet _blockNumber = this._onChainFile._metadata.startRef[0];\n\t\tlet _extIndex = this._onChainFile._metadata.startRef[1];\n\n\t\twhile (_blockNumber !== 0) {\n\t\t\tconst prependedChunk = await readDataFromChain(this._api, [\n\t\t\t\t_blockNumber,\n\t\t\t\t_extIndex,\n\t\t\t]);\n\t\t\tconst chunk = prependedChunk.slice(12);\n\t\t\tchunks.push(chunk);\n\n\t\t\tconst view = new DataView(new Uint8Array(prependedChunk).buffer);\n\t\t\t_blockNumber = view.getUint32(4);\n\t\t\t_extIndex = view.getUint32(8);\n\t\t}\n\n\t\t// Combine all chunks into a single blob\n\t\tconst blob = new Blob(chunks.reverse());\n\n\t\t// Create download link\n\t\tconst url = URL.createObjectURL(blob);\n\t\tconst a = document.createElement(\"a\");\n\t\ta.href = url;\n\t\ta.download = this._filename;\n\t\tdocument.body.appendChild(a);\n\t\ta.click();\n\t\tdocument.body.removeChild(a);\n\t\tURL.revokeObjectURL(url);\n\n\t\treturn blob;\n\t}\n}\n\nconst FileFromMetadataRef = async (mcryptApi: any, metadataRef: [number, number]) => {\n\tconst metadata = await getFileMetadata(mcryptApi, metadataRef);\n\treturn new MCryptFs(mcryptApi, metadataRef, metadata);\n};\n\nexport { MCryptFs, MCryptFsWriter, MCryptFsReader, FileFromMetadataRef };\n","import { getApi, getGuardianAddress, getKeyring, signAndSend } from \"../chain\";\nimport { assert, debugLog, toAtomicPaliAmount } from \"../utils\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\nimport type { SubmittableExtrinsic } from \"@polkadot/api/types\";\nimport type { GuardianAddress } from \"../da/types\";\n\nexport interface ComputeContract {\n contract_type: \"Active\" | \"Dormant\";\n guardians: GuardianAddress[];\n pre_check?: unknown;\n compute: Record<string, unknown>;\n post_check?: unknown;\n result_cipher: unknown;\n}\n\nexport async function createAgreement(\n contract: ComputeContract,\n account: KeyringPair,\n): Promise<{\n blockNumber: number;\n index: number;\n hash: string;\n agreementId?: string;\n}> {\n const api = await getApi();\n if (!api) throw new Error(\"Api not initialized\");\n\n const tx = (\n api.tx as Record<\n string,\n Record<string, (...args: unknown[]) => SubmittableExtrinsic<\"promise\">>\n >\n )[\"compute\"][\"agreement\"](contract);\n const opts = {\n compute: {\n da_type: 1,\n verification: 0,\n compute: contract.contract_type === \"Active\" ? 1 : 0,\n },\n };\n\n const { tx_result, blockNumber, index, hash } = await signAndSend(\n tx,\n account,\n opts,\n );\n\n if (!tx_result.isError) {\n const agreementCreatedEvent = tx_result.events.find(\n (event: {\n event: { section: string; method: string; data: unknown[] };\n }) => {\n return (\n event.event.section === \"compute\" &&\n event.event.method === \"AgreementCreated\"\n );\n },\n );\n\n if (agreementCreatedEvent) {\n debugLog(\"Agreement data:\", agreementCreatedEvent.event.data.toString());\n return {\n blockNumber,\n index: index ?? 0,\n hash,\n agreementId:\n agreementCreatedEvent.event.data[0]?.toHex?.() ??\n agreementCreatedEvent.event.data.toString(),\n };\n } else {\n debugLog(\"AgreementCreated event not found\");\n }\n }\n\n return { blockNumber, index: index ?? 0, hash };\n}\n\nexport async function createSimpleAgreement() {\n const guardianIds = (await getGuardianAddress())\n .slice(0, 3)\n .map((g) => g.address);\n assert(guardianIds.length === 3, \"Not enough guardians to create agreement\");\n\n const contract = {\n contract_type: \"Dormant\" as const,\n guardians: guardianIds,\n pre_check: null,\n compute: {\n cipher: \"Plaintext\",\n computer_indices: [0, 1, 2],\n fees: toAtomicPaliAmount(\"0.01\") ,\n deadline: 0,\n confidentiality: { Trusted: 0 },\n fee_function: null,\n input: null,\n program: { NativeData: \"DaFalse\" },\n metadata: null,\n },\n post_check: null,\n result_cipher: \"Plaintext\",\n };\n\n const keyring = await getKeyring();\n const account = keyring.getPairs()[0];\n\n return createAgreement(contract, account);\n}\n\nexport default createSimpleAgreement;\n","import { KeyringPair } from \"@polkadot/keyring/types\";\nimport { getKeyring } from \"../chain\";\nimport { createAgreement } from \"../compute\";\nimport { toAtomicPaliAmount, type PaliAmountInput } from \"../utils/token\";\n\nexport interface DataContractParams {\n /** URL pointing to the data to store. */\n url: string;\n /** Guardian account IDs that participate in this contract. */\n guardians: string[];\n /** Fee offered for the contract in PALI. Defaults to 0. */\n fees?: PaliAmountInput;\n /** Block number deadline. Defaults to 0 (no deadline). */\n deadline?: number;\n /** Trusted guardian index in the guardians list. Defaults to 0. */\n trustIndex?: number;\n}\n\n/**\n * Submits a dormant data-store contract on-chain via `compute.agreement`.\n *\n * - No encryption (Plaintext cipher suite)\n * - Trusted confidentiality mode\n * - Input fetched from a URL\n * - No pre-check or post-check verifications\n * - Plain (unencrypted) result\n */\nexport async function dataContract(params: DataContractParams, account: KeyringPair) {\n const plaintextCipher = \"Plaintext\";\n const atomicFees = toAtomicPaliAmount(params.fees ?? \"0\");\n\n const computeStep = {\n cipher: plaintextCipher,\n computer_indices: params.guardians.map((_, i) => i),\n fees: atomicFees,\n deadline: params.deadline ?? 0,\n confidentiality: { Trusted: params.trustIndex ?? 0 },\n fee_function: null,\n input: {\n Url: {\n url: Array.from(new TextEncoder().encode(params.url)),\n },\n },\n program: {\n NativeData: \"DaFalse\",\n },\n };\n\n const contract = {\n contract_type: \"Dormant\" as const,\n guardians: params.guardians,\n pre_check: null,\n compute: computeStep,\n post_check: null,\n result_cipher: plaintextCipher,\n };\n\n return createAgreement(contract, account);\n}\n","import { KeyringPair } from \"@polkadot/keyring/types\";\nimport { getKeyring } from \"../chain\";\nimport { createAgreement } from \"../compute\";\nimport { toAtomicPaliAmount, type PaliAmountInput } from \"../utils/token\";\n\nexport interface InferenceComputeParams {\n /** Raw input data — string will be UTF-8 encoded, Uint8Array used as-is. */\n input: Uint8Array | string;\n /** Guardian account IDs that participate in this compute. */\n guardians: string[];\n /** Fee offered for the compute step in PALI. Defaults to 0. */\n fees?: PaliAmountInput;\n /** Block number deadline for the compute step. Defaults to 0 (no deadline). */\n deadline?: number;\n}\n\n/**\n * Submits a plain (unencrypted, no-confidentiality) inference compute request\n * on-chain via the `compute.agreement` extrinsic.\n *\n * - Input is sent inline (no DA layer indirection).\n * - Program is the native `Inference` executor.\n * - Pre-check and post-check are no-ops (no verification).\n * - Cipher fields carry zero-value placeholders (unused in the trusted path).\n * - Result is returned in plain (no re-encryption).\n */\nexport async function inferenceCompute(params: InferenceComputeParams, account: KeyringPair) {\n const inputData =\n typeof params.input === \"string\"\n ? Array.from(new TextEncoder().encode(params.input))\n : Array.from(params.input);\n const atomicFees = toAtomicPaliAmount(params.fees ?? \"0\");\n\n // No encryption — use the Plaintext variant of CipherSuite.\n const plaintextCipher = \"Plaintext\";\n\n // Primary compute step: inline input + native inference execution.\n const computeStep = {\n cipher: plaintextCipher,\n computer_indices: params.guardians.map((_, i) => i),\n fees: atomicFees,\n deadline: params.deadline ?? 0,\n confidentiality: { Trusted: 0 },\n fee_function: null,\n input: { Inline: { data: inputData } },\n program: { NativeExecute: \"Inference\" },\n };\n\n const contract = {\n contract_type: \"Active\" as const,\n guardians: params.guardians,\n compute: computeStep,\n result_cipher: plaintextCipher,\n };\n\n return createAgreement(contract, account);\n}\n","import bs58 from 'bs58';\nimport { getApi } from '../chain';\n\nexport interface GuardianParticipants {\n\tnwState: {\n\t\tlocalPeerId: string | undefined;\n\t\tworker: unknown;\n\t\tcurrentEra: unknown;\n\t\tguardians: string | null;\n\t\tnextGuardians: string | null;\n\t\tcurrentIndex: unknown;\n\t\tnextIndex: number;\n\t};\n\tcurrentGuardians: unknown[];\n\tupcomingGuardians: unknown[];\n}\n\nexport async function getGuardianParticipants(): Promise<GuardianParticipants> {\n\tconst api = await getApi();\n\tif (!api) throw new Error('Api not initialized');\n\n\ttry {\n\t\tconst guardians = await api.query.guardian.guardians();\n\t\tconst nextGuardians = await api.query.guardian.nextGuardians();\n\t\tconst currentEra = await api.query.staking.currentEra();\n\t\tconst currentIndex = await api.query.guardian.currentIndex();\n\t\tconst peerid = await api.rpc.system.localPeerId();\n\t\tconst _peerid = bs58.decode((peerid || '').toString());\n\t\tconst account = await api.query.guardian.workerByKey(_peerid.slice(6, 38));\n\t\tconst nextIndex = currentIndex ? Number(currentIndex) + 1 : 1;\n\n\t\tconst guardiansList = (guardians?.toJSON() || []) as string[];\n\t\tconst nextGuardiansList = (nextGuardians?.toJSON() || []) as string[];\n\n\t\tconst buildDetails = async (list: string[]) => {\n\t\t\treturn Promise.all(\n\t\t\t\tlist.map(async (guardian: string) => {\n\t\t\t\t\tconst guardianPrefs = await api.query.staking.guardians(guardian);\n\t\t\t\t\tconst ledger = await api.query.staking.ledger(guardian);\n\t\t\t\t\tconst bonded = await api.query.staking.bonded(guardian);\n\t\t\t\t\tconst payee = await api.query.staking.payee(guardian);\n\t\t\t\t\tconst stakersOverview = await api.query.staking.erasStakersOverview(\n\t\t\t\t\t\tcurrentEra?.toPrimitive(),\n\t\t\t\t\t\tguardian,\n\t\t\t\t\t);\n\t\t\t\t\tconst guardianErasPrefs = await api.query.staking.erasGuardianPrefs(\n\t\t\t\t\t\tcurrentEra?.toPrimitive(),\n\t\t\t\t\t\tguardian,\n\t\t\t\t\t);\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tguardian,\n\t\t\t\t\t\trewardDestination: payee?.toHuman ? payee.toHuman() : null,\n\t\t\t\t\t\tcurrentPreferences: (guardianErasPrefs?.toHuman ? guardianErasPrefs.toHuman() : null),\n\t\t\t\t\t\tupcomingPreferences: (guardianPrefs?.toHuman ? guardianPrefs.toHuman() : null),\n\t\t\t\t\t\tstash: bonded?.toHuman ? bonded.toHuman() : null,\n\t\t\t\t\t\tcurrentStakeOverview: stakersOverview?.toHuman ? stakersOverview.toHuman() : null,\n\t\t\t\t\t\tupcomingStakeOverview: ledger?.toHuman ? ledger.toHuman() : null,\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t);\n\t\t};\n\n\t\tconst currentGuardians = await buildDetails(guardiansList);\n\t\tconst upcomingGuardians = await buildDetails(nextGuardiansList);\n\n\t\treturn {\n nwState: {\n localPeerId: peerid?.toString(),\n worker: account?.toHuman ? account.toHuman() : null,\n currentEra: currentEra?.toHuman ? currentEra.toHuman() : null,\n guardians: JSON.stringify(guardians?.toHuman ? guardians.toHuman() : null, null, 2),\n nextGuardians: JSON.stringify(nextGuardians?.toHuman ? nextGuardians.toHuman() : null, null, 2),\n currentIndex: currentIndex?.toHuman ? currentIndex.toHuman() : null,\n nextIndex,\n },\n\t\t\tcurrentGuardians,\n\t\t\tupcomingGuardians,\n\t\t};\n\t} finally {\n\t\tapi.disconnect();\n\t}\n}\n\nexport default getGuardianParticipants;\n\n","import { KeyringPair } from \"@polkadot/keyring/types\";\nimport { getKeyring } from \"../chain\";\nimport { createAgreement } from \"../compute\";\nimport { toAtomicPaliAmount, type PaliAmountInput } from \"../utils/token\";\n\nexport interface SimpleComputeParams {\n /** Guardian account IDs that participate in this compute. */\n guardians: string[];\n /** Input reference block number from which to read the tx payload. */\n inputBlockNumber?: number;\n /** Input reference extrinsic index within the input block. */\n inputExtrinsicIndex?: number;\n /** Program location as URL. */\n programUrl: string;\n /** Fee offered for the compute step in PALI. Defaults to 0. */\n fees?: PaliAmountInput;\n /** Block number deadline for the compute step. Defaults to 0 (no deadline). */\n deadline?: number;\n /** Trusted guardian index in the guardians list. Defaults to 0. */\n trustIndex?: number;\n}\n\n/**\n * Submits a minimal trusted compute agreement:\n * - no encryption (plaintext cipher)\n * - trusted confidentiality mode\n * - input from chain transaction reference\n * - program fetched from URL\n * - no pre/post verification\n */\nexport async function simpleCompute(params: SimpleComputeParams, account: KeyringPair) {\n const plaintextCipher = \"Plaintext\";\n const atomicFees = toAtomicPaliAmount(params.fees ?? \"0\");\n const computeStep = {\n cipher: plaintextCipher,\n computer_indices: params.guardians.map((_, i) => i),\n fees: atomicFees,\n deadline: params.deadline ?? 0,\n confidentiality: { Trusted: params.trustIndex ?? 0 },\n fee_function: null,\n input: null,\n program: {\n Url: {\n url: Array.from(new TextEncoder().encode(params.programUrl)),\n },\n },\n };\n\n const contract = {\n contract_type: \"Active\" as const,\n guardians: params.guardians,\n pre_check: null,\n compute: computeStep,\n post_check: null,\n result_cipher: plaintextCipher,\n };\n\n return createAgreement(contract, account);\n}\n","/**\n * Generates random bytes of the specified length.\n * Uses Web Crypto API (crypto.getRandomValues) - available in all modern browsers\n * and Node.js 18+.\n *\n * @param length Number of bytes.\n * @returns Uint8Array containing random bytes.\n */\nexport function generateRandomBytes(length: number = 32): Uint8Array {\n const bytes = new Uint8Array(length);\n const cr = globalThis.crypto;\n if (!cr || typeof cr.getRandomValues !== \"function\") {\n throw new Error(\n \"crypto.getRandomValues is not available. Ensure you're running in a supported environment (browser or Node.js 18+).\"\n );\n }\n cr.getRandomValues(bytes);\n return bytes;\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { createAgreement } from \"../compute\";\nimport { assert, debugLog } from \"../utils\";\nimport { formatPaliAmount } from \"../utils/token\";\nimport { CipherSuite, OnChainRef } from \"./types\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\n\nexport async function writeMetadata(\n account: KeyringPair,\n name: string,\n description: string,\n ref: OnChainRef,\n price: bigint,\n dataType: number,\n l2Owner: string,\n groupId: string,\n) {\n const blobRef = [ref.blockNumber, ref.index];\n const encoder = new TextEncoder();\n const nameBytes = Array.from(encoder.encode(name));\n const descriptionBytes = Array.from(encoder.encode(description));\n const ownerBytes = Array.from(encoder.encode(l2Owner));\n\n const api = await getApi();\n assert(api, \"Failed to get API connection\");\n\n debugLog(`Registering metadata for ${name} at ${formatPaliAmount(price)}`);\n\n const request = api.tx.dataAvailability.daccRegisterData(\n nameBytes,\n descriptionBytes,\n blobRef,\n price,\n dataType,\n ownerBytes,\n groupId,\n );\n\n const hash = await signAndSend(request, account);\n\n debugLog(`Metadata registration transaction sent with hash: ${hash.hash}`);\n\n return hash;\n}\n\nexport interface DataAgreementMetadata {\n name: string;\n description: string;\n /** Maps to the on-chain StoreType enum. */\n storeType: \"Dataset\" | \"Model\" | \"Agent\" | \"Other\";\n /** H256 group identifier. */\n groupId: string;\n}\n\nexport interface DataAgreementParams {\n /** DA blob reference returned by submitTEData. */\n ref: OnChainRef;\n /** Guardian account IDs that participate in this agreement. */\n guardians: string[];\n /** Fee for the agreement in PALI atomic units. */\n fees: bigint;\n /** If provided, populates ComputeInfo.metadata in the contract. */\n metadata?: DataAgreementMetadata;\n /** Block number deadline. Defaults to 0 (no deadline). */\n deadline?: number;\n /** Trusted guardian index in the guardians list. Defaults to 0. */\n trustIndex?: number;\n /**\n * CipherSuite for the compute step input. Defaults to \"Plaintext\".\n * Pass the `cipher` from submitTEDataWithCipher for the threshold-encrypted path.\n */\n cipher?: CipherSuite;\n /**\n * CipherSuite for the agreement result. Defaults to \"Plaintext\".\n */\n resultCipher?: CipherSuite;\n}\n\nexport async function registerDataAgreement(\n account: KeyringPair,\n params: DataAgreementParams,\n) {\n debugLog(\n `Registering data agreement for DA ref ${params.ref.blockNumber}-${params.ref.index} at ${formatPaliAmount(params.fees)}`,\n );\n\n const cipher = params.cipher ?? \"Plaintext\";\n const resultCipher = params.resultCipher ?? \"Plaintext\";\n const encoder = new TextEncoder();\n const computeMetadata = params.metadata\n ? {\n name: Array.from(encoder.encode(params.metadata.name)),\n description: Array.from(encoder.encode(params.metadata.description)),\n store_type: params.metadata.storeType,\n group_id: params.metadata.groupId,\n }\n : null;\n\n const computeStep = {\n cipher,\n computer_indices: params.guardians.map((_, i) => i),\n fees: params.fees,\n deadline: params.deadline ?? 0,\n confidentiality: { Trusted: params.trustIndex ?? 0 },\n fee_function: null,\n input: {\n ChainTransaction: {\n block_number: params.ref.blockNumber,\n extrinsic_index: params.ref.index,\n },\n },\n program: {\n NativeData: \"DaFalse\",\n },\n metadata: computeMetadata,\n };\n\n const contract = {\n contract_type: \"Dormant\" as const,\n guardians: params.guardians,\n pre_check: null,\n compute: computeStep,\n post_check: null,\n result_cipher: resultCipher,\n };\n\n return createAgreement(contract, account);\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\nimport { OnChainRef } from \"./types\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\n\nexport async function runAgent(\n account: KeyringPair,\n agentRef: OnChainRef,\n nonce: Uint8Array,\n ciphertext: Uint8Array,\n tdParams: Uint8Array,\n pkBytes: Uint8Array,\n tauParams: Uint8Array,\n baseModel: OnChainRef,\n publicKey: Uint8Array,\n guardians: Uint8Array[],\n guardian?: Uint8Array,\n agreementId?: Uint8Array,\n) {\n const agentRefTuple = [agentRef.blockNumber, agentRef.index];\n const baseModelTuple = [baseModel.blockNumber, baseModel.index];\n\n const api = await getApi();\n assert(api, \"Failed to get API connection\");\n\n const request = api.tx.dataAvailability.daccRunAgent(\n agentRefTuple,\n Array.from(nonce),\n Array.from(ciphertext),\n guardian ? Array.from(guardian) : null,\n Array.from(tdParams),\n Array.from(pkBytes),\n Array.from(tauParams),\n baseModelTuple,\n Array.from(publicKey),\n guardians.map((g) => Array.from(g)),\n );\n\n const opts = {\n compute: {\n da_type: 4,\n verification: 0,\n compute: 1,\n agreement: [agreementId]\n }\n };\n const hash = await signAndSend(request, account, opts);\n\n debugLog(`Run agent transaction sent with hash: ${hash.hash}`);\n\n return hash;\n}\n","import { DEFAULT_EMPTY_PAYLOAD, getApi, signAndSend } from \"../chain\";\nimport { encrypt, gen_stretched_key, testCrypt } from \"../crypto\";\nimport {\n assert,\n debugLog,\n Hex,\n hexToUint8Array,\n uint8ArrayToBase64,\n} from \"../utils\";\nimport { OnChainRef, SubmitTEDataResult } from \"./types\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\n\nexport async function submitData(account: KeyringPair, data: string) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n\n debugLog(`\\nSubmitting data with content length: ${data.length}`);\n\n const tx = api.tx.dataAvailability.submitData(data);\n const hash = await signAndSend(tx, account, DEFAULT_EMPTY_PAYLOAD);\n\n debugLog(`Data availability transaction sent with hash: ${hash.hash}`);\n}\n\nexport async function submitTEData(\n account: KeyringPair,\n data: string,\n chosenGuardians: string[],\n tau_params: string,\n agg_key: string,\n group_pk: string,\n): Promise<OnChainRef> {\n const { encoded: encryptedKey, ikm } = testCrypt(tau_params, agg_key);\n const td_params = uint8ArrayToBase64(hexToUint8Array(encryptedKey as Hex));\n const shared_key = gen_stretched_key(hexToUint8Array(ikm as Hex));\n\n const encoder = new TextEncoder();\n const dataUint8Array = encoder.encode(data);\n const { ciphertext, nonce } = encrypt(dataUint8Array, shared_key);\n\n const modelSubmit = JSON.stringify({\n nonce: uint8ArrayToBase64(nonce),\n ciphertext: uint8ArrayToBase64(ciphertext),\n td_params,\n group_pk: Array.from(new Uint8Array(hexToUint8Array(group_pk as Hex))),\n tau_params: Array.from(new Uint8Array(hexToUint8Array(tau_params as Hex))),\n chosen_guardians: chosenGuardians,\n });\n\n const api = await getApi();\n assert(api, \"Failed to get API connection\");\n\n const request = await api.tx.dataAvailability.submitData(modelSubmit);\n const hash = await signAndSend(request, account, DEFAULT_EMPTY_PAYLOAD);\n\n debugLog(`TE data availability transaction sent with hash: ${hash.hash}`);\n\n return hash;\n}\n\n/**\n * Identical to submitTEData but additionally returns the populated CipherSuite\n * so callers can pass it directly to registerDataAgreement without\n * re-deriving the cipher parameters.\n */\nexport async function submitTEDataWithCipher(\n account: KeyringPair,\n data: string,\n chosenGuardians: string[],\n tau_params: string,\n agg_key: string,\n group_pk: string,\n): Promise<SubmitTEDataResult> {\n const { encoded: encryptedKey, ikm } = testCrypt(tau_params, agg_key);\n const shared_key = gen_stretched_key(hexToUint8Array(ikm as Hex));\n\n const encoder = new TextEncoder();\n const dataUint8Array = encoder.encode(data);\n const { ciphertext, nonce } = encrypt(dataUint8Array, shared_key);\n\n const ciphertextHex =\n \"0x\" +\n Array.from(ciphertext)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n\n const api = await getApi();\n assert(api, \"Failed to get API connection\");\n\n const request = await api.tx.dataAvailability.submitData(ciphertextHex);\n const ref = await signAndSend(request, account, DEFAULT_EMPTY_PAYLOAD);\n\n debugLog(`TE data availability transaction sent with hash: ${ref.hash}`);\n\n return {\n ref,\n cipher: {\n ThresholdHybrid: {\n threshold_params: {\n SilentThreshold: {\n td_params: Array.from(hexToUint8Array(encryptedKey as Hex)),\n pk_bytes: Array.from(hexToUint8Array(group_pk as Hex)),\n tau_params: Array.from(hexToUint8Array(tau_params as Hex)),\n },\n },\n symmetric_params: {\n ChaCha20Poly1305: { nonce: Array.from(nonce) },\n },\n },\n },\n };\n}\n","import fs from \"fs\";\nimport path from \"path\";\nimport bs58 from \"bs58\";\nimport { getApi, getKeyring, MCryptFsWriter } from \"../chain\";\nimport { assert } from \"../utils\";\nimport { toAtomicPaliAmount } from \"../utils/token\";\nimport { UploadOptions } from \"./types\";\nimport { submitTEData, submitTEDataWithCipher } from \"./submit\";\nimport { registerDataAgreement, writeMetadata } from \"./register\";\n\nexport async function uploadData(options: UploadOptions) {\n const { name, description, price, type, guardianGroupInfo, ref, filePath } =\n options;\n\n assert(\n guardianGroupInfo.guardians &&\n guardianGroupInfo.tauParams &&\n guardianGroupInfo.aggKey &&\n guardianGroupInfo.groupPk,\n \"Guardian group info is missing required properties\",\n );\n console.log(\"Guardian group info:\", guardianGroupInfo);\n\n const account = (await getKeyring()).pairs[0];\n const atomicPrice = toAtomicPaliAmount(price);\n\n if (filePath) {\n throw new Error(\"uploadData: file path upload is not implemented\");\n } else {\n const storeType =\n type === \"model\" ? \"Model\" : type === \"agent\" ? \"Agent\" : \"Dataset\";\n const { ref: dataRef, cipher } = await submitTEDataWithCipher(\n account,\n ref || \"\",\n guardianGroupInfo.guardians,\n guardianGroupInfo.tauParams,\n guardianGroupInfo.aggKey,\n guardianGroupInfo.groupPk,\n );\n await registerDataAgreement(account, {\n ref: dataRef,\n guardians: guardianGroupInfo.guardians,\n fees: atomicPrice,\n cipher,\n metadata: {\n name,\n description,\n storeType,\n groupId: guardianGroupInfo.groupId,\n },\n });\n }\n}\n\n/**\n * Legacy upload: uses submitTEData (returns only OnChainRef) and registers\n * the agreement with Plaintext cipher and no ComputePayload opts.\n * Kept for backward compatibility with callers that do not need cipher\n * parameters surfaced in the on-chain agreement.\n */\nexport async function uploadDataLegacy(options: Omit<UploadOptions, \"opts\">) {\n const { name, description, price, type, guardianGroupInfo, ref, filePath } =\n options;\n\n assert(\n guardianGroupInfo.guardians &&\n guardianGroupInfo.tauParams &&\n guardianGroupInfo.aggKey &&\n guardianGroupInfo.groupPk,\n \"Guardian group info is missing required properties\",\n );\n\n const account = (await getKeyring()).pairs[0];\n const ethAddress = \"\";\n const atomicPrice = toAtomicPaliAmount(price);\n\n if (type === \"dataset\" && filePath) {\n const fileContent = fs.readFileSync(filePath);\n const selectedFile = new File([fileContent], path.basename(filePath), {\n type: \"application/octet-stream\",\n lastModified: Date.now(),\n });\n\n const msCryptFsWriter = new MCryptFsWriter(\n {\n file: selectedFile,\n fileName: selectedFile.name,\n filePath: \"\",\n description,\n baseCost: atomicPrice,\n ownerL2Address: ethAddress,\n guardianInfo: guardianGroupInfo,\n },\n 500,\n await getApi(),\n account,\n );\n\n await msCryptFsWriter.writeFile();\n } else {\n const dataRef = await submitTEData(\n account,\n ref || \"\",\n guardianGroupInfo.guardians,\n guardianGroupInfo.tauParams,\n guardianGroupInfo.aggKey,\n guardianGroupInfo.groupPk,\n );\n\n const dtype = type === \"model\" ? 1 : type === \"agent\" ? 2 : 0;\n await writeMetadata(\n account,\n name,\n description,\n dataRef,\n BigInt(Number(price) * 10 ** 18),\n dtype,\n ethAddress,\n guardianGroupInfo.groupId,\n );\n }\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\nimport { formatPaliAmount } from \"../utils/token\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\n\nexport async function addStake(account: KeyringPair, amountBaseUnits: bigint) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n debugLog(\"Using account:\", account.address, \"adding:\", formatPaliAmount(amountBaseUnits));\n\n const stakeTx = api.tx.staking.bondExtra(amountBaseUnits);\n const hash = await signAndSend(stakeTx, account);\n\n debugLog(`Stake transaction sent with hash: ${hash.hash}`);\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\n\nexport async function joinIdleStaker(account: KeyringPair) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n const chillTx = api.tx.staking.chill();\n const hash = await signAndSend(chillTx, account);\n\n debugLog(\"Idle staker chill tx sent with hash:\", hash.hash);\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\nimport { formatPaliAmount } from \"../utils/token\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\n\nexport async function newStake(\n account: KeyringPair,\n amountBaseUnits: bigint,\n rewardDestination: string = \"Staked\"\n) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n debugLog(\n `Staking amount: ${formatPaliAmount(amountBaseUnits)} for account: ${account.address} with reward destination: ${rewardDestination}`\n );\n\n const stakeTx = api.tx.staking.bond(amountBaseUnits, rewardDestination);\n const hash = await signAndSend(stakeTx, account);\n\n debugLog(`Stake transaction sent with hash: ${hash.hash}`);\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\n\nexport async function payoutStake(account: KeyringPair, eras: Array<number>, address?: string) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n for (const era of eras) {\n debugLog(\"Paying account: \", address || account.address, \" for era \", era);\n }\n\n const unstakeTxs = eras.map((era) =>\n api.tx.staking.payoutStakers(address || account.address, era)\n );\n const batchTx = api.tx.utility.batch(unstakeTxs);\n const hash = await signAndSend(batchTx, account);\n\n debugLog(`Batch payout transaction sent with hash: ${hash.hash}`);\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\nimport { formatPaliAmount } from \"../utils/token\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\n\nexport async function reduceStake(account: KeyringPair, amountBaseUnits: bigint) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n debugLog(\"Using account:\", account.address, \"reducing:\", formatPaliAmount(amountBaseUnits));\n\n const unstakeTx = api.tx.staking.unbond(amountBaseUnits);\n const hash = await signAndSend(unstakeTx, account);\n\n debugLog(`Unstake transaction sent with hash: ${hash.hash}`);\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\nimport { formatPaliAmount } from \"../utils/token\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\n\nexport async function removeStake(account: KeyringPair) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n const stakeAmount = (await api.query.staking.ledger(account.address))?.toPrimitive() as { active?: bigint } | null;\n\n debugLog(\"Removing entire stake amount:\", formatPaliAmount(stakeAmount?.active || 0n));\n\n const unstakeTx = api.tx.staking.unbond(stakeAmount?.active || 0n);\n const hash = await signAndSend(unstakeTx, account);\n\n debugLog(`Unstake transaction sent with hash: ${hash.hash}`);\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\n\nexport async function withdrawStake(account: KeyringPair) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n const unstakeTx = api.tx.staking.withdrawUnbonded(0);\n const hash = await signAndSend(unstakeTx, account);\n\n debugLog(`Unstake transaction sent with hash: ${hash.hash}`);\n}\n","import { getApi, getKeyring, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\nimport { formatPaliAmount } from \"../utils/token\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\n\nexport async function fundAccount(account: KeyringPair, amountBaseUnits: bigint, address?: string) {\n const addr = address ? address : account.address;\n const keyring = await getKeyring();\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n\n debugLog(`\\nFunding account: ${addr} with amount: ${formatPaliAmount(amountBaseUnits)}`);\n\n const tx = api.tx.balances.transferKeepAlive(addr, amountBaseUnits);\n const hash = await signAndSend(tx, keyring.getPairs()[0]);\n\n debugLog(`Fund transaction sent with hash: ${hash.hash}`);\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\nimport { formatPaliAmount } from \"../utils/token\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\n\nexport async function transfer(account: KeyringPair, amountBaseUnits: bigint, address: string) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n\n debugLog(`\\nTransferring funds to account: ${address} with amount: ${formatPaliAmount(amountBaseUnits)}`);\n\n const tx = api.tx.balances.transferKeepAlive(address, amountBaseUnits);\n const hash = await signAndSend(tx, account);\n\n debugLog(`Transfer transaction sent with hash: ${hash.hash}`);\n}\n","import { getApi, signAndSend } from \"../chain\";\nimport { assert, debugLog } from \"../utils\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\n\nexport async function joinValidator(account: KeyringPair, commission: number) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n assert(account, \"Account not initialized\");\n\n const validateTx = api.tx.staking.validate({commission, blocked: true});\n const hash = await signAndSend(validateTx, account);\n\n debugLog(\"Validator join tx sent with hash:\", hash.hash);\n}\n","import assert from \"assert\";\nimport { getApi, signAndSend } from \"./chain\";\nimport { debugLog } from \"./utils/helper\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\n\nexport interface IdentityFields {\n\tdisplay?: string;\n}\n\nexport async function setIdentity(account: KeyringPair, { display = undefined }: IdentityFields) {\n\tconst api = await getApi();\n\n\tassert(api, \"API not initialized\");\n\n\tdebugLog(`\\nSetting identity for account: ${account.address} as ${display}`);\n\n\tconst tx = api.tx.identity.setIdentity({display: {Raw: display}});\n\tconst hash = await signAndSend(tx, account);\n\n\tdebugLog(`Set identity transaction sent with hash: ${hash.hash}`);\n}\n\n","import { getApi, provider, signAndSend } from \"./chain\";\nimport bs58 from 'bs58';\nimport { debugLog } from \"./utils/helper\";\nimport assert from \"assert\";\nimport type { KeyringPair } from \"@polkadot/keyring/types\";\n\nexport async function rotateAndSetKeys(account: KeyringPair) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n\n debugLog(`Rotating session keys for ${account.meta.name} on ${provider.endpoint}`);\n\n const newKeys = await api.rpc.author.rotateKeys();\n debugLog(`${account.meta.name} rotated keys on ${provider.endpoint}:`, newKeys?.toHex?.() ?? newKeys);\n\n const setKeysTx = api.tx.session.setKeys(newKeys, []);\n const hash = await signAndSend(setKeysTx, account);\n\n debugLog(`Rotate session transaction sent with hash: ${hash.hash}`);\n}\n\nexport async function setWorker(account: KeyringPair) {\n const api = await getApi();\n\n assert(api, \"API not initialized\");\n\n const peerid = bs58.decode((await api.rpc.system.localPeerId()).toString());\n const setWorkerTx = api.tx.guardian.setWorker(peerid.slice(6, 38));\n const hash = await signAndSend(setWorkerTx, account);\n\n debugLog(`Set worker id transaction sent with hash: ${hash.hash}`);\n}","export * from \"./account\";\nexport * from \"./chain\";\nexport * from \"./compute\";\nexport * from \"./crypto\";\nexport * from \"./da\";\nexport * from \"./guardian\";\nexport * from \"./stake\";\nexport * from \"./token\";\nexport * from \"./utils/helper\";\nexport * from \"./utils/token\";\nexport * from \"./validator\";\nexport * from \"./config\";\nexport * from \"./identity\";\nexport * from \"./rotateKeys\";\n\nexport * from \"@polkadot/util\";\nexport * as utilCrypto from \"@polkadot/util-crypto\";\nexport * as wasmCrypto from \"@polkadot/wasm-crypto\";\nexport { ApiPromise, WsProvider, HttpProvider } from \"@polkadot/api\";\n"]}
|