@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.js CHANGED
@@ -220,12 +220,182 @@ var API_TYPES = {
220
220
  extra: "CheckAppIdExtra",
221
221
  types: "CheckAppIdTypes"
222
222
  },
223
+ FeePayload: {
224
+ compute: "u128",
225
+ guardian: "u128",
226
+ verifier: "u128"
227
+ },
228
+ SilentThresholdParams: {
229
+ td_params: "Vec<u8>",
230
+ pk_bytes: "Vec<u8>",
231
+ tau_params: "Vec<u8>"
232
+ },
233
+ ThresholdParams: {
234
+ _enum: {
235
+ SilentThreshold: "SilentThresholdParams"
236
+ }
237
+ },
238
+ ChaCha20Poly1305Params: {
239
+ nonce: "[u8; 12]"
240
+ },
241
+ Aes256GcmParams: {
242
+ nonce: "[u8; 12]"
243
+ },
244
+ SymmetricParams: {
245
+ _enum: {
246
+ ChaCha20Poly1305: "ChaCha20Poly1305Params",
247
+ Aes256Gcm: "Aes256GcmParams"
248
+ }
249
+ },
250
+ KdfParams: {
251
+ _enum: {
252
+ HkdfSha256: "Null",
253
+ HkdfSha512: "Null"
254
+ }
255
+ },
256
+ Secp256k1Params: {
257
+ recipient_public_key: "Vec<u8>",
258
+ ephemeral_public_key: "Option<Vec<u8>>",
259
+ compressed: "bool",
260
+ kdf: "KdfParams",
261
+ salt: "Option<Vec<u8>>",
262
+ info: "Option<Vec<u8>>"
263
+ },
264
+ Ed25519Params: {
265
+ recipient_public_key: "Vec<u8>",
266
+ ephemeral_public_key: "Option<Vec<u8>>",
267
+ kdf: "KdfParams",
268
+ salt: "Option<Vec<u8>>",
269
+ info: "Option<Vec<u8>>"
270
+ },
271
+ AsymmetricParams: {
272
+ _enum: {
273
+ Secp256k1: "Secp256k1Params",
274
+ Ed25519: "Ed25519Params"
275
+ }
276
+ },
277
+ ThresholdHybridParams: {
278
+ threshold_params: "ThresholdParams",
279
+ symmetric_params: "SymmetricParams"
280
+ },
281
+ AsymmetricHybridParams: {
282
+ asymmetric_params: "AsymmetricParams",
283
+ symmetric_params: "SymmetricParams"
284
+ },
285
+ CipherSuite: {
286
+ _enum: {
287
+ Plaintext: "Null",
288
+ ThresholdHybrid: "ThresholdHybridParams",
289
+ AsymmetricHybrid: "AsymmetricHybridParams"
290
+ }
291
+ },
292
+ ConfidentialityLevel: {
293
+ _enum: {
294
+ Trusted: "u32",
295
+ TEE: "Null",
296
+ FHE: "Null",
297
+ SMPC: "Null"
298
+ }
299
+ },
300
+ NativeExecuteDA: {
301
+ _enum: ["Inference"]
302
+ },
303
+ NativeDataDA: {
304
+ _enum: ["DaFalse", "DaTrue"]
305
+ },
306
+ DAInputInline: {
307
+ data: "Vec<u8>"
308
+ },
309
+ DAInputChainTransaction: {
310
+ block_number: "u64",
311
+ extrinsic_index: "u32"
312
+ },
313
+ DAInputIpfs: {
314
+ cid: "Vec<u8>",
315
+ size: "u64"
316
+ },
317
+ DAInputUrl: {
318
+ url: "Vec<u8>",
319
+ size: "u64",
320
+ hash: "Option<Vec<u8>>"
321
+ },
322
+ DAInput: {
323
+ _enum: {
324
+ Null: "Null",
325
+ Inline: "DAInputInline",
326
+ ChainTransaction: "DAInputChainTransaction",
327
+ Ipfs: "DAInputIpfs",
328
+ Url: "DAInputUrl",
329
+ NativeExecute: "NativeExecuteDA",
330
+ NativeData: "NativeDataDA"
331
+ }
332
+ },
333
+ ContractType: {
334
+ _enum: {
335
+ Dormant: "Null",
336
+ Active: "Null"
337
+ }
338
+ },
339
+ StoreType: {
340
+ _enum: {
341
+ Dataset: "Null",
342
+ Model: "Null",
343
+ Agent: "Null",
344
+ Other: "Null"
345
+ }
346
+ },
347
+ ComputeMetadata: {
348
+ name: "Vec<u8>",
349
+ description: "Vec<u8>",
350
+ store_type: "StoreType",
351
+ group_id: "H256"
352
+ },
353
+ ComputeInfo: {
354
+ cipher: "CipherSuite",
355
+ computer_indices: "Vec<u32>",
356
+ fees: "u128",
357
+ deadline: "u64",
358
+ confidentiality: "ConfidentialityLevel",
359
+ fee_function: "Option<u8>",
360
+ program_env: "Option<Vec<u8>>",
361
+ input: "DAInput",
362
+ program: "DAInput",
363
+ metadata: "Option<ComputeMetadata>"
364
+ },
365
+ Contract: {
366
+ contract_type: "ContractType",
367
+ guardians: "Vec<AccountId>",
368
+ pre_check: "Option<ComputeInfo>",
369
+ compute: "ComputeInfo",
370
+ post_check: "Option<ComputeInfo>",
371
+ result_cipher: "CipherSuite"
372
+ },
373
+ AgreementInfo: {
374
+ status: "AgreementStatus",
375
+ creator: "AccountId",
376
+ index: "u32"
377
+ },
223
378
  ComputePayload: {
224
379
  da_type: "u8",
225
380
  agreement: "Option<BoundedVec<[u8; 32], 10>>",
226
381
  verification: "u8",
227
382
  compute: "u8"
228
383
  },
384
+ ComputePrefs: {
385
+ trusted: "bool",
386
+ tee: "bool",
387
+ mpc: "bool",
388
+ fhe: "bool",
389
+ zkp: "bool"
390
+ },
391
+ GuardianPrefs: {
392
+ pubKey: "[u8; 32]",
393
+ guardian: "bool",
394
+ verifier: "bool",
395
+ compute: "bool",
396
+ computePrefs: "Option<ComputePrefs>",
397
+ feeThreshold: "u128"
398
+ },
229
399
  BlockLengthColumns: "Compact<u32>",
230
400
  BlockLengthRows: "Compact<u32>",
231
401
  BlockLength: {
@@ -599,10 +769,6 @@ function configure(opts) {
599
769
  }
600
770
 
601
771
  // src/utils/helper.ts
602
- var tokenToBigint = (arg) => {
603
- const val = typeof arg === "bigint" ? arg : BigInt(arg);
604
- return val * 10n ** 15n;
605
- };
606
772
  function hexToUint8Array(hex) {
607
773
  if (hex.length % 2 !== 0) {
608
774
  throw new Error("Invalid hex string");
@@ -653,8 +819,23 @@ var debugLog = (message, ...optionalParams) => {
653
819
  };
654
820
 
655
821
  // src/utils/token.ts
656
- import { formatBalance } from "@polkadot/util";
822
+ import { formatUnits, parseUnits } from "viem";
823
+ var PALI_SYMBOL = "PALI";
824
+ var PALI_DECIMALS = 18;
657
825
  var tokenCache = null;
826
+ var toAtomicPaliAmount = (amount) => {
827
+ const normalizedAmount = String(amount).trim();
828
+ if (!normalizedAmount) {
829
+ throw new Error("Token amount cannot be empty");
830
+ }
831
+ return parseUnits(normalizedAmount, PALI_DECIMALS);
832
+ };
833
+ var fromAtomicPaliAmount = (amount) => {
834
+ return formatUnits(amount, PALI_DECIMALS);
835
+ };
836
+ var formatPaliAmount = (amount, symbol = PALI_SYMBOL) => {
837
+ return `${fromAtomicPaliAmount(amount)} ${symbol}`;
838
+ };
658
839
  async function fetchTokenProperties() {
659
840
  if (tokenCache) {
660
841
  return tokenCache;
@@ -663,13 +844,12 @@ async function fetchTokenProperties() {
663
844
  const systemProperties = (await (await getApi())?.rpc.system.properties())?.toHuman();
664
845
  assert(systemProperties, "Failed to fetch system properties from RPC");
665
846
  const tokenProperties = {
666
- symbol: (systemProperties?.tokenSymbol || ["UNIT"])[0],
667
- decimals: Number((systemProperties?.tokenDecimals || ["18"])[0])
847
+ symbol: (systemProperties?.tokenSymbol || [PALI_SYMBOL])[0],
848
+ decimals: Number((systemProperties?.tokenDecimals || [String(PALI_DECIMALS)])[0])
668
849
  };
669
850
  tokenCache = tokenProperties;
670
851
  return tokenProperties;
671
852
  } catch (error) {
672
- console.error("Failed to fetch token properties:", error);
673
853
  throw error;
674
854
  }
675
855
  }
@@ -681,20 +861,12 @@ function clearTokenCache() {
681
861
  }
682
862
  async function formatBalanceWithTokenProperties(balance) {
683
863
  const tokenProperties = await fetchTokenProperties();
684
- if (!tokenProperties) {
685
- throw new Error(
686
- "Token properties not yet cached. Call fetchTokenProperties first."
687
- );
688
- }
689
- return formatBalance(balance, {
690
- decimals: tokenProperties.decimals,
691
- withSi: true,
692
- withUnit: tokenProperties.symbol
693
- });
864
+ return `${formatUnits(typeof balance === "bigint" ? balance : BigInt(balance), tokenProperties.decimals)} ${tokenProperties.symbol}`;
694
865
  }
866
+ var tokenToBigint = toAtomicPaliAmount;
695
867
 
696
868
  // src/chain/singleton.ts
697
- import { ApiPromise, Keyring as Keyring2, WsProvider as WsProvider2 } from "@polkadot/api";
869
+ import { ApiPromise, Keyring as Keyring2 } from "@polkadot/api";
698
870
 
699
871
  // src/chain/wsProvider.ts
700
872
  import { WsProvider } from "@polkadot/api";
@@ -702,128 +874,13 @@ var provider = new WsProvider(PALLIORA_WS, 1e4);
702
874
 
703
875
  // src/chain/singleton.ts
704
876
  import { waitReady as waitReady2 } from "@polkadot/wasm-crypto";
705
- var wsProvider = null;
706
877
  var api = null;
707
878
  var keyring = null;
708
879
  var encKeyring = null;
709
- var RpcApi = class {
710
- constructor() {
711
- this.isConnected = false;
712
- this.isConnecting = false;
713
- this.error = null;
714
- }
715
- /**
716
- * Establishes a connection to a node at `endpoint` and returns the singleton
717
- * API and Keyring instances.
718
- *
719
- * @param endpoint - WebSocket endpoint URL to connect to (e.g. "wss://...").
720
- * @returns A promise resolving to an object containing the singleton {@link ApiPromise}
721
- * instance and the singleton {@link Keyring} instance.
722
- *
723
- * @remarks
724
- * - If a connection already exists (`isConnected === true`) the method returns
725
- * the already-initialized instances without recreating them.
726
- * - The method sets `isConnecting` to true while establishing the connection and
727
- * clears it in a `finally` block.
728
- * - Provider and API event listeners update the instance `error` and `isConnected`
729
- * fields on runtime errors and disconnects.
730
- * - The Keyring created here uses `sr25519` keys. If the standalone `getKeyring`
731
- * helper is used elsewhere, it will additionally add a default development
732
- * account derived from the well-known dev URI `//Bob` (named "Bob default").
733
- *
734
- * @throws Will re-throw underlying errors encountered while creating the provider
735
- * or API. In that case `error` will contain the textual error message.
736
- */
737
- async connect(endpoint) {
738
- try {
739
- if (this.isConnected) {
740
- return { api, keyring };
741
- }
742
- this.isConnecting = true;
743
- this.error = null;
744
- if (!wsProvider) {
745
- wsProvider = new WsProvider2(endpoint);
746
- wsProvider.on("error", (err) => {
747
- console.error("WsProvider error:", err);
748
- this.error = "WebSocket connection error";
749
- this.isConnected = false;
750
- });
751
- wsProvider.on("disconnected", () => {
752
- console.log("WsProvider disconnected");
753
- this.isConnected = false;
754
- });
755
- }
756
- if (!api) {
757
- api = await ApiPromise.create({
758
- provider: wsProvider,
759
- rpc: API_RPC,
760
- types: API_TYPES,
761
- signedExtensions: API_EXTENSIONS
762
- });
763
- api.on("error", (err) => {
764
- console.error("API error:", err);
765
- this.error = "API error occurred";
766
- });
767
- api.on("disconnected", () => {
768
- this.isConnected = false;
769
- });
770
- }
771
- if (!keyring) {
772
- keyring = new Keyring2({ type: "sr25519" });
773
- }
774
- if (!encKeyring) {
775
- encKeyring = new Keyring2({ type: "ed25519" });
776
- }
777
- await api.isReady;
778
- this.isConnected = true;
779
- return { api, keyring };
780
- } catch (err) {
781
- console.error("Failed to connect to Polkadot:", err);
782
- this.error = err instanceof Error ? err.message : "Failed to connect to Polkadot";
783
- throw err;
784
- } finally {
785
- this.isConnecting = false;
786
- }
787
- }
788
- /**
789
- * Gracefully disconnects and nullifies the singleton API, provider and keyring
790
- * instances managed by this RpcApi instance.
791
- *
792
- * @remarks
793
- * - The method calls `api.disconnect()` and `wsProvider.disconnect()` if they
794
- * exist, then sets the internal singletons to `null` and `isConnected` to false.
795
- * - Any error during disconnect is captured in `error`.
796
- */
797
- async disconnect() {
798
- try {
799
- if (api) {
800
- await api.disconnect();
801
- api = null;
802
- }
803
- if (wsProvider) {
804
- await wsProvider.disconnect();
805
- wsProvider = null;
806
- }
807
- keyring = null;
808
- this.isConnected = false;
809
- } catch (err) {
810
- console.error("Error disconnecting:", err);
811
- this.error = err instanceof Error ? err.message : "Failed to disconnect";
812
- }
813
- }
814
- getApi() {
815
- return api;
816
- }
817
- getKeyring() {
818
- return keyring;
819
- }
820
- getEncKeyring() {
821
- return encKeyring;
822
- }
823
- };
824
- async function getApi() {
880
+ var apiListenersAttached = false;
881
+ var apiTeardownInProgress = false;
882
+ async function getApi(cb) {
825
883
  if (!provider) return;
826
- console.debug(provider.endpoint);
827
884
  if (!api) {
828
885
  api = await ApiPromise.create({
829
886
  provider,
@@ -834,14 +891,24 @@ async function getApi() {
834
891
  }
835
892
  const isNode = typeof process !== "undefined" && typeof process.exit === "function";
836
893
  const isTest = typeof process !== "undefined" && process.env?.NODE_ENV === "test";
837
- if (isNode && !isTest) {
894
+ if (isNode && !isTest && api && !apiListenersAttached) {
895
+ apiListenersAttached = true;
838
896
  api.on("error", (err) => {
839
- console.error("api error, will restart:", err);
840
- process.exit(0);
897
+ if (apiTeardownInProgress) return;
898
+ apiTeardownInProgress = true;
899
+ apiListenersAttached = false;
900
+ const currentApi = api;
901
+ api = null;
902
+ void currentApi?.disconnect().catch((disconnectErr) => {
903
+ apiTeardownInProgress = false;
904
+ console.error("api disconnect after error failed:", disconnectErr);
905
+ });
841
906
  });
842
907
  api.on("disconnected", () => {
843
- console.error("api disconnected, will restart.");
844
- process.exit(0);
908
+ api = null;
909
+ apiListenersAttached = false;
910
+ apiTeardownInProgress = false;
911
+ if (cb) cb();
845
912
  });
846
913
  }
847
914
  return api;
@@ -862,13 +929,6 @@ async function getEncKeyring() {
862
929
  }
863
930
  return encKeyring;
864
931
  }
865
- var apiInstance = null;
866
- function getRpcApi() {
867
- if (!apiInstance) {
868
- apiInstance = new RpcApi();
869
- }
870
- return apiInstance;
871
- }
872
932
 
873
933
  // src/chain/utils.ts
874
934
  import { isFunction as isFunction2 } from "@polkadot/util";
@@ -907,11 +967,48 @@ var createGuardianGroup = async (account, selectedGuardians) => {
907
967
  );
908
968
  const result = await signAndSend(tx, account);
909
969
  debugLog("Guardian group created:", result);
970
+ return result;
910
971
  } catch (error) {
911
972
  console.error("Error creating guardian group:", error);
912
973
  throw new Error(`Failed to create guardian group: ${error instanceof Error ? error.message : error}`);
913
974
  }
914
975
  };
976
+ var createGuardianGroupAndWatch = async (account, guardians, maxBlocks = 20) => {
977
+ assert(guardians.length === 3, "Exactly 3 guardians are required");
978
+ assert(account, "Failed to load account");
979
+ const api2 = await getApi();
980
+ assert(api2, "Failed to initialize API");
981
+ debugLog(`Submitting guardian group creation...`);
982
+ const creationResult = await createGuardianGroup(account, guardians);
983
+ const startBlock = (creationResult?.blockNumber ?? 0) + 1;
984
+ debugLog(`Group creation tx confirmed at block ${startBlock - 1}. Listening for DaccGuardianGroup event from block ${startBlock}...`);
985
+ const match = await scanForBlockEvent(
986
+ api2,
987
+ {
988
+ predicate: async (block2, event, phase) => {
989
+ if (event.section.toLowerCase() !== "dataavailability" || event.method.toLowerCase() !== "daccguardiangroup") return false;
990
+ if (!phase.isApplyExtrinsic) return false;
991
+ const ext2 = block2.block.extrinsics[phase.asApplyExtrinsic.toNumber()];
992
+ return ext2?.method?.section?.toLowerCase() === "dataavailability" && ext2?.method?.method?.toLowerCase() === "daccguardiangroupinfo";
993
+ }
994
+ },
995
+ startBlock,
996
+ maxBlocks
997
+ );
998
+ assert(match.extrinsicIndex !== null, "DaccGuardianGroup event was not emitted by an extrinsic");
999
+ debugLog(`DaccGuardianGroup event found at block ${match.blockNumber}, extrinsic index ${match.extrinsicIndex}. Decoding args...`);
1000
+ const block = await match.block();
1001
+ const ext = block.block.extrinsics[match.extrinsicIndex];
1002
+ const [group_id, group_pk, tau_params, agg_key] = ext.method.args;
1003
+ debugLog(`Guardian group parameters decoded: group_id=${group_id.toHex()}`);
1004
+ return {
1005
+ groupId: group_id.toHex(),
1006
+ groupPk: group_pk.toHex(),
1007
+ tauParams: tau_params.toHex(),
1008
+ aggKey: agg_key.toHex(),
1009
+ guardians
1010
+ };
1011
+ };
915
1012
 
916
1013
  // src/guardian/join.ts
917
1014
  async function joinGuardian(account, prefs) {
@@ -919,6 +1016,7 @@ async function joinGuardian(account, prefs) {
919
1016
  assert(api2, "API not initialized");
920
1017
  assert(account, "Account not initialized");
921
1018
  const computeOpts = prefs.compute?.split(",").map((s) => s.trim()).filter((s) => s.length > 0) || void 0;
1019
+ const feeThreshold = typeof prefs.fee === "bigint" ? prefs.fee : BigInt(prefs.fee || "0");
922
1020
  const guardianPrefs = {
923
1021
  pubKey: account.publicKey,
924
1022
  guardian: prefs.standard,
@@ -930,12 +1028,13 @@ async function joinGuardian(account, prefs) {
930
1028
  mpc: computeOpts?.includes("mpc") || false,
931
1029
  fhe: computeOpts?.includes("fhe") || false,
932
1030
  zkp: computeOpts?.includes("zkp") || false
933
- }
1031
+ },
1032
+ feeThreshold
934
1033
  };
935
1034
  debugLog(
936
1035
  account.address,
937
1036
  "joining as guardian with preferences:",
938
- guardianPrefs
1037
+ { ...guardianPrefs, feeThreshold: formatPaliAmount(feeThreshold) }
939
1038
  );
940
1039
  const guardTx = api2.tx.staking.guard(guardianPrefs);
941
1040
  const hash = await signAndSend(guardTx, account);
@@ -956,7 +1055,7 @@ var signAndSend = async (request, account, opts = DEFAULT_COMPUTE_PAYLOAD) => {
956
1055
  });
957
1056
  });
958
1057
  if (tx_result.isError) {
959
- throw new Error(`Transaction failed with error: ${tx_result.error}`);
1058
+ throw new Error(`Transaction failed with error: ${tx_result.dispatchError}`);
960
1059
  }
961
1060
  if (tx_result.dispatchError) {
962
1061
  throw new Error(
@@ -967,8 +1066,8 @@ var signAndSend = async (request, account, opts = DEFAULT_COMPUTE_PAYLOAD) => {
967
1066
  `Transaction ${tx_result.txHash.toHex()} included in timepoint ${tx_result.blockNumber}-${tx_result.txIndex}`
968
1067
  );
969
1068
  return {
970
- blockNumber: tx_result?.blockNumber?.toNumber(),
971
- index: tx_result?.txIndex,
1069
+ blockNumber: tx_result.blockNumber?.toNumber() ?? 0,
1070
+ index: tx_result.txIndex ?? 0,
972
1071
  hash: tx_result.txHash.toHex(),
973
1072
  tx_result
974
1073
  };
@@ -986,14 +1085,14 @@ var getGuardianAddress = async () => {
986
1085
  const api2 = await getApi();
987
1086
  if (!api2) throw new Error("API not initialized");
988
1087
  assert(
989
- isFunction2(api2.query["guardian"]?.["worker"]),
990
- `api.query.guardian.worker does not exist`
1088
+ isFunction2(api2.query["guardian"]?.["workerByKey"]),
1089
+ `api.query.guardian.workerByKey does not exist`
991
1090
  );
992
1091
  const list = await getGuardianList();
993
1092
  const addresses = await Promise.all(
994
1093
  list.map(async (item) => {
995
- const peerid = bs58.decode(item).slice(0, 32);
996
- return (await api2.query["guardian"]["worker"](peerid)).toString();
1094
+ const peerid = bs58.decode(item).slice(6, 38);
1095
+ return (await api2.query["guardian"]["workerByKey"](peerid)).toString();
997
1096
  })
998
1097
  );
999
1098
  return list.map((peerid, index) => ({ peerid, address: addresses[index] }));
@@ -1020,6 +1119,149 @@ var getGuardianNwParams = async () => {
1020
1119
  throw error;
1021
1120
  }
1022
1121
  };
1122
+ async function fetchAndDecodeExtrinsic(blockHeight, extrinsicIndex) {
1123
+ const api2 = await getApi();
1124
+ if (!api2) throw new Error("API not initialized");
1125
+ const blockHash = await api2.rpc.chain.getBlockHash(blockHeight);
1126
+ const signedBlock = await api2.rpc.chain.getBlock(blockHash);
1127
+ const extrinsics = signedBlock.block.extrinsics;
1128
+ if (extrinsicIndex >= extrinsics.length) {
1129
+ throw new Error(
1130
+ `extrinsic index ${extrinsicIndex} out of range \u2014 block ${blockHeight} has ${extrinsics.length} extrinsics`
1131
+ );
1132
+ }
1133
+ const raw = extrinsics[extrinsicIndex];
1134
+ const decoded = raw.toHuman();
1135
+ return { raw, decoded };
1136
+ }
1137
+ var scanForBlockEvent = (api2, filter, startBlock, maxBlocks = 20) => {
1138
+ const hasPredicate = "predicate" in filter;
1139
+ let blocksScanned = 0;
1140
+ let done = false;
1141
+ return new Promise((resolve, reject) => {
1142
+ const unsubPromise = api2.rpc.chain.subscribeNewHeads(
1143
+ async (header) => {
1144
+ if (done) return;
1145
+ const currentBlock = header.number.toNumber();
1146
+ if (startBlock !== void 0 && currentBlock < startBlock) return;
1147
+ blocksScanned++;
1148
+ if (maxBlocks > 0 && blocksScanned > maxBlocks) {
1149
+ done = true;
1150
+ unsubPromise.then((unsub) => unsub());
1151
+ reject(new Error(`No matching event found within ${maxBlocks} blocks`));
1152
+ return;
1153
+ }
1154
+ try {
1155
+ const blockHash = await api2.rpc.chain.getBlockHash(currentBlock);
1156
+ const eventsResult = await api2.query.system.events.at(blockHash);
1157
+ const events = eventsResult;
1158
+ const blockData = await (hasPredicate ? api2.rpc.chain.getBlock(blockHash) : Promise.resolve(null));
1159
+ for (const record of events) {
1160
+ const { event, phase } = record;
1161
+ const matched = hasPredicate ? await filter.predicate(blockData, event, phase) : event.section.toLowerCase() === filter.section.toLowerCase() && event.method.toLowerCase() === filter.method.toLowerCase();
1162
+ if (!matched) continue;
1163
+ done = true;
1164
+ unsubPromise.then((unsub) => unsub());
1165
+ resolve({
1166
+ blockHash: blockHash.toHex(),
1167
+ blockNumber: currentBlock,
1168
+ extrinsicIndex: phase.isApplyExtrinsic ? phase.asApplyExtrinsic.toNumber() : null,
1169
+ block: blockData ? () => Promise.resolve(blockData) : () => api2.rpc.chain.getBlock(blockHash),
1170
+ events
1171
+ });
1172
+ return;
1173
+ }
1174
+ } catch (err) {
1175
+ debugLog(`scanForBlockEvent: error scanning block ${currentBlock}: ${err}`);
1176
+ }
1177
+ }
1178
+ );
1179
+ });
1180
+ };
1181
+ async function watchForSubmissionReceipt(requestId, timeoutMs = 10 * 60 * 1e3) {
1182
+ const api2 = await getApi();
1183
+ if (!api2) throw new Error("API not initialized");
1184
+ return new Promise((resolve, reject) => {
1185
+ let unsubFn;
1186
+ let settled = false;
1187
+ const cleanup = (settleFn) => {
1188
+ if (settled) return;
1189
+ settled = true;
1190
+ unsubFn?.();
1191
+ settleFn();
1192
+ };
1193
+ const timer = setTimeout(
1194
+ () => cleanup(() => reject(new Error(`receipt watch timed out for requestId=${requestId}`))),
1195
+ timeoutMs
1196
+ );
1197
+ api2.rpc.chain.subscribeNewHeads(async (header) => {
1198
+ if (settled) return;
1199
+ try {
1200
+ const blockNumber = header.number.toNumber();
1201
+ const blockHash = header.hash;
1202
+ const signedBlock = await api2.rpc.chain.getBlock(blockHash);
1203
+ const extrinsics = signedBlock.block.extrinsics;
1204
+ for (let i = 0; i < extrinsics.length; i++) {
1205
+ const ext = extrinsics[i];
1206
+ const decoded = ext.toHuman();
1207
+ const method = decoded?.method;
1208
+ if (String(method?.section ?? "").toLowerCase() === "compute" && String(method?.method ?? "").toLowerCase() === "result") {
1209
+ const args = method?.args;
1210
+ const onChainId = String(args?.request_id ?? args?.requestId ?? args?.[0] ?? "");
1211
+ if (onChainId === requestId) {
1212
+ clearTimeout(timer);
1213
+ cleanup(
1214
+ () => resolve({
1215
+ extrinsicHash: ext.hash.toHex(),
1216
+ blockHeight: blockNumber,
1217
+ extrinsicIndex: i
1218
+ })
1219
+ );
1220
+ return;
1221
+ }
1222
+ }
1223
+ }
1224
+ } catch (err) {
1225
+ const msg = err instanceof Error ? err.message : String(err);
1226
+ console.warn(`[watchReceipt] block check failed requestId=${requestId}: ${msg}`);
1227
+ }
1228
+ }).then((fn) => {
1229
+ if (settled) {
1230
+ fn();
1231
+ } else {
1232
+ unsubFn = fn;
1233
+ }
1234
+ }).catch((err) => {
1235
+ clearTimeout(timer);
1236
+ cleanup(() => reject(err));
1237
+ });
1238
+ });
1239
+ }
1240
+ async function getAgreementCreatedRequestId(blockHeight, extrinsicIndex) {
1241
+ const api2 = await getApi();
1242
+ if (!api2) throw new Error("API not initialized");
1243
+ const blockHash = await api2.rpc.chain.getBlockHash(blockHeight);
1244
+ const apiAt = await api2.at(blockHash);
1245
+ const allEvents = await apiAt.query.system.events();
1246
+ for (const record of allEvents) {
1247
+ const { phase, event } = record;
1248
+ if (!phase.isApplyExtrinsic || phase.asApplyExtrinsic.toNumber() !== extrinsicIndex) {
1249
+ continue;
1250
+ }
1251
+ if (String(event.section ?? "").toLowerCase() !== "compute" || String(event.method ?? "").toLowerCase() !== "agreementcreated") {
1252
+ continue;
1253
+ }
1254
+ const dataHuman = event.data.toHuman();
1255
+ if (Array.isArray(dataHuman)) {
1256
+ const first = dataHuman[0];
1257
+ if (first != null) return String(first);
1258
+ } else if (dataHuman !== null && typeof dataHuman === "object") {
1259
+ const id = dataHuman["requestId"] ?? dataHuman["request_id"] ?? dataHuman["id"];
1260
+ if (id != null) return String(id);
1261
+ }
1262
+ }
1263
+ return null;
1264
+ }
1023
1265
 
1024
1266
  // src/chain/onchainfs.ts
1025
1267
  var getBlock2 = async (api2, blockNumber) => {
@@ -1058,12 +1300,10 @@ var MCryptFs = class _MCryptFs {
1058
1300
  this._metaRef = metadataRef;
1059
1301
  this._metadata = metadata;
1060
1302
  this._init = true;
1303
+ this._chunkRefs = [];
1061
1304
  }
1062
1305
  static dummyInstance(mcryptApi) {
1063
- return new _MCryptFs(mcryptApi, null, {
1064
- name: "on-chain-file-name.txt",
1065
- description: "File uploaded using mcrypt-onchain-fs"
1066
- });
1306
+ return new _MCryptFs(mcryptApi, null, null);
1067
1307
  }
1068
1308
  isValid() {
1069
1309
  if (!this._metaRef) {
@@ -1127,8 +1367,8 @@ var MCryptFsWriter = class {
1127
1367
  request.signAndSend(this._account, { app_id: 1 }, (result) => {
1128
1368
  if (result.isInBlock || result.isFinalized || result.isError) {
1129
1369
  resolve({
1130
- blockNumber: result.blockNumber?.toNumber(),
1131
- index: result.txIndex
1370
+ blockNumber: result.blockNumber?.toNumber() ?? 0,
1371
+ index: result.txIndex ?? 0
1132
1372
  });
1133
1373
  }
1134
1374
  });
@@ -1150,7 +1390,7 @@ var MCryptFsWriter = class {
1150
1390
  ciphertext: uint8ArrayToBase64(Uint8Array.from(ciphertext)),
1151
1391
  td_params,
1152
1392
  group_pk: this._guardianInfo.groupPk,
1153
- tau_params: this._guardianInfo.tau_params,
1393
+ tau_params: this._guardianInfo.tauParams,
1154
1394
  chosen_guardians: this._guardianInfo.guardians,
1155
1395
  blobRef: [blobRef.blockNumber, blobRef.extrinsicIndex]
1156
1396
  });
@@ -1193,7 +1433,7 @@ var MCryptFsWriter = class {
1193
1433
  const metadataRef = await this.writeMetadata();
1194
1434
  return await FileFromMetadataRef(this._api, [
1195
1435
  metadataRef.blockNumber,
1196
- metadataRef.index
1436
+ metadataRef.index ?? 0
1197
1437
  ]);
1198
1438
  }
1199
1439
  };
@@ -1205,6 +1445,9 @@ var MCryptFsReader = class {
1205
1445
  }
1206
1446
  async downloadFile() {
1207
1447
  const chunks = [];
1448
+ if (!this._onChainFile._metadata) {
1449
+ throw new Error("Metadata not loaded");
1450
+ }
1208
1451
  let _blockNumber = this._onChainFile._metadata.startRef[0];
1209
1452
  let _extIndex = this._onChainFile._metadata.startRef[1];
1210
1453
  while (_blockNumber !== 0) {
@@ -1236,36 +1479,125 @@ var FileFromMetadataRef = async (mcryptApi, metadataRef) => {
1236
1479
  };
1237
1480
 
1238
1481
  // src/compute/agreement.ts
1239
- import bs582 from "bs58";
1240
- async function createAgreement() {
1482
+ async function createAgreement(contract, account) {
1241
1483
  const api2 = await getApi();
1242
1484
  if (!api2) throw new Error("Api not initialized");
1243
- const tx = api2.tx.compute.agreement();
1244
- const guardians = await getGuardianList();
1245
- const agreement = guardians.slice(0, 3).map((g) => bs582.decode(g).subarray(6));
1246
- assert(agreement.length === 3, "Not enough guardians to create agreement");
1247
- const keyring2 = await getKeyring();
1248
- const account = keyring2.getPairs()[0];
1249
- const { tx_result } = await signAndSend(tx, account, {
1250
- compute: { da_type: 1, agreement, verification: 0, compute: 1 }
1251
- });
1485
+ const tx = api2.tx["compute"]["agreement"](contract);
1486
+ const opts = {
1487
+ compute: {
1488
+ da_type: 1,
1489
+ verification: 0,
1490
+ compute: contract.contract_type === "Active" ? 1 : 0
1491
+ }
1492
+ };
1493
+ const { tx_result, blockNumber, index, hash } = await signAndSend(
1494
+ tx,
1495
+ account,
1496
+ opts
1497
+ );
1252
1498
  if (!tx_result.isError) {
1253
- const agreementCreatedEvent = tx_result.events.find((event) => {
1254
- return event.event.section === "compute" && event.event.method === "AgreementCreated";
1255
- });
1499
+ const agreementCreatedEvent = tx_result.events.find(
1500
+ (event) => {
1501
+ return event.event.section === "compute" && event.event.method === "AgreementCreated";
1502
+ }
1503
+ );
1256
1504
  if (agreementCreatedEvent) {
1257
- debugLog(
1258
- "Agreement data:",
1259
- agreementCreatedEvent.event.data.toString()
1260
- );
1505
+ debugLog("Agreement data:", agreementCreatedEvent.event.data.toString());
1506
+ return {
1507
+ blockNumber,
1508
+ index: index ?? 0,
1509
+ hash,
1510
+ agreementId: agreementCreatedEvent.event.data[0]?.toHex?.() ?? agreementCreatedEvent.event.data.toString()
1511
+ };
1261
1512
  } else {
1262
1513
  debugLog("AgreementCreated event not found");
1263
1514
  }
1264
1515
  }
1516
+ return { blockNumber, index: index ?? 0, hash };
1517
+ }
1518
+ async function createSimpleAgreement() {
1519
+ const guardianIds = (await getGuardianAddress()).slice(0, 3).map((g) => g.address);
1520
+ assert(guardianIds.length === 3, "Not enough guardians to create agreement");
1521
+ const contract = {
1522
+ contract_type: "Dormant",
1523
+ guardians: guardianIds,
1524
+ pre_check: null,
1525
+ compute: {
1526
+ cipher: "Plaintext",
1527
+ computer_indices: [0, 1, 2],
1528
+ fees: toAtomicPaliAmount("0.01"),
1529
+ deadline: 0,
1530
+ confidentiality: { Trusted: 0 },
1531
+ fee_function: null,
1532
+ input: null,
1533
+ program: { NativeData: "DaFalse" },
1534
+ metadata: null
1535
+ },
1536
+ post_check: null,
1537
+ result_cipher: "Plaintext"
1538
+ };
1539
+ const keyring2 = await getKeyring();
1540
+ const account = keyring2.getPairs()[0];
1541
+ return createAgreement(contract, account);
1542
+ }
1543
+
1544
+ // src/compute/data.ts
1545
+ async function dataContract(params, account) {
1546
+ const plaintextCipher = "Plaintext";
1547
+ const atomicFees = toAtomicPaliAmount(params.fees ?? "0");
1548
+ const computeStep = {
1549
+ cipher: plaintextCipher,
1550
+ computer_indices: params.guardians.map((_, i) => i),
1551
+ fees: atomicFees,
1552
+ deadline: params.deadline ?? 0,
1553
+ confidentiality: { Trusted: params.trustIndex ?? 0 },
1554
+ fee_function: null,
1555
+ input: {
1556
+ Url: {
1557
+ url: Array.from(new TextEncoder().encode(params.url))
1558
+ }
1559
+ },
1560
+ program: {
1561
+ NativeData: "DaFalse"
1562
+ }
1563
+ };
1564
+ const contract = {
1565
+ contract_type: "Dormant",
1566
+ guardians: params.guardians,
1567
+ pre_check: null,
1568
+ compute: computeStep,
1569
+ post_check: null,
1570
+ result_cipher: plaintextCipher
1571
+ };
1572
+ return createAgreement(contract, account);
1573
+ }
1574
+
1575
+ // src/compute/inference.ts
1576
+ async function inferenceCompute(params, account) {
1577
+ const inputData = typeof params.input === "string" ? Array.from(new TextEncoder().encode(params.input)) : Array.from(params.input);
1578
+ const atomicFees = toAtomicPaliAmount(params.fees ?? "0");
1579
+ const plaintextCipher = "Plaintext";
1580
+ const computeStep = {
1581
+ cipher: plaintextCipher,
1582
+ computer_indices: params.guardians.map((_, i) => i),
1583
+ fees: atomicFees,
1584
+ deadline: params.deadline ?? 0,
1585
+ confidentiality: { Trusted: 0 },
1586
+ fee_function: null,
1587
+ input: { Inline: { data: inputData } },
1588
+ program: { NativeExecute: "Inference" }
1589
+ };
1590
+ const contract = {
1591
+ contract_type: "Active",
1592
+ guardians: params.guardians,
1593
+ compute: computeStep,
1594
+ result_cipher: plaintextCipher
1595
+ };
1596
+ return createAgreement(contract, account);
1265
1597
  }
1266
1598
 
1267
1599
  // src/compute/participants.ts
1268
- import bs583 from "bs58";
1600
+ import bs582 from "bs58";
1269
1601
  async function getGuardianParticipants() {
1270
1602
  const api2 = await getApi();
1271
1603
  if (!api2) throw new Error("Api not initialized");
@@ -1275,8 +1607,8 @@ async function getGuardianParticipants() {
1275
1607
  const currentEra = await api2.query.staking.currentEra();
1276
1608
  const currentIndex = await api2.query.guardian.currentIndex();
1277
1609
  const peerid = await api2.rpc.system.localPeerId();
1278
- const _peerid = bs583.decode((peerid || "").toString());
1279
- const account = await api2.query.guardian.worker(_peerid.slice(0, 32));
1610
+ const _peerid = bs582.decode((peerid || "").toString());
1611
+ const account = await api2.query.guardian.workerByKey(_peerid.slice(6, 38));
1280
1612
  const nextIndex = currentIndex ? Number(currentIndex) + 1 : 1;
1281
1613
  const guardiansList = guardians?.toJSON() || [];
1282
1614
  const nextGuardiansList = nextGuardians?.toJSON() || [];
@@ -1327,6 +1659,35 @@ async function getGuardianParticipants() {
1327
1659
  }
1328
1660
  }
1329
1661
 
1662
+ // src/compute/simple.ts
1663
+ async function simpleCompute(params, account) {
1664
+ const plaintextCipher = "Plaintext";
1665
+ const atomicFees = toAtomicPaliAmount(params.fees ?? "0");
1666
+ const computeStep = {
1667
+ cipher: plaintextCipher,
1668
+ computer_indices: params.guardians.map((_, i) => i),
1669
+ fees: atomicFees,
1670
+ deadline: params.deadline ?? 0,
1671
+ confidentiality: { Trusted: params.trustIndex ?? 0 },
1672
+ fee_function: null,
1673
+ input: null,
1674
+ program: {
1675
+ Url: {
1676
+ url: Array.from(new TextEncoder().encode(params.programUrl))
1677
+ }
1678
+ }
1679
+ };
1680
+ const contract = {
1681
+ contract_type: "Active",
1682
+ guardians: params.guardians,
1683
+ pre_check: null,
1684
+ compute: computeStep,
1685
+ post_check: null,
1686
+ result_cipher: plaintextCipher
1687
+ };
1688
+ return createAgreement(contract, account);
1689
+ }
1690
+
1330
1691
  // src/crypto/random.ts
1331
1692
  function generateRandomBytes(length = 32) {
1332
1693
  const bytes = new Uint8Array(length);
@@ -1349,6 +1710,7 @@ async function writeMetadata(account, name, description, ref, price, dataType, l
1349
1710
  const ownerBytes = Array.from(encoder.encode(l2Owner));
1350
1711
  const api2 = await getApi();
1351
1712
  assert(api2, "Failed to get API connection");
1713
+ debugLog(`Registering metadata for ${name} at ${formatPaliAmount(price)}`);
1352
1714
  const request = api2.tx.dataAvailability.daccRegisterData(
1353
1715
  nameBytes,
1354
1716
  descriptionBytes,
@@ -1362,6 +1724,78 @@ async function writeMetadata(account, name, description, ref, price, dataType, l
1362
1724
  debugLog(`Metadata registration transaction sent with hash: ${hash.hash}`);
1363
1725
  return hash;
1364
1726
  }
1727
+ async function registerDataAgreement(account, params) {
1728
+ debugLog(
1729
+ `Registering data agreement for DA ref ${params.ref.blockNumber}-${params.ref.index} at ${formatPaliAmount(params.fees)}`
1730
+ );
1731
+ const cipher = params.cipher ?? "Plaintext";
1732
+ const resultCipher = params.resultCipher ?? "Plaintext";
1733
+ const encoder = new TextEncoder();
1734
+ const computeMetadata = params.metadata ? {
1735
+ name: Array.from(encoder.encode(params.metadata.name)),
1736
+ description: Array.from(encoder.encode(params.metadata.description)),
1737
+ store_type: params.metadata.storeType,
1738
+ group_id: params.metadata.groupId
1739
+ } : null;
1740
+ const computeStep = {
1741
+ cipher,
1742
+ computer_indices: params.guardians.map((_, i) => i),
1743
+ fees: params.fees,
1744
+ deadline: params.deadline ?? 0,
1745
+ confidentiality: { Trusted: params.trustIndex ?? 0 },
1746
+ fee_function: null,
1747
+ input: {
1748
+ ChainTransaction: {
1749
+ block_number: params.ref.blockNumber,
1750
+ extrinsic_index: params.ref.index
1751
+ }
1752
+ },
1753
+ program: {
1754
+ NativeData: "DaFalse"
1755
+ },
1756
+ metadata: computeMetadata
1757
+ };
1758
+ const contract = {
1759
+ contract_type: "Dormant",
1760
+ guardians: params.guardians,
1761
+ pre_check: null,
1762
+ compute: computeStep,
1763
+ post_check: null,
1764
+ result_cipher: resultCipher
1765
+ };
1766
+ return createAgreement(contract, account);
1767
+ }
1768
+
1769
+ // src/da/runAgent.ts
1770
+ async function runAgent(account, agentRef, nonce, ciphertext, tdParams, pkBytes, tauParams, baseModel, publicKey, guardians, guardian, agreementId) {
1771
+ const agentRefTuple = [agentRef.blockNumber, agentRef.index];
1772
+ const baseModelTuple = [baseModel.blockNumber, baseModel.index];
1773
+ const api2 = await getApi();
1774
+ assert(api2, "Failed to get API connection");
1775
+ const request = api2.tx.dataAvailability.daccRunAgent(
1776
+ agentRefTuple,
1777
+ Array.from(nonce),
1778
+ Array.from(ciphertext),
1779
+ guardian ? Array.from(guardian) : null,
1780
+ Array.from(tdParams),
1781
+ Array.from(pkBytes),
1782
+ Array.from(tauParams),
1783
+ baseModelTuple,
1784
+ Array.from(publicKey),
1785
+ guardians.map((g) => Array.from(g))
1786
+ );
1787
+ const opts = {
1788
+ compute: {
1789
+ da_type: 4,
1790
+ verification: 0,
1791
+ compute: 1,
1792
+ agreement: [agreementId]
1793
+ }
1794
+ };
1795
+ const hash = await signAndSend(request, account, opts);
1796
+ debugLog(`Run agent transaction sent with hash: ${hash.hash}`);
1797
+ return hash;
1798
+ }
1365
1799
 
1366
1800
  // src/da/submit.ts
1367
1801
  async function submitData(account, data) {
@@ -1395,11 +1829,76 @@ async function submitTEData(account, data, chosenGuardians, tau_params, agg_key,
1395
1829
  debugLog(`TE data availability transaction sent with hash: ${hash.hash}`);
1396
1830
  return hash;
1397
1831
  }
1832
+ async function submitTEDataWithCipher(account, data, chosenGuardians, tau_params, agg_key, group_pk) {
1833
+ const { encoded: encryptedKey, ikm } = testCrypt(tau_params, agg_key);
1834
+ const shared_key = gen_stretched_key(hexToUint8Array(ikm));
1835
+ const encoder = new TextEncoder();
1836
+ const dataUint8Array = encoder.encode(data);
1837
+ const { ciphertext, nonce } = encrypt2(dataUint8Array, shared_key);
1838
+ const ciphertextHex = "0x" + Array.from(ciphertext).map((b) => b.toString(16).padStart(2, "0")).join("");
1839
+ const api2 = await getApi();
1840
+ assert(api2, "Failed to get API connection");
1841
+ const request = await api2.tx.dataAvailability.submitData(ciphertextHex);
1842
+ const ref = await signAndSend(request, account, DEFAULT_EMPTY_PAYLOAD);
1843
+ debugLog(`TE data availability transaction sent with hash: ${ref.hash}`);
1844
+ return {
1845
+ ref,
1846
+ cipher: {
1847
+ ThresholdHybrid: {
1848
+ threshold_params: {
1849
+ SilentThreshold: {
1850
+ td_params: Array.from(hexToUint8Array(encryptedKey)),
1851
+ pk_bytes: Array.from(hexToUint8Array(group_pk)),
1852
+ tau_params: Array.from(hexToUint8Array(tau_params))
1853
+ }
1854
+ },
1855
+ symmetric_params: {
1856
+ ChaCha20Poly1305: { nonce: Array.from(nonce) }
1857
+ }
1858
+ }
1859
+ }
1860
+ };
1861
+ }
1398
1862
 
1399
1863
  // src/da/upload.ts
1400
1864
  import fs from "fs";
1401
1865
  import path from "path";
1402
1866
  async function uploadData(options) {
1867
+ const { name, description, price, type, guardianGroupInfo, ref, filePath } = options;
1868
+ assert(
1869
+ guardianGroupInfo.guardians && guardianGroupInfo.tauParams && guardianGroupInfo.aggKey && guardianGroupInfo.groupPk,
1870
+ "Guardian group info is missing required properties"
1871
+ );
1872
+ console.log("Guardian group info:", guardianGroupInfo);
1873
+ const account = (await getKeyring()).pairs[0];
1874
+ const atomicPrice = toAtomicPaliAmount(price);
1875
+ if (filePath) {
1876
+ throw new Error("uploadData: file path upload is not implemented");
1877
+ } else {
1878
+ const storeType = type === "model" ? "Model" : type === "agent" ? "Agent" : "Dataset";
1879
+ const { ref: dataRef, cipher } = await submitTEDataWithCipher(
1880
+ account,
1881
+ ref || "",
1882
+ guardianGroupInfo.guardians,
1883
+ guardianGroupInfo.tauParams,
1884
+ guardianGroupInfo.aggKey,
1885
+ guardianGroupInfo.groupPk
1886
+ );
1887
+ await registerDataAgreement(account, {
1888
+ ref: dataRef,
1889
+ guardians: guardianGroupInfo.guardians,
1890
+ fees: atomicPrice,
1891
+ cipher,
1892
+ metadata: {
1893
+ name,
1894
+ description,
1895
+ storeType,
1896
+ groupId: guardianGroupInfo.groupId
1897
+ }
1898
+ });
1899
+ }
1900
+ }
1901
+ async function uploadDataLegacy(options) {
1403
1902
  const { name, description, price, type, guardianGroupInfo, ref, filePath } = options;
1404
1903
  assert(
1405
1904
  guardianGroupInfo.guardians && guardianGroupInfo.tauParams && guardianGroupInfo.aggKey && guardianGroupInfo.groupPk,
@@ -1407,6 +1906,7 @@ async function uploadData(options) {
1407
1906
  );
1408
1907
  const account = (await getKeyring()).pairs[0];
1409
1908
  const ethAddress = "";
1909
+ const atomicPrice = toAtomicPaliAmount(price);
1410
1910
  if (type === "dataset" && filePath) {
1411
1911
  const fileContent = fs.readFileSync(filePath);
1412
1912
  const selectedFile = new File([fileContent], path.basename(filePath), {
@@ -1419,7 +1919,7 @@ async function uploadData(options) {
1419
1919
  fileName: selectedFile.name,
1420
1920
  filePath: "",
1421
1921
  description,
1422
- baseCost: BigInt(Number(price) * 10 ** 18),
1922
+ baseCost: atomicPrice,
1423
1923
  ownerL2Address: ethAddress,
1424
1924
  guardianInfo: guardianGroupInfo
1425
1925
  },
@@ -1452,12 +1952,12 @@ async function uploadData(options) {
1452
1952
  }
1453
1953
 
1454
1954
  // src/stake/add.ts
1455
- async function addStake(account, amount) {
1955
+ async function addStake(account, amountBaseUnits) {
1456
1956
  const api2 = await getApi();
1457
1957
  assert(api2, "API not initialized");
1458
1958
  assert(account, "Account not initialized");
1459
- debugLog("Using account:", account.address);
1460
- const stakeTx = api2.tx.staking.bondExtra(amount);
1959
+ debugLog("Using account:", account.address, "adding:", formatPaliAmount(amountBaseUnits));
1960
+ const stakeTx = api2.tx.staking.bondExtra(amountBaseUnits);
1461
1961
  const hash = await signAndSend(stakeTx, account);
1462
1962
  debugLog(`Stake transaction sent with hash: ${hash.hash}`);
1463
1963
  }
@@ -1473,14 +1973,14 @@ async function joinIdleStaker(account) {
1473
1973
  }
1474
1974
 
1475
1975
  // src/stake/new.ts
1476
- async function newStake(account, amount, rewardDestination = "Staked") {
1976
+ async function newStake(account, amountBaseUnits, rewardDestination = "Staked") {
1477
1977
  const api2 = await getApi();
1478
1978
  assert(api2, "API not initialized");
1479
1979
  assert(account, "Account not initialized");
1480
1980
  debugLog(
1481
- `Staking amount: ${amount} for account: ${account.address} with reward destination: ${rewardDestination}`
1981
+ `Staking amount: ${formatPaliAmount(amountBaseUnits)} for account: ${account.address} with reward destination: ${rewardDestination}`
1482
1982
  );
1483
- const stakeTx = api2.tx.staking.bond(amount, rewardDestination);
1983
+ const stakeTx = api2.tx.staking.bond(amountBaseUnits, rewardDestination);
1484
1984
  const hash = await signAndSend(stakeTx, account);
1485
1985
  debugLog(`Stake transaction sent with hash: ${hash.hash}`);
1486
1986
  }
@@ -1502,12 +2002,12 @@ async function payoutStake(account, eras, address) {
1502
2002
  }
1503
2003
 
1504
2004
  // src/stake/reduce.ts
1505
- async function reduceStake(account, amount) {
2005
+ async function reduceStake(account, amountBaseUnits) {
1506
2006
  const api2 = await getApi();
1507
2007
  assert(api2, "API not initialized");
1508
2008
  assert(account, "Account not initialized");
1509
- debugLog("Using account:", account.address);
1510
- const unstakeTx = api2.tx.staking.unbond(amount);
2009
+ debugLog("Using account:", account.address, "reducing:", formatPaliAmount(amountBaseUnits));
2010
+ const unstakeTx = api2.tx.staking.unbond(amountBaseUnits);
1511
2011
  const hash = await signAndSend(unstakeTx, account);
1512
2012
  debugLog(`Unstake transaction sent with hash: ${hash.hash}`);
1513
2013
  }
@@ -1518,7 +2018,7 @@ async function removeStake(account) {
1518
2018
  assert(api2, "API not initialized");
1519
2019
  assert(account, "Account not initialized");
1520
2020
  const stakeAmount = (await api2.query.staking.ledger(account.address))?.toPrimitive();
1521
- debugLog("Removing entire stake amount:", stakeAmount?.active || 0n);
2021
+ debugLog("Removing entire stake amount:", formatPaliAmount(stakeAmount?.active || 0n));
1522
2022
  const unstakeTx = api2.tx.staking.unbond(stakeAmount?.active || 0n);
1523
2023
  const hash = await signAndSend(unstakeTx, account);
1524
2024
  debugLog(`Unstake transaction sent with hash: ${hash.hash}`);
@@ -1535,25 +2035,25 @@ async function withdrawStake(account) {
1535
2035
  }
1536
2036
 
1537
2037
  // src/token/fund.ts
1538
- async function fundAccount(account, amount, address) {
2038
+ async function fundAccount(account, amountBaseUnits, address) {
1539
2039
  const addr = address ? address : account.address;
1540
2040
  const keyring2 = await getKeyring();
1541
2041
  const api2 = await getApi();
1542
2042
  assert(api2, "API not initialized");
1543
2043
  debugLog(`
1544
- Funding account: ${addr} with amount: ${amount}`);
1545
- const tx = api2.tx.balances.transferKeepAlive(addr, amount);
2044
+ Funding account: ${addr} with amount: ${formatPaliAmount(amountBaseUnits)}`);
2045
+ const tx = api2.tx.balances.transferKeepAlive(addr, amountBaseUnits);
1546
2046
  const hash = await signAndSend(tx, keyring2.getPairs()[0]);
1547
2047
  debugLog(`Fund transaction sent with hash: ${hash.hash}`);
1548
2048
  }
1549
2049
 
1550
2050
  // src/token/transfer.ts
1551
- async function transfer(account, amount, address) {
2051
+ async function transfer(account, amountBaseUnits, address) {
1552
2052
  const api2 = await getApi();
1553
2053
  assert(api2, "API not initialized");
1554
2054
  debugLog(`
1555
- Transferring funds to account: ${address} with amount: ${amount}`);
1556
- const tx = api2.tx.balances.transferKeepAlive(address, amount);
2055
+ Transferring funds to account: ${address} with amount: ${formatPaliAmount(amountBaseUnits)}`);
2056
+ const tx = api2.tx.balances.transferKeepAlive(address, amountBaseUnits);
1557
2057
  const hash = await signAndSend(tx, account);
1558
2058
  debugLog(`Transfer transaction sent with hash: ${hash.hash}`);
1559
2059
  }
@@ -1581,7 +2081,7 @@ Setting identity for account: ${account.address} as ${display}`);
1581
2081
  }
1582
2082
 
1583
2083
  // src/rotateKeys.ts
1584
- import bs584 from "bs58";
2084
+ import bs583 from "bs58";
1585
2085
  import assert3 from "assert";
1586
2086
  async function rotateAndSetKeys(account) {
1587
2087
  const api2 = await getApi();
@@ -1596,8 +2096,8 @@ async function rotateAndSetKeys(account) {
1596
2096
  async function setWorker(account) {
1597
2097
  const api2 = await getApi();
1598
2098
  assert3(api2, "API not initialized");
1599
- const peerid = bs584.decode((await api2.rpc.system.localPeerId()).toString());
1600
- const setWorkerTx = api2.tx.guardian.setWorker(peerid.slice(0, 32));
2099
+ const peerid = bs583.decode((await api2.rpc.system.localPeerId()).toString());
2100
+ const setWorkerTx = api2.tx.guardian.setWorker(peerid.slice(6, 38));
1601
2101
  const hash = await signAndSend(setWorkerTx, account);
1602
2102
  debugLog(`Set worker id transaction sent with hash: ${hash.hash}`);
1603
2103
  }
@@ -1622,9 +2122,10 @@ export {
1622
2122
  MCryptFs,
1623
2123
  MCryptFsReader,
1624
2124
  MCryptFsWriter,
2125
+ PALI_DECIMALS,
2126
+ PALI_SYMBOL,
1625
2127
  PALLIORA_RPC_URL,
1626
2128
  PALLIORA_WS,
1627
- RpcApi,
1628
2129
  TX_WAIT_FINALIZATION,
1629
2130
  WsProvider3 as WsProvider,
1630
2131
  addStake,
@@ -1634,6 +2135,9 @@ export {
1634
2135
  createAccount,
1635
2136
  createAgreement,
1636
2137
  createGuardianGroup,
2138
+ createGuardianGroupAndWatch,
2139
+ createSimpleAgreement,
2140
+ dataContract,
1637
2141
  debugLog,
1638
2142
  decodeAggregateKey,
1639
2143
  decodeField,
@@ -1642,12 +2146,16 @@ export {
1642
2146
  encrypt as ecncryptTest,
1643
2147
  encodeCiphertext,
1644
2148
  encrypt2 as encrypt,
2149
+ fetchAndDecodeExtrinsic,
1645
2150
  fetchTokenProperties,
1646
2151
  formatBalanceWithTokenProperties,
2152
+ formatPaliAmount,
2153
+ fromAtomicPaliAmount,
1647
2154
  fundAccount,
1648
2155
  gen_shared_key,
1649
2156
  gen_stretched_key,
1650
2157
  generateRandomBytes,
2158
+ getAgreementCreatedRequestId,
1651
2159
  getApi,
1652
2160
  getCachedTokenProperties,
1653
2161
  getEncKeyring,
@@ -1657,8 +2165,8 @@ export {
1657
2165
  getGuardianNwParams,
1658
2166
  getGuardianParticipants,
1659
2167
  getKeyring,
1660
- getRpcApi,
1661
2168
  hexToUint8Array,
2169
+ inferenceCompute,
1662
2170
  joinGuardian,
1663
2171
  joinIdleStaker,
1664
2172
  joinValidator,
@@ -1667,20 +2175,28 @@ export {
1667
2175
  payoutStake,
1668
2176
  provider,
1669
2177
  reduceStake,
2178
+ registerDataAgreement,
1670
2179
  removeStake,
1671
2180
  rotateAndSetKeys,
2181
+ runAgent,
2182
+ scanForBlockEvent,
1672
2183
  setIdentity,
1673
2184
  setWorker,
1674
2185
  signAndSend,
2186
+ simpleCompute,
1675
2187
  submitData,
1676
2188
  submitTEData,
2189
+ submitTEDataWithCipher,
1677
2190
  testCrypt,
2191
+ toAtomicPaliAmount,
1678
2192
  tokenToBigint,
1679
2193
  transfer,
1680
2194
  uint8ArrayToBase64,
1681
2195
  uploadData,
2196
+ uploadDataLegacy,
1682
2197
  utilCrypto,
1683
2198
  wasmCrypto,
2199
+ watchForSubmissionReceipt,
1684
2200
  withdrawStake,
1685
2201
  writeMetadata
1686
2202
  };