@palliora.org/chainsdk 0.1.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/README.md +254 -0
- package/dist/index.cjs +1687 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +811 -0
- package/dist/index.d.ts +811 -0
- package/dist/index.js +1687 -0
- package/dist/index.js.map +1 -0
- package/package.json +65 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1687 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _createStarExport(obj) { Object.keys(obj) .filter((key) => key !== "default" && key !== "__esModule") .forEach((key) => { if (exports.hasOwnProperty(key)) { return; } Object.defineProperty(exports, key, {enumerable: true, configurable: true, get: () => obj[key]}); }); } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } async function _asyncOptionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = await fn(value); } else if (op === 'call' || op === 'optionalCall') { value = await fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/account/account.ts
|
|
2
|
+
var _wasmcrypto = require('@polkadot/wasm-crypto'); var wasmCrypto = _interopRequireWildcard(_wasmcrypto);
|
|
3
|
+
|
|
4
|
+
// src/account/types.ts
|
|
5
|
+
var CryptoType = /* @__PURE__ */ ((CryptoType2) => {
|
|
6
|
+
CryptoType2["SR25519"] = "sr25519";
|
|
7
|
+
CryptoType2["ED25519"] = "ed25519";
|
|
8
|
+
CryptoType2["ECDSA"] = "ecdsa";
|
|
9
|
+
return CryptoType2;
|
|
10
|
+
})(CryptoType || {});
|
|
11
|
+
var AccountSourceType = /* @__PURE__ */ ((AccountSourceType2) => {
|
|
12
|
+
AccountSourceType2["PRIVATE_KEY"] = "privateKey";
|
|
13
|
+
AccountSourceType2["SEED"] = "seed";
|
|
14
|
+
AccountSourceType2["MNEMONIC"] = "mnemonic";
|
|
15
|
+
AccountSourceType2["DERIVED"] = "derived";
|
|
16
|
+
AccountSourceType2["ADDRESS"] = "address";
|
|
17
|
+
return AccountSourceType2;
|
|
18
|
+
})(AccountSourceType || {});
|
|
19
|
+
|
|
20
|
+
// src/account/account.ts
|
|
21
|
+
var _api2 = require('@polkadot/api');
|
|
22
|
+
var _util = require('@polkadot/util'); _createStarExport(_util);
|
|
23
|
+
var _utilcrypto = require('@polkadot/util-crypto'); var utilCrypto = _interopRequireWildcard(_utilcrypto);
|
|
24
|
+
async function createAccount(input, type, name = "default", cryptoType = "sr25519" /* SR25519 */) {
|
|
25
|
+
await _wasmcrypto.waitReady.call(void 0, );
|
|
26
|
+
const keyring2 = new (0, _api2.Keyring)({ type: cryptoType });
|
|
27
|
+
switch (type) {
|
|
28
|
+
case "privateKey" /* PRIVATE_KEY */: {
|
|
29
|
+
const pair = pairFromPrivateKeyHex(input, cryptoType);
|
|
30
|
+
return keyring2.addFromPair(pair, { name }, cryptoType);
|
|
31
|
+
}
|
|
32
|
+
case "seed" /* SEED */: {
|
|
33
|
+
const seed = _util.hexToU8a.call(void 0, input);
|
|
34
|
+
if (seed.length !== 32) {
|
|
35
|
+
throw new Error(
|
|
36
|
+
`Invalid ${cryptoType} seed length. Expected 32 bytes, got ${seed.length}`
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
return keyring2.addFromSeed(seed, { name }, cryptoType);
|
|
40
|
+
}
|
|
41
|
+
case "mnemonic" /* MNEMONIC */:
|
|
42
|
+
return keyring2.createFromUri(input, { name }, cryptoType);
|
|
43
|
+
case "address" /* ADDRESS */:
|
|
44
|
+
const account = keyring2.addFromAddress(
|
|
45
|
+
input,
|
|
46
|
+
{ name },
|
|
47
|
+
null,
|
|
48
|
+
cryptoType
|
|
49
|
+
);
|
|
50
|
+
return account;
|
|
51
|
+
default:
|
|
52
|
+
throw new Error("Invalid input type");
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function pairFromPrivateKeyHex(privateKeyHex, cryptoType) {
|
|
56
|
+
const privateKey = _util.hexToU8a.call(void 0, privateKeyHex);
|
|
57
|
+
switch (cryptoType) {
|
|
58
|
+
case "ed25519" /* ED25519 */:
|
|
59
|
+
if (privateKey.length !== 64) {
|
|
60
|
+
throw new Error(
|
|
61
|
+
`Invalid ed25519 private key length. Expected 64 bytes, got ${privateKey.length}`
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
return _utilcrypto.ed25519PairFromSecret.call(void 0, privateKey);
|
|
65
|
+
case "ecdsa" /* ECDSA */:
|
|
66
|
+
if (privateKey.length !== 32) {
|
|
67
|
+
throw new Error(
|
|
68
|
+
`Invalid ecdsa private key length. Expected 32 bytes, got ${privateKey.length}`
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
return _utilcrypto.secp256k1PairFromSeed.call(void 0, privateKey);
|
|
72
|
+
case "sr25519" /* SR25519 */:
|
|
73
|
+
if (privateKey.length !== 96) {
|
|
74
|
+
throw new Error(
|
|
75
|
+
`Invalid sr25519 private key length. Expected 96 bytes (secret+public), got ${privateKey.length}`
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
secretKey: privateKey.slice(0, 64),
|
|
80
|
+
publicKey: privateKey.slice(64, 96)
|
|
81
|
+
};
|
|
82
|
+
default:
|
|
83
|
+
throw new Error(`Unsupported crypto type: ${cryptoType}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// src/chain/spec.ts
|
|
88
|
+
var API_RPC = {
|
|
89
|
+
kate: {
|
|
90
|
+
queryRows: {
|
|
91
|
+
description: "",
|
|
92
|
+
params: [
|
|
93
|
+
{
|
|
94
|
+
name: "rows",
|
|
95
|
+
type: "Vec<u32>"
|
|
96
|
+
},
|
|
97
|
+
{
|
|
98
|
+
name: "at",
|
|
99
|
+
type: "Hash",
|
|
100
|
+
isOptional: true
|
|
101
|
+
}
|
|
102
|
+
],
|
|
103
|
+
type: "Vec<GRow>"
|
|
104
|
+
},
|
|
105
|
+
queryProof: {
|
|
106
|
+
description: "Generate the kate proof for the given `cells`",
|
|
107
|
+
params: [
|
|
108
|
+
{
|
|
109
|
+
name: "cells",
|
|
110
|
+
type: "Vec<Cell>"
|
|
111
|
+
},
|
|
112
|
+
{
|
|
113
|
+
name: "at",
|
|
114
|
+
type: "Hash",
|
|
115
|
+
isOptional: true
|
|
116
|
+
}
|
|
117
|
+
],
|
|
118
|
+
type: "Vec<GDataProof>"
|
|
119
|
+
},
|
|
120
|
+
blockLength: {
|
|
121
|
+
description: "Get Block Length",
|
|
122
|
+
params: [
|
|
123
|
+
{
|
|
124
|
+
name: "at",
|
|
125
|
+
type: "Hash",
|
|
126
|
+
isOptional: true
|
|
127
|
+
}
|
|
128
|
+
],
|
|
129
|
+
type: "BlockLength"
|
|
130
|
+
},
|
|
131
|
+
queryDataProof: {
|
|
132
|
+
description: "Generate the data proof for the given `transaction_index`",
|
|
133
|
+
params: [
|
|
134
|
+
{
|
|
135
|
+
name: "transaction_index",
|
|
136
|
+
type: "u32"
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
name: "at",
|
|
140
|
+
type: "Hash",
|
|
141
|
+
isOptional: true
|
|
142
|
+
}
|
|
143
|
+
],
|
|
144
|
+
type: "ProofResponse"
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
guardian: {
|
|
148
|
+
runtimeInfo: {
|
|
149
|
+
description: "Fetch guardian runtime info",
|
|
150
|
+
params: [
|
|
151
|
+
{
|
|
152
|
+
name: "at",
|
|
153
|
+
type: "Hash",
|
|
154
|
+
isOptional: true
|
|
155
|
+
}
|
|
156
|
+
],
|
|
157
|
+
type: "GuardianInfo"
|
|
158
|
+
},
|
|
159
|
+
guardianList: {
|
|
160
|
+
description: "Fetch guardian list",
|
|
161
|
+
params: [],
|
|
162
|
+
type: "Vec<String>"
|
|
163
|
+
},
|
|
164
|
+
guardianNwParams: {
|
|
165
|
+
description: "Fetch guardian network parameters",
|
|
166
|
+
params: [],
|
|
167
|
+
type: "GuardianNwParams"
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
var API_TYPES = {
|
|
172
|
+
GuardianInfo: {
|
|
173
|
+
active: "u32",
|
|
174
|
+
maximum: "u32"
|
|
175
|
+
},
|
|
176
|
+
GuardianNwParams: {
|
|
177
|
+
kzg: "Vec<u8>",
|
|
178
|
+
agg_key: "Vec<u8>"
|
|
179
|
+
},
|
|
180
|
+
AppId: "Compact<u32>",
|
|
181
|
+
DataLookupItem: {
|
|
182
|
+
appId: "AppId",
|
|
183
|
+
start: "Compact<u32>"
|
|
184
|
+
},
|
|
185
|
+
CompactDataLookup: {
|
|
186
|
+
size: "Compact<u32>",
|
|
187
|
+
index: "Vec<DataLookupItem>"
|
|
188
|
+
},
|
|
189
|
+
KateCommitment: {
|
|
190
|
+
rows: "Compact<u16>",
|
|
191
|
+
cols: "Compact<u16>",
|
|
192
|
+
commitment: "Vec<u8>",
|
|
193
|
+
dataRoot: "H256"
|
|
194
|
+
},
|
|
195
|
+
V3HeaderExtension: {
|
|
196
|
+
appLookup: "CompactDataLookup",
|
|
197
|
+
commitment: "KateCommitment"
|
|
198
|
+
},
|
|
199
|
+
HeaderExtension: {
|
|
200
|
+
_enum: {
|
|
201
|
+
V1: null,
|
|
202
|
+
V2: null,
|
|
203
|
+
V3: "V3HeaderExtension"
|
|
204
|
+
}
|
|
205
|
+
},
|
|
206
|
+
DaHeader: {
|
|
207
|
+
parentHash: "Hash",
|
|
208
|
+
number: "Compact<BlockNumber>",
|
|
209
|
+
stateRoot: "Hash",
|
|
210
|
+
extrinsicsRoot: "Hash",
|
|
211
|
+
digest: "Digest",
|
|
212
|
+
extension: "HeaderExtension"
|
|
213
|
+
},
|
|
214
|
+
Header: "DaHeader",
|
|
215
|
+
CheckAppIdExtra: {
|
|
216
|
+
appId: "AppId"
|
|
217
|
+
},
|
|
218
|
+
CheckAppIdTypes: {},
|
|
219
|
+
CheckAppId: {
|
|
220
|
+
extra: "CheckAppIdExtra",
|
|
221
|
+
types: "CheckAppIdTypes"
|
|
222
|
+
},
|
|
223
|
+
ComputePayload: {
|
|
224
|
+
da_type: "u8",
|
|
225
|
+
agreement: "Option<BoundedVec<[u8; 32], 10>>",
|
|
226
|
+
verification: "u8",
|
|
227
|
+
compute: "u8"
|
|
228
|
+
},
|
|
229
|
+
BlockLengthColumns: "Compact<u32>",
|
|
230
|
+
BlockLengthRows: "Compact<u32>",
|
|
231
|
+
BlockLength: {
|
|
232
|
+
max: "PerDispatchClass",
|
|
233
|
+
cols: "BlockLengthColumns",
|
|
234
|
+
rows: "BlockLengthRows",
|
|
235
|
+
chunkSize: "Compact<u32>"
|
|
236
|
+
},
|
|
237
|
+
PerDispatchClass: {
|
|
238
|
+
normal: "u32",
|
|
239
|
+
operational: "u32",
|
|
240
|
+
mandatory: "u32"
|
|
241
|
+
},
|
|
242
|
+
TxDataRoots: {
|
|
243
|
+
dataRoot: "H256",
|
|
244
|
+
blobRoot: "H256",
|
|
245
|
+
bridgeRoot: "H256"
|
|
246
|
+
},
|
|
247
|
+
DataProof: {
|
|
248
|
+
roots: "TxDataRoots",
|
|
249
|
+
proof: "Vec<H256>",
|
|
250
|
+
numberOfLeaves: "Compact<u32>",
|
|
251
|
+
leafIndex: "Compact<u32>",
|
|
252
|
+
leaf: "H256"
|
|
253
|
+
},
|
|
254
|
+
ProofResponse: {
|
|
255
|
+
dataProof: "DataProof",
|
|
256
|
+
message: "Option<AddressedMessage>"
|
|
257
|
+
},
|
|
258
|
+
AddressedMessage: {
|
|
259
|
+
message: "Message",
|
|
260
|
+
from: "H256",
|
|
261
|
+
to: "H256",
|
|
262
|
+
originDomain: "u32",
|
|
263
|
+
destinationDomain: "u32",
|
|
264
|
+
id: "u64"
|
|
265
|
+
},
|
|
266
|
+
Message: {
|
|
267
|
+
_enum: {
|
|
268
|
+
ArbitraryMessage: "ArbitraryMessage",
|
|
269
|
+
FungibleToken: "FungibleToken"
|
|
270
|
+
}
|
|
271
|
+
},
|
|
272
|
+
FungibleToken: {
|
|
273
|
+
assetId: "H256",
|
|
274
|
+
amount: "u128"
|
|
275
|
+
},
|
|
276
|
+
BoundedData: "Vec<u8>",
|
|
277
|
+
ArbitraryMessage: "BoundedData",
|
|
278
|
+
Cell: {
|
|
279
|
+
row: "u32",
|
|
280
|
+
col: "u32"
|
|
281
|
+
},
|
|
282
|
+
GRawScalar: "U256",
|
|
283
|
+
GProof: "[u8; 48]",
|
|
284
|
+
GRow: "Vec<GRawScalar>",
|
|
285
|
+
GDataProof: "(GRawScalar, GProof)"
|
|
286
|
+
};
|
|
287
|
+
var DEFAULT_COMPUTE_PAYLOAD = { compute: { da_type: 0, verification: 0, compute: 0 } };
|
|
288
|
+
var DEFAULT_EMPTY_PAYLOAD = { compute: { da_type: 0, verification: 0, compute: 0, agreement: [] } };
|
|
289
|
+
var API_EXTENSIONS = {
|
|
290
|
+
CheckAppId: {
|
|
291
|
+
extrinsic: {
|
|
292
|
+
appId: "AppId"
|
|
293
|
+
},
|
|
294
|
+
payload: {}
|
|
295
|
+
},
|
|
296
|
+
CheckCompute: {
|
|
297
|
+
extrinsic: {
|
|
298
|
+
compute: "ComputePayload"
|
|
299
|
+
},
|
|
300
|
+
payload: {}
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
// src/crypto/core.ts
|
|
305
|
+
var _bls12381 = require('@noble/curves/bls12-381');
|
|
306
|
+
var encrypt = (params, apk, t) => {
|
|
307
|
+
const gamma = _bls12381.bls12_381.fields.Fr.create(
|
|
308
|
+
BigInt(
|
|
309
|
+
"0x" + reverseEndianess(
|
|
310
|
+
"8660d3c2a2ab458dd6da04d3e7cb5cf6edb702dfa2fa0c952cd6f3bcdc0fdb1a"
|
|
311
|
+
)
|
|
312
|
+
)
|
|
313
|
+
);
|
|
314
|
+
const gamma_g2 = params.powers_of_h[0].multiply(gamma);
|
|
315
|
+
let g = params.powers_of_g[0];
|
|
316
|
+
let h = params.powers_of_h[0];
|
|
317
|
+
let sa1 = [_bls12381.bls12_381.G1.ProjectivePoint.BASE, _bls12381.bls12_381.G1.ProjectivePoint.BASE];
|
|
318
|
+
let sa2 = Array(6).fill(_bls12381.bls12_381.G2.ProjectivePoint.BASE);
|
|
319
|
+
const hexValues = [
|
|
320
|
+
reverseEndianess(
|
|
321
|
+
"08ca6f2a35f8f6f9cad58e9d764d450af154c246fc04266151e2a5493ff02943"
|
|
322
|
+
),
|
|
323
|
+
reverseEndianess(
|
|
324
|
+
"8696a66087578b92e1b4b11c6b4c06d4694a9bed1f9468f0115e7f2648eb021d"
|
|
325
|
+
),
|
|
326
|
+
reverseEndianess(
|
|
327
|
+
"91e201cc83dc03cc47d63cfb8a9016e73ffd1a78fffd14e4dfcdf2cbb9a7245d"
|
|
328
|
+
),
|
|
329
|
+
reverseEndianess(
|
|
330
|
+
"a90598c6e0f25c3a104fc94632b1d58cf21bca3bbd7e41da07feb9c14e0fa60d"
|
|
331
|
+
),
|
|
332
|
+
reverseEndianess(
|
|
333
|
+
"d3f5a9fc8abfef02fb6095c08ba4f3445b36f0fb963579bc5112d34a02044567"
|
|
334
|
+
)
|
|
335
|
+
];
|
|
336
|
+
const s = Array.from({ length: 5 }, () => _bls12381.bls12_381.G1.normPrivateKeyToScalar(_bls12381.bls12_381.utils.randomPrivateKey()));
|
|
337
|
+
sa1[0] = apk.ask.multiply(s[0]).add(params.powers_of_g[t].multiply(s[3])).add(params.powers_of_g[0].multiply(s[4]));
|
|
338
|
+
sa1[1] = g.multiply(s[2]);
|
|
339
|
+
sa2[0] = h.multiply(s[0]).add(gamma_g2.multiply(s[2]));
|
|
340
|
+
sa2[1] = apk.z_g2.multiply(s[0]);
|
|
341
|
+
sa2[2] = params.powers_of_h[1].multiply(s[0]).add(params.powers_of_h[1].multiply(s[1]));
|
|
342
|
+
sa2[3] = h.multiply(s[1]);
|
|
343
|
+
sa2[4] = h.multiply(s[3]);
|
|
344
|
+
sa2[5] = params.powers_of_h[1].add(apk.h_minus1).multiply(s[4]);
|
|
345
|
+
const enc_key = _bls12381.bls12_381.fields.Fp12.pow(apk.e_gh, s[4]);
|
|
346
|
+
return { gamma_g2, sa1, sa2, enc_key, t };
|
|
347
|
+
};
|
|
348
|
+
var decodePowersOfTau = (input) => {
|
|
349
|
+
try {
|
|
350
|
+
if (!input || input.length % 2 !== 0) {
|
|
351
|
+
throw new Error("Invalid input hex string");
|
|
352
|
+
}
|
|
353
|
+
const hexArray = input.match(/.{1,2}/g) || [];
|
|
354
|
+
const buffer = new Uint8Array(hexArray.map((byte) => parseInt(byte, 16)));
|
|
355
|
+
const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
|
|
356
|
+
const view = new DataView(arrayBuffer);
|
|
357
|
+
const powers_of_g = [];
|
|
358
|
+
const powers_of_h = [];
|
|
359
|
+
const G1_POINT_SIZE = 48;
|
|
360
|
+
const G2_POINT_SIZE = 96;
|
|
361
|
+
let offset = 0;
|
|
362
|
+
if (offset + 8 > buffer.length) {
|
|
363
|
+
throw new Error("Buffer too small to read count");
|
|
364
|
+
}
|
|
365
|
+
const count = view.getBigUint64(offset, true);
|
|
366
|
+
offset += 8;
|
|
367
|
+
for (let i = 0; i < count; i++) {
|
|
368
|
+
if (offset + G1_POINT_SIZE > buffer.length) {
|
|
369
|
+
throw new Error("Buffer too small to read G1 point");
|
|
370
|
+
}
|
|
371
|
+
const pointBuffer = buffer.slice(offset, offset + G1_POINT_SIZE);
|
|
372
|
+
const point = _bls12381.bls12_381.G1.ProjectivePoint.fromHex(pointBuffer);
|
|
373
|
+
powers_of_g.push(point);
|
|
374
|
+
offset += G1_POINT_SIZE;
|
|
375
|
+
}
|
|
376
|
+
if (offset + 8 > buffer.length) {
|
|
377
|
+
throw new Error("Buffer too small to read second count");
|
|
378
|
+
}
|
|
379
|
+
offset += 8;
|
|
380
|
+
for (let i = 0; i < count; i++) {
|
|
381
|
+
if (offset + G2_POINT_SIZE > buffer.length) {
|
|
382
|
+
throw new Error("Buffer too small to read G2 point");
|
|
383
|
+
}
|
|
384
|
+
const pointBuffer = buffer.slice(offset, offset + G2_POINT_SIZE);
|
|
385
|
+
const point = _bls12381.bls12_381.G2.ProjectivePoint.fromHex(pointBuffer);
|
|
386
|
+
powers_of_h.push(point);
|
|
387
|
+
offset += G2_POINT_SIZE;
|
|
388
|
+
}
|
|
389
|
+
return { powers_of_g, powers_of_h };
|
|
390
|
+
} catch (error) {
|
|
391
|
+
console.error("Error in decodePowersOfTau:", error);
|
|
392
|
+
console.log("Input length:", input.length);
|
|
393
|
+
console.log("Input preview:", input.slice(0, 100));
|
|
394
|
+
throw error;
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
var isValidHex = (hex) => {
|
|
398
|
+
return /^[0-9A-Fa-f]*$/.test(hex) && hex.length % 2 === 0;
|
|
399
|
+
};
|
|
400
|
+
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))]) || []);
|
|
402
|
+
let offset = 0;
|
|
403
|
+
const view = new DataView(buffer.buffer);
|
|
404
|
+
const readBigUInt64LE = () => {
|
|
405
|
+
const value = view.getBigUint64(offset, true);
|
|
406
|
+
offset += 8;
|
|
407
|
+
return value;
|
|
408
|
+
};
|
|
409
|
+
const readProjPointTypeFp = (count) => {
|
|
410
|
+
const points = [];
|
|
411
|
+
for (let i = 0; i < count; i++) {
|
|
412
|
+
const pointBuffer = buffer.slice(offset, offset + 48);
|
|
413
|
+
const point = _bls12381.bls12_381.G1.ProjectivePoint.fromHex(pointBuffer);
|
|
414
|
+
points.push(point);
|
|
415
|
+
offset += 48;
|
|
416
|
+
}
|
|
417
|
+
return points;
|
|
418
|
+
};
|
|
419
|
+
const readProjPointTypeFp2 = (count) => {
|
|
420
|
+
const points = [];
|
|
421
|
+
for (let i = 0; i < count; i++) {
|
|
422
|
+
const pointBuffer = buffer.slice(offset, offset + 96);
|
|
423
|
+
const point = _bls12381.bls12_381.G2.ProjectivePoint.fromHex(pointBuffer);
|
|
424
|
+
points.push(point);
|
|
425
|
+
offset += 96;
|
|
426
|
+
}
|
|
427
|
+
return points;
|
|
428
|
+
};
|
|
429
|
+
const readProjPointTypeFp12 = () => {
|
|
430
|
+
const points = [];
|
|
431
|
+
for (let i = 0; i < 12; i++) {
|
|
432
|
+
const pointBuffer = buffer.slice(offset, offset + 48);
|
|
433
|
+
const hexValue = Array.from(pointBuffer).reverse().map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
434
|
+
const point = BigInt("0x" + hexValue);
|
|
435
|
+
points.push(point);
|
|
436
|
+
offset += 48;
|
|
437
|
+
}
|
|
438
|
+
if (points.length !== 12) {
|
|
439
|
+
throw new Error("Invalid number of points for Fp12");
|
|
440
|
+
}
|
|
441
|
+
return _bls12381.bls12_381.fields.Fp12.create({
|
|
442
|
+
c0: _bls12381.bls12_381.fields.Fp6.create({
|
|
443
|
+
c0: _bls12381.bls12_381.fields.Fp2.create({ c0: points[0], c1: points[1] }),
|
|
444
|
+
c1: _bls12381.bls12_381.fields.Fp2.create({ c0: points[2], c1: points[3] }),
|
|
445
|
+
c2: _bls12381.bls12_381.fields.Fp2.create({ c0: points[4], c1: points[5] })
|
|
446
|
+
}),
|
|
447
|
+
c1: _bls12381.bls12_381.fields.Fp6.create({
|
|
448
|
+
c0: _bls12381.bls12_381.fields.Fp2.create({ c0: points[6], c1: points[7] }),
|
|
449
|
+
c1: _bls12381.bls12_381.fields.Fp2.create({ c0: points[8], c1: points[9] }),
|
|
450
|
+
c2: _bls12381.bls12_381.fields.Fp2.create({ c0: points[10], c1: points[11] })
|
|
451
|
+
})
|
|
452
|
+
});
|
|
453
|
+
};
|
|
454
|
+
const pkCount = readBigUInt64LE();
|
|
455
|
+
const pk = [];
|
|
456
|
+
for (let i = 0; i < pkCount; i++) {
|
|
457
|
+
const id = Number(readBigUInt64LE());
|
|
458
|
+
const bls_pk = readProjPointTypeFp(BigInt(1))[0];
|
|
459
|
+
const sk_li = readProjPointTypeFp(BigInt(1))[0];
|
|
460
|
+
const sk_li_minus0 = readProjPointTypeFp(BigInt(1))[0];
|
|
461
|
+
const sk_li_lj_z = readProjPointTypeFp(readBigUInt64LE());
|
|
462
|
+
const sk_li_x = readProjPointTypeFp(BigInt(1))[0];
|
|
463
|
+
pk.push({ id, bls_pk, sk_li, sk_li_minus0, sk_li_x, sk_li_lj_z });
|
|
464
|
+
}
|
|
465
|
+
const agg_sk_li_lj_z = readProjPointTypeFp(readBigUInt64LE());
|
|
466
|
+
const ask = readProjPointTypeFp(BigInt(1))[0];
|
|
467
|
+
const z_g2 = readProjPointTypeFp2(BigInt(1))[0];
|
|
468
|
+
const h_minus1 = readProjPointTypeFp2(BigInt(1))[0];
|
|
469
|
+
const e_gh = readProjPointTypeFp12();
|
|
470
|
+
return { pk, agg_sk_li_lj_z, ask, z_g2, h_minus1, e_gh };
|
|
471
|
+
};
|
|
472
|
+
var encodeCiphertext = (input) => {
|
|
473
|
+
const writeProjPointTypeFp = (point) => {
|
|
474
|
+
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))]) || []);
|
|
476
|
+
};
|
|
477
|
+
const writeProjPointTypeFp2 = (point) => {
|
|
478
|
+
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))]) || []);
|
|
480
|
+
};
|
|
481
|
+
const gamma_g2Buffer = writeProjPointTypeFp2(input.gamma_g2);
|
|
482
|
+
const sa1Buffer = new Uint8Array(input.sa1.flatMap((p) => Array.from(writeProjPointTypeFp(p))));
|
|
483
|
+
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))]) || []);
|
|
485
|
+
const tBuffer = new Uint8Array(8);
|
|
486
|
+
new DataView(tBuffer.buffer).setBigUint64(0, BigInt(input.t), true);
|
|
487
|
+
const totalLength = gamma_g2Buffer.length + sa1Buffer.length + sa2Buffer.length + enc_keyBuffer.length + tBuffer.length;
|
|
488
|
+
const resultBuffer = new Uint8Array(totalLength);
|
|
489
|
+
let offset = 0;
|
|
490
|
+
resultBuffer.set(gamma_g2Buffer, offset);
|
|
491
|
+
offset += gamma_g2Buffer.length;
|
|
492
|
+
resultBuffer.set(sa1Buffer, offset);
|
|
493
|
+
offset += sa1Buffer.length;
|
|
494
|
+
resultBuffer.set(sa2Buffer, offset);
|
|
495
|
+
offset += sa2Buffer.length;
|
|
496
|
+
resultBuffer.set(enc_keyBuffer, offset);
|
|
497
|
+
offset += enc_keyBuffer.length;
|
|
498
|
+
resultBuffer.set(tBuffer, offset);
|
|
499
|
+
return Array.from(resultBuffer).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
500
|
+
};
|
|
501
|
+
function fp12ToHex(fp12) {
|
|
502
|
+
const c0 = fp12.c0;
|
|
503
|
+
const c1 = fp12.c1;
|
|
504
|
+
return [
|
|
505
|
+
bigintToBigEndianHex(c0.c0.c0, 48),
|
|
506
|
+
bigintToBigEndianHex(c0.c0.c1, 48),
|
|
507
|
+
bigintToBigEndianHex(c0.c1.c0, 48),
|
|
508
|
+
bigintToBigEndianHex(c0.c1.c1, 48),
|
|
509
|
+
bigintToBigEndianHex(c0.c2.c0, 48),
|
|
510
|
+
bigintToBigEndianHex(c0.c2.c1, 48),
|
|
511
|
+
bigintToBigEndianHex(c1.c0.c0, 48),
|
|
512
|
+
bigintToBigEndianHex(c1.c0.c1, 48),
|
|
513
|
+
bigintToBigEndianHex(c1.c1.c0, 48),
|
|
514
|
+
bigintToBigEndianHex(c1.c1.c1, 48),
|
|
515
|
+
bigintToBigEndianHex(c1.c2.c0, 48),
|
|
516
|
+
bigintToBigEndianHex(c1.c2.c1, 48)
|
|
517
|
+
].join("");
|
|
518
|
+
}
|
|
519
|
+
var testCrypt = (kzg, agg_key) => {
|
|
520
|
+
try {
|
|
521
|
+
if (!isValidHex(kzg) || !isValidHex(agg_key)) {
|
|
522
|
+
throw new Error("Invalid input hex strings");
|
|
523
|
+
}
|
|
524
|
+
const powersOfTau = decodePowersOfTau(kzg);
|
|
525
|
+
const aggregateKey = decodeAggregateKey(agg_key);
|
|
526
|
+
const ciph = encrypt(powersOfTau, aggregateKey, 2);
|
|
527
|
+
const encoded = encodeCiphertext(ciph);
|
|
528
|
+
const ikm = fp12ToHex(ciph.enc_key);
|
|
529
|
+
return { encoded, ikm, ciph };
|
|
530
|
+
} catch (error) {
|
|
531
|
+
console.error("Error in testCrypt:", error);
|
|
532
|
+
throw error;
|
|
533
|
+
}
|
|
534
|
+
};
|
|
535
|
+
function bigintToBigEndianHex(value, length) {
|
|
536
|
+
let hex = value.toString(16);
|
|
537
|
+
if (hex.length > length * 2) {
|
|
538
|
+
throw new Error("BigInt value is too large to fit in the specified length");
|
|
539
|
+
}
|
|
540
|
+
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))]) || [];
|
|
542
|
+
const reversedByteArray = byteArray.reverse();
|
|
543
|
+
const bigEndianHex = reversedByteArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
544
|
+
return bigEndianHex;
|
|
545
|
+
}
|
|
546
|
+
function reverseEndianess(hex) {
|
|
547
|
+
if (hex.length % 2 !== 0) {
|
|
548
|
+
throw new Error("Hex string must have an even length");
|
|
549
|
+
}
|
|
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("")]) || "";
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// src/crypto/cipher.ts
|
|
554
|
+
var _ed25519 = require('@noble/curves/ed25519');
|
|
555
|
+
var _hkdf = require('@noble/hashes/hkdf');
|
|
556
|
+
var _sha256 = require('@noble/hashes/sha256');
|
|
557
|
+
var _chacha20poly1305 = require('@stablelib/chacha20poly1305');
|
|
558
|
+
var gen_stretched_key = (input) => {
|
|
559
|
+
const salt = new Uint8Array(32);
|
|
560
|
+
const info = new TextEncoder().encode("aes_encryption");
|
|
561
|
+
return _hkdf.hkdf.call(void 0, _sha256.sha256, input, salt, info, 32);
|
|
562
|
+
};
|
|
563
|
+
var gen_shared_key = (key, pk) => {
|
|
564
|
+
const mg_key = _ed25519.edwardsToMontgomeryPriv.call(void 0, key);
|
|
565
|
+
const mg_pk = _ed25519.edwardsToMontgomeryPub.call(void 0, pk);
|
|
566
|
+
return _ed25519.x25519.getSharedSecret(mg_key, mg_pk);
|
|
567
|
+
};
|
|
568
|
+
var encrypt2 = (plaintext, key) => {
|
|
569
|
+
const cipher = new (0, _chacha20poly1305.ChaCha20Poly1305)(key);
|
|
570
|
+
const nonce = new Uint8Array(cipher.nonceLength);
|
|
571
|
+
globalThis.crypto.getRandomValues(nonce);
|
|
572
|
+
const ciphertext = cipher.seal(nonce, plaintext);
|
|
573
|
+
return { ciphertext, nonce };
|
|
574
|
+
};
|
|
575
|
+
var decrypt = (ciphertext, key, nonce) => {
|
|
576
|
+
const cipher = new (0, _chacha20poly1305.ChaCha20Poly1305)(key);
|
|
577
|
+
const res = cipher.open(nonce, ciphertext);
|
|
578
|
+
return res;
|
|
579
|
+
};
|
|
580
|
+
|
|
581
|
+
// src/utils/assert.ts
|
|
582
|
+
function assert(condition, message) {
|
|
583
|
+
if (!condition) {
|
|
584
|
+
throw new Error(_nullishCoalesce(message, () => ( "Assertion failed")));
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// src/config.ts
|
|
589
|
+
var env = typeof process !== "undefined" && process.env ? process.env : {};
|
|
590
|
+
var PALLIORA_WS = env.PALLIORA_WS || "wss://manas-rpc.palliora.org";
|
|
591
|
+
var PALLIORA_RPC_URL = env.PALLIORA_RPC_URL || "wss://manas-rpc.palliora.org";
|
|
592
|
+
var DEBUG = env.DEBUG === "true" || false;
|
|
593
|
+
var TX_WAIT_FINALIZATION = env.TX_WAIT_FINALIZATION === "true" || false;
|
|
594
|
+
function configure(opts) {
|
|
595
|
+
if (opts.pallioraWs !== void 0) PALLIORA_WS = exports.PALLIORA_WS = opts.pallioraWs;
|
|
596
|
+
if (opts.pallioraRpcUrl !== void 0) PALLIORA_RPC_URL = exports.PALLIORA_RPC_URL = opts.pallioraRpcUrl;
|
|
597
|
+
if (opts.debug !== void 0) DEBUG = exports.DEBUG = opts.debug;
|
|
598
|
+
if (opts.txWaitFinalization !== void 0) TX_WAIT_FINALIZATION = exports.TX_WAIT_FINALIZATION = opts.txWaitFinalization;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// src/utils/helper.ts
|
|
602
|
+
var tokenToBigint = (arg) => {
|
|
603
|
+
const val = typeof arg === "bigint" ? arg : BigInt(arg);
|
|
604
|
+
return val * 10n ** 15n;
|
|
605
|
+
};
|
|
606
|
+
function hexToUint8Array(hex) {
|
|
607
|
+
if (hex.length % 2 !== 0) {
|
|
608
|
+
throw new Error("Invalid hex string");
|
|
609
|
+
}
|
|
610
|
+
const arr = new Uint8Array(hex.length / 2);
|
|
611
|
+
for (let i = 0; i < arr.length; i++) {
|
|
612
|
+
arr[i] = parseInt(hex.substr(i * 2, 2), 16);
|
|
613
|
+
}
|
|
614
|
+
return arr;
|
|
615
|
+
}
|
|
616
|
+
function uint8ArrayToBase64(uint8Array) {
|
|
617
|
+
let binary = "";
|
|
618
|
+
for (let i = 0; i < uint8Array.length; i++) {
|
|
619
|
+
binary += String.fromCharCode(uint8Array[i]);
|
|
620
|
+
}
|
|
621
|
+
return btoa(binary);
|
|
622
|
+
}
|
|
623
|
+
var base64ToUint8Array = (base64) => {
|
|
624
|
+
base64 = base64.replace(/-/g, "+").replace(/_/g, "/");
|
|
625
|
+
while (base64.length % 4) {
|
|
626
|
+
base64 += "=";
|
|
627
|
+
}
|
|
628
|
+
const binaryString = atob(base64);
|
|
629
|
+
const len = binaryString.length;
|
|
630
|
+
const bytes = new Uint8Array(len);
|
|
631
|
+
for (let i = 0; i < len; i++) {
|
|
632
|
+
bytes[i] = binaryString.charCodeAt(i);
|
|
633
|
+
}
|
|
634
|
+
return bytes;
|
|
635
|
+
};
|
|
636
|
+
var decodeField = (field, expectedLength) => {
|
|
637
|
+
const bytes = base64ToUint8Array(field);
|
|
638
|
+
if (expectedLength && bytes.length !== expectedLength) {
|
|
639
|
+
if (bytes.length === expectedLength * 2) {
|
|
640
|
+
const intermediateStr = new TextDecoder().decode(bytes);
|
|
641
|
+
const secondBytes = base64ToUint8Array(intermediateStr);
|
|
642
|
+
if (secondBytes.length === expectedLength) {
|
|
643
|
+
return secondBytes;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
return bytes;
|
|
648
|
+
};
|
|
649
|
+
var debugLog = (message, ...optionalParams) => {
|
|
650
|
+
if (DEBUG) {
|
|
651
|
+
console.log(message, ...optionalParams);
|
|
652
|
+
}
|
|
653
|
+
};
|
|
654
|
+
|
|
655
|
+
// src/utils/token.ts
|
|
656
|
+
|
|
657
|
+
var tokenCache = null;
|
|
658
|
+
async function fetchTokenProperties() {
|
|
659
|
+
if (tokenCache) {
|
|
660
|
+
return tokenCache;
|
|
661
|
+
}
|
|
662
|
+
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()]);
|
|
664
|
+
assert(systemProperties, "Failed to fetch system properties from RPC");
|
|
665
|
+
const tokenProperties = {
|
|
666
|
+
symbol: (_optionalChain([systemProperties, 'optionalAccess', _34 => _34.tokenSymbol]) || ["UNIT"])[0],
|
|
667
|
+
decimals: Number((_optionalChain([systemProperties, 'optionalAccess', _35 => _35.tokenDecimals]) || ["18"])[0])
|
|
668
|
+
};
|
|
669
|
+
tokenCache = tokenProperties;
|
|
670
|
+
return tokenProperties;
|
|
671
|
+
} catch (error) {
|
|
672
|
+
console.error("Failed to fetch token properties:", error);
|
|
673
|
+
throw error;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
function getCachedTokenProperties() {
|
|
677
|
+
return tokenCache;
|
|
678
|
+
}
|
|
679
|
+
function clearTokenCache() {
|
|
680
|
+
tokenCache = null;
|
|
681
|
+
}
|
|
682
|
+
async function formatBalanceWithTokenProperties(balance) {
|
|
683
|
+
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
|
+
});
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// src/chain/singleton.ts
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
// src/chain/wsProvider.ts
|
|
700
|
+
|
|
701
|
+
var provider = new (0, _api2.WsProvider)(PALLIORA_WS, 1e4);
|
|
702
|
+
|
|
703
|
+
// src/chain/singleton.ts
|
|
704
|
+
|
|
705
|
+
var wsProvider = null;
|
|
706
|
+
var api = null;
|
|
707
|
+
var keyring = null;
|
|
708
|
+
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() {
|
|
825
|
+
if (!provider) return;
|
|
826
|
+
console.debug(provider.endpoint);
|
|
827
|
+
if (!api) {
|
|
828
|
+
api = await _api2.ApiPromise.create({
|
|
829
|
+
provider,
|
|
830
|
+
rpc: API_RPC,
|
|
831
|
+
types: API_TYPES,
|
|
832
|
+
signedExtensions: API_EXTENSIONS
|
|
833
|
+
});
|
|
834
|
+
}
|
|
835
|
+
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) {
|
|
838
|
+
api.on("error", (err) => {
|
|
839
|
+
console.error("api error, will restart:", err);
|
|
840
|
+
process.exit(0);
|
|
841
|
+
});
|
|
842
|
+
api.on("disconnected", () => {
|
|
843
|
+
console.error("api disconnected, will restart.");
|
|
844
|
+
process.exit(0);
|
|
845
|
+
});
|
|
846
|
+
}
|
|
847
|
+
return api;
|
|
848
|
+
}
|
|
849
|
+
async function getKeyring() {
|
|
850
|
+
if (!keyring) {
|
|
851
|
+
await _wasmcrypto.waitReady.call(void 0, );
|
|
852
|
+
keyring = new (0, _api2.Keyring)({ type: "sr25519" });
|
|
853
|
+
keyring.addFromUri("//Bob", { name: "Bob default" });
|
|
854
|
+
}
|
|
855
|
+
return keyring;
|
|
856
|
+
}
|
|
857
|
+
async function getEncKeyring() {
|
|
858
|
+
if (!encKeyring) {
|
|
859
|
+
await _wasmcrypto.waitReady.call(void 0, );
|
|
860
|
+
encKeyring = new (0, _api2.Keyring)({ type: "ed25519" });
|
|
861
|
+
encKeyring.addFromUri("//Bob", { name: "Bob default (enc)" });
|
|
862
|
+
}
|
|
863
|
+
return encKeyring;
|
|
864
|
+
}
|
|
865
|
+
var apiInstance = null;
|
|
866
|
+
function getRpcApi() {
|
|
867
|
+
if (!apiInstance) {
|
|
868
|
+
apiInstance = new RpcApi();
|
|
869
|
+
}
|
|
870
|
+
return apiInstance;
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
// src/chain/utils.ts
|
|
874
|
+
|
|
875
|
+
var _bs58 = require('bs58'); var _bs582 = _interopRequireDefault(_bs58);
|
|
876
|
+
|
|
877
|
+
// src/guardian/active.ts
|
|
878
|
+
|
|
879
|
+
var getGuardianList = async () => {
|
|
880
|
+
const api2 = await getApi();
|
|
881
|
+
if (!api2) throw new Error("API not initialized");
|
|
882
|
+
const rpc = api2.rpc;
|
|
883
|
+
const section = "guardian";
|
|
884
|
+
const method = "guardianList";
|
|
885
|
+
assert(
|
|
886
|
+
_util.isFunction.call(void 0, _optionalChain([rpc, 'access', _38 => _38[section], 'optionalAccess', _39 => _39[method]])),
|
|
887
|
+
`api.rpc.${section}.${method} does not exist`
|
|
888
|
+
);
|
|
889
|
+
const list = (await rpc[section]["guardianList"]()).map((item) => [item.toString()]).flat(1);
|
|
890
|
+
return list;
|
|
891
|
+
};
|
|
892
|
+
|
|
893
|
+
// src/guardian/group.ts
|
|
894
|
+
var createGuardianGroup = async (account, selectedGuardians) => {
|
|
895
|
+
try {
|
|
896
|
+
const api2 = await getApi();
|
|
897
|
+
assert(selectedGuardians.length >= 3, "Not enough guardians available to create a group");
|
|
898
|
+
assert(account, "Failed to load account");
|
|
899
|
+
assert(api2, "Failed to initialize API");
|
|
900
|
+
const tau_params = await getGuardianNwParams();
|
|
901
|
+
assert(tau_params && tau_params !== "", "Failed to retrieve guardian network parameters");
|
|
902
|
+
debugLog(`Selected guardians: ${selectedGuardians.join(", ")} and tau_params: ${tau_params}`);
|
|
903
|
+
const tx = api2.tx.dataAvailability.daccGuardianGroup(
|
|
904
|
+
selectedGuardians,
|
|
905
|
+
Array.from(hexToUint8Array(tau_params))
|
|
906
|
+
// Use the new helper function
|
|
907
|
+
);
|
|
908
|
+
const result = await signAndSend(tx, account);
|
|
909
|
+
debugLog("Guardian group created:", result);
|
|
910
|
+
} catch (error) {
|
|
911
|
+
console.error("Error creating guardian group:", error);
|
|
912
|
+
throw new Error(`Failed to create guardian group: ${error instanceof Error ? error.message : error}`);
|
|
913
|
+
}
|
|
914
|
+
};
|
|
915
|
+
|
|
916
|
+
// src/guardian/join.ts
|
|
917
|
+
async function joinGuardian(account, prefs) {
|
|
918
|
+
const api2 = await getApi();
|
|
919
|
+
assert(api2, "API not initialized");
|
|
920
|
+
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;
|
|
922
|
+
const guardianPrefs = {
|
|
923
|
+
pubKey: account.publicKey,
|
|
924
|
+
guardian: prefs.standard,
|
|
925
|
+
verifier: prefs.verifier,
|
|
926
|
+
compute: prefs.compute ? true : false,
|
|
927
|
+
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
|
+
}
|
|
934
|
+
};
|
|
935
|
+
debugLog(
|
|
936
|
+
account.address,
|
|
937
|
+
"joining as guardian with preferences:",
|
|
938
|
+
guardianPrefs
|
|
939
|
+
);
|
|
940
|
+
const guardTx = api2.tx.staking.guard(guardianPrefs);
|
|
941
|
+
const hash = await signAndSend(guardTx, account);
|
|
942
|
+
debugLog("Guardian join tx sent with hash:", hash.hash);
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
// src/chain/utils.ts
|
|
946
|
+
var signAndSend = async (request, account, opts = DEFAULT_COMPUTE_PAYLOAD) => {
|
|
947
|
+
const tx_result = await new Promise((res, err) => {
|
|
948
|
+
request.signAndSend(account, opts, (result) => {
|
|
949
|
+
if (result.isFinalized) {
|
|
950
|
+
res(result);
|
|
951
|
+
}
|
|
952
|
+
if (!TX_WAIT_FINALIZATION && result.isInBlock) {
|
|
953
|
+
res(result);
|
|
954
|
+
}
|
|
955
|
+
if (result.isError) err(result);
|
|
956
|
+
});
|
|
957
|
+
});
|
|
958
|
+
if (tx_result.isError) {
|
|
959
|
+
throw new Error(`Transaction failed with error: ${tx_result.error}`);
|
|
960
|
+
}
|
|
961
|
+
if (tx_result.dispatchError) {
|
|
962
|
+
throw new Error(
|
|
963
|
+
`Transaction dispatched with error: ${tx_result.dispatchError}`
|
|
964
|
+
);
|
|
965
|
+
}
|
|
966
|
+
console.debug(
|
|
967
|
+
`Transaction ${tx_result.txHash.toHex()} included in timepoint ${tx_result.blockNumber}-${tx_result.txIndex}`
|
|
968
|
+
);
|
|
969
|
+
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]),
|
|
972
|
+
hash: tx_result.txHash.toHex(),
|
|
973
|
+
tx_result
|
|
974
|
+
};
|
|
975
|
+
};
|
|
976
|
+
var getFileMetadataCall = async (api2, metadataRef) => {
|
|
977
|
+
const block = await getBlock(api2, metadataRef[0]);
|
|
978
|
+
const call = block.block.extrinsics[metadataRef[1]];
|
|
979
|
+
return call.method;
|
|
980
|
+
};
|
|
981
|
+
var getBlock = async (api2, blockNumber) => {
|
|
982
|
+
const blockHash = await api2.rpc.chain.getBlockHash(blockNumber);
|
|
983
|
+
return await api2.rpc.chain.getBlock(blockHash);
|
|
984
|
+
};
|
|
985
|
+
var getGuardianAddress = async () => {
|
|
986
|
+
const api2 = await getApi();
|
|
987
|
+
if (!api2) throw new Error("API not initialized");
|
|
988
|
+
assert(
|
|
989
|
+
_util.isFunction.call(void 0, _optionalChain([api2, 'access', _61 => _61.query, 'access', _62 => _62["guardian"], 'optionalAccess', _63 => _63["worker"]])),
|
|
990
|
+
`api.query.guardian.worker does not exist`
|
|
991
|
+
);
|
|
992
|
+
const list = await getGuardianList();
|
|
993
|
+
const addresses = await Promise.all(
|
|
994
|
+
list.map(async (item) => {
|
|
995
|
+
const peerid = _bs582.default.decode(item).slice(0, 32);
|
|
996
|
+
return (await api2.query["guardian"]["worker"](peerid)).toString();
|
|
997
|
+
})
|
|
998
|
+
);
|
|
999
|
+
return list.map((peerid, index) => ({ peerid, address: addresses[index] }));
|
|
1000
|
+
};
|
|
1001
|
+
var getGuardianNwParams = async () => {
|
|
1002
|
+
try {
|
|
1003
|
+
const api2 = await getApi();
|
|
1004
|
+
if (!api2) throw new Error("API not initialized");
|
|
1005
|
+
const rpc = api2.rpc;
|
|
1006
|
+
const section = "guardian";
|
|
1007
|
+
const method = "guardianNwParams";
|
|
1008
|
+
assert(
|
|
1009
|
+
_util.isFunction.call(void 0, _optionalChain([rpc, 'access', _64 => _64[section], 'optionalAccess', _65 => _65[method]])),
|
|
1010
|
+
`api.rpc.${section}.guardianNwParams does not exist`
|
|
1011
|
+
);
|
|
1012
|
+
const guardianNwParams = await rpc[section][method]();
|
|
1013
|
+
if (typeof guardianNwParams === "object" && guardianNwParams !== null && "kzg" in guardianNwParams) {
|
|
1014
|
+
return guardianNwParams.kzg.toHex().slice(2);
|
|
1015
|
+
} else {
|
|
1016
|
+
throw new Error(`Invalid ${guardianNwParams} format`);
|
|
1017
|
+
}
|
|
1018
|
+
} catch (error) {
|
|
1019
|
+
console.error({ error });
|
|
1020
|
+
throw error;
|
|
1021
|
+
}
|
|
1022
|
+
};
|
|
1023
|
+
|
|
1024
|
+
// src/chain/onchainfs.ts
|
|
1025
|
+
var getBlock2 = async (api2, blockNumber) => {
|
|
1026
|
+
const blockHash = await api2.rpc.chain.getBlockHash(blockNumber);
|
|
1027
|
+
return await api2.rpc.chain.getBlock(blockHash);
|
|
1028
|
+
};
|
|
1029
|
+
var getFileMetadataCall2 = async (api2, metadataRef) => {
|
|
1030
|
+
const block = await getBlock2(api2, metadataRef[0]);
|
|
1031
|
+
const call = block.block.extrinsics[metadataRef[1]];
|
|
1032
|
+
return call.method;
|
|
1033
|
+
};
|
|
1034
|
+
var getFileMetadata = async (api2, metadataRef) => {
|
|
1035
|
+
const call = await getFileMetadataCall2(api2, metadataRef);
|
|
1036
|
+
const name = new TextDecoder().decode(call.args[0]);
|
|
1037
|
+
const description = new TextDecoder().decode(call.args[1]);
|
|
1038
|
+
const startRef = [call.args[2][0].toNumber(), call.args[2][1].toNumber()];
|
|
1039
|
+
return {
|
|
1040
|
+
name,
|
|
1041
|
+
description,
|
|
1042
|
+
startRef
|
|
1043
|
+
};
|
|
1044
|
+
};
|
|
1045
|
+
async function getFileSHA256(file) {
|
|
1046
|
+
const buffer = new Array(12).fill(8);
|
|
1047
|
+
const hashArray = Array.from(new Uint8Array(buffer));
|
|
1048
|
+
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
1049
|
+
return hashHex;
|
|
1050
|
+
}
|
|
1051
|
+
var readDataFromChain = async (api2, dataRef) => {
|
|
1052
|
+
const call = await getFileMetadataCall2(api2, dataRef);
|
|
1053
|
+
return call.args[0].toU8a();
|
|
1054
|
+
};
|
|
1055
|
+
var MCryptFs = class _MCryptFs {
|
|
1056
|
+
constructor(mcryptApi, metadataRef, metadata) {
|
|
1057
|
+
this._api = mcryptApi;
|
|
1058
|
+
this._metaRef = metadataRef;
|
|
1059
|
+
this._metadata = metadata;
|
|
1060
|
+
this._init = true;
|
|
1061
|
+
}
|
|
1062
|
+
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
|
+
});
|
|
1067
|
+
}
|
|
1068
|
+
isValid() {
|
|
1069
|
+
if (!this._metaRef) {
|
|
1070
|
+
throw new Error("Metadata reference not set");
|
|
1071
|
+
}
|
|
1072
|
+
if (!this._metadata || !this._metadata.name || !this._metadata.description || !this._metadata.startRef) {
|
|
1073
|
+
throw new Error("Metadata not set properly");
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
getMetadata() {
|
|
1077
|
+
this.isValid();
|
|
1078
|
+
return this._metadata;
|
|
1079
|
+
}
|
|
1080
|
+
};
|
|
1081
|
+
var MCryptFsWriter = class {
|
|
1082
|
+
constructor(fileOptions, chunkSize = 500, mcryptApi, account) {
|
|
1083
|
+
const {
|
|
1084
|
+
file: iFile,
|
|
1085
|
+
filePath,
|
|
1086
|
+
fileName,
|
|
1087
|
+
description,
|
|
1088
|
+
baseCost,
|
|
1089
|
+
ownerL2Address,
|
|
1090
|
+
guardianInfo
|
|
1091
|
+
} = fileOptions;
|
|
1092
|
+
this._file = iFile;
|
|
1093
|
+
this._filePath = filePath;
|
|
1094
|
+
this._description = description;
|
|
1095
|
+
this._fileName = fileName;
|
|
1096
|
+
this._baseCost = baseCost;
|
|
1097
|
+
this._fileKey = "";
|
|
1098
|
+
this._ownerL2Address = ownerL2Address;
|
|
1099
|
+
this._guardianInfo = guardianInfo;
|
|
1100
|
+
this._chunkSize = chunkSize * 1024;
|
|
1101
|
+
this._api = mcryptApi;
|
|
1102
|
+
this._account = account;
|
|
1103
|
+
this._chunkRefs = [];
|
|
1104
|
+
this._blockNumber = 0;
|
|
1105
|
+
this._extrinsicIndex = 0;
|
|
1106
|
+
this._progress = {
|
|
1107
|
+
iFileSize: iFile.size,
|
|
1108
|
+
iBlocksWritten: 0
|
|
1109
|
+
};
|
|
1110
|
+
this._error = null;
|
|
1111
|
+
}
|
|
1112
|
+
prependMetadata(chunk) {
|
|
1113
|
+
const blockNumberBuffer = new ArrayBuffer(4);
|
|
1114
|
+
const blockView = new DataView(blockNumberBuffer);
|
|
1115
|
+
blockView.setUint32(0, this._blockNumber, false);
|
|
1116
|
+
const extIndexBuffer = new ArrayBuffer(4);
|
|
1117
|
+
const extView = new DataView(extIndexBuffer);
|
|
1118
|
+
extView.setUint32(0, this._extrinsicIndex, false);
|
|
1119
|
+
return new Blob([blockNumberBuffer, extIndexBuffer, chunk]);
|
|
1120
|
+
}
|
|
1121
|
+
async writeChunk(chunk) {
|
|
1122
|
+
const request = this._api.tx.dataAvailability.submitData(
|
|
1123
|
+
Array.from(new Uint8Array(await chunk.arrayBuffer()))
|
|
1124
|
+
);
|
|
1125
|
+
console.log("account: ", this._account);
|
|
1126
|
+
return new Promise((resolve) => {
|
|
1127
|
+
request.signAndSend(this._account, { app_id: 1 }, (result) => {
|
|
1128
|
+
if (result.isInBlock || result.isFinalized || result.isError) {
|
|
1129
|
+
resolve({
|
|
1130
|
+
blockNumber: _optionalChain([result, 'access', _66 => _66.blockNumber, 'optionalAccess', _67 => _67.toNumber, 'call', _68 => _68()]),
|
|
1131
|
+
index: result.txIndex
|
|
1132
|
+
});
|
|
1133
|
+
}
|
|
1134
|
+
});
|
|
1135
|
+
});
|
|
1136
|
+
}
|
|
1137
|
+
async submitKey(account, data) {
|
|
1138
|
+
const { encoded: encryptedKey, ikm } = testCrypt(this._guardianInfo.tauParams, this._guardianInfo.aggKey);
|
|
1139
|
+
const td_params = uint8ArrayToBase64(hexToUint8Array(encryptedKey));
|
|
1140
|
+
const shared_key = gen_stretched_key(
|
|
1141
|
+
hexToUint8Array(ikm)
|
|
1142
|
+
);
|
|
1143
|
+
const { ciphertext, nonce } = encrypt2(
|
|
1144
|
+
new Uint8Array(Uint8Array.from(data)),
|
|
1145
|
+
shared_key
|
|
1146
|
+
);
|
|
1147
|
+
const blobRef = this._chunkRefs[this._chunkRefs.length - 1];
|
|
1148
|
+
const modelSubmit = JSON.stringify({
|
|
1149
|
+
nonce: uint8ArrayToBase64(Uint8Array.from(nonce)),
|
|
1150
|
+
ciphertext: uint8ArrayToBase64(Uint8Array.from(ciphertext)),
|
|
1151
|
+
td_params,
|
|
1152
|
+
group_pk: this._guardianInfo.groupPk,
|
|
1153
|
+
tau_params: this._guardianInfo.tau_params,
|
|
1154
|
+
chosen_guardians: this._guardianInfo.guardians,
|
|
1155
|
+
blobRef: [blobRef.blockNumber, blobRef.extrinsicIndex]
|
|
1156
|
+
});
|
|
1157
|
+
const request = this._api.tx.dataAvailability.submitData(modelSubmit);
|
|
1158
|
+
return await signAndSend(request, account);
|
|
1159
|
+
}
|
|
1160
|
+
async writeMetadata() {
|
|
1161
|
+
const encoder = new TextEncoder();
|
|
1162
|
+
const fileName = this._fileName;
|
|
1163
|
+
const datasetRef = await this.submitKey(this._account, this._fileKey);
|
|
1164
|
+
const keyRef = [datasetRef.blockNumber, datasetRef.index];
|
|
1165
|
+
const request = this._api.tx.dataAvailability.daccRegisterData(
|
|
1166
|
+
Array.from(new TextEncoder().encode(fileName)),
|
|
1167
|
+
Array.from(new TextEncoder().encode(this._description)),
|
|
1168
|
+
keyRef,
|
|
1169
|
+
this._baseCost,
|
|
1170
|
+
0,
|
|
1171
|
+
Array.from(encoder.encode(this._ownerL2Address)),
|
|
1172
|
+
this._guardianInfo.groupId
|
|
1173
|
+
);
|
|
1174
|
+
return await signAndSend(request, this._account);
|
|
1175
|
+
}
|
|
1176
|
+
async writeFile() {
|
|
1177
|
+
const chunks = [];
|
|
1178
|
+
let offset = 0;
|
|
1179
|
+
while (offset < this._file.size) {
|
|
1180
|
+
const chunk = this._file.slice(offset, offset + this._chunkSize);
|
|
1181
|
+
const prependedChunk = this.prependMetadata(chunk);
|
|
1182
|
+
const blockInfo = await this.writeChunk(prependedChunk);
|
|
1183
|
+
this._blockNumber = blockInfo.blockNumber;
|
|
1184
|
+
this._extrinsicIndex = blockInfo.index;
|
|
1185
|
+
this._progress.iBlocksWritten += chunk.size;
|
|
1186
|
+
this._chunkRefs.push({
|
|
1187
|
+
blockNumber: this._blockNumber,
|
|
1188
|
+
extrinsicIndex: this._extrinsicIndex
|
|
1189
|
+
});
|
|
1190
|
+
offset += this._chunkSize;
|
|
1191
|
+
}
|
|
1192
|
+
this._fileKey = await getFileSHA256(this._file);
|
|
1193
|
+
const metadataRef = await this.writeMetadata();
|
|
1194
|
+
return await FileFromMetadataRef(this._api, [
|
|
1195
|
+
metadataRef.blockNumber,
|
|
1196
|
+
metadataRef.index
|
|
1197
|
+
]);
|
|
1198
|
+
}
|
|
1199
|
+
};
|
|
1200
|
+
var MCryptFsReader = class {
|
|
1201
|
+
constructor(filename, mcryptApi, onChainFile) {
|
|
1202
|
+
this._filename = filename;
|
|
1203
|
+
this._api = mcryptApi;
|
|
1204
|
+
this._onChainFile = onChainFile;
|
|
1205
|
+
}
|
|
1206
|
+
async downloadFile() {
|
|
1207
|
+
const chunks = [];
|
|
1208
|
+
let _blockNumber = this._onChainFile._metadata.startRef[0];
|
|
1209
|
+
let _extIndex = this._onChainFile._metadata.startRef[1];
|
|
1210
|
+
while (_blockNumber !== 0) {
|
|
1211
|
+
const prependedChunk = await readDataFromChain(this._api, [
|
|
1212
|
+
_blockNumber,
|
|
1213
|
+
_extIndex
|
|
1214
|
+
]);
|
|
1215
|
+
const chunk = prependedChunk.slice(12);
|
|
1216
|
+
chunks.push(chunk);
|
|
1217
|
+
const view = new DataView(new Uint8Array(prependedChunk).buffer);
|
|
1218
|
+
_blockNumber = view.getUint32(4);
|
|
1219
|
+
_extIndex = view.getUint32(8);
|
|
1220
|
+
}
|
|
1221
|
+
const blob = new Blob(chunks.reverse());
|
|
1222
|
+
const url = URL.createObjectURL(blob);
|
|
1223
|
+
const a = document.createElement("a");
|
|
1224
|
+
a.href = url;
|
|
1225
|
+
a.download = this._filename;
|
|
1226
|
+
document.body.appendChild(a);
|
|
1227
|
+
a.click();
|
|
1228
|
+
document.body.removeChild(a);
|
|
1229
|
+
URL.revokeObjectURL(url);
|
|
1230
|
+
return blob;
|
|
1231
|
+
}
|
|
1232
|
+
};
|
|
1233
|
+
var FileFromMetadataRef = async (mcryptApi, metadataRef) => {
|
|
1234
|
+
const metadata = await getFileMetadata(mcryptApi, metadataRef);
|
|
1235
|
+
return new MCryptFs(mcryptApi, metadataRef, metadata);
|
|
1236
|
+
};
|
|
1237
|
+
|
|
1238
|
+
// src/compute/agreement.ts
|
|
1239
|
+
|
|
1240
|
+
async function createAgreement() {
|
|
1241
|
+
const api2 = await getApi();
|
|
1242
|
+
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
|
+
});
|
|
1252
|
+
if (!tx_result.isError) {
|
|
1253
|
+
const agreementCreatedEvent = tx_result.events.find((event) => {
|
|
1254
|
+
return event.event.section === "compute" && event.event.method === "AgreementCreated";
|
|
1255
|
+
});
|
|
1256
|
+
if (agreementCreatedEvent) {
|
|
1257
|
+
debugLog(
|
|
1258
|
+
"Agreement data:",
|
|
1259
|
+
agreementCreatedEvent.event.data.toString()
|
|
1260
|
+
);
|
|
1261
|
+
} else {
|
|
1262
|
+
debugLog("AgreementCreated event not found");
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
// src/compute/participants.ts
|
|
1268
|
+
|
|
1269
|
+
async function getGuardianParticipants() {
|
|
1270
|
+
const api2 = await getApi();
|
|
1271
|
+
if (!api2) throw new Error("Api not initialized");
|
|
1272
|
+
try {
|
|
1273
|
+
const guardians = await api2.query.guardian.guardians();
|
|
1274
|
+
const nextGuardians = await api2.query.guardian.nextGuardians();
|
|
1275
|
+
const currentEra = await api2.query.staking.currentEra();
|
|
1276
|
+
const currentIndex = await api2.query.guardian.currentIndex();
|
|
1277
|
+
const peerid = await api2.rpc.system.localPeerId();
|
|
1278
|
+
const _peerid = _bs582.default.decode((peerid || "").toString());
|
|
1279
|
+
const account = await api2.query.guardian.worker(_peerid.slice(0, 32));
|
|
1280
|
+
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()]) || [];
|
|
1283
|
+
const buildDetails = async (list) => {
|
|
1284
|
+
return Promise.all(
|
|
1285
|
+
list.map(async (guardian) => {
|
|
1286
|
+
const guardianPrefs = await api2.query.staking.guardians(guardian);
|
|
1287
|
+
const ledger = await api2.query.staking.ledger(guardian);
|
|
1288
|
+
const bonded = await api2.query.staking.bonded(guardian);
|
|
1289
|
+
const payee = await api2.query.staking.payee(guardian);
|
|
1290
|
+
const stakersOverview = await api2.query.staking.erasStakersOverview(
|
|
1291
|
+
_optionalChain([currentEra, 'optionalAccess', _73 => _73.toPrimitive, 'call', _74 => _74()]),
|
|
1292
|
+
guardian
|
|
1293
|
+
);
|
|
1294
|
+
const guardianErasPrefs = await api2.query.staking.erasGuardianPrefs(
|
|
1295
|
+
_optionalChain([currentEra, 'optionalAccess', _75 => _75.toPrimitive, 'call', _76 => _76()]),
|
|
1296
|
+
guardian
|
|
1297
|
+
);
|
|
1298
|
+
return {
|
|
1299
|
+
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
|
|
1306
|
+
};
|
|
1307
|
+
})
|
|
1308
|
+
);
|
|
1309
|
+
};
|
|
1310
|
+
const currentGuardians = await buildDetails(guardiansList);
|
|
1311
|
+
const upcomingGuardians = await buildDetails(nextGuardiansList);
|
|
1312
|
+
return {
|
|
1313
|
+
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,
|
|
1320
|
+
nextIndex
|
|
1321
|
+
},
|
|
1322
|
+
currentGuardians,
|
|
1323
|
+
upcomingGuardians
|
|
1324
|
+
};
|
|
1325
|
+
} finally {
|
|
1326
|
+
api2.disconnect();
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
// src/crypto/random.ts
|
|
1331
|
+
function generateRandomBytes(length = 32) {
|
|
1332
|
+
const bytes = new Uint8Array(length);
|
|
1333
|
+
const cr = globalThis.crypto;
|
|
1334
|
+
if (!cr || typeof cr.getRandomValues !== "function") {
|
|
1335
|
+
throw new Error(
|
|
1336
|
+
"crypto.getRandomValues is not available. Ensure you're running in a supported environment (browser or Node.js 18+)."
|
|
1337
|
+
);
|
|
1338
|
+
}
|
|
1339
|
+
cr.getRandomValues(bytes);
|
|
1340
|
+
return bytes;
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
// src/da/register.ts
|
|
1344
|
+
async function writeMetadata(account, name, description, ref, price, dataType, l2Owner, groupId) {
|
|
1345
|
+
const blobRef = [ref.blockNumber, ref.index];
|
|
1346
|
+
const encoder = new TextEncoder();
|
|
1347
|
+
const nameBytes = Array.from(encoder.encode(name));
|
|
1348
|
+
const descriptionBytes = Array.from(encoder.encode(description));
|
|
1349
|
+
const ownerBytes = Array.from(encoder.encode(l2Owner));
|
|
1350
|
+
const api2 = await getApi();
|
|
1351
|
+
assert(api2, "Failed to get API connection");
|
|
1352
|
+
const request = api2.tx.dataAvailability.daccRegisterData(
|
|
1353
|
+
nameBytes,
|
|
1354
|
+
descriptionBytes,
|
|
1355
|
+
blobRef,
|
|
1356
|
+
price,
|
|
1357
|
+
dataType,
|
|
1358
|
+
ownerBytes,
|
|
1359
|
+
groupId
|
|
1360
|
+
);
|
|
1361
|
+
const hash = await signAndSend(request, account);
|
|
1362
|
+
debugLog(`Metadata registration transaction sent with hash: ${hash.hash}`);
|
|
1363
|
+
return hash;
|
|
1364
|
+
}
|
|
1365
|
+
|
|
1366
|
+
// src/da/submit.ts
|
|
1367
|
+
async function submitData(account, data) {
|
|
1368
|
+
const api2 = await getApi();
|
|
1369
|
+
assert(api2, "API not initialized");
|
|
1370
|
+
debugLog(`
|
|
1371
|
+
Submitting data with content length: ${data.length}`);
|
|
1372
|
+
const tx = api2.tx.dataAvailability.submitData(data);
|
|
1373
|
+
const hash = await signAndSend(tx, account, DEFAULT_EMPTY_PAYLOAD);
|
|
1374
|
+
debugLog(`Data availability transaction sent with hash: ${hash.hash}`);
|
|
1375
|
+
}
|
|
1376
|
+
async function submitTEData(account, data, chosenGuardians, tau_params, agg_key, group_pk) {
|
|
1377
|
+
const { encoded: encryptedKey, ikm } = testCrypt(tau_params, agg_key);
|
|
1378
|
+
const td_params = uint8ArrayToBase64(hexToUint8Array(encryptedKey));
|
|
1379
|
+
const shared_key = gen_stretched_key(hexToUint8Array(ikm));
|
|
1380
|
+
const encoder = new TextEncoder();
|
|
1381
|
+
const dataUint8Array = encoder.encode(data);
|
|
1382
|
+
const { ciphertext, nonce } = encrypt2(dataUint8Array, shared_key);
|
|
1383
|
+
const modelSubmit = JSON.stringify({
|
|
1384
|
+
nonce: uint8ArrayToBase64(nonce),
|
|
1385
|
+
ciphertext: uint8ArrayToBase64(ciphertext),
|
|
1386
|
+
td_params,
|
|
1387
|
+
group_pk: Array.from(new Uint8Array(hexToUint8Array(group_pk))),
|
|
1388
|
+
tau_params: Array.from(new Uint8Array(hexToUint8Array(tau_params))),
|
|
1389
|
+
chosen_guardians: chosenGuardians
|
|
1390
|
+
});
|
|
1391
|
+
const api2 = await getApi();
|
|
1392
|
+
assert(api2, "Failed to get API connection");
|
|
1393
|
+
const request = await api2.tx.dataAvailability.submitData(modelSubmit);
|
|
1394
|
+
const hash = await signAndSend(request, account, DEFAULT_EMPTY_PAYLOAD);
|
|
1395
|
+
debugLog(`TE data availability transaction sent with hash: ${hash.hash}`);
|
|
1396
|
+
return hash;
|
|
1397
|
+
}
|
|
1398
|
+
|
|
1399
|
+
// src/da/upload.ts
|
|
1400
|
+
var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
|
|
1401
|
+
var _path = require('path'); var _path2 = _interopRequireDefault(_path);
|
|
1402
|
+
async function uploadData(options) {
|
|
1403
|
+
const { name, description, price, type, guardianGroupInfo, ref, filePath } = options;
|
|
1404
|
+
assert(
|
|
1405
|
+
guardianGroupInfo.guardians && guardianGroupInfo.tauParams && guardianGroupInfo.aggKey && guardianGroupInfo.groupPk,
|
|
1406
|
+
"Guardian group info is missing required properties"
|
|
1407
|
+
);
|
|
1408
|
+
const account = (await getKeyring()).pairs[0];
|
|
1409
|
+
const ethAddress = "";
|
|
1410
|
+
if (type === "dataset" && filePath) {
|
|
1411
|
+
const fileContent = _fs2.default.readFileSync(filePath);
|
|
1412
|
+
const selectedFile = new File([fileContent], _path2.default.basename(filePath), {
|
|
1413
|
+
type: "application/octet-stream",
|
|
1414
|
+
lastModified: Date.now()
|
|
1415
|
+
});
|
|
1416
|
+
const msCryptFsWriter = new MCryptFsWriter(
|
|
1417
|
+
{
|
|
1418
|
+
file: selectedFile,
|
|
1419
|
+
fileName: selectedFile.name,
|
|
1420
|
+
filePath: "",
|
|
1421
|
+
description,
|
|
1422
|
+
baseCost: BigInt(Number(price) * 10 ** 18),
|
|
1423
|
+
ownerL2Address: ethAddress,
|
|
1424
|
+
guardianInfo: guardianGroupInfo
|
|
1425
|
+
},
|
|
1426
|
+
500,
|
|
1427
|
+
await getApi(),
|
|
1428
|
+
account
|
|
1429
|
+
);
|
|
1430
|
+
await msCryptFsWriter.writeFile();
|
|
1431
|
+
} else {
|
|
1432
|
+
const dataRef = await submitTEData(
|
|
1433
|
+
account,
|
|
1434
|
+
ref || "",
|
|
1435
|
+
guardianGroupInfo.guardians,
|
|
1436
|
+
guardianGroupInfo.tauParams,
|
|
1437
|
+
guardianGroupInfo.aggKey,
|
|
1438
|
+
guardianGroupInfo.groupPk
|
|
1439
|
+
);
|
|
1440
|
+
const dtype = type === "model" ? 1 : type === "agent" ? 2 : 0;
|
|
1441
|
+
await writeMetadata(
|
|
1442
|
+
account,
|
|
1443
|
+
name,
|
|
1444
|
+
description,
|
|
1445
|
+
dataRef,
|
|
1446
|
+
BigInt(Number(price) * 10 ** 18),
|
|
1447
|
+
dtype,
|
|
1448
|
+
ethAddress,
|
|
1449
|
+
guardianGroupInfo.groupId
|
|
1450
|
+
);
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
// src/stake/add.ts
|
|
1455
|
+
async function addStake(account, amount) {
|
|
1456
|
+
const api2 = await getApi();
|
|
1457
|
+
assert(api2, "API not initialized");
|
|
1458
|
+
assert(account, "Account not initialized");
|
|
1459
|
+
debugLog("Using account:", account.address);
|
|
1460
|
+
const stakeTx = api2.tx.staking.bondExtra(amount);
|
|
1461
|
+
const hash = await signAndSend(stakeTx, account);
|
|
1462
|
+
debugLog(`Stake transaction sent with hash: ${hash.hash}`);
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
// src/stake/idle.ts
|
|
1466
|
+
async function joinIdleStaker(account) {
|
|
1467
|
+
const api2 = await getApi();
|
|
1468
|
+
assert(api2, "API not initialized");
|
|
1469
|
+
assert(account, "Account not initialized");
|
|
1470
|
+
const chillTx = api2.tx.staking.chill();
|
|
1471
|
+
const hash = await signAndSend(chillTx, account);
|
|
1472
|
+
debugLog("Idle staker chill tx sent with hash:", hash.hash);
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
// src/stake/new.ts
|
|
1476
|
+
async function newStake(account, amount, rewardDestination = "Staked") {
|
|
1477
|
+
const api2 = await getApi();
|
|
1478
|
+
assert(api2, "API not initialized");
|
|
1479
|
+
assert(account, "Account not initialized");
|
|
1480
|
+
debugLog(
|
|
1481
|
+
`Staking amount: ${amount} for account: ${account.address} with reward destination: ${rewardDestination}`
|
|
1482
|
+
);
|
|
1483
|
+
const stakeTx = api2.tx.staking.bond(amount, rewardDestination);
|
|
1484
|
+
const hash = await signAndSend(stakeTx, account);
|
|
1485
|
+
debugLog(`Stake transaction sent with hash: ${hash.hash}`);
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
// src/stake/payout.ts
|
|
1489
|
+
async function payoutStake(account, eras, address) {
|
|
1490
|
+
const api2 = await getApi();
|
|
1491
|
+
assert(api2, "API not initialized");
|
|
1492
|
+
assert(account, "Account not initialized");
|
|
1493
|
+
for (const era of eras) {
|
|
1494
|
+
debugLog("Paying account: ", address || account.address, " for era ", era);
|
|
1495
|
+
}
|
|
1496
|
+
const unstakeTxs = eras.map(
|
|
1497
|
+
(era) => api2.tx.staking.payoutStakers(address || account.address, era)
|
|
1498
|
+
);
|
|
1499
|
+
const batchTx = api2.tx.utility.batch(unstakeTxs);
|
|
1500
|
+
const hash = await signAndSend(batchTx, account);
|
|
1501
|
+
debugLog(`Batch payout transaction sent with hash: ${hash.hash}`);
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
// src/stake/reduce.ts
|
|
1505
|
+
async function reduceStake(account, amount) {
|
|
1506
|
+
const api2 = await getApi();
|
|
1507
|
+
assert(api2, "API not initialized");
|
|
1508
|
+
assert(account, "Account not initialized");
|
|
1509
|
+
debugLog("Using account:", account.address);
|
|
1510
|
+
const unstakeTx = api2.tx.staking.unbond(amount);
|
|
1511
|
+
const hash = await signAndSend(unstakeTx, account);
|
|
1512
|
+
debugLog(`Unstake transaction sent with hash: ${hash.hash}`);
|
|
1513
|
+
}
|
|
1514
|
+
|
|
1515
|
+
// src/stake/remove.ts
|
|
1516
|
+
async function removeStake(account) {
|
|
1517
|
+
const api2 = await getApi();
|
|
1518
|
+
assert(api2, "API not initialized");
|
|
1519
|
+
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);
|
|
1523
|
+
const hash = await signAndSend(unstakeTx, account);
|
|
1524
|
+
debugLog(`Unstake transaction sent with hash: ${hash.hash}`);
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
// src/stake/withdraw.ts
|
|
1528
|
+
async function withdrawStake(account) {
|
|
1529
|
+
const api2 = await getApi();
|
|
1530
|
+
assert(api2, "API not initialized");
|
|
1531
|
+
assert(account, "Account not initialized");
|
|
1532
|
+
const unstakeTx = api2.tx.staking.withdrawUnbonded(0);
|
|
1533
|
+
const hash = await signAndSend(unstakeTx, account);
|
|
1534
|
+
debugLog(`Unstake transaction sent with hash: ${hash.hash}`);
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
// src/token/fund.ts
|
|
1538
|
+
async function fundAccount(account, amount, address) {
|
|
1539
|
+
const addr = address ? address : account.address;
|
|
1540
|
+
const keyring2 = await getKeyring();
|
|
1541
|
+
const api2 = await getApi();
|
|
1542
|
+
assert(api2, "API not initialized");
|
|
1543
|
+
debugLog(`
|
|
1544
|
+
Funding account: ${addr} with amount: ${amount}`);
|
|
1545
|
+
const tx = api2.tx.balances.transferKeepAlive(addr, amount);
|
|
1546
|
+
const hash = await signAndSend(tx, keyring2.getPairs()[0]);
|
|
1547
|
+
debugLog(`Fund transaction sent with hash: ${hash.hash}`);
|
|
1548
|
+
}
|
|
1549
|
+
|
|
1550
|
+
// src/token/transfer.ts
|
|
1551
|
+
async function transfer(account, amount, address) {
|
|
1552
|
+
const api2 = await getApi();
|
|
1553
|
+
assert(api2, "API not initialized");
|
|
1554
|
+
debugLog(`
|
|
1555
|
+
Transferring funds to account: ${address} with amount: ${amount}`);
|
|
1556
|
+
const tx = api2.tx.balances.transferKeepAlive(address, amount);
|
|
1557
|
+
const hash = await signAndSend(tx, account);
|
|
1558
|
+
debugLog(`Transfer transaction sent with hash: ${hash.hash}`);
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
// src/validator/join.ts
|
|
1562
|
+
async function joinValidator(account, commission) {
|
|
1563
|
+
const api2 = await getApi();
|
|
1564
|
+
assert(api2, "API not initialized");
|
|
1565
|
+
assert(account, "Account not initialized");
|
|
1566
|
+
const validateTx = api2.tx.staking.validate({ commission, blocked: true });
|
|
1567
|
+
const hash = await signAndSend(validateTx, account);
|
|
1568
|
+
debugLog("Validator join tx sent with hash:", hash.hash);
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
// src/identity.ts
|
|
1572
|
+
var _assert = require('assert'); var _assert2 = _interopRequireDefault(_assert);
|
|
1573
|
+
async function setIdentity(account, { display = void 0 }) {
|
|
1574
|
+
const api2 = await getApi();
|
|
1575
|
+
_assert2.default.call(void 0, api2, "API not initialized");
|
|
1576
|
+
debugLog(`
|
|
1577
|
+
Setting identity for account: ${account.address} as ${display}`);
|
|
1578
|
+
const tx = api2.tx.identity.setIdentity({ display: { Raw: display } });
|
|
1579
|
+
const hash = await signAndSend(tx, account);
|
|
1580
|
+
debugLog(`Set identity transaction sent with hash: ${hash.hash}`);
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
// src/rotateKeys.ts
|
|
1584
|
+
|
|
1585
|
+
|
|
1586
|
+
async function rotateAndSetKeys(account) {
|
|
1587
|
+
const api2 = await getApi();
|
|
1588
|
+
_assert2.default.call(void 0, api2, "API not initialized");
|
|
1589
|
+
debugLog(`Rotating session keys for ${account.meta.name} on ${provider.endpoint}`);
|
|
1590
|
+
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)));
|
|
1592
|
+
const setKeysTx = api2.tx.session.setKeys(newKeys, []);
|
|
1593
|
+
const hash = await signAndSend(setKeysTx, account);
|
|
1594
|
+
debugLog(`Rotate session transaction sent with hash: ${hash.hash}`);
|
|
1595
|
+
}
|
|
1596
|
+
async function setWorker(account) {
|
|
1597
|
+
const api2 = await getApi();
|
|
1598
|
+
_assert2.default.call(void 0, api2, "API not initialized");
|
|
1599
|
+
const peerid = _bs582.default.decode((await api2.rpc.system.localPeerId()).toString());
|
|
1600
|
+
const setWorkerTx = api2.tx.guardian.setWorker(peerid.slice(0, 32));
|
|
1601
|
+
const hash = await signAndSend(setWorkerTx, account);
|
|
1602
|
+
debugLog(`Set worker id transaction sent with hash: ${hash.hash}`);
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
// src/index.ts
|
|
1606
|
+
|
|
1607
|
+
|
|
1608
|
+
|
|
1609
|
+
|
|
1610
|
+
|
|
1611
|
+
|
|
1612
|
+
|
|
1613
|
+
|
|
1614
|
+
|
|
1615
|
+
|
|
1616
|
+
|
|
1617
|
+
|
|
1618
|
+
|
|
1619
|
+
|
|
1620
|
+
|
|
1621
|
+
|
|
1622
|
+
|
|
1623
|
+
|
|
1624
|
+
|
|
1625
|
+
|
|
1626
|
+
|
|
1627
|
+
|
|
1628
|
+
|
|
1629
|
+
|
|
1630
|
+
|
|
1631
|
+
|
|
1632
|
+
|
|
1633
|
+
|
|
1634
|
+
|
|
1635
|
+
|
|
1636
|
+
|
|
1637
|
+
|
|
1638
|
+
|
|
1639
|
+
|
|
1640
|
+
|
|
1641
|
+
|
|
1642
|
+
|
|
1643
|
+
|
|
1644
|
+
|
|
1645
|
+
|
|
1646
|
+
|
|
1647
|
+
|
|
1648
|
+
|
|
1649
|
+
|
|
1650
|
+
|
|
1651
|
+
|
|
1652
|
+
|
|
1653
|
+
|
|
1654
|
+
|
|
1655
|
+
|
|
1656
|
+
|
|
1657
|
+
|
|
1658
|
+
|
|
1659
|
+
|
|
1660
|
+
|
|
1661
|
+
|
|
1662
|
+
|
|
1663
|
+
|
|
1664
|
+
|
|
1665
|
+
|
|
1666
|
+
|
|
1667
|
+
|
|
1668
|
+
|
|
1669
|
+
|
|
1670
|
+
|
|
1671
|
+
|
|
1672
|
+
|
|
1673
|
+
|
|
1674
|
+
|
|
1675
|
+
|
|
1676
|
+
|
|
1677
|
+
|
|
1678
|
+
|
|
1679
|
+
|
|
1680
|
+
|
|
1681
|
+
|
|
1682
|
+
|
|
1683
|
+
|
|
1684
|
+
|
|
1685
|
+
|
|
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;
|
|
1687
|
+
//# sourceMappingURL=index.cjs.map
|