@palliora.org/chainsdk 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +754 -238
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +658 -193
- package/dist/index.d.ts +658 -193
- package/dist/index.js +725 -209
- package/dist/index.js.map +1 -1
- package/package.json +12 -8
package/dist/index.cjs
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: {
|
|
@@ -398,7 +568,7 @@ var isValidHex = (hex) => {
|
|
|
398
568
|
return /^[0-9A-Fa-f]*$/.test(hex) && hex.length % 2 === 0;
|
|
399
569
|
};
|
|
400
570
|
var decodeAggregateKey = (input) => {
|
|
401
|
-
const buffer = new Uint8Array(_optionalChain([input, 'access',
|
|
571
|
+
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
572
|
let offset = 0;
|
|
403
573
|
const view = new DataView(buffer.buffer);
|
|
404
574
|
const readBigUInt64LE = () => {
|
|
@@ -472,16 +642,16 @@ var decodeAggregateKey = (input) => {
|
|
|
472
642
|
var encodeCiphertext = (input) => {
|
|
473
643
|
const writeProjPointTypeFp = (point) => {
|
|
474
644
|
const hex = point.toHex(true);
|
|
475
|
-
return new Uint8Array(_optionalChain([hex, 'access',
|
|
645
|
+
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
646
|
};
|
|
477
647
|
const writeProjPointTypeFp2 = (point) => {
|
|
478
648
|
const hex = point.toHex(true);
|
|
479
|
-
return new Uint8Array(_optionalChain([hex, 'access',
|
|
649
|
+
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
650
|
};
|
|
481
651
|
const gamma_g2Buffer = writeProjPointTypeFp2(input.gamma_g2);
|
|
482
652
|
const sa1Buffer = new Uint8Array(input.sa1.flatMap((p) => Array.from(writeProjPointTypeFp(p))));
|
|
483
653
|
const sa2Buffer = new Uint8Array(input.sa2.flatMap((p) => Array.from(writeProjPointTypeFp2(p))));
|
|
484
|
-
const enc_keyBuffer = new Uint8Array(_optionalChain([fp12ToHex, 'call',
|
|
654
|
+
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
655
|
const tBuffer = new Uint8Array(8);
|
|
486
656
|
new DataView(tBuffer.buffer).setBigUint64(0, BigInt(input.t), true);
|
|
487
657
|
const totalLength = gamma_g2Buffer.length + sa1Buffer.length + sa2Buffer.length + enc_keyBuffer.length + tBuffer.length;
|
|
@@ -538,7 +708,7 @@ function bigintToBigEndianHex(value, length) {
|
|
|
538
708
|
throw new Error("BigInt value is too large to fit in the specified length");
|
|
539
709
|
}
|
|
540
710
|
hex = hex.padStart(length * 2, "0");
|
|
541
|
-
const byteArray = _optionalChain([hex, 'access',
|
|
711
|
+
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
712
|
const reversedByteArray = byteArray.reverse();
|
|
543
713
|
const bigEndianHex = reversedByteArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
544
714
|
return bigEndianHex;
|
|
@@ -547,7 +717,7 @@ function reverseEndianess(hex) {
|
|
|
547
717
|
if (hex.length % 2 !== 0) {
|
|
548
718
|
throw new Error("Hex string must have an even length");
|
|
549
719
|
}
|
|
550
|
-
return _optionalChain([hex, 'access',
|
|
720
|
+
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
721
|
}
|
|
552
722
|
|
|
553
723
|
// src/crypto/cipher.ts
|
|
@@ -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,23 +819,37 @@ var debugLog = (message, ...optionalParams) => {
|
|
|
653
819
|
};
|
|
654
820
|
|
|
655
821
|
// src/utils/token.ts
|
|
656
|
-
|
|
822
|
+
var _viem = require('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 _viem.parseUnits.call(void 0, normalizedAmount, PALI_DECIMALS);
|
|
832
|
+
};
|
|
833
|
+
var fromAtomicPaliAmount = (amount) => {
|
|
834
|
+
return _viem.formatUnits.call(void 0, 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;
|
|
661
842
|
}
|
|
662
843
|
try {
|
|
663
|
-
const systemProperties = await _asyncOptionalChain([(await await _asyncOptionalChain([(await getApi()), 'optionalAccess', async
|
|
844
|
+
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
845
|
assert(systemProperties, "Failed to fetch system properties from RPC");
|
|
665
846
|
const tokenProperties = {
|
|
666
|
-
symbol: (_optionalChain([systemProperties, 'optionalAccess',
|
|
667
|
-
decimals: Number((_optionalChain([systemProperties, 'optionalAccess',
|
|
847
|
+
symbol: (_optionalChain([systemProperties, 'optionalAccess', _35 => _35.tokenSymbol]) || [PALI_SYMBOL])[0],
|
|
848
|
+
decimals: Number((_optionalChain([systemProperties, 'optionalAccess', _36 => _36.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,17 +861,9 @@ function clearTokenCache() {
|
|
|
681
861
|
}
|
|
682
862
|
async function formatBalanceWithTokenProperties(balance) {
|
|
683
863
|
const tokenProperties = await fetchTokenProperties();
|
|
684
|
-
|
|
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
|
-
});
|
|
864
|
+
return `${_viem.formatUnits.call(void 0, 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
869
|
|
|
@@ -702,128 +874,13 @@ var provider = new (0, _api2.WsProvider)(PALLIORA_WS, 1e4);
|
|
|
702
874
|
|
|
703
875
|
// src/chain/singleton.ts
|
|
704
876
|
|
|
705
|
-
var wsProvider = null;
|
|
706
877
|
var api = null;
|
|
707
878
|
var keyring = null;
|
|
708
879
|
var encKeyring = null;
|
|
709
|
-
var
|
|
710
|
-
|
|
711
|
-
|
|
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() {
|
|
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 _api2.ApiPromise.create({
|
|
829
886
|
provider,
|
|
@@ -833,15 +890,25 @@ async function getApi() {
|
|
|
833
890
|
});
|
|
834
891
|
}
|
|
835
892
|
const isNode = typeof process !== "undefined" && typeof process.exit === "function";
|
|
836
|
-
const isTest = typeof process !== "undefined" && _optionalChain([process, 'access',
|
|
837
|
-
if (isNode && !isTest) {
|
|
893
|
+
const isTest = typeof process !== "undefined" && _optionalChain([process, 'access', _37 => _37.env, 'optionalAccess', _38 => _38.NODE_ENV]) === "test";
|
|
894
|
+
if (isNode && !isTest && api && !apiListenersAttached) {
|
|
895
|
+
apiListenersAttached = true;
|
|
838
896
|
api.on("error", (err) => {
|
|
839
|
-
|
|
840
|
-
|
|
897
|
+
if (apiTeardownInProgress) return;
|
|
898
|
+
apiTeardownInProgress = true;
|
|
899
|
+
apiListenersAttached = false;
|
|
900
|
+
const currentApi = api;
|
|
901
|
+
api = null;
|
|
902
|
+
void _optionalChain([currentApi, 'optionalAccess', _39 => _39.disconnect, 'call', _40 => _40(), 'access', _41 => _41.catch, 'call', _42 => _42((disconnectErr) => {
|
|
903
|
+
apiTeardownInProgress = false;
|
|
904
|
+
console.error("api disconnect after error failed:", disconnectErr);
|
|
905
|
+
})]);
|
|
841
906
|
});
|
|
842
907
|
api.on("disconnected", () => {
|
|
843
|
-
|
|
844
|
-
|
|
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
|
|
|
@@ -883,7 +943,7 @@ var getGuardianList = async () => {
|
|
|
883
943
|
const section = "guardian";
|
|
884
944
|
const method = "guardianList";
|
|
885
945
|
assert(
|
|
886
|
-
_util.isFunction.call(void 0, _optionalChain([rpc, 'access',
|
|
946
|
+
_util.isFunction.call(void 0, _optionalChain([rpc, 'access', _43 => _43[section], 'optionalAccess', _44 => _44[method]])),
|
|
887
947
|
`api.rpc.${section}.${method} does not exist`
|
|
888
948
|
);
|
|
889
949
|
const list = (await rpc[section]["guardianList"]()).map((item) => [item.toString()]).flat(1);
|
|
@@ -907,35 +967,74 @@ 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 = (_nullishCoalesce(_optionalChain([creationResult, 'optionalAccess', _45 => _45.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 _optionalChain([ext2, 'optionalAccess', _46 => _46.method, 'optionalAccess', _47 => _47.section, 'optionalAccess', _48 => _48.toLowerCase, 'call', _49 => _49()]) === "dataavailability" && _optionalChain([ext2, 'optionalAccess', _50 => _50.method, 'optionalAccess', _51 => _51.method, 'optionalAccess', _52 => _52.toLowerCase, 'call', _53 => _53()]) === "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) {
|
|
918
1015
|
const api2 = await getApi();
|
|
919
1016
|
assert(api2, "API not initialized");
|
|
920
1017
|
assert(account, "Account not initialized");
|
|
921
|
-
const computeOpts = _optionalChain([prefs, 'access',
|
|
1018
|
+
const computeOpts = _optionalChain([prefs, 'access', _54 => _54.compute, 'optionalAccess', _55 => _55.split, 'call', _56 => _56(","), 'access', _57 => _57.map, 'call', _58 => _58((s) => s.trim()), 'access', _59 => _59.filter, 'call', _60 => _60((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,
|
|
925
1023
|
verifier: prefs.verifier,
|
|
926
1024
|
compute: prefs.compute ? true : false,
|
|
927
1025
|
computePrefs: {
|
|
928
|
-
trusted: _optionalChain([computeOpts, 'optionalAccess',
|
|
929
|
-
tee: _optionalChain([computeOpts, 'optionalAccess',
|
|
930
|
-
mpc: _optionalChain([computeOpts, 'optionalAccess',
|
|
931
|
-
fhe: _optionalChain([computeOpts, 'optionalAccess',
|
|
932
|
-
zkp: _optionalChain([computeOpts, 'optionalAccess',
|
|
933
|
-
}
|
|
1026
|
+
trusted: _optionalChain([computeOpts, 'optionalAccess', _61 => _61.includes, 'call', _62 => _62("trusted")]) || false,
|
|
1027
|
+
tee: _optionalChain([computeOpts, 'optionalAccess', _63 => _63.includes, 'call', _64 => _64("tee")]) || false,
|
|
1028
|
+
mpc: _optionalChain([computeOpts, 'optionalAccess', _65 => _65.includes, 'call', _66 => _66("mpc")]) || false,
|
|
1029
|
+
fhe: _optionalChain([computeOpts, 'optionalAccess', _67 => _67.includes, 'call', _68 => _68("fhe")]) || false,
|
|
1030
|
+
zkp: _optionalChain([computeOpts, 'optionalAccess', _69 => _69.includes, 'call', _70 => _70("zkp")]) || false
|
|
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.
|
|
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: _optionalChain([tx_result, '
|
|
971
|
-
index:
|
|
1069
|
+
blockNumber: _nullishCoalesce(_optionalChain([tx_result, 'access', _71 => _71.blockNumber, 'optionalAccess', _72 => _72.toNumber, 'call', _73 => _73()]), () => ( 0)),
|
|
1070
|
+
index: _nullishCoalesce(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
|
-
_util.isFunction.call(void 0, _optionalChain([api2, 'access',
|
|
990
|
-
`api.query.guardian.
|
|
1088
|
+
_util.isFunction.call(void 0, _optionalChain([api2, 'access', _74 => _74.query, 'access', _75 => _75["guardian"], 'optionalAccess', _76 => _76["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 = _bs582.default.decode(item).slice(
|
|
996
|
-
return (await api2.query["guardian"]["
|
|
1094
|
+
const peerid = _bs582.default.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] }));
|
|
@@ -1006,7 +1105,7 @@ var getGuardianNwParams = async () => {
|
|
|
1006
1105
|
const section = "guardian";
|
|
1007
1106
|
const method = "guardianNwParams";
|
|
1008
1107
|
assert(
|
|
1009
|
-
_util.isFunction.call(void 0, _optionalChain([rpc, 'access',
|
|
1108
|
+
_util.isFunction.call(void 0, _optionalChain([rpc, 'access', _77 => _77[section], 'optionalAccess', _78 => _78[method]])),
|
|
1010
1109
|
`api.rpc.${section}.guardianNwParams does not exist`
|
|
1011
1110
|
);
|
|
1012
1111
|
const guardianNwParams = await rpc[section][method]();
|
|
@@ -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
|
+
_optionalChain([unsubFn, 'optionalCall', _79 => _79()]);
|
|
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 = _optionalChain([decoded, 'optionalAccess', _80 => _80.method]);
|
|
1208
|
+
if (String(_nullishCoalesce(_optionalChain([method, 'optionalAccess', _81 => _81.section]), () => ( ""))).toLowerCase() === "compute" && String(_nullishCoalesce(_optionalChain([method, 'optionalAccess', _82 => _82.method]), () => ( ""))).toLowerCase() === "result") {
|
|
1209
|
+
const args = _optionalChain([method, 'optionalAccess', _83 => _83.args]);
|
|
1210
|
+
const onChainId = String(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([args, 'optionalAccess', _84 => _84.request_id]), () => ( _optionalChain([args, 'optionalAccess', _85 => _85.requestId]))), () => ( _optionalChain([args, 'optionalAccess', _86 => _86[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(_nullishCoalesce(event.section, () => ( ""))).toLowerCase() !== "compute" || String(_nullishCoalesce(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 = _nullishCoalesce(_nullishCoalesce(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: _optionalChain([result, 'access',
|
|
1131
|
-
index: result.txIndex
|
|
1370
|
+
blockNumber: _nullishCoalesce(_optionalChain([result, 'access', _87 => _87.blockNumber, 'optionalAccess', _88 => _88.toNumber, 'call', _89 => _89()]), () => ( 0)),
|
|
1371
|
+
index: _nullishCoalesce(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.
|
|
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
|
+
_nullishCoalesce(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,32 +1479,121 @@ var FileFromMetadataRef = async (mcryptApi, metadataRef) => {
|
|
|
1236
1479
|
};
|
|
1237
1480
|
|
|
1238
1481
|
// src/compute/agreement.ts
|
|
1239
|
-
|
|
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
|
|
1244
|
-
const
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
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(
|
|
1254
|
-
|
|
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
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1505
|
+
debugLog("Agreement data:", agreementCreatedEvent.event.data.toString());
|
|
1506
|
+
return {
|
|
1507
|
+
blockNumber,
|
|
1508
|
+
index: _nullishCoalesce(index, () => ( 0)),
|
|
1509
|
+
hash,
|
|
1510
|
+
agreementId: _nullishCoalesce(_optionalChain([agreementCreatedEvent, 'access', _90 => _90.event, 'access', _91 => _91.data, 'access', _92 => _92[0], 'optionalAccess', _93 => _93.toHex, 'optionalCall', _94 => _94()]), () => ( agreementCreatedEvent.event.data.toString()))
|
|
1511
|
+
};
|
|
1261
1512
|
} else {
|
|
1262
1513
|
debugLog("AgreementCreated event not found");
|
|
1263
1514
|
}
|
|
1264
1515
|
}
|
|
1516
|
+
return { blockNumber, index: _nullishCoalesce(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(_nullishCoalesce(params.fees, () => ( "0")));
|
|
1548
|
+
const computeStep = {
|
|
1549
|
+
cipher: plaintextCipher,
|
|
1550
|
+
computer_indices: params.guardians.map((_, i) => i),
|
|
1551
|
+
fees: atomicFees,
|
|
1552
|
+
deadline: _nullishCoalesce(params.deadline, () => ( 0)),
|
|
1553
|
+
confidentiality: { Trusted: _nullishCoalesce(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(_nullishCoalesce(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: _nullishCoalesce(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
|
|
@@ -1276,10 +1608,10 @@ async function getGuardianParticipants() {
|
|
|
1276
1608
|
const currentIndex = await api2.query.guardian.currentIndex();
|
|
1277
1609
|
const peerid = await api2.rpc.system.localPeerId();
|
|
1278
1610
|
const _peerid = _bs582.default.decode((peerid || "").toString());
|
|
1279
|
-
const account = await api2.query.guardian.
|
|
1611
|
+
const account = await api2.query.guardian.workerByKey(_peerid.slice(6, 38));
|
|
1280
1612
|
const nextIndex = currentIndex ? Number(currentIndex) + 1 : 1;
|
|
1281
|
-
const guardiansList = _optionalChain([guardians, 'optionalAccess',
|
|
1282
|
-
const nextGuardiansList = _optionalChain([nextGuardians, 'optionalAccess',
|
|
1613
|
+
const guardiansList = _optionalChain([guardians, 'optionalAccess', _95 => _95.toJSON, 'call', _96 => _96()]) || [];
|
|
1614
|
+
const nextGuardiansList = _optionalChain([nextGuardians, 'optionalAccess', _97 => _97.toJSON, 'call', _98 => _98()]) || [];
|
|
1283
1615
|
const buildDetails = async (list) => {
|
|
1284
1616
|
return Promise.all(
|
|
1285
1617
|
list.map(async (guardian) => {
|
|
@@ -1288,21 +1620,21 @@ async function getGuardianParticipants() {
|
|
|
1288
1620
|
const bonded = await api2.query.staking.bonded(guardian);
|
|
1289
1621
|
const payee = await api2.query.staking.payee(guardian);
|
|
1290
1622
|
const stakersOverview = await api2.query.staking.erasStakersOverview(
|
|
1291
|
-
_optionalChain([currentEra, 'optionalAccess',
|
|
1623
|
+
_optionalChain([currentEra, 'optionalAccess', _99 => _99.toPrimitive, 'call', _100 => _100()]),
|
|
1292
1624
|
guardian
|
|
1293
1625
|
);
|
|
1294
1626
|
const guardianErasPrefs = await api2.query.staking.erasGuardianPrefs(
|
|
1295
|
-
_optionalChain([currentEra, 'optionalAccess',
|
|
1627
|
+
_optionalChain([currentEra, 'optionalAccess', _101 => _101.toPrimitive, 'call', _102 => _102()]),
|
|
1296
1628
|
guardian
|
|
1297
1629
|
);
|
|
1298
1630
|
return {
|
|
1299
1631
|
guardian,
|
|
1300
|
-
rewardDestination: _optionalChain([payee, 'optionalAccess',
|
|
1301
|
-
currentPreferences: _optionalChain([guardianErasPrefs, 'optionalAccess',
|
|
1302
|
-
upcomingPreferences: _optionalChain([guardianPrefs, 'optionalAccess',
|
|
1303
|
-
stash: _optionalChain([bonded, 'optionalAccess',
|
|
1304
|
-
currentStakeOverview: _optionalChain([stakersOverview, 'optionalAccess',
|
|
1305
|
-
upcomingStakeOverview: _optionalChain([ledger, 'optionalAccess',
|
|
1632
|
+
rewardDestination: _optionalChain([payee, 'optionalAccess', _103 => _103.toHuman]) ? payee.toHuman() : null,
|
|
1633
|
+
currentPreferences: _optionalChain([guardianErasPrefs, 'optionalAccess', _104 => _104.toHuman]) ? guardianErasPrefs.toHuman() : null,
|
|
1634
|
+
upcomingPreferences: _optionalChain([guardianPrefs, 'optionalAccess', _105 => _105.toHuman]) ? guardianPrefs.toHuman() : null,
|
|
1635
|
+
stash: _optionalChain([bonded, 'optionalAccess', _106 => _106.toHuman]) ? bonded.toHuman() : null,
|
|
1636
|
+
currentStakeOverview: _optionalChain([stakersOverview, 'optionalAccess', _107 => _107.toHuman]) ? stakersOverview.toHuman() : null,
|
|
1637
|
+
upcomingStakeOverview: _optionalChain([ledger, 'optionalAccess', _108 => _108.toHuman]) ? ledger.toHuman() : null
|
|
1306
1638
|
};
|
|
1307
1639
|
})
|
|
1308
1640
|
);
|
|
@@ -1311,12 +1643,12 @@ async function getGuardianParticipants() {
|
|
|
1311
1643
|
const upcomingGuardians = await buildDetails(nextGuardiansList);
|
|
1312
1644
|
return {
|
|
1313
1645
|
nwState: {
|
|
1314
|
-
localPeerId: _optionalChain([peerid, 'optionalAccess',
|
|
1315
|
-
worker: _optionalChain([account, 'optionalAccess',
|
|
1316
|
-
currentEra: _optionalChain([currentEra, 'optionalAccess',
|
|
1317
|
-
guardians: JSON.stringify(_optionalChain([guardians, 'optionalAccess',
|
|
1318
|
-
nextGuardians: JSON.stringify(_optionalChain([nextGuardians, 'optionalAccess',
|
|
1319
|
-
currentIndex: _optionalChain([currentIndex, 'optionalAccess',
|
|
1646
|
+
localPeerId: _optionalChain([peerid, 'optionalAccess', _109 => _109.toString, 'call', _110 => _110()]),
|
|
1647
|
+
worker: _optionalChain([account, 'optionalAccess', _111 => _111.toHuman]) ? account.toHuman() : null,
|
|
1648
|
+
currentEra: _optionalChain([currentEra, 'optionalAccess', _112 => _112.toHuman]) ? currentEra.toHuman() : null,
|
|
1649
|
+
guardians: JSON.stringify(_optionalChain([guardians, 'optionalAccess', _113 => _113.toHuman]) ? guardians.toHuman() : null, null, 2),
|
|
1650
|
+
nextGuardians: JSON.stringify(_optionalChain([nextGuardians, 'optionalAccess', _114 => _114.toHuman]) ? nextGuardians.toHuman() : null, null, 2),
|
|
1651
|
+
currentIndex: _optionalChain([currentIndex, 'optionalAccess', _115 => _115.toHuman]) ? currentIndex.toHuman() : null,
|
|
1320
1652
|
nextIndex
|
|
1321
1653
|
},
|
|
1322
1654
|
currentGuardians,
|
|
@@ -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(_nullishCoalesce(params.fees, () => ( "0")));
|
|
1666
|
+
const computeStep = {
|
|
1667
|
+
cipher: plaintextCipher,
|
|
1668
|
+
computer_indices: params.guardians.map((_, i) => i),
|
|
1669
|
+
fees: atomicFees,
|
|
1670
|
+
deadline: _nullishCoalesce(params.deadline, () => ( 0)),
|
|
1671
|
+
confidentiality: { Trusted: _nullishCoalesce(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 = _nullishCoalesce(params.cipher, () => ( "Plaintext"));
|
|
1732
|
+
const resultCipher = _nullishCoalesce(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: _nullishCoalesce(params.deadline, () => ( 0)),
|
|
1745
|
+
confidentiality: { Trusted: _nullishCoalesce(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
|
var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
|
|
1401
1865
|
var _path = require('path'); var _path2 = _interopRequireDefault(_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 = _fs2.default.readFileSync(filePath);
|
|
1412
1912
|
const selectedFile = new File([fileContent], _path2.default.basename(filePath), {
|
|
@@ -1419,7 +1919,7 @@ async function uploadData(options) {
|
|
|
1419
1919
|
fileName: selectedFile.name,
|
|
1420
1920
|
filePath: "",
|
|
1421
1921
|
description,
|
|
1422
|
-
baseCost:
|
|
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,
|
|
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(
|
|
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,
|
|
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: ${
|
|
1981
|
+
`Staking amount: ${formatPaliAmount(amountBaseUnits)} for account: ${account.address} with reward destination: ${rewardDestination}`
|
|
1482
1982
|
);
|
|
1483
|
-
const stakeTx = api2.tx.staking.bond(
|
|
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,
|
|
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(
|
|
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
|
}
|
|
@@ -1517,9 +2017,9 @@ async function removeStake(account) {
|
|
|
1517
2017
|
const api2 = await getApi();
|
|
1518
2018
|
assert(api2, "API not initialized");
|
|
1519
2019
|
assert(account, "Account not initialized");
|
|
1520
|
-
const stakeAmount = await _asyncOptionalChain([(await api2.query.staking.ledger(account.address)), 'optionalAccess', async
|
|
1521
|
-
debugLog("Removing entire stake amount:", _optionalChain([stakeAmount, 'optionalAccess',
|
|
1522
|
-
const unstakeTx = api2.tx.staking.unbond(_optionalChain([stakeAmount, 'optionalAccess',
|
|
2020
|
+
const stakeAmount = await _asyncOptionalChain([(await api2.query.staking.ledger(account.address)), 'optionalAccess', async _116 => _116.toPrimitive, 'call', async _117 => _117()]);
|
|
2021
|
+
debugLog("Removing entire stake amount:", formatPaliAmount(_optionalChain([stakeAmount, 'optionalAccess', _118 => _118.active]) || 0n));
|
|
2022
|
+
const unstakeTx = api2.tx.staking.unbond(_optionalChain([stakeAmount, 'optionalAccess', _119 => _119.active]) || 0n);
|
|
1523
2023
|
const hash = await signAndSend(unstakeTx, account);
|
|
1524
2024
|
debugLog(`Unstake transaction sent with hash: ${hash.hash}`);
|
|
1525
2025
|
}
|
|
@@ -1535,25 +2035,25 @@ async function withdrawStake(account) {
|
|
|
1535
2035
|
}
|
|
1536
2036
|
|
|
1537
2037
|
// src/token/fund.ts
|
|
1538
|
-
async function fundAccount(account,
|
|
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: ${
|
|
1545
|
-
const tx = api2.tx.balances.transferKeepAlive(addr,
|
|
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,
|
|
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: ${
|
|
1556
|
-
const tx = api2.tx.balances.transferKeepAlive(address,
|
|
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
|
}
|
|
@@ -1588,7 +2088,7 @@ async function rotateAndSetKeys(account) {
|
|
|
1588
2088
|
_assert2.default.call(void 0, api2, "API not initialized");
|
|
1589
2089
|
debugLog(`Rotating session keys for ${account.meta.name} on ${provider.endpoint}`);
|
|
1590
2090
|
const newKeys = await api2.rpc.author.rotateKeys();
|
|
1591
|
-
debugLog(`${account.meta.name} rotated keys on ${provider.endpoint}:`, _nullishCoalesce(_optionalChain([newKeys, 'optionalAccess',
|
|
2091
|
+
debugLog(`${account.meta.name} rotated keys on ${provider.endpoint}:`, _nullishCoalesce(_optionalChain([newKeys, 'optionalAccess', _120 => _120.toHex, 'optionalCall', _121 => _121()]), () => ( newKeys)));
|
|
1592
2092
|
const setKeysTx = api2.tx.session.setKeys(newKeys, []);
|
|
1593
2093
|
const hash = await signAndSend(setKeysTx, account);
|
|
1594
2094
|
debugLog(`Rotate session transaction sent with hash: ${hash.hash}`);
|
|
@@ -1597,7 +2097,7 @@ async function setWorker(account) {
|
|
|
1597
2097
|
const api2 = await getApi();
|
|
1598
2098
|
_assert2.default.call(void 0, api2, "API not initialized");
|
|
1599
2099
|
const peerid = _bs582.default.decode((await api2.rpc.system.localPeerId()).toString());
|
|
1600
|
-
const setWorkerTx = api2.tx.guardian.setWorker(peerid.slice(
|
|
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
|
}
|
|
@@ -1683,5 +2183,21 @@ async function setWorker(account) {
|
|
|
1683
2183
|
|
|
1684
2184
|
|
|
1685
2185
|
|
|
1686
|
-
|
|
2186
|
+
|
|
2187
|
+
|
|
2188
|
+
|
|
2189
|
+
|
|
2190
|
+
|
|
2191
|
+
|
|
2192
|
+
|
|
2193
|
+
|
|
2194
|
+
|
|
2195
|
+
|
|
2196
|
+
|
|
2197
|
+
|
|
2198
|
+
|
|
2199
|
+
|
|
2200
|
+
|
|
2201
|
+
|
|
2202
|
+
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.createGuardianGroupAndWatch = createGuardianGroupAndWatch; 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.fetchAndDecodeExtrinsic = fetchAndDecodeExtrinsic; 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.getAgreementCreatedRequestId = getAgreementCreatedRequestId; 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.scanForBlockEvent = scanForBlockEvent; 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.watchForSubmissionReceipt = watchForSubmissionReceipt; exports.withdrawStake = withdrawStake; exports.writeMetadata = writeMetadata;
|
|
1687
2203
|
//# sourceMappingURL=index.cjs.map
|