@palliora.org/chainsdk 0.1.0 → 0.2.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 CHANGED
@@ -220,12 +220,144 @@ 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
+ ThresholdAlgos: {
234
+ _enum: {
235
+ SilentThreshold: "SilentThresholdParams"
236
+ }
237
+ },
238
+ ChaCha20Poly1305Params: {
239
+ nonce: "[u8; 12]"
240
+ },
241
+ Aes256GcmParams: {
242
+ nonce: "[u8; 12]"
243
+ },
244
+ SymmetricAlgos: {
245
+ _enum: {
246
+ ChaCha20Poly1305: "ChaCha20Poly1305Params",
247
+ Aes256Gcm: "Aes256GcmParams"
248
+ }
249
+ },
250
+ CipherSuiteEncrypted: {
251
+ threshold: "ThresholdAlgos",
252
+ symmetric: "SymmetricAlgos"
253
+ },
254
+ CipherSuite: {
255
+ _enum: {
256
+ Plaintext: "Null",
257
+ Encrypted: "CipherSuiteEncrypted"
258
+ }
259
+ },
260
+ ConfidentialityLevel: {
261
+ _enum: ["Trusted", "TEE", "FHE", "SMPC"]
262
+ },
263
+ NativeExecuteDA: {
264
+ _enum: ["Inference"]
265
+ },
266
+ NativeDataDA: {
267
+ _enum: ["DaFalse", "DaTrue"]
268
+ },
269
+ DAInputInline: {
270
+ data: "Vec<u8>"
271
+ },
272
+ DAInputChainTransaction: {
273
+ block_number: "u64",
274
+ extrinsic_index: "u32"
275
+ },
276
+ DAInputIpfs: {
277
+ cid: "Vec<u8>",
278
+ size: "u64"
279
+ },
280
+ DAInputUrl: {
281
+ url: "Vec<u8>",
282
+ size: "u64",
283
+ hash: "Option<Vec<u8>>"
284
+ },
285
+ DAInput: {
286
+ _enum: {
287
+ Inline: "DAInputInline",
288
+ ChainTransaction: "DAInputChainTransaction",
289
+ Ipfs: "DAInputIpfs",
290
+ Url: "DAInputUrl",
291
+ NativeExecute: "NativeExecuteDA",
292
+ NativeData: "NativeDataDA"
293
+ }
294
+ },
295
+ ContractType: {
296
+ _enum: {
297
+ Dormant: "Dormant",
298
+ Active: "Active"
299
+ }
300
+ },
301
+ StoreType: {
302
+ _enum: {
303
+ Dataset: "Dataset",
304
+ Model: "Model",
305
+ Agent: "Agent",
306
+ Other: "Other"
307
+ }
308
+ },
309
+ ComputeMetadata: {
310
+ name: "Vec<u8>",
311
+ description: "Vec<u8>",
312
+ store_type: "StoreType",
313
+ group_id: "H256"
314
+ },
315
+ ComputeInfo: {
316
+ cipher: "CipherSuite",
317
+ computer_indices: "Vec<u32>",
318
+ fees: "u128",
319
+ deadline: "u64",
320
+ confidentiality: "ConfidentialityLevel",
321
+ fee_function: "Option<u8>",
322
+ program_env: "Option<Vec<u8>>",
323
+ input: "DAInput",
324
+ program: "DAInput",
325
+ metadata: "Option<ComputeMetadata>"
326
+ },
327
+ Contract: {
328
+ contract_type: "ContractType",
329
+ guardians: "Vec<AccountId>",
330
+ pre_check: "Option<ComputeInfo>",
331
+ compute: "ComputeInfo",
332
+ post_check: "Option<ComputeInfo>",
333
+ result_cipher: "CipherSuite"
334
+ },
335
+ AgreementInfo: {
336
+ status: "AgreementStatus",
337
+ creator: "AccountId",
338
+ index: "u32"
339
+ },
223
340
  ComputePayload: {
224
341
  da_type: "u8",
225
342
  agreement: "Option<BoundedVec<[u8; 32], 10>>",
226
343
  verification: "u8",
227
344
  compute: "u8"
228
345
  },
346
+ ComputePrefs: {
347
+ trusted: "bool",
348
+ tee: "bool",
349
+ mpc: "bool",
350
+ fhe: "bool",
351
+ zkp: "bool"
352
+ },
353
+ GuardianPrefs: {
354
+ pubKey: "[u8; 32]",
355
+ guardian: "bool",
356
+ verifier: "bool",
357
+ compute: "bool",
358
+ computePrefs: "Option<ComputePrefs>",
359
+ feeThreshold: "u128"
360
+ },
229
361
  BlockLengthColumns: "Compact<u32>",
230
362
  BlockLengthRows: "Compact<u32>",
231
363
  BlockLength: {
@@ -398,7 +530,7 @@ var isValidHex = (hex) => {
398
530
  return /^[0-9A-Fa-f]*$/.test(hex) && hex.length % 2 === 0;
399
531
  };
400
532
  var decodeAggregateKey = (input) => {
401
- const buffer = new Uint8Array(_optionalChain([input, 'access', _ => _.match, 'call', _2 => _2(/.{1,2}/g), 'optionalAccess', _3 => _3.map, 'call', _4 => _4((byte) => parseInt(byte, 16))]) || []);
533
+ const buffer = new Uint8Array(_optionalChain([input, 'access', _2 => _2.match, 'call', _3 => _3(/.{1,2}/g), 'optionalAccess', _4 => _4.map, 'call', _5 => _5((byte) => parseInt(byte, 16))]) || []);
402
534
  let offset = 0;
403
535
  const view = new DataView(buffer.buffer);
404
536
  const readBigUInt64LE = () => {
@@ -472,16 +604,16 @@ var decodeAggregateKey = (input) => {
472
604
  var encodeCiphertext = (input) => {
473
605
  const writeProjPointTypeFp = (point) => {
474
606
  const hex = point.toHex(true);
475
- return new Uint8Array(_optionalChain([hex, 'access', _5 => _5.match, 'call', _6 => _6(/.{1,2}/g), 'optionalAccess', _7 => _7.map, 'call', _8 => _8((byte) => parseInt(byte, 16))]) || []);
607
+ return new Uint8Array(_optionalChain([hex, 'access', _6 => _6.match, 'call', _7 => _7(/.{1,2}/g), 'optionalAccess', _8 => _8.map, 'call', _9 => _9((byte) => parseInt(byte, 16))]) || []);
476
608
  };
477
609
  const writeProjPointTypeFp2 = (point) => {
478
610
  const hex = point.toHex(true);
479
- return new Uint8Array(_optionalChain([hex, 'access', _9 => _9.match, 'call', _10 => _10(/.{1,2}/g), 'optionalAccess', _11 => _11.map, 'call', _12 => _12((byte) => parseInt(byte, 16))]) || []);
611
+ return new Uint8Array(_optionalChain([hex, 'access', _10 => _10.match, 'call', _11 => _11(/.{1,2}/g), 'optionalAccess', _12 => _12.map, 'call', _13 => _13((byte) => parseInt(byte, 16))]) || []);
480
612
  };
481
613
  const gamma_g2Buffer = writeProjPointTypeFp2(input.gamma_g2);
482
614
  const sa1Buffer = new Uint8Array(input.sa1.flatMap((p) => Array.from(writeProjPointTypeFp(p))));
483
615
  const sa2Buffer = new Uint8Array(input.sa2.flatMap((p) => Array.from(writeProjPointTypeFp2(p))));
484
- const enc_keyBuffer = new Uint8Array(_optionalChain([fp12ToHex, 'call', _13 => _13(input.enc_key), 'access', _14 => _14.match, 'call', _15 => _15(/.{1,2}/g), 'optionalAccess', _16 => _16.map, 'call', _17 => _17((byte) => parseInt(byte, 16))]) || []);
616
+ const enc_keyBuffer = new Uint8Array(_optionalChain([fp12ToHex, 'call', _14 => _14(input.enc_key), 'access', _15 => _15.match, 'call', _16 => _16(/.{1,2}/g), 'optionalAccess', _17 => _17.map, 'call', _18 => _18((byte) => parseInt(byte, 16))]) || []);
485
617
  const tBuffer = new Uint8Array(8);
486
618
  new DataView(tBuffer.buffer).setBigUint64(0, BigInt(input.t), true);
487
619
  const totalLength = gamma_g2Buffer.length + sa1Buffer.length + sa2Buffer.length + enc_keyBuffer.length + tBuffer.length;
@@ -538,7 +670,7 @@ function bigintToBigEndianHex(value, length) {
538
670
  throw new Error("BigInt value is too large to fit in the specified length");
539
671
  }
540
672
  hex = hex.padStart(length * 2, "0");
541
- const byteArray = _optionalChain([hex, 'access', _18 => _18.match, 'call', _19 => _19(/.{1,2}/g), 'optionalAccess', _20 => _20.map, 'call', _21 => _21((byte) => parseInt(byte, 16))]) || [];
673
+ const byteArray = _optionalChain([hex, 'access', _19 => _19.match, 'call', _20 => _20(/.{1,2}/g), 'optionalAccess', _21 => _21.map, 'call', _22 => _22((byte) => parseInt(byte, 16))]) || [];
542
674
  const reversedByteArray = byteArray.reverse();
543
675
  const bigEndianHex = reversedByteArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
544
676
  return bigEndianHex;
@@ -547,7 +679,7 @@ function reverseEndianess(hex) {
547
679
  if (hex.length % 2 !== 0) {
548
680
  throw new Error("Hex string must have an even length");
549
681
  }
550
- return _optionalChain([hex, 'access', _22 => _22.match, 'call', _23 => _23(/.{1,2}/g), 'optionalAccess', _24 => _24.reverse, 'call', _25 => _25(), 'access', _26 => _26.join, 'call', _27 => _27("")]) || "";
682
+ return _optionalChain([hex, 'access', _23 => _23.match, 'call', _24 => _24(/.{1,2}/g), 'optionalAccess', _25 => _25.reverse, 'call', _26 => _26(), 'access', _27 => _27.join, 'call', _28 => _28("")]) || "";
551
683
  }
552
684
 
553
685
  // src/crypto/cipher.ts
@@ -599,10 +731,6 @@ function configure(opts) {
599
731
  }
600
732
 
601
733
  // src/utils/helper.ts
602
- var tokenToBigint = (arg) => {
603
- const val = typeof arg === "bigint" ? arg : BigInt(arg);
604
- return val * 10n ** 15n;
605
- };
606
734
  function hexToUint8Array(hex) {
607
735
  if (hex.length % 2 !== 0) {
608
736
  throw new Error("Invalid hex string");
@@ -653,23 +781,37 @@ var debugLog = (message, ...optionalParams) => {
653
781
  };
654
782
 
655
783
  // src/utils/token.ts
656
-
784
+ var _viem = require('viem');
785
+ var PALI_SYMBOL = "PALI";
786
+ var PALI_DECIMALS = 18;
657
787
  var tokenCache = null;
788
+ var toAtomicPaliAmount = (amount) => {
789
+ const normalizedAmount = String(amount).trim();
790
+ if (!normalizedAmount) {
791
+ throw new Error("Token amount cannot be empty");
792
+ }
793
+ return _viem.parseUnits.call(void 0, normalizedAmount, PALI_DECIMALS);
794
+ };
795
+ var fromAtomicPaliAmount = (amount) => {
796
+ return _viem.formatUnits.call(void 0, amount, PALI_DECIMALS);
797
+ };
798
+ var formatPaliAmount = (amount, symbol = PALI_SYMBOL) => {
799
+ return `${fromAtomicPaliAmount(amount)} ${symbol}`;
800
+ };
658
801
  async function fetchTokenProperties() {
659
802
  if (tokenCache) {
660
803
  return tokenCache;
661
804
  }
662
805
  try {
663
- const systemProperties = await _asyncOptionalChain([(await await _asyncOptionalChain([(await getApi()), 'optionalAccess', async _28 => _28.rpc, 'access', async _29 => _29.system, 'access', async _30 => _30.properties, 'call', async _31 => _31()])), 'optionalAccess', async _32 => _32.toHuman, 'call', async _33 => _33()]);
806
+ const systemProperties = await _asyncOptionalChain([(await await _asyncOptionalChain([(await getApi()), 'optionalAccess', async _29 => _29.rpc, 'access', async _30 => _30.system, 'access', async _31 => _31.properties, 'call', async _32 => _32()])), 'optionalAccess', async _33 => _33.toHuman, 'call', async _34 => _34()]);
664
807
  assert(systemProperties, "Failed to fetch system properties from RPC");
665
808
  const tokenProperties = {
666
- symbol: (_optionalChain([systemProperties, 'optionalAccess', _34 => _34.tokenSymbol]) || ["UNIT"])[0],
667
- decimals: Number((_optionalChain([systemProperties, 'optionalAccess', _35 => _35.tokenDecimals]) || ["18"])[0])
809
+ symbol: (_optionalChain([systemProperties, 'optionalAccess', _35 => _35.tokenSymbol]) || [PALI_SYMBOL])[0],
810
+ decimals: Number((_optionalChain([systemProperties, 'optionalAccess', _36 => _36.tokenDecimals]) || [String(PALI_DECIMALS)])[0])
668
811
  };
669
812
  tokenCache = tokenProperties;
670
813
  return tokenProperties;
671
814
  } catch (error) {
672
- console.error("Failed to fetch token properties:", error);
673
815
  throw error;
674
816
  }
675
817
  }
@@ -681,17 +823,9 @@ function clearTokenCache() {
681
823
  }
682
824
  async function formatBalanceWithTokenProperties(balance) {
683
825
  const tokenProperties = await fetchTokenProperties();
684
- if (!tokenProperties) {
685
- throw new Error(
686
- "Token properties not yet cached. Call fetchTokenProperties first."
687
- );
688
- }
689
- return _util.formatBalance.call(void 0, balance, {
690
- decimals: tokenProperties.decimals,
691
- withSi: true,
692
- withUnit: tokenProperties.symbol
693
- });
826
+ return `${_viem.formatUnits.call(void 0, typeof balance === "bigint" ? balance : BigInt(balance), tokenProperties.decimals)} ${tokenProperties.symbol}`;
694
827
  }
828
+ var tokenToBigint = toAtomicPaliAmount;
695
829
 
696
830
  // src/chain/singleton.ts
697
831
 
@@ -702,128 +836,13 @@ var provider = new (0, _api2.WsProvider)(PALLIORA_WS, 1e4);
702
836
 
703
837
  // src/chain/singleton.ts
704
838
 
705
- var wsProvider = null;
706
839
  var api = null;
707
840
  var keyring = null;
708
841
  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 (0, _api2.WsProvider)(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 _api2.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 (0, _api2.Keyring)({ type: "sr25519" });
773
- }
774
- if (!encKeyring) {
775
- encKeyring = new (0, _api2.Keyring)({ 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() {
842
+ var apiListenersAttached = false;
843
+ var apiTeardownInProgress = false;
844
+ async function getApi(cb) {
825
845
  if (!provider) return;
826
- console.debug(provider.endpoint);
827
846
  if (!api) {
828
847
  api = await _api2.ApiPromise.create({
829
848
  provider,
@@ -833,15 +852,25 @@ async function getApi() {
833
852
  });
834
853
  }
835
854
  const isNode = typeof process !== "undefined" && typeof process.exit === "function";
836
- const isTest = typeof process !== "undefined" && _optionalChain([process, 'access', _36 => _36.env, 'optionalAccess', _37 => _37.NODE_ENV]) === "test";
837
- if (isNode && !isTest) {
855
+ const isTest = typeof process !== "undefined" && _optionalChain([process, 'access', _37 => _37.env, 'optionalAccess', _38 => _38.NODE_ENV]) === "test";
856
+ if (isNode && !isTest && api && !apiListenersAttached) {
857
+ apiListenersAttached = true;
838
858
  api.on("error", (err) => {
839
- console.error("api error, will restart:", err);
840
- process.exit(0);
859
+ if (apiTeardownInProgress) return;
860
+ apiTeardownInProgress = true;
861
+ apiListenersAttached = false;
862
+ const currentApi = api;
863
+ api = null;
864
+ void _optionalChain([currentApi, 'optionalAccess', _39 => _39.disconnect, 'call', _40 => _40(), 'access', _41 => _41.catch, 'call', _42 => _42((disconnectErr) => {
865
+ apiTeardownInProgress = false;
866
+ console.error("api disconnect after error failed:", disconnectErr);
867
+ })]);
841
868
  });
842
869
  api.on("disconnected", () => {
843
- console.error("api disconnected, will restart.");
844
- process.exit(0);
870
+ api = null;
871
+ apiListenersAttached = false;
872
+ apiTeardownInProgress = false;
873
+ if (cb) cb();
845
874
  });
846
875
  }
847
876
  return api;
@@ -862,13 +891,6 @@ async function getEncKeyring() {
862
891
  }
863
892
  return encKeyring;
864
893
  }
865
- var apiInstance = null;
866
- function getRpcApi() {
867
- if (!apiInstance) {
868
- apiInstance = new RpcApi();
869
- }
870
- return apiInstance;
871
- }
872
894
 
873
895
  // src/chain/utils.ts
874
896
 
@@ -883,7 +905,7 @@ var getGuardianList = async () => {
883
905
  const section = "guardian";
884
906
  const method = "guardianList";
885
907
  assert(
886
- _util.isFunction.call(void 0, _optionalChain([rpc, 'access', _38 => _38[section], 'optionalAccess', _39 => _39[method]])),
908
+ _util.isFunction.call(void 0, _optionalChain([rpc, 'access', _43 => _43[section], 'optionalAccess', _44 => _44[method]])),
887
909
  `api.rpc.${section}.${method} does not exist`
888
910
  );
889
911
  const list = (await rpc[section]["guardianList"]()).map((item) => [item.toString()]).flat(1);
@@ -918,24 +940,26 @@ async function joinGuardian(account, prefs) {
918
940
  const api2 = await getApi();
919
941
  assert(api2, "API not initialized");
920
942
  assert(account, "Account not initialized");
921
- const computeOpts = _optionalChain([prefs, 'access', _40 => _40.compute, 'optionalAccess', _41 => _41.split, 'call', _42 => _42(","), 'access', _43 => _43.map, 'call', _44 => _44((s) => s.trim()), 'access', _45 => _45.filter, 'call', _46 => _46((s) => s.length > 0)]) || void 0;
943
+ const computeOpts = _optionalChain([prefs, 'access', _45 => _45.compute, 'optionalAccess', _46 => _46.split, 'call', _47 => _47(","), 'access', _48 => _48.map, 'call', _49 => _49((s) => s.trim()), 'access', _50 => _50.filter, 'call', _51 => _51((s) => s.length > 0)]) || void 0;
944
+ const feeThreshold = typeof prefs.fee === "bigint" ? prefs.fee : BigInt(prefs.fee || "0");
922
945
  const guardianPrefs = {
923
946
  pubKey: account.publicKey,
924
947
  guardian: prefs.standard,
925
948
  verifier: prefs.verifier,
926
949
  compute: prefs.compute ? true : false,
927
950
  computePrefs: {
928
- trusted: _optionalChain([computeOpts, 'optionalAccess', _47 => _47.includes, 'call', _48 => _48("trusted")]) || false,
929
- tee: _optionalChain([computeOpts, 'optionalAccess', _49 => _49.includes, 'call', _50 => _50("tee")]) || false,
930
- mpc: _optionalChain([computeOpts, 'optionalAccess', _51 => _51.includes, 'call', _52 => _52("mpc")]) || false,
931
- fhe: _optionalChain([computeOpts, 'optionalAccess', _53 => _53.includes, 'call', _54 => _54("fhe")]) || false,
932
- zkp: _optionalChain([computeOpts, 'optionalAccess', _55 => _55.includes, 'call', _56 => _56("zkp")]) || false
933
- }
951
+ trusted: _optionalChain([computeOpts, 'optionalAccess', _52 => _52.includes, 'call', _53 => _53("trusted")]) || false,
952
+ tee: _optionalChain([computeOpts, 'optionalAccess', _54 => _54.includes, 'call', _55 => _55("tee")]) || false,
953
+ mpc: _optionalChain([computeOpts, 'optionalAccess', _56 => _56.includes, 'call', _57 => _57("mpc")]) || false,
954
+ fhe: _optionalChain([computeOpts, 'optionalAccess', _58 => _58.includes, 'call', _59 => _59("fhe")]) || false,
955
+ zkp: _optionalChain([computeOpts, 'optionalAccess', _60 => _60.includes, 'call', _61 => _61("zkp")]) || false
956
+ },
957
+ feeThreshold
934
958
  };
935
959
  debugLog(
936
960
  account.address,
937
961
  "joining as guardian with preferences:",
938
- guardianPrefs
962
+ { ...guardianPrefs, feeThreshold: formatPaliAmount(feeThreshold) }
939
963
  );
940
964
  const guardTx = api2.tx.staking.guard(guardianPrefs);
941
965
  const hash = await signAndSend(guardTx, account);
@@ -967,8 +991,8 @@ var signAndSend = async (request, account, opts = DEFAULT_COMPUTE_PAYLOAD) => {
967
991
  `Transaction ${tx_result.txHash.toHex()} included in timepoint ${tx_result.blockNumber}-${tx_result.txIndex}`
968
992
  );
969
993
  return {
970
- blockNumber: _optionalChain([tx_result, 'optionalAccess', _57 => _57.blockNumber, 'optionalAccess', _58 => _58.toNumber, 'call', _59 => _59()]),
971
- index: _optionalChain([tx_result, 'optionalAccess', _60 => _60.txIndex]),
994
+ blockNumber: _optionalChain([tx_result, 'optionalAccess', _62 => _62.blockNumber, 'optionalAccess', _63 => _63.toNumber, 'call', _64 => _64()]),
995
+ index: _optionalChain([tx_result, 'optionalAccess', _65 => _65.txIndex]),
972
996
  hash: tx_result.txHash.toHex(),
973
997
  tx_result
974
998
  };
@@ -986,7 +1010,7 @@ var getGuardianAddress = async () => {
986
1010
  const api2 = await getApi();
987
1011
  if (!api2) throw new Error("API not initialized");
988
1012
  assert(
989
- _util.isFunction.call(void 0, _optionalChain([api2, 'access', _61 => _61.query, 'access', _62 => _62["guardian"], 'optionalAccess', _63 => _63["worker"]])),
1013
+ _util.isFunction.call(void 0, _optionalChain([api2, 'access', _66 => _66.query, 'access', _67 => _67["guardian"], 'optionalAccess', _68 => _68["worker"]])),
990
1014
  `api.query.guardian.worker does not exist`
991
1015
  );
992
1016
  const list = await getGuardianList();
@@ -1006,7 +1030,7 @@ var getGuardianNwParams = async () => {
1006
1030
  const section = "guardian";
1007
1031
  const method = "guardianNwParams";
1008
1032
  assert(
1009
- _util.isFunction.call(void 0, _optionalChain([rpc, 'access', _64 => _64[section], 'optionalAccess', _65 => _65[method]])),
1033
+ _util.isFunction.call(void 0, _optionalChain([rpc, 'access', _69 => _69[section], 'optionalAccess', _70 => _70[method]])),
1010
1034
  `api.rpc.${section}.guardianNwParams does not exist`
1011
1035
  );
1012
1036
  const guardianNwParams = await rpc[section][method]();
@@ -1127,7 +1151,7 @@ var MCryptFsWriter = class {
1127
1151
  request.signAndSend(this._account, { app_id: 1 }, (result) => {
1128
1152
  if (result.isInBlock || result.isFinalized || result.isError) {
1129
1153
  resolve({
1130
- blockNumber: _optionalChain([result, 'access', _66 => _66.blockNumber, 'optionalAccess', _67 => _67.toNumber, 'call', _68 => _68()]),
1154
+ blockNumber: _optionalChain([result, 'access', _71 => _71.blockNumber, 'optionalAccess', _72 => _72.toNumber, 'call', _73 => _73()]),
1131
1155
  index: result.txIndex
1132
1156
  });
1133
1157
  }
@@ -1237,18 +1261,29 @@ var FileFromMetadataRef = async (mcryptApi, metadataRef) => {
1237
1261
 
1238
1262
  // src/compute/agreement.ts
1239
1263
 
1240
- async function createAgreement() {
1264
+ async function createAgreement(contract, account) {
1241
1265
  const api2 = await getApi();
1242
1266
  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.default.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
- });
1267
+ const guardians = contract.guardians;
1268
+ const agreement = guardians.map((g) => _bs582.default.decode(g.peerid).subarray(6));
1269
+ const txContract = {
1270
+ ...contract,
1271
+ guardians: guardians.map((g) => g.address)
1272
+ };
1273
+ const tx = api2.tx.compute.agreement(txContract);
1274
+ const opts = {
1275
+ compute: {
1276
+ da_type: 1,
1277
+ agreement,
1278
+ verification: 0,
1279
+ compute: contract.contract_type === "Active" ? 1 : 0
1280
+ }
1281
+ };
1282
+ const { tx_result, blockNumber, index, hash } = await signAndSend(
1283
+ tx,
1284
+ account,
1285
+ opts
1286
+ );
1252
1287
  if (!tx_result.isError) {
1253
1288
  const agreementCreatedEvent = tx_result.events.find((event) => {
1254
1289
  return event.event.section === "compute" && event.event.method === "AgreementCreated";
@@ -1258,10 +1293,105 @@ async function createAgreement() {
1258
1293
  "Agreement data:",
1259
1294
  agreementCreatedEvent.event.data.toString()
1260
1295
  );
1296
+ return {
1297
+ blockNumber,
1298
+ index,
1299
+ hash,
1300
+ agreementId: _nullishCoalesce(_optionalChain([agreementCreatedEvent, 'access', _74 => _74.event, 'access', _75 => _75.data, 'access', _76 => _76[0], 'optionalAccess', _77 => _77.toHex, 'optionalCall', _78 => _78()]), () => ( agreementCreatedEvent.event.data.toString()))
1301
+ };
1261
1302
  } else {
1262
1303
  debugLog("AgreementCreated event not found");
1263
1304
  }
1264
1305
  }
1306
+ return { blockNumber, index, hash };
1307
+ }
1308
+ async function createSimpleAgreement() {
1309
+ const guardianIds = (await getGuardianAddress()).slice(0, 3);
1310
+ assert(guardianIds.length === 3, "Not enough guardians to create agreement");
1311
+ const contract = {
1312
+ contract_type: "Dormant",
1313
+ guardians: guardianIds,
1314
+ pre_check: null,
1315
+ compute: {
1316
+ cipher: "Plaintext",
1317
+ computer_indices: [0, 1, 2],
1318
+ fees: 0n,
1319
+ deadline: 0,
1320
+ confidentiality: { Trusted: { trust_index: 0 } },
1321
+ fee_function: null,
1322
+ input: null,
1323
+ program: { NativeData: "DaFalse" },
1324
+ metadata: null
1325
+ },
1326
+ post_check: null,
1327
+ result_cipher: "Plaintext"
1328
+ };
1329
+ const keyring2 = await getKeyring();
1330
+ const account = keyring2.getPairs()[0];
1331
+ return createAgreement(contract, account);
1332
+ }
1333
+
1334
+ // src/compute/data.ts
1335
+ async function dataContract(params) {
1336
+ const keyring2 = await getKeyring();
1337
+ const account = keyring2.getPairs()[0];
1338
+ const plaintextCipher = "Plaintext";
1339
+ const atomicFees = toAtomicPaliAmount(_nullishCoalesce(params.fees, () => ( "0")));
1340
+ const computeStep = {
1341
+ cipher: plaintextCipher,
1342
+ computer_indices: params.guardians.map((_, i) => i),
1343
+ fees: atomicFees,
1344
+ deadline: _nullishCoalesce(params.deadline, () => ( 0)),
1345
+ confidentiality: {
1346
+ Trusted: {
1347
+ trust_index: _nullishCoalesce(params.trustIndex, () => ( 0))
1348
+ }
1349
+ },
1350
+ fee_function: null,
1351
+ input: {
1352
+ Url: {
1353
+ url: Array.from(new TextEncoder().encode(params.url))
1354
+ }
1355
+ },
1356
+ program: {
1357
+ NativeData: "DaFalse"
1358
+ }
1359
+ };
1360
+ const contract = {
1361
+ contract_type: "Dormant",
1362
+ guardians: params.guardians,
1363
+ pre_check: null,
1364
+ compute: computeStep,
1365
+ post_check: null,
1366
+ result_cipher: plaintextCipher
1367
+ };
1368
+ return createAgreement(contract, account);
1369
+ }
1370
+
1371
+ // src/compute/inference.ts
1372
+ async function inferenceCompute(params) {
1373
+ const keyring2 = await getKeyring();
1374
+ const account = keyring2.getPairs()[0];
1375
+ const inputData = typeof params.input === "string" ? Array.from(new TextEncoder().encode(params.input)) : Array.from(params.input);
1376
+ const atomicFees = toAtomicPaliAmount(_nullishCoalesce(params.fees, () => ( "0")));
1377
+ const plaintextCipher = "Plaintext";
1378
+ const computeStep = {
1379
+ cipher: plaintextCipher,
1380
+ computer_indices: params.guardians.map((_, i) => i),
1381
+ fees: atomicFees,
1382
+ deadline: _nullishCoalesce(params.deadline, () => ( 0)),
1383
+ confidentiality: { Trusted: { trust_index: 0 } },
1384
+ fee_function: null,
1385
+ input: { Inline: { data: inputData } },
1386
+ program: { NativeExecute: "Inference" }
1387
+ };
1388
+ const contract = {
1389
+ contract_type: "Active",
1390
+ guardians: params.guardians,
1391
+ compute: computeStep,
1392
+ result_cipher: plaintextCipher
1393
+ };
1394
+ return createAgreement(contract, account);
1265
1395
  }
1266
1396
 
1267
1397
  // src/compute/participants.ts
@@ -1278,8 +1408,8 @@ async function getGuardianParticipants() {
1278
1408
  const _peerid = _bs582.default.decode((peerid || "").toString());
1279
1409
  const account = await api2.query.guardian.worker(_peerid.slice(0, 32));
1280
1410
  const nextIndex = currentIndex ? Number(currentIndex) + 1 : 1;
1281
- const guardiansList = _optionalChain([guardians, 'optionalAccess', _69 => _69.toJSON, 'call', _70 => _70()]) || [];
1282
- const nextGuardiansList = _optionalChain([nextGuardians, 'optionalAccess', _71 => _71.toJSON, 'call', _72 => _72()]) || [];
1411
+ const guardiansList = _optionalChain([guardians, 'optionalAccess', _79 => _79.toJSON, 'call', _80 => _80()]) || [];
1412
+ const nextGuardiansList = _optionalChain([nextGuardians, 'optionalAccess', _81 => _81.toJSON, 'call', _82 => _82()]) || [];
1283
1413
  const buildDetails = async (list) => {
1284
1414
  return Promise.all(
1285
1415
  list.map(async (guardian) => {
@@ -1288,21 +1418,21 @@ async function getGuardianParticipants() {
1288
1418
  const bonded = await api2.query.staking.bonded(guardian);
1289
1419
  const payee = await api2.query.staking.payee(guardian);
1290
1420
  const stakersOverview = await api2.query.staking.erasStakersOverview(
1291
- _optionalChain([currentEra, 'optionalAccess', _73 => _73.toPrimitive, 'call', _74 => _74()]),
1421
+ _optionalChain([currentEra, 'optionalAccess', _83 => _83.toPrimitive, 'call', _84 => _84()]),
1292
1422
  guardian
1293
1423
  );
1294
1424
  const guardianErasPrefs = await api2.query.staking.erasGuardianPrefs(
1295
- _optionalChain([currentEra, 'optionalAccess', _75 => _75.toPrimitive, 'call', _76 => _76()]),
1425
+ _optionalChain([currentEra, 'optionalAccess', _85 => _85.toPrimitive, 'call', _86 => _86()]),
1296
1426
  guardian
1297
1427
  );
1298
1428
  return {
1299
1429
  guardian,
1300
- rewardDestination: _optionalChain([payee, 'optionalAccess', _77 => _77.toHuman]) ? payee.toHuman() : null,
1301
- currentPreferences: _optionalChain([guardianErasPrefs, 'optionalAccess', _78 => _78.toHuman]) ? guardianErasPrefs.toHuman() : null,
1302
- upcomingPreferences: _optionalChain([guardianPrefs, 'optionalAccess', _79 => _79.toHuman]) ? guardianPrefs.toHuman() : null,
1303
- stash: _optionalChain([bonded, 'optionalAccess', _80 => _80.toHuman]) ? bonded.toHuman() : null,
1304
- currentStakeOverview: _optionalChain([stakersOverview, 'optionalAccess', _81 => _81.toHuman]) ? stakersOverview.toHuman() : null,
1305
- upcomingStakeOverview: _optionalChain([ledger, 'optionalAccess', _82 => _82.toHuman]) ? ledger.toHuman() : null
1430
+ rewardDestination: _optionalChain([payee, 'optionalAccess', _87 => _87.toHuman]) ? payee.toHuman() : null,
1431
+ currentPreferences: _optionalChain([guardianErasPrefs, 'optionalAccess', _88 => _88.toHuman]) ? guardianErasPrefs.toHuman() : null,
1432
+ upcomingPreferences: _optionalChain([guardianPrefs, 'optionalAccess', _89 => _89.toHuman]) ? guardianPrefs.toHuman() : null,
1433
+ stash: _optionalChain([bonded, 'optionalAccess', _90 => _90.toHuman]) ? bonded.toHuman() : null,
1434
+ currentStakeOverview: _optionalChain([stakersOverview, 'optionalAccess', _91 => _91.toHuman]) ? stakersOverview.toHuman() : null,
1435
+ upcomingStakeOverview: _optionalChain([ledger, 'optionalAccess', _92 => _92.toHuman]) ? ledger.toHuman() : null
1306
1436
  };
1307
1437
  })
1308
1438
  );
@@ -1311,12 +1441,12 @@ async function getGuardianParticipants() {
1311
1441
  const upcomingGuardians = await buildDetails(nextGuardiansList);
1312
1442
  return {
1313
1443
  nwState: {
1314
- localPeerId: _optionalChain([peerid, 'optionalAccess', _83 => _83.toString, 'call', _84 => _84()]),
1315
- worker: _optionalChain([account, 'optionalAccess', _85 => _85.toHuman]) ? account.toHuman() : null,
1316
- currentEra: _optionalChain([currentEra, 'optionalAccess', _86 => _86.toHuman]) ? currentEra.toHuman() : null,
1317
- guardians: JSON.stringify(_optionalChain([guardians, 'optionalAccess', _87 => _87.toHuman]) ? guardians.toHuman() : null, null, 2),
1318
- nextGuardians: JSON.stringify(_optionalChain([nextGuardians, 'optionalAccess', _88 => _88.toHuman]) ? nextGuardians.toHuman() : null, null, 2),
1319
- currentIndex: _optionalChain([currentIndex, 'optionalAccess', _89 => _89.toHuman]) ? currentIndex.toHuman() : null,
1444
+ localPeerId: _optionalChain([peerid, 'optionalAccess', _93 => _93.toString, 'call', _94 => _94()]),
1445
+ worker: _optionalChain([account, 'optionalAccess', _95 => _95.toHuman]) ? account.toHuman() : null,
1446
+ currentEra: _optionalChain([currentEra, 'optionalAccess', _96 => _96.toHuman]) ? currentEra.toHuman() : null,
1447
+ guardians: JSON.stringify(_optionalChain([guardians, 'optionalAccess', _97 => _97.toHuman]) ? guardians.toHuman() : null, null, 2),
1448
+ nextGuardians: JSON.stringify(_optionalChain([nextGuardians, 'optionalAccess', _98 => _98.toHuman]) ? nextGuardians.toHuman() : null, null, 2),
1449
+ currentIndex: _optionalChain([currentIndex, 'optionalAccess', _99 => _99.toHuman]) ? currentIndex.toHuman() : null,
1320
1450
  nextIndex
1321
1451
  },
1322
1452
  currentGuardians,
@@ -1327,6 +1457,46 @@ async function getGuardianParticipants() {
1327
1457
  }
1328
1458
  }
1329
1459
 
1460
+ // src/compute/simple.ts
1461
+ async function simpleCompute(params) {
1462
+ const keyring2 = await getKeyring();
1463
+ const account = keyring2.getPairs()[0];
1464
+ const plaintextCipher = "Plaintext";
1465
+ const atomicFees = toAtomicPaliAmount(_nullishCoalesce(params.fees, () => ( "0")));
1466
+ const computeStep = {
1467
+ cipher: plaintextCipher,
1468
+ computer_indices: params.guardians.map((_, i) => i),
1469
+ fees: atomicFees,
1470
+ deadline: _nullishCoalesce(params.deadline, () => ( 0)),
1471
+ confidentiality: {
1472
+ Trusted: {
1473
+ trust_index: _nullishCoalesce(params.trustIndex, () => ( 0))
1474
+ }
1475
+ },
1476
+ fee_function: null,
1477
+ input: {
1478
+ ChainTransaction: {
1479
+ block_number: params.inputBlockNumber,
1480
+ extrinsic_index: params.inputExtrinsicIndex
1481
+ }
1482
+ },
1483
+ program: {
1484
+ Url: {
1485
+ url: Array.from(new TextEncoder().encode(params.programUrl))
1486
+ }
1487
+ }
1488
+ };
1489
+ const contract = {
1490
+ contract_type: "Active",
1491
+ guardians: params.guardians,
1492
+ pre_check: null,
1493
+ compute: computeStep,
1494
+ post_check: null,
1495
+ result_cipher: plaintextCipher
1496
+ };
1497
+ return createAgreement(contract, account);
1498
+ }
1499
+
1330
1500
  // src/crypto/random.ts
1331
1501
  function generateRandomBytes(length = 32) {
1332
1502
  const bytes = new Uint8Array(length);
@@ -1349,6 +1519,7 @@ async function writeMetadata(account, name, description, ref, price, dataType, l
1349
1519
  const ownerBytes = Array.from(encoder.encode(l2Owner));
1350
1520
  const api2 = await getApi();
1351
1521
  assert(api2, "Failed to get API connection");
1522
+ debugLog(`Registering metadata for ${name} at ${formatPaliAmount(price)}`);
1352
1523
  const request = api2.tx.dataAvailability.daccRegisterData(
1353
1524
  nameBytes,
1354
1525
  descriptionBytes,
@@ -1362,6 +1533,82 @@ async function writeMetadata(account, name, description, ref, price, dataType, l
1362
1533
  debugLog(`Metadata registration transaction sent with hash: ${hash.hash}`);
1363
1534
  return hash;
1364
1535
  }
1536
+ async function registerDataAgreement(account, params) {
1537
+ debugLog(
1538
+ `Registering data agreement for DA ref ${params.ref.blockNumber}-${params.ref.index} at ${formatPaliAmount(params.fees)}`
1539
+ );
1540
+ const cipher = _nullishCoalesce(params.cipher, () => ( "Plaintext"));
1541
+ const resultCipher = _nullishCoalesce(params.resultCipher, () => ( "Plaintext"));
1542
+ const encoder = new TextEncoder();
1543
+ const computeMetadata = params.metadata ? {
1544
+ name: Array.from(encoder.encode(params.metadata.name)),
1545
+ description: Array.from(encoder.encode(params.metadata.description)),
1546
+ store_type: params.metadata.storeType,
1547
+ group_id: params.metadata.groupId
1548
+ } : null;
1549
+ const computeStep = {
1550
+ cipher,
1551
+ computer_indices: params.guardians.map((_, i) => i),
1552
+ fees: params.fees,
1553
+ deadline: _nullishCoalesce(params.deadline, () => ( 0)),
1554
+ confidentiality: {
1555
+ Trusted: {
1556
+ trust_index: _nullishCoalesce(params.trustIndex, () => ( 0))
1557
+ }
1558
+ },
1559
+ fee_function: null,
1560
+ input: {
1561
+ ChainTransaction: {
1562
+ block_number: params.ref.blockNumber,
1563
+ extrinsic_index: params.ref.index
1564
+ }
1565
+ },
1566
+ program: {
1567
+ NativeData: "DaFalse"
1568
+ },
1569
+ metadata: computeMetadata
1570
+ };
1571
+ const contract = {
1572
+ contract_type: "Dormant",
1573
+ guardians: params.guardians,
1574
+ pre_check: null,
1575
+ compute: computeStep,
1576
+ post_check: null,
1577
+ result_cipher: resultCipher
1578
+ };
1579
+ return createAgreement(contract, account);
1580
+ }
1581
+
1582
+ // src/da/runAgent.ts
1583
+ async function runAgent(account, agentRef, nonce, ciphertext, tdParams, pkBytes, tauParams, baseModel, publicKey, guardians, guardian, agreementId) {
1584
+ const agentRefTuple = [agentRef.blockNumber, agentRef.index];
1585
+ const baseModelTuple = [baseModel.blockNumber, baseModel.index];
1586
+ const api2 = await getApi();
1587
+ assert(api2, "Failed to get API connection");
1588
+ const request = api2.tx.dataAvailability.daccRunAgent(
1589
+ agentRefTuple,
1590
+ Array.from(nonce),
1591
+ Array.from(ciphertext),
1592
+ guardian ? Array.from(guardian) : null,
1593
+ Array.from(tdParams),
1594
+ Array.from(pkBytes),
1595
+ Array.from(tauParams),
1596
+ baseModelTuple,
1597
+ Array.from(publicKey),
1598
+ guardians.map((g) => Array.from(g))
1599
+ );
1600
+ const opts = {
1601
+ compute: {
1602
+ da_type: 4,
1603
+ verification: 0,
1604
+ compute: 1,
1605
+ agreement: [agreementId]
1606
+ }
1607
+ };
1608
+ const hash = await signAndSend(request, account, opts);
1609
+ debugLog(`Run agent transaction sent with hash: ${hash.hash}`);
1610
+ return hash;
1611
+ }
1365
1612
 
1366
1613
  // src/da/submit.ts
1367
1614
  async function submitData(account, data) {
@@ -1395,11 +1642,76 @@ async function submitTEData(account, data, chosenGuardians, tau_params, agg_key,
1395
1642
  debugLog(`TE data availability transaction sent with hash: ${hash.hash}`);
1396
1643
  return hash;
1397
1644
  }
1645
+ async function submitTEDataWithCipher(account, data, chosenGuardians, tau_params, agg_key, group_pk) {
1646
+ const { encoded: encryptedKey, ikm } = testCrypt(tau_params, agg_key);
1647
+ const shared_key = gen_stretched_key(hexToUint8Array(ikm));
1648
+ const encoder = new TextEncoder();
1649
+ const dataUint8Array = encoder.encode(data);
1650
+ const { ciphertext, nonce } = encrypt2(dataUint8Array, shared_key);
1651
+ const ciphertextHex = "0x" + Array.from(ciphertext).map((b) => b.toString(16).padStart(2, "0")).join("");
1652
+ const api2 = await getApi();
1653
+ assert(api2, "Failed to get API connection");
1654
+ const request = await api2.tx.dataAvailability.submitData(ciphertextHex);
1655
+ const ref = await signAndSend(request, account, DEFAULT_EMPTY_PAYLOAD);
1656
+ debugLog(`TE data availability transaction sent with hash: ${ref.hash}`);
1657
+ return {
1658
+ ref,
1659
+ cipher: {
1660
+ Encrypted: {
1661
+ threshold: {
1662
+ SilentThreshold: {
1663
+ td_params: Array.from(hexToUint8Array(encryptedKey)),
1664
+ pk_bytes: Array.from(hexToUint8Array(group_pk)),
1665
+ tau_params: Array.from(hexToUint8Array(tau_params))
1666
+ }
1667
+ },
1668
+ symmetric: {
1669
+ ChaCha20Poly1305: { nonce: Array.from(nonce) }
1670
+ }
1671
+ }
1672
+ }
1673
+ };
1674
+ }
1398
1675
 
1399
1676
  // src/da/upload.ts
1400
1677
  var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
1401
1678
  var _path = require('path'); var _path2 = _interopRequireDefault(_path);
1402
1679
  async function uploadData(options) {
1680
+ const { name, description, price, type, guardianGroupInfo, ref, filePath } = options;
1681
+ assert(
1682
+ guardianGroupInfo.guardians && guardianGroupInfo.tauParams && guardianGroupInfo.aggKey && guardianGroupInfo.groupPk,
1683
+ "Guardian group info is missing required properties"
1684
+ );
1685
+ console.log("Guardian group info:", guardianGroupInfo);
1686
+ const account = (await getKeyring()).pairs[0];
1687
+ const atomicPrice = toAtomicPaliAmount(price);
1688
+ if (filePath) {
1689
+ throw new Error("uploadData: file path upload is not implemented");
1690
+ } else {
1691
+ const storeType = type === "model" ? "Model" : type === "agent" ? "Agent" : "Dataset";
1692
+ const { ref: dataRef, cipher } = await submitTEDataWithCipher(
1693
+ account,
1694
+ ref || "",
1695
+ guardianGroupInfo.guardians,
1696
+ guardianGroupInfo.tauParams,
1697
+ guardianGroupInfo.aggKey,
1698
+ guardianGroupInfo.groupPk
1699
+ );
1700
+ await registerDataAgreement(account, {
1701
+ ref: dataRef,
1702
+ guardians: guardianGroupInfo.guardians,
1703
+ fees: atomicPrice,
1704
+ cipher,
1705
+ metadata: {
1706
+ name,
1707
+ description,
1708
+ storeType,
1709
+ groupId: guardianGroupInfo.groupId
1710
+ }
1711
+ });
1712
+ }
1713
+ }
1714
+ async function uploadDataLegacy(options) {
1403
1715
  const { name, description, price, type, guardianGroupInfo, ref, filePath } = options;
1404
1716
  assert(
1405
1717
  guardianGroupInfo.guardians && guardianGroupInfo.tauParams && guardianGroupInfo.aggKey && guardianGroupInfo.groupPk,
@@ -1407,6 +1719,7 @@ async function uploadData(options) {
1407
1719
  );
1408
1720
  const account = (await getKeyring()).pairs[0];
1409
1721
  const ethAddress = "";
1722
+ const atomicPrice = toAtomicPaliAmount(price);
1410
1723
  if (type === "dataset" && filePath) {
1411
1724
  const fileContent = _fs2.default.readFileSync(filePath);
1412
1725
  const selectedFile = new File([fileContent], _path2.default.basename(filePath), {
@@ -1419,7 +1732,7 @@ async function uploadData(options) {
1419
1732
  fileName: selectedFile.name,
1420
1733
  filePath: "",
1421
1734
  description,
1422
- baseCost: BigInt(Number(price) * 10 ** 18),
1735
+ baseCost: atomicPrice,
1423
1736
  ownerL2Address: ethAddress,
1424
1737
  guardianInfo: guardianGroupInfo
1425
1738
  },
@@ -1452,12 +1765,12 @@ async function uploadData(options) {
1452
1765
  }
1453
1766
 
1454
1767
  // src/stake/add.ts
1455
- async function addStake(account, amount) {
1768
+ async function addStake(account, amountBaseUnits) {
1456
1769
  const api2 = await getApi();
1457
1770
  assert(api2, "API not initialized");
1458
1771
  assert(account, "Account not initialized");
1459
- debugLog("Using account:", account.address);
1460
- const stakeTx = api2.tx.staking.bondExtra(amount);
1772
+ debugLog("Using account:", account.address, "adding:", formatPaliAmount(amountBaseUnits));
1773
+ const stakeTx = api2.tx.staking.bondExtra(amountBaseUnits);
1461
1774
  const hash = await signAndSend(stakeTx, account);
1462
1775
  debugLog(`Stake transaction sent with hash: ${hash.hash}`);
1463
1776
  }
@@ -1473,14 +1786,14 @@ async function joinIdleStaker(account) {
1473
1786
  }
1474
1787
 
1475
1788
  // src/stake/new.ts
1476
- async function newStake(account, amount, rewardDestination = "Staked") {
1789
+ async function newStake(account, amountBaseUnits, rewardDestination = "Staked") {
1477
1790
  const api2 = await getApi();
1478
1791
  assert(api2, "API not initialized");
1479
1792
  assert(account, "Account not initialized");
1480
1793
  debugLog(
1481
- `Staking amount: ${amount} for account: ${account.address} with reward destination: ${rewardDestination}`
1794
+ `Staking amount: ${formatPaliAmount(amountBaseUnits)} for account: ${account.address} with reward destination: ${rewardDestination}`
1482
1795
  );
1483
- const stakeTx = api2.tx.staking.bond(amount, rewardDestination);
1796
+ const stakeTx = api2.tx.staking.bond(amountBaseUnits, rewardDestination);
1484
1797
  const hash = await signAndSend(stakeTx, account);
1485
1798
  debugLog(`Stake transaction sent with hash: ${hash.hash}`);
1486
1799
  }
@@ -1502,12 +1815,12 @@ async function payoutStake(account, eras, address) {
1502
1815
  }
1503
1816
 
1504
1817
  // src/stake/reduce.ts
1505
- async function reduceStake(account, amount) {
1818
+ async function reduceStake(account, amountBaseUnits) {
1506
1819
  const api2 = await getApi();
1507
1820
  assert(api2, "API not initialized");
1508
1821
  assert(account, "Account not initialized");
1509
- debugLog("Using account:", account.address);
1510
- const unstakeTx = api2.tx.staking.unbond(amount);
1822
+ debugLog("Using account:", account.address, "reducing:", formatPaliAmount(amountBaseUnits));
1823
+ const unstakeTx = api2.tx.staking.unbond(amountBaseUnits);
1511
1824
  const hash = await signAndSend(unstakeTx, account);
1512
1825
  debugLog(`Unstake transaction sent with hash: ${hash.hash}`);
1513
1826
  }
@@ -1517,9 +1830,9 @@ async function removeStake(account) {
1517
1830
  const api2 = await getApi();
1518
1831
  assert(api2, "API not initialized");
1519
1832
  assert(account, "Account not initialized");
1520
- const stakeAmount = await _asyncOptionalChain([(await api2.query.staking.ledger(account.address)), 'optionalAccess', async _90 => _90.toPrimitive, 'call', async _91 => _91()]);
1521
- debugLog("Removing entire stake amount:", _optionalChain([stakeAmount, 'optionalAccess', _92 => _92.active]) || 0n);
1522
- const unstakeTx = api2.tx.staking.unbond(_optionalChain([stakeAmount, 'optionalAccess', _93 => _93.active]) || 0n);
1833
+ const stakeAmount = await _asyncOptionalChain([(await api2.query.staking.ledger(account.address)), 'optionalAccess', async _100 => _100.toPrimitive, 'call', async _101 => _101()]);
1834
+ debugLog("Removing entire stake amount:", formatPaliAmount(_optionalChain([stakeAmount, 'optionalAccess', _102 => _102.active]) || 0n));
1835
+ const unstakeTx = api2.tx.staking.unbond(_optionalChain([stakeAmount, 'optionalAccess', _103 => _103.active]) || 0n);
1523
1836
  const hash = await signAndSend(unstakeTx, account);
1524
1837
  debugLog(`Unstake transaction sent with hash: ${hash.hash}`);
1525
1838
  }
@@ -1535,25 +1848,25 @@ async function withdrawStake(account) {
1535
1848
  }
1536
1849
 
1537
1850
  // src/token/fund.ts
1538
- async function fundAccount(account, amount, address) {
1851
+ async function fundAccount(account, amountBaseUnits, address) {
1539
1852
  const addr = address ? address : account.address;
1540
1853
  const keyring2 = await getKeyring();
1541
1854
  const api2 = await getApi();
1542
1855
  assert(api2, "API not initialized");
1543
1856
  debugLog(`
1544
- Funding account: ${addr} with amount: ${amount}`);
1545
- const tx = api2.tx.balances.transferKeepAlive(addr, amount);
1857
+ Funding account: ${addr} with amount: ${formatPaliAmount(amountBaseUnits)}`);
1858
+ const tx = api2.tx.balances.transferKeepAlive(addr, amountBaseUnits);
1546
1859
  const hash = await signAndSend(tx, keyring2.getPairs()[0]);
1547
1860
  debugLog(`Fund transaction sent with hash: ${hash.hash}`);
1548
1861
  }
1549
1862
 
1550
1863
  // src/token/transfer.ts
1551
- async function transfer(account, amount, address) {
1864
+ async function transfer(account, amountBaseUnits, address) {
1552
1865
  const api2 = await getApi();
1553
1866
  assert(api2, "API not initialized");
1554
1867
  debugLog(`
1555
- Transferring funds to account: ${address} with amount: ${amount}`);
1556
- const tx = api2.tx.balances.transferKeepAlive(address, amount);
1868
+ Transferring funds to account: ${address} with amount: ${formatPaliAmount(amountBaseUnits)}`);
1869
+ const tx = api2.tx.balances.transferKeepAlive(address, amountBaseUnits);
1557
1870
  const hash = await signAndSend(tx, account);
1558
1871
  debugLog(`Transfer transaction sent with hash: ${hash.hash}`);
1559
1872
  }
@@ -1588,7 +1901,7 @@ async function rotateAndSetKeys(account) {
1588
1901
  _assert2.default.call(void 0, api2, "API not initialized");
1589
1902
  debugLog(`Rotating session keys for ${account.meta.name} on ${provider.endpoint}`);
1590
1903
  const newKeys = await api2.rpc.author.rotateKeys();
1591
- debugLog(`${account.meta.name} rotated keys on ${provider.endpoint}:`, _nullishCoalesce(_optionalChain([newKeys, 'optionalAccess', _94 => _94.toHex, 'optionalCall', _95 => _95()]), () => ( newKeys)));
1904
+ debugLog(`${account.meta.name} rotated keys on ${provider.endpoint}:`, _nullishCoalesce(_optionalChain([newKeys, 'optionalAccess', _104 => _104.toHex, 'optionalCall', _105 => _105()]), () => ( newKeys)));
1592
1905
  const setKeysTx = api2.tx.session.setKeys(newKeys, []);
1593
1906
  const hash = await signAndSend(setKeysTx, account);
1594
1907
  debugLog(`Rotate session transaction sent with hash: ${hash.hash}`);
@@ -1683,5 +1996,16 @@ async function setWorker(account) {
1683
1996
 
1684
1997
 
1685
1998
 
1686
- exports.API_EXTENSIONS = API_EXTENSIONS; exports.API_RPC = API_RPC; exports.API_TYPES = API_TYPES; exports.AccountSourceType = AccountSourceType; exports.ApiPromise = _api2.ApiPromise; exports.CryptoType = CryptoType; exports.DEBUG = DEBUG; exports.DEFAULT_COMPUTE_PAYLOAD = DEFAULT_COMPUTE_PAYLOAD; exports.DEFAULT_EMPTY_PAYLOAD = DEFAULT_EMPTY_PAYLOAD; exports.FileFromMetadataRef = FileFromMetadataRef; exports.HttpProvider = _api2.HttpProvider; exports.MCryptFs = MCryptFs; exports.MCryptFsReader = MCryptFsReader; exports.MCryptFsWriter = MCryptFsWriter; exports.PALLIORA_RPC_URL = PALLIORA_RPC_URL; exports.PALLIORA_WS = PALLIORA_WS; exports.RpcApi = RpcApi; exports.TX_WAIT_FINALIZATION = TX_WAIT_FINALIZATION; exports.WsProvider = _api2.WsProvider; exports.addStake = addStake; exports.base64ToUint8Array = base64ToUint8Array; exports.clearTokenCache = clearTokenCache; exports.configure = configure; exports.createAccount = createAccount; exports.createAgreement = createAgreement; exports.createGuardianGroup = createGuardianGroup; exports.debugLog = debugLog; exports.decodeAggregateKey = decodeAggregateKey; exports.decodeField = decodeField; exports.decodePowersOfTau = decodePowersOfTau; exports.decrypt = decrypt; exports.ecncryptTest = encrypt; exports.encodeCiphertext = encodeCiphertext; exports.encrypt = encrypt2; exports.fetchTokenProperties = fetchTokenProperties; exports.formatBalanceWithTokenProperties = formatBalanceWithTokenProperties; exports.fundAccount = fundAccount; exports.gen_shared_key = gen_shared_key; exports.gen_stretched_key = gen_stretched_key; exports.generateRandomBytes = generateRandomBytes; exports.getApi = getApi; exports.getCachedTokenProperties = getCachedTokenProperties; exports.getEncKeyring = getEncKeyring; exports.getFileMetadataCall = getFileMetadataCall; exports.getGuardianAddress = getGuardianAddress; exports.getGuardianList = getGuardianList; exports.getGuardianNwParams = getGuardianNwParams; exports.getGuardianParticipants = getGuardianParticipants; exports.getKeyring = getKeyring; exports.getRpcApi = getRpcApi; exports.hexToUint8Array = hexToUint8Array; exports.joinGuardian = joinGuardian; exports.joinIdleStaker = joinIdleStaker; exports.joinValidator = joinValidator; exports.newStake = newStake; exports.pairFromPrivateKeyHex = pairFromPrivateKeyHex; exports.payoutStake = payoutStake; exports.provider = provider; exports.reduceStake = reduceStake; exports.removeStake = removeStake; exports.rotateAndSetKeys = rotateAndSetKeys; exports.setIdentity = setIdentity; exports.setWorker = setWorker; exports.signAndSend = signAndSend; exports.submitData = submitData; exports.submitTEData = submitTEData; exports.testCrypt = testCrypt; exports.tokenToBigint = tokenToBigint; exports.transfer = transfer; exports.uint8ArrayToBase64 = uint8ArrayToBase64; exports.uploadData = uploadData; exports.utilCrypto = utilCrypto; exports.wasmCrypto = wasmCrypto; exports.withdrawStake = withdrawStake; exports.writeMetadata = writeMetadata;
1999
+
2000
+
2001
+
2002
+
2003
+
2004
+
2005
+
2006
+
2007
+
2008
+
2009
+
2010
+ exports.API_EXTENSIONS = API_EXTENSIONS; exports.API_RPC = API_RPC; exports.API_TYPES = API_TYPES; exports.AccountSourceType = AccountSourceType; exports.ApiPromise = _api2.ApiPromise; exports.CryptoType = CryptoType; exports.DEBUG = DEBUG; exports.DEFAULT_COMPUTE_PAYLOAD = DEFAULT_COMPUTE_PAYLOAD; exports.DEFAULT_EMPTY_PAYLOAD = DEFAULT_EMPTY_PAYLOAD; exports.FileFromMetadataRef = FileFromMetadataRef; exports.HttpProvider = _api2.HttpProvider; exports.MCryptFs = MCryptFs; exports.MCryptFsReader = MCryptFsReader; exports.MCryptFsWriter = MCryptFsWriter; exports.PALI_DECIMALS = PALI_DECIMALS; exports.PALI_SYMBOL = PALI_SYMBOL; exports.PALLIORA_RPC_URL = PALLIORA_RPC_URL; exports.PALLIORA_WS = PALLIORA_WS; exports.TX_WAIT_FINALIZATION = TX_WAIT_FINALIZATION; exports.WsProvider = _api2.WsProvider; exports.addStake = addStake; exports.base64ToUint8Array = base64ToUint8Array; exports.clearTokenCache = clearTokenCache; exports.configure = configure; exports.createAccount = createAccount; exports.createAgreement = createAgreement; exports.createGuardianGroup = createGuardianGroup; exports.createSimpleAgreement = createSimpleAgreement; exports.dataContract = dataContract; exports.debugLog = debugLog; exports.decodeAggregateKey = decodeAggregateKey; exports.decodeField = decodeField; exports.decodePowersOfTau = decodePowersOfTau; exports.decrypt = decrypt; exports.ecncryptTest = encrypt; exports.encodeCiphertext = encodeCiphertext; exports.encrypt = encrypt2; exports.fetchTokenProperties = fetchTokenProperties; exports.formatBalanceWithTokenProperties = formatBalanceWithTokenProperties; exports.formatPaliAmount = formatPaliAmount; exports.fromAtomicPaliAmount = fromAtomicPaliAmount; exports.fundAccount = fundAccount; exports.gen_shared_key = gen_shared_key; exports.gen_stretched_key = gen_stretched_key; exports.generateRandomBytes = generateRandomBytes; exports.getApi = getApi; exports.getCachedTokenProperties = getCachedTokenProperties; exports.getEncKeyring = getEncKeyring; exports.getFileMetadataCall = getFileMetadataCall; exports.getGuardianAddress = getGuardianAddress; exports.getGuardianList = getGuardianList; exports.getGuardianNwParams = getGuardianNwParams; exports.getGuardianParticipants = getGuardianParticipants; exports.getKeyring = getKeyring; exports.hexToUint8Array = hexToUint8Array; exports.inferenceCompute = inferenceCompute; exports.joinGuardian = joinGuardian; exports.joinIdleStaker = joinIdleStaker; exports.joinValidator = joinValidator; exports.newStake = newStake; exports.pairFromPrivateKeyHex = pairFromPrivateKeyHex; exports.payoutStake = payoutStake; exports.provider = provider; exports.reduceStake = reduceStake; exports.registerDataAgreement = registerDataAgreement; exports.removeStake = removeStake; exports.rotateAndSetKeys = rotateAndSetKeys; exports.runAgent = runAgent; exports.setIdentity = setIdentity; exports.setWorker = setWorker; exports.signAndSend = signAndSend; exports.simpleCompute = simpleCompute; exports.submitData = submitData; exports.submitTEData = submitTEData; exports.submitTEDataWithCipher = submitTEDataWithCipher; exports.testCrypt = testCrypt; exports.toAtomicPaliAmount = toAtomicPaliAmount; exports.tokenToBigint = tokenToBigint; exports.transfer = transfer; exports.uint8ArrayToBase64 = uint8ArrayToBase64; exports.uploadData = uploadData; exports.uploadDataLegacy = uploadDataLegacy; exports.utilCrypto = utilCrypto; exports.wasmCrypto = wasmCrypto; exports.withdrawStake = withdrawStake; exports.writeMetadata = writeMetadata;
1687
2011
  //# sourceMappingURL=index.cjs.map