@aboutcircles/sdk-invitations 0.1.18 → 0.1.19
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/Invitations.d.ts +16 -9
- package/dist/Invitations.d.ts.map +1 -1
- package/dist/Invitations.js +58 -29
- package/dist/index.js +3 -3
- package/package.json +1 -1
package/dist/Invitations.d.ts
CHANGED
|
@@ -16,7 +16,16 @@ export declare class Invitations {
|
|
|
16
16
|
private hubV2;
|
|
17
17
|
private referralsModule;
|
|
18
18
|
private invitationFarm;
|
|
19
|
+
private invitationModuleContract;
|
|
19
20
|
constructor(config: CirclesConfig);
|
|
21
|
+
/**
|
|
22
|
+
* Check if the inviter has the invitation module enabled on their Safe
|
|
23
|
+
* and is trusted by the invitation module. Returns setup transactions if needed.
|
|
24
|
+
*
|
|
25
|
+
* @param inviter - Address of the inviter (Safe wallet)
|
|
26
|
+
* @returns Array of setup transactions (enableModule + trustInviter) needed before inviting
|
|
27
|
+
*/
|
|
28
|
+
ensureInviterSetup(inviter: Address): Promise<TransactionRequest[]>;
|
|
20
29
|
/**
|
|
21
30
|
* Save referral data to the referrals service
|
|
22
31
|
*
|
|
@@ -96,21 +105,19 @@ export declare class Invitations {
|
|
|
96
105
|
*
|
|
97
106
|
* @param inviter - Address of the inviter
|
|
98
107
|
* @returns Array of real inviters with their addresses and possible number of invitations
|
|
99
|
-
* @throws InvitationError if inviter has not enabled the invitation module
|
|
100
108
|
*
|
|
101
109
|
* @description
|
|
102
110
|
* This function:
|
|
103
111
|
* 1. Gets all addresses that trust the inviter (set1) - includes both one-way trusts and mutual trusts
|
|
104
112
|
* 2. Gets all addresses trusted by the invitation module (set2) - includes both one-way trusts and mutual trusts
|
|
105
113
|
* 3. Gets all addresses trusted by the gnosis group (set3) - these will be excluded
|
|
106
|
-
* 4.
|
|
107
|
-
* 5.
|
|
108
|
-
* 6.
|
|
109
|
-
* 7.
|
|
110
|
-
* 8.
|
|
111
|
-
* 9.
|
|
112
|
-
* 10.
|
|
113
|
-
* 11. Returns only those token owners whose total amounts exceed the invitation fee (96 CRC)
|
|
114
|
+
* 4. Finds the intersection of set1 and set2, excluding addresses in set3
|
|
115
|
+
* 5. Adds the inviter's own address to the list of possible tokens
|
|
116
|
+
* 6. Builds a path from inviter to invitation module using intersection addresses as toTokens
|
|
117
|
+
* 7. Sums up transferred token amounts by tokenOwner
|
|
118
|
+
* 8. Calculates possible invites (1 invite = 96 CRC)
|
|
119
|
+
* 9. Orders real inviters by preference (best candidates first)
|
|
120
|
+
* 10. Returns only those token owners whose total amounts exceed the invitation fee (96 CRC)
|
|
114
121
|
*/
|
|
115
122
|
getRealInviters(inviter: Address): Promise<ProxyInviter[]>;
|
|
116
123
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Invitations.d.ts","sourceRoot":"","sources":["../src/Invitations.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAO,MAAM,yBAAyB,CAAC;
|
|
1
|
+
{"version":3,"file":"Invitations.d.ts","sourceRoot":"","sources":["../src/Invitations.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAO,MAAM,yBAAyB,CAAC;AAU/F,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAkBnD,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,OAAO,CAAC;IACjB,eAAe,EAAE,MAAM,CAAC;CACzB;AAOD;;;GAGG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,MAAM,CAAgB;IAC9B,OAAO,CAAC,SAAS,CAAY;IAC7B,OAAO,CAAC,UAAU,CAAoB;IACtC,OAAO,CAAC,KAAK,CAAe;IAC5B,OAAO,CAAC,KAAK,CAAuB;IACpC,OAAO,CAAC,eAAe,CAAiC;IACxD,OAAO,CAAC,cAAc,CAAgC;IACtD,OAAO,CAAC,wBAAwB,CAAkC;gBAEtD,MAAM,EAAE,aAAa;IA8BjC;;;;;;OAMG;IACG,kBAAkB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,kBAAkB,EAAE,CAAC;IA2BzE;;;;;;;;OAQG;IACG,gBAAgB,CACpB,OAAO,EAAE,OAAO,EAChB,UAAU,EAAE,KAAK,MAAM,EAAE,GACxB,OAAO,CAAC,IAAI,CAAC;IA+BhB;;;;;;;OAOG;IACG,aAAa,CACjB,OAAO,EAAE,OAAO,EAChB,KAAK,GAAE,MAAW,EAClB,MAAM,GAAE,MAAU,GACjB,OAAO,CAAC,mBAAmB,CAAC;IAiC/B;;;;;;;;;;OAUG;IACH,OAAO,CAAC,iBAAiB;IAezB;;;;;;;;;;;;;;;;;OAiBG;IACG,cAAc,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,kBAAkB,EAAE,CAAC;IA2FvF;;;;;;;;;;;OAWG;IACG,cAAc,CAAC,OAAO,EAAE,OAAO,EAAE,mBAAmB,CAAC,EAAE,OAAO;IAiDpE;;;;;;;;;OASG;IACG,kBAAkB,CAAC,OAAO,EAAE,OAAO;IAkCzC;;;;;;;;;;;;;;;;;;OAkBG;IACG,eAAe,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;IA6GhE;;;;;;;;;;;;;;;;;OAiBG;IACG,gBAAgB,CACpB,OAAO,EAAE,OAAO,GACf,OAAO,CAAC;QAAE,YAAY,EAAE,kBAAkB,EAAE,CAAC;QAAC,UAAU,EAAE,KAAK,MAAM,EAAE,CAAA;KAAE,CAAC;IA0F7E;;;;;;;;;;;;;OAaG;IACG,kBAAkB,CAAC,SAAS,EAAE,OAAO,EAAE,EAAE,eAAe,GAAE,OAAc,GAAG,OAAO,CAAC,KAAK,MAAM,EAAE,CAAC;IA8CvG;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,cAAc,CAAC,MAAM,EAAE,OAAO,GAAG,OAAO;IA8BxC;;;OAGG;IACH,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,CAAC;QAAE,MAAM,EAAE,KAAK,MAAM,EAAE,CAAC;QAAC,MAAM,EAAE,OAAO,CAAA;KAAE,CAAC;CAOlF"}
|
package/dist/Invitations.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { RpcClient, PathfinderMethods, TrustMethods } from '@aboutcircles/sdk-rpc';
|
|
2
|
-
import { HubV2ContractMinimal, ReferralsModuleContractMinimal, InvitationFarmContractMinimal } from '@aboutcircles/sdk-core/minimal';
|
|
2
|
+
import { HubV2ContractMinimal, ReferralsModuleContractMinimal, InvitationFarmContractMinimal, SafeContractMinimal, InvitationModuleContractMinimal } from '@aboutcircles/sdk-core/minimal';
|
|
3
3
|
import { InvitationError } from './errors';
|
|
4
4
|
import { TransferBuilder } from '@aboutcircles/sdk-transfers';
|
|
5
5
|
import { hexToBytes, INVITATION_FEE, MAX_FLOW, generatePrivateKey, privateKeyToAddress, encodeAbiParameters, keccak256, SAFE_PROXY_FACTORY, ACCOUNT_INITIALIZER_HASH, ACCOUNT_CREATION_CODE_HASH, checksumAddress, GNOSIS_GROUP_ADDRESS, FARM_DESTINATION } from '@aboutcircles/sdk-utils';
|
|
@@ -19,6 +19,7 @@ export class Invitations {
|
|
|
19
19
|
hubV2;
|
|
20
20
|
referralsModule;
|
|
21
21
|
invitationFarm;
|
|
22
|
+
invitationModuleContract;
|
|
22
23
|
constructor(config) {
|
|
23
24
|
if (!config.referralsServiceUrl) {
|
|
24
25
|
throw new InvitationError('referralsServiceUrl is required in config', {
|
|
@@ -43,6 +44,41 @@ export class Invitations {
|
|
|
43
44
|
address: config.invitationFarmAddress,
|
|
44
45
|
rpcUrl: config.circlesRpcUrl,
|
|
45
46
|
});
|
|
47
|
+
this.invitationModuleContract = new InvitationModuleContractMinimal({
|
|
48
|
+
address: config.invitationModuleAddress,
|
|
49
|
+
rpcUrl: config.circlesRpcUrl,
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Check if the inviter has the invitation module enabled on their Safe
|
|
54
|
+
* and is trusted by the invitation module. Returns setup transactions if needed.
|
|
55
|
+
*
|
|
56
|
+
* @param inviter - Address of the inviter (Safe wallet)
|
|
57
|
+
* @returns Array of setup transactions (enableModule + trustInviter) needed before inviting
|
|
58
|
+
*/
|
|
59
|
+
async ensureInviterSetup(inviter) {
|
|
60
|
+
const inviterLower = inviter.toLowerCase();
|
|
61
|
+
const moduleAddress = this.config.invitationModuleAddress;
|
|
62
|
+
const setupTxs = [];
|
|
63
|
+
// Check if invitation module is enabled on the inviter's Safe
|
|
64
|
+
const safeContract = new SafeContractMinimal({
|
|
65
|
+
address: inviterLower,
|
|
66
|
+
rpcUrl: this.config.circlesRpcUrl,
|
|
67
|
+
});
|
|
68
|
+
const moduleEnabled = await safeContract.isModuleEnabled(moduleAddress);
|
|
69
|
+
if (!moduleEnabled) {
|
|
70
|
+
setupTxs.push(safeContract.enableModule(moduleAddress));
|
|
71
|
+
// Module wasn't enabled so inviter can't be trusted yet — add trustInviter tx
|
|
72
|
+
setupTxs.push(this.invitationModuleContract.trustInviter(inviterLower));
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
// Module is enabled — check if the invitation module trusts the inviter
|
|
76
|
+
const inviterTrusted = await this.hubV2.isTrusted(moduleAddress, inviterLower);
|
|
77
|
+
if (!inviterTrusted) {
|
|
78
|
+
setupTxs.push(this.invitationModuleContract.trustInviter(inviterLower));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return setupTxs;
|
|
46
82
|
}
|
|
47
83
|
/**
|
|
48
84
|
* Save referral data to the referrals service
|
|
@@ -168,9 +204,11 @@ export class Invitations {
|
|
|
168
204
|
if (isHuman) {
|
|
169
205
|
throw InvitationError.inviteeAlreadyRegistered(inviterLower, inviteeLower);
|
|
170
206
|
}
|
|
171
|
-
// Step 2:
|
|
207
|
+
// Step 2: Ensure inviter has module enabled and is trusted
|
|
208
|
+
const setupTxs = await this.ensureInviterSetup(inviterLower);
|
|
209
|
+
// Step 3: Try to find proxy inviters
|
|
172
210
|
const realInviters = await this.getRealInviters(inviterLower);
|
|
173
|
-
const transactions = [];
|
|
211
|
+
const transactions = [...setupTxs];
|
|
174
212
|
if (realInviters.length > 0) {
|
|
175
213
|
// Standard path: use proxy inviters
|
|
176
214
|
console.log('[generateInvite] Using STANDARD PATH (proxy inviters available)');
|
|
@@ -292,21 +330,19 @@ export class Invitations {
|
|
|
292
330
|
*
|
|
293
331
|
* @param inviter - Address of the inviter
|
|
294
332
|
* @returns Array of real inviters with their addresses and possible number of invitations
|
|
295
|
-
* @throws InvitationError if inviter has not enabled the invitation module
|
|
296
333
|
*
|
|
297
334
|
* @description
|
|
298
335
|
* This function:
|
|
299
336
|
* 1. Gets all addresses that trust the inviter (set1) - includes both one-way trusts and mutual trusts
|
|
300
337
|
* 2. Gets all addresses trusted by the invitation module (set2) - includes both one-way trusts and mutual trusts
|
|
301
338
|
* 3. Gets all addresses trusted by the gnosis group (set3) - these will be excluded
|
|
302
|
-
* 4.
|
|
303
|
-
* 5.
|
|
304
|
-
* 6.
|
|
305
|
-
* 7.
|
|
306
|
-
* 8.
|
|
307
|
-
* 9.
|
|
308
|
-
* 10.
|
|
309
|
-
* 11. Returns only those token owners whose total amounts exceed the invitation fee (96 CRC)
|
|
339
|
+
* 4. Finds the intersection of set1 and set2, excluding addresses in set3
|
|
340
|
+
* 5. Adds the inviter's own address to the list of possible tokens
|
|
341
|
+
* 6. Builds a path from inviter to invitation module using intersection addresses as toTokens
|
|
342
|
+
* 7. Sums up transferred token amounts by tokenOwner
|
|
343
|
+
* 8. Calculates possible invites (1 invite = 96 CRC)
|
|
344
|
+
* 9. Orders real inviters by preference (best candidates first)
|
|
345
|
+
* 10. Returns only those token owners whose total amounts exceed the invitation fee (96 CRC)
|
|
310
346
|
*/
|
|
311
347
|
async getRealInviters(inviter) {
|
|
312
348
|
console.log('[getRealInviters] Finding valid proxy inviters for:', inviter);
|
|
@@ -342,16 +378,7 @@ export class Invitations {
|
|
|
342
378
|
}
|
|
343
379
|
else {
|
|
344
380
|
}
|
|
345
|
-
// Step 4:
|
|
346
|
-
const inviterTrustedByModule = trustedByModule.has(inviterLower);
|
|
347
|
-
if (!inviterTrustedByModule) {
|
|
348
|
-
throw new InvitationError('Inviter must enable the invitation module before creating invitations', {
|
|
349
|
-
code: 'INVITATION_MODULE_NOT_ENABLED',
|
|
350
|
-
source: 'INVITATIONS',
|
|
351
|
-
context: { inviter: inviterLower, invitationModule: this.config.invitationModuleAddress }
|
|
352
|
-
});
|
|
353
|
-
}
|
|
354
|
-
// Step 5: Find intersection - addresses that trust inviter AND are trusted by invitation module
|
|
381
|
+
// Step 4: Find intersection - addresses that trust inviter AND are trusted by invitation module
|
|
355
382
|
// AND are NOT trusted by the gnosis group
|
|
356
383
|
const intersection = [];
|
|
357
384
|
for (const address of trustedByInviter) {
|
|
@@ -359,7 +386,7 @@ export class Invitations {
|
|
|
359
386
|
intersection.push(address);
|
|
360
387
|
}
|
|
361
388
|
}
|
|
362
|
-
// Step
|
|
389
|
+
// Step 5: Add the inviter's own address to the list of possible tokens
|
|
363
390
|
const tokensToUse = [...intersection];
|
|
364
391
|
const inviterExcluded = trustedByGnosisGroup.has(inviterLower);
|
|
365
392
|
if (!inviterExcluded) {
|
|
@@ -369,7 +396,7 @@ export class Invitations {
|
|
|
369
396
|
if (tokensToUse.length === 0) {
|
|
370
397
|
return [];
|
|
371
398
|
}
|
|
372
|
-
// Step
|
|
399
|
+
// Step 6: Build path from inviter to invitation module
|
|
373
400
|
const path = await this.pathfinder.findPath({
|
|
374
401
|
from: inviterLower,
|
|
375
402
|
to: this.config.invitationModuleAddress,
|
|
@@ -380,7 +407,7 @@ export class Invitations {
|
|
|
380
407
|
if (!path.transfers || path.transfers.length === 0) {
|
|
381
408
|
return [];
|
|
382
409
|
}
|
|
383
|
-
// Step
|
|
410
|
+
// Step 7: Sum up transferred token amounts by tokenOwner (only terminal transfers to invitation module)
|
|
384
411
|
const tokenOwnerAmounts = new Map();
|
|
385
412
|
const invitationModuleLower = this.config.invitationModuleAddress.toLowerCase();
|
|
386
413
|
for (const transfer of path.transfers) {
|
|
@@ -391,7 +418,7 @@ export class Invitations {
|
|
|
391
418
|
tokenOwnerAmounts.set(tokenOwnerLower, currentAmount + transfer.value);
|
|
392
419
|
}
|
|
393
420
|
}
|
|
394
|
-
// Step
|
|
421
|
+
// Step 8: Calculate possible invites and filter token owners
|
|
395
422
|
const realInviters = [];
|
|
396
423
|
for (const [tokenOwner, amount] of tokenOwnerAmounts.entries()) {
|
|
397
424
|
const possibleInvites = Number(amount / INVITATION_FEE);
|
|
@@ -402,7 +429,7 @@ export class Invitations {
|
|
|
402
429
|
});
|
|
403
430
|
}
|
|
404
431
|
}
|
|
405
|
-
// Step
|
|
432
|
+
// Step 9: Order real inviters by preference (best candidates first)
|
|
406
433
|
const orderedRealInviters = this.orderRealInviters(realInviters, inviterLower);
|
|
407
434
|
console.log('[getRealInviters] Final result:', orderedRealInviters.length, 'valid proxy inviters');
|
|
408
435
|
for (const ri of orderedRealInviters) {
|
|
@@ -432,9 +459,11 @@ export class Invitations {
|
|
|
432
459
|
// Step 1: Generate private key and derive signer address
|
|
433
460
|
const privateKey = generatePrivateKey();
|
|
434
461
|
const signerAddress = privateKeyToAddress(privateKey);
|
|
435
|
-
// Step 2:
|
|
462
|
+
// Step 2: Ensure inviter has module enabled and is trusted
|
|
463
|
+
const setupTxs = await this.ensureInviterSetup(inviterLower);
|
|
464
|
+
// Step 3: Get real inviters (filtered by gnosis group)
|
|
436
465
|
const realInviters = await this.getRealInviters(inviterLower);
|
|
437
|
-
const transactions = [];
|
|
466
|
+
const transactions = [...setupTxs];
|
|
438
467
|
if (realInviters.length > 0) {
|
|
439
468
|
// Standard path: use proxy inviters
|
|
440
469
|
console.log('[generateReferral] Using STANDARD PATH (proxy inviters available)');
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
Context: ${JSON.stringify(this.context,null,2)}`;return $}}class a extends J${constructor($,J){super("RpcError",$,{...J,source:J?.source??"RPC_REQUEST"})}static connectionFailed($,J){return new a("Failed to connect to RPC endpoint",{code:"RPC_CONNECTION_FAILED",source:"RPC_CONNECTION",cause:J,context:{url:$}})}static timeout($,J){return new a("RPC request timed out",{code:"RPC_TIMEOUT",source:"RPC_TIMEOUT",context:{method:$,timeout:J}})}static invalidResponse($,J){return new a("Invalid RPC response",{code:"RPC_INVALID_RESPONSE",source:"RPC_RESPONSE",context:{method:$,response:J}})}static fromJsonRpcError($){return new a($.message,{code:$.code,source:"RPC_RESPONSE",context:{data:$.data}})}static websocketError($,J){return new a($,{code:"RPC_WEBSOCKET_ERROR",source:"RPC_WEBSOCKET",cause:J})}}class R0{rpcUrl;requestId=0;websocket=null;websocketConnected=!1;pendingResponses={};subscriptionListeners={};reconnectAttempt=0;initialBackoff=2000;maxBackoff=120000;constructor($){this.rpcUrl=$}async call($,J){this.requestId++;let Q={jsonrpc:"2.0",id:this.requestId,method:$,params:J};try{let Y=await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)});if(!Y.ok)throw a.connectionFailed(this.rpcUrl,Error(`HTTP ${Y.status}: ${Y.statusText}`));let G=await Y.json();if(G.error)throw a.fromJsonRpcError(G.error);if(G.result===void 0)throw a.invalidResponse($,G);return G.result}catch(Y){if(Y instanceof a)throw Y;throw a.connectionFailed(this.rpcUrl,Y)}}setRpcUrl($){this.rpcUrl=$}getRpcUrl(){return this.rpcUrl}connect(){return new Promise(($)=>{let J=this.rpcUrl.replace("http","ws");if(J.endsWith("/"))J+="ws";else J+="/ws";this.websocket=new WebSocket(J),this.websocket.onopen=()=>{console.log("WebSocket connected"),this.websocketConnected=!0,this.reconnectAttempt=0,$()},this.websocket.onmessage=(Q)=>{let Y=JSON.parse(Q.data),{id:G,method:Z,params:K}=Y;if(G!==void 0&&this.pendingResponses[G])this.pendingResponses[G].resolve(Y),delete this.pendingResponses[G];if(Z==="eth_subscription"&&K){let{subscription:X,result:q}=K;if(this.subscriptionListeners[X])this.subscriptionListeners[X].forEach((M)=>M(q))}},this.websocket.onclose=()=>{console.warn("WebSocket closed"),this.websocketConnected=!1},this.websocket.onerror=(Q)=>{console.error("WebSocket error:",Q),this.websocketConnected=!1,this.scheduleReconnect()}})}scheduleReconnect(){let $=Math.min(this.initialBackoff*Math.pow(2,this.reconnectAttempt),this.maxBackoff),J=$*(Math.random()*0.5),Q=$+J;console.log(`Reconnecting in ${Math.round(Q)}ms (attempt #${this.reconnectAttempt+1})`),this.reconnectAttempt++,setTimeout(()=>{this.reconnect()},Q)}async reconnect(){if(this.websocketConnected)return;try{await this.connect(),console.log("Reconnection successful")}catch($){console.error("Reconnection attempt failed:",$),this.scheduleReconnect()}}sendMessage($,J,Q=5000){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return Promise.reject(a.connectionFailed(this.rpcUrl));let Y=this.requestId++,G={jsonrpc:"2.0",method:$,params:J,id:Y};return new Promise((Z,K)=>{this.pendingResponses[Y]={resolve:Z,reject:K},this.websocket.send(JSON.stringify(G)),setTimeout(()=>{if(this.pendingResponses[Y])this.pendingResponses[Y].reject(a.timeout($,Q)),delete this.pendingResponses[Y]},Q)})}async subscribe($){let J=$?.toLowerCase();if(!this.websocketConnected)await this.connect();let Q=u0.create(),Y=JSON.stringify(J?{address:J}:{}),Z=(await this.sendMessage("eth_subscribe",["circles",Y])).result;if(!this.subscriptionListeners[Z])this.subscriptionListeners[Z]=[];return this.subscriptionListeners[Z].push((K)=>{O$(K).forEach((X)=>Q.emit(X))}),Q.property}}var R$=BigInt(4294967295),EJ=BigInt(32);function y8($,J=!1){if(J)return{h:Number($&R$),l:Number($>>EJ&R$)};return{h:Number($>>EJ&R$)|0,l:Number($&R$)|0}}function kJ($,J=!1){let Q=$.length,Y=new Uint32Array(Q),G=new Uint32Array(Q);for(let Z=0;Z<Q;Z++){let{h:K,l:X}=y8($[Z],J);[Y[Z],G[Z]]=[K,X]}return[Y,G]}var AJ=($,J,Q)=>$<<Q|J>>>32-Q,wJ=($,J,Q)=>J<<Q|$>>>32-Q,yJ=($,J,Q)=>J<<Q-32|$>>>64-Q,bJ=($,J,Q)=>$<<Q-32|J>>>64-Q;var I0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function b8($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function T0($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function K0($,...J){if(!b8($))throw Error("Uint8Array expected");if(J.length>0&&!J.includes($.length))throw Error("Uint8Array expected of length "+J+", got length="+$.length)}function FJ($){if(typeof $!=="function"||typeof $.create!=="function")throw Error("Hash should be wrapped by utils.createHasher");T0($.outputLen),T0($.blockLen)}function M0($,J=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(J&&$.finished)throw Error("Hash#digest() has already been called")}function C$($,J){K0($);let Q=J.outputLen;if($.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function gJ($){return new Uint32Array($.buffer,$.byteOffset,Math.floor($.byteLength/4))}function X0(...$){for(let J=0;J<$.length;J++)$[J].fill(0)}function P$($){return new DataView($.buffer,$.byteOffset,$.byteLength)}function Z0($,J){return $<<32-J|$>>>J}var F8=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function g8($){return $<<24&4278190080|$<<8&16711680|$>>>8&65280|$>>>24&255}function f8($){for(let J=0;J<$.length;J++)$[J]=g8($[J]);return $}var h$=F8?($)=>$:f8;function v8($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function _0($){if(typeof $==="string")$=v8($);return K0($),$}function fJ(...$){let J=0;for(let Y=0;Y<$.length;Y++){let G=$[Y];K0(G),J+=G.length}let Q=new Uint8Array(J);for(let Y=0,G=0;Y<$.length;Y++){let Z=$[Y];Q.set(Z,G),G+=Z.length}return Q}class x0{}function B$($){let J=(Y)=>$().update(_0(Y)).digest(),Q=$();return J.outputLen=Q.outputLen,J.blockLen=Q.blockLen,J.create=()=>$(),J}function vJ($=32){if(I0&&typeof I0.getRandomValues==="function")return I0.getRandomValues(new Uint8Array($));if(I0&&typeof I0.randomBytes==="function")return Uint8Array.from(I0.randomBytes($));throw Error("crypto.getRandomValues must be defined")}var h8=BigInt(0),Q$=BigInt(1),m8=BigInt(2),u8=BigInt(7),c8=BigInt(256),l8=BigInt(113),uJ=[],cJ=[],lJ=[];for(let $=0,J=Q$,Q=1,Y=0;$<24;$++){[Q,Y]=[Y,(2*Q+3*Y)%5],uJ.push(2*(5*Y+Q)),cJ.push(($+1)*($+2)/2%64);let G=h8;for(let Z=0;Z<7;Z++)if(J=(J<<Q$^(J>>u8)*l8)%c8,J&m8)G^=Q$<<(Q$<<BigInt(Z))-Q$;lJ.push(G)}var pJ=kJ(lJ,!0),p8=pJ[0],d8=pJ[1],hJ=($,J,Q)=>Q>32?yJ($,J,Q):AJ($,J,Q),mJ=($,J,Q)=>Q>32?bJ($,J,Q):wJ($,J,Q);function i8($,J=24){let Q=new Uint32Array(10);for(let Y=24-J;Y<24;Y++){for(let K=0;K<10;K++)Q[K]=$[K]^$[K+10]^$[K+20]^$[K+30]^$[K+40];for(let K=0;K<10;K+=2){let X=(K+8)%10,q=(K+2)%10,M=Q[q],j=Q[q+1],z=hJ(M,j,1)^Q[X],N=mJ(M,j,1)^Q[X+1];for(let D=0;D<50;D+=10)$[K+D]^=z,$[K+D+1]^=N}let G=$[2],Z=$[3];for(let K=0;K<24;K++){let X=cJ[K],q=hJ(G,Z,X),M=mJ(G,Z,X),j=uJ[K];G=$[j],Z=$[j+1],$[j]=q,$[j+1]=M}for(let K=0;K<50;K+=10){for(let X=0;X<10;X++)Q[X]=$[K+X];for(let X=0;X<10;X++)$[K+X]^=~Q[(X+2)%10]&Q[(X+4)%10]}$[0]^=p8[Y],$[1]^=d8[Y]}X0(Q)}class m$ extends x0{constructor($,J,Q,Y=!1,G=24){super();if(this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=$,this.suffix=J,this.outputLen=Q,this.enableXOF=Y,this.rounds=G,T0(Q),!(0<$&&$<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=gJ(this.state)}clone(){return this._cloneInto()}keccak(){h$(this.state32),i8(this.state32,this.rounds),h$(this.state32),this.posOut=0,this.pos=0}update($){M0(this),$=_0($),K0($);let{blockLen:J,state:Q}=this,Y=$.length;for(let G=0;G<Y;){let Z=Math.min(J-this.pos,Y-G);for(let K=0;K<Z;K++)Q[this.pos++]^=$[G++];if(this.pos===J)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:$,suffix:J,pos:Q,blockLen:Y}=this;if($[Q]^=J,(J&128)!==0&&Q===Y-1)this.keccak();$[Y-1]^=128,this.keccak()}writeInto($){M0(this,!1),K0($),this.finish();let J=this.state,{blockLen:Q}=this;for(let Y=0,G=$.length;Y<G;){if(this.posOut>=Q)this.keccak();let Z=Math.min(Q-this.posOut,G-Y);$.set(J.subarray(this.posOut,this.posOut+Z),Y),this.posOut+=Z,Y+=Z}return $}xofInto($){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto($)}xof($){return T0($),this.xofInto(new Uint8Array($))}digestInto($){if(C$($,this),this.finished)throw Error("digest() was already called");return this.writeInto($),this.destroy(),$}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,X0(this.state)}_cloneInto($){let{blockLen:J,suffix:Q,outputLen:Y,rounds:G,enableXOF:Z}=this;return $||($=new m$(J,Q,Y,Z,G)),$.state32.set(this.state32),$.pos=this.pos,$.posOut=this.posOut,$.finished=this.finished,$.rounds=G,$.suffix=Q,$.outputLen=Y,$.enableXOF=Z,$.destroyed=this.destroyed,$}}var n8=($,J,Q)=>B$(()=>new m$(J,$,Q));var c0=(()=>n8(1,136,32))();var dJ=[];for(let $=0;$<256;$++)dJ[$]=$.toString(16).padStart(2,"0");function L$($){let J="0x";for(let Q=0;Q<$.length;Q++)J+=dJ[$[Q]];return J}function H$($){let J=$.startsWith("0x")?$.slice(2):$,Q=new Uint8Array(J.length/2);for(let Y=0;Y<J.length;Y+=2)Q[Y/2]=parseInt(J.slice(Y,Y+2),16);return Q}var u=64,I$=32,S$=($)=>$.startsWith("0x")?$.slice(2):$;var q0=($)=>$.toString(16).padStart(u,"0");function P0($){let J=$.toLowerCase().replace("0x",""),Q=L$(c0(new TextEncoder().encode(J))).slice(2),Y="0x";for(let G=0;G<J.length;G++)Y+=parseInt(Q[G],16)>=8?J[G].toUpperCase():J[G];return Y}function u$($,J){if($==="tuple"&&J)return`(${J.map((G)=>u$(G.type,G.components)).join(",")})`;let Q=$.match(/^tuple(\[\d*\])$/);if(Q&&J)return`${u$("tuple",J)}${Q[1]}`;return $}function o8($){let Q=($.inputs||[]).map((Y)=>u$(Y.type,Y.components));return`${$.name}(${Q.join(",")})`}function t8($){let J=o8($),Q=c0(new TextEncoder().encode(J));return L$(Q.slice(0,4))}function l0($,J){if($==="string"||$==="bytes")return!0;if($.includes("[")){let Q=$.slice(0,$.indexOf("["));if($.endsWith("[]"))return!0;if(Q==="tuple")return iJ(J);return l0(Q)}if($==="tuple")return iJ(J);return!1}function iJ($){return $?.some((J)=>l0(J.type,J.components))??!1}function C0($,J,Q){if($==="tuple"&&Q)return s8(Q,J);if($.includes("["))return a8($,J,Q);return r8($,J)}function a8($,J,Q){let Y=$.slice(0,$.indexOf("[")),G=$.endsWith("[]"),Z=l0(Y,Q),K;if(Z){let X=J.map((j)=>C0(Y,j,Q)),q=J.length*I$;K=X.map((j)=>{let z=q;return q+=j.length/2,q0(z)}).join("")+X.join("")}else K=J.map((X)=>C0(Y,X,Q)).join("");return G?q0(J.length)+K:K}function s8($,J){let Q=Array.isArray(J),Y=[],G=[],Z=[];for(let K=0;K<$.length;K++){let X=$[K],q=Q?J[K]:J[X.name||""],M=l0(X.type,X.components);if(Z.push(M),M)Y.push(""),G.push(C0(X.type,q,X.components));else Y.push(C0(X.type,q,X.components))}if(G.length>0){let K=Y.reduce((M,j,z)=>M+(Z[z]?I$:j.length/2),0),X="",q=0;for(let M=0;M<$.length;M++)if(Z[M])X+=q0(K),K+=G[q].length/2,q++;else X+=Y[M];return X+G.join("")}return Y.join("")}function r8($,J){if($==="address")return S$(J).toLowerCase().padStart(u,"0");if($==="bool")return q0(J?1:0);if($.startsWith("uint")){let Q=typeof J==="bigint"?J:BigInt(J);return q0(Q)}if($.startsWith("int")){let Q=typeof J==="bigint"?J:BigInt(J);if(Q<0n){let Y=$==="int"?256:parseInt($.slice(3));Q=(1n<<BigInt(Y))+Q}return q0(Q)}if($.startsWith("bytes")&&$!=="bytes")return S$(J).padEnd(u,"0");if($==="bytes"){let Q=S$(J),Y=q0(Q.length/2),G=Q.padEnd(Math.ceil(Q.length/u)*u,"0");return Y+G}if($==="string"){let Q=Array.from(new TextEncoder().encode(J)).map((Z)=>Z.toString(16).padStart(2,"0")).join(""),Y=q0(Q.length/2),G=Q.padEnd(Math.ceil(Q.length/u)*u,"0");return Y+G}throw Error(`Unsupported type: ${$}`)}function Y$($,J,Q=0,Y){if($==="tuple"&&Y)return $Q(Y,J,Q);if($.includes("["))return e8($,J,Q,Y);return JQ($,J,Q)}function e8($,J,Q,Y){let G=$.slice(0,$.indexOf("[")),Z=J.slice(Q,Q+u);if($.endsWith("[]")){let X=parseInt(Z,16)*2,q=parseInt(J.slice(X,X+u),16),M=[],j=X+u;for(let z=0;z<q;z++){let N=Y$(G,J,j,Y);M.push(N.value),j+=N.consumed}return{value:M,consumed:u}}let K=$.match(/\[(\d+)\]$/);if(K){let X=parseInt(K[1]),q=[],M=0;for(let j=0;j<X;j++){let z=Y$(G,J,Q+M,Y);q.push(z.value),M+=z.consumed}return{value:q,consumed:M}}throw Error(`Invalid array type: ${$}`)}function $Q($,J,Q){let Y=[],G=Q;for(let Z of $){let K=Y$(Z.type,J,G,Z.components);Y.push(K.value),G+=K.consumed}return{value:Y,consumed:G-Q}}function JQ($,J,Q){let Y=J.slice(Q,Q+u);if($==="address")return{value:P0("0x"+Y.slice(24)),consumed:u};if($==="bool")return{value:parseInt(Y,16)!==0,consumed:u};if($.startsWith("uint"))return{value:BigInt("0x"+Y),consumed:u};if($.startsWith("int")){let G=BigInt("0x"+Y),Z=$==="int"?256:parseInt($.slice(3)),K=1n<<BigInt(Z-1);return{value:G>=K?G-(1n<<BigInt(Z)):G,consumed:u}}if($.startsWith("bytes")&&$!=="bytes"){let G=parseInt($.match(/^bytes(\d+)$/)[1]);return{value:"0x"+Y.slice(0,G*2),consumed:u}}if($==="bytes"){let G=parseInt(Y,16)*2,Z=parseInt(J.slice(G,G+u),16)*2;return{value:"0x"+J.slice(G+u,G+u+Z),consumed:u}}if($==="string"){let G=parseInt(Y,16)*2,Z=parseInt(J.slice(G,G+u),16)*2,K=J.slice(G+u,G+u+Z),X=new Uint8Array(K.match(/.{2}/g)?.map((q)=>parseInt(q,16))||[]);return{value:new TextDecoder().decode(X),consumed:u}}throw Error(`Unsupported type: ${$}`)}function T$($){let{abi:J,functionName:Q,args:Y=[]}=$,G=J.find((D)=>D.type==="function"&&D.name===Q);if(!G)throw Error(`Function "${Q}" not found in ABI`);let Z=t8(G),K=G.inputs||[];if(K.length===0)return Z;if(Y.length!==K.length)throw Error(`Expected ${K.length} arguments, got ${Y.length}`);let X=[],q=[],M=[];for(let D=0;D<K.length;D++){let P=K[D],V=P.components,y=l0(P.type,V);if(M.push(y),y)X.push(""),q.push(C0(P.type,Y[D],V));else X.push(C0(P.type,Y[D],V))}if(q.length===0)return Z+X.join("");let j=X.reduce((D,P,V)=>D+(M[V]?I$:P.length/2),0),z="",N=0;for(let D=0;D<K.length;D++)if(M[D])z+=q0(j),j+=q[N].length/2,N++;else z+=X[D];return Z+z+q.join("")}function c$($){let{abi:J,functionName:Q,data:Y}=$,G=J.find((M)=>M.type==="function"&&M.name===Q);if(!G)throw Error(`Function "${Q}" not found in ABI`);let Z=G.outputs||[];if(Z.length===0)return;let K=S$(Y);if(Z.length===1)return Y$(Z[0].type,K,0,Z[0].components).value;let X=[],q=0;for(let M of Z){let j=Y$(M.type,K,q,M.components);X.push(j.value),q+=j.consumed}return X}function J0($,J){if($.length!==J.length)throw Error(`Type/value length mismatch: ${$.length} types, ${J.length} values`);let Q=[],Y=[],G=[];for(let q=0;q<$.length;q++){let M=$[q],j=l0(M);if(G.push(j),j)Q.push(""),Y.push(C0(M,J[q]));else Q.push(C0(M,J[q]))}if(Y.length===0)return"0x"+Q.join("");let Z=Q.reduce((q,M,j)=>q+(G[j]?I$:M.length/2),0),K="",X=0;for(let q=0;q<$.length;q++)if(G[q])K+=q0(Z),Z+=Y[X].length/2,X++;else K+=Q[q];return"0x"+K+Y.join("")}function B($){return $.toLowerCase()}function QQ($){return P0($)}function YQ($){if(typeof $!=="string")return!1;let J=$.replace("0x","");return J.length===40&&/^[0-9a-fA-F]{40}$/.test(J)}function v($){if($===null||$===void 0)return $;if(YQ($))return QQ($);if(Array.isArray($))return $.map((J)=>v(J));if(typeof $==="object"&&$!==null){let J={};for(let Q in $)if(Object.prototype.hasOwnProperty.call($,Q))J[Q]=v($[Q]);return J}return $}function nJ($){return{Source:B($.from),Sink:B($.to),TargetFlow:$.targetFlow.toString(),WithWrap:$.useWrappedBalances,FromTokens:$.fromTokens?.map(B),ToTokens:$.toTokens?.map(B),ExcludedFromTokens:$.excludeFromTokens?.map(B),ExcludedToTokens:$.excludeToTokens?.map(B),SimulatedBalances:$.simulatedBalances?.map((J)=>({Holder:B(J.holder),Token:B(J.token),Amount:J.amount.toString(),IsWrapped:J.isWrapped,IsStatic:J.isStatic})),SimulatedTrusts:$.simulatedTrusts?.map((J)=>({Truster:B(J.truster),Trustee:B(J.trustee)})),MaxTransfers:$.maxTransfers}}function j0($){let J={};for(let Q in $){let Y=$[Q];if(Y===null||Y===void 0)J[Q]=Y;else if(typeof Y==="string"&&/^\d+$/.test(Y))J[Q]=BigInt(Y);else if(typeof Y==="object"&&!Array.isArray(Y))J[Q]=j0(Y);else if(Array.isArray(Y))J[Q]=Y.map((G)=>typeof G==="object"&&G!==null?j0(G):G);else J[Q]=Y}return J}var _$="0x0000000000000000000000000000000000000000",p=BigInt(96)*BigInt(1000000000000000000),G$=BigInt("9999999999999999999999999999999999999"),l$="0x4e1DCf7AD4e460CfD30791CCC4F9c8a4f820ec67",p$="0x89867a67674bd4bf33165a653cde826b696ab7d050166b71066dfa0b9b6f90f4",d$="0xe298282cefe913ab5d282047161268a8222e4bd4ed106300c547894bbefd31ee",p0="0xc19bc204eb1c1d5b3fe500e5e5dfabab625f286c",E0="0x9Eb51E6A39B3F17bB1883B80748b56170039ff1d";class W0{client;constructor($){this.client=$}async findPath($){let J=nJ($),Q=await this.client.call("circlesV2_findPath",[J]),Y=j0(Q);return v(Y)}async findMaxFlow($){let J=await this.findPath({...$,targetFlow:G$});return BigInt(J.maxFlow)}}class Z${client;constructor($){this.client=$}async query($){let J=await this.client.call("circles_query",[$]);return v(J)}async tables(){return this.client.call("circles_tables",[])}async events($,J,Q=null,Y=null,G=!1){let Z=await this.client.call("circles_events",[$,J,Q,Y,G]);return v(Z)}}var GQ=[{name:"blockNumber",sortOrder:"DESC"},{name:"transactionIndex",sortOrder:"DESC"},{name:"logIndex",sortOrder:"DESC"}];class Q0{params;client;rowTransformer;cursorColumns;orderColumns;get currentPage(){return this._currentPage}_currentPage;constructor($,J,Q){this.client=$,this.params=J,this.rowTransformer=Q||J.rowTransformer,this.orderColumns=J.orderColumns,this.cursorColumns=J.cursorColumns||this.buildEventCursorColumns()}buildEventCursorColumns(){let $=GQ.map((J)=>({...J,sortOrder:this.params.sortOrder}));if(this.params.table==="TransferBatch")$.push({name:"batchIndex",sortOrder:this.params.sortOrder});return $}transformCursorValue($,J){if(J)return J($);if(typeof $==="bigint")return $.toString();return $}createEqualityPredicate($,J){return{Type:"FilterPredicate",FilterType:"Equals",Column:$.name,Value:this.transformCursorValue(J,$.toValue)}}createComparisonPredicate($,J){return{Type:"FilterPredicate",FilterType:$.sortOrder==="ASC"?"GreaterThan":"LessThan",Column:$.name,Value:this.transformCursorValue(J,$.toValue)}}buildCursorFilter($){if(!$)return[];let J=[];for(let Q=0;Q<this.cursorColumns.length;Q++){let Y=this.cursorColumns[Q],G=$[Y.name];if(G===void 0)continue;if(Q===0)J.push(this.createComparisonPredicate(Y,G));else{let Z=[];for(let K=0;K<Q;K++){let X=this.cursorColumns[K],q=$[X.name];if(q!==void 0)Z.push(this.createEqualityPredicate(X,q))}Z.push(this.createComparisonPredicate(Y,G)),J.push({Type:"Conjunction",ConjunctionType:"And",Predicates:Z})}}if(J.length===0)return[];return[{Type:"Conjunction",ConjunctionType:"Or",Predicates:J}]}buildOrderBy(){if(this.orderColumns&&this.orderColumns.length>0)return this.orderColumns;return this.cursorColumns.map(($)=>({Column:$.name,SortOrder:$.sortOrder}))}combineFilters($,J){if(!$?.length&&!J?.length)return[];if(!$?.length)return J||[];if(!J?.length)return $;return[{Type:"Conjunction",ConjunctionType:"And",Predicates:[...$,...J]}]}rowsToObjects($){let{columns:J,rows:Q}=$;return Q.map((Y)=>{let G={};return J.forEach((Z,K)=>{G[Z]=Y[K]}),this.rowTransformer?this.rowTransformer(G):G})}rowToCursor($){let J={};for(let Q of this.cursorColumns)J[Q.name]=$[Q.name];return J}getCursors($){if($.length===0)return{};return{first:this.rowToCursor($[0]),last:this.rowToCursor($[$.length-1])}}async queryNextPage(){let $=this.buildCursorFilter(this._currentPage?.lastCursor),J=this.combineFilters(this.params.filter,$),Q={Namespace:this.params.namespace,Table:this.params.table,Columns:this.params.columns,Filter:J,Order:this.buildOrderBy(),Limit:this.params.limit},Y=await this.client.call("circles_query",[Q]),G=this.rowsToObjects(Y),Z=this.getCursors(G);return this._currentPage={limit:this.params.limit,size:G.length,firstCursor:Z.first,lastCursor:Z.last,sortOrder:this.params.sortOrder,hasMore:G.length===this.params.limit,results:G},G.length>0}reset(){this._currentPage=void 0}}class k0{client;constructor($){this.client=$}transformQueryResponse($){let{columns:J,rows:Q}=$;return Q.map((Y)=>{let G={};return J.forEach((Z,K)=>{G[Z]=Y[K]}),G})}async getCommonTrust($,J){let Q=await this.client.call("circles_getCommonTrust",[B($),B(J)]);return v(Q)}getTrustRelations($,J=100,Q="DESC"){let Y=B($),G=[{Type:"Conjunction",ConjunctionType:"And",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"version",Value:2},{Type:"Conjunction",ConjunctionType:"Or",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"trustee",Value:Y},{Type:"FilterPredicate",FilterType:"Equals",Column:"truster",Value:Y}]}]}];return new Q0(this.client,{namespace:"V_Crc",table:"TrustRelations",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","version","trustee","truster","expiryTime"],filter:G,limit:J},(Z)=>v(Z))}async getAggregatedTrustRelations($){let J=B($),Q=this.getTrustRelations(J,1000),Y=[];while(await Q.queryNextPage())if(Y.push(...Q.currentPage.results),!Q.currentPage.hasMore)break;let G={};Y.forEach((K)=>{let X=B(K.truster),q=B(K.trustee),M=X!==J?K.truster:K.trustee;if(!G[M])G[M]=[];G[M].push(K)});let Z=Object.entries(G).filter(([K])=>B(K)!==J).map(([K,X])=>{let q=Math.max(...X.map((j)=>j.timestamp)),M;if(X.length===2)M="mutuallyTrusts";else if(B(X[0]?.trustee)===J)M="trustedBy";else if(B(X[0]?.truster)===J)M="trusts";else throw Error("Unexpected trust list row. Couldn't determine trust relation.");return{subjectAvatar:J,relation:M,objectAvatar:K,timestamp:q}});return v(Z)}async getTrustedBy($){let J=B($),Y=(await this.getAggregatedTrustRelations(J)).filter((G)=>G.relation==="trustedBy");return v(Y)}async getTrusts($){let J=B($),Y=(await this.getAggregatedTrustRelations(J)).filter((G)=>G.relation==="trusts");return v(Y)}async getMutualTrusts($){let J=B($),Y=(await this.getAggregatedTrustRelations(J)).filter((G)=>G.relation==="mutuallyTrusts");return v(Y)}}class i{static ONE_64=1n<<64n;static GAMMA_64=18443079296116538654n;static BETA_64=18450409579521241655n;static SECONDS_PER_DAY=86400n;static INFLATION_DAY_ZERO_UNIX=1602720000n;static ATTO_FACTOR=1000000000000000000n;static FACTOR_1E12=1000000000000n;static V1_ACCURACY=100000000n;static V1_INFLATION_PCT_NUM=107n;static V1_INFLATION_PCT_DEN=100n;static PERIOD_SEC=31556952n;static mul64($,J){return $*J>>64n}static mulU($,J){return $*J>>64n}static pow64($,J){let Q=$,Y=J,G=this.ONE_64;while(Y>0n){if((Y&1n)===1n)G=this.mul64(G,Q);Q=this.mul64(Q,Q),Y>>=1n}return G}static ONE_36=1000000000000000000000000000000000000000n;static GAMMA_36=999801332008598957430613406568191166n;static BETA_36=1000198707468214629156271489013303962n;static mul36($,J){return $*J/this.ONE_36}static pow36($,J){let Q=this.ONE_36,Y=$,G=J;while(G>0n){if((G&1n)===1n)Q=this.mul36(Q,Y);Y=this.mul36(Y,Y),G>>=1n}return Q}static attoCirclesToCircles($){if($===0n)return 0;let J=$/this.ATTO_FACTOR,Q=$%this.ATTO_FACTOR,Y=BigInt(Number.MAX_SAFE_INTEGER);if(J>Y||J<-Y)throw RangeError("Atto value’s integer component exceeds JS double precision.");return Number(J)+Number(Q)/Number(this.ATTO_FACTOR)}static circlesToAttoCircles($){return BigInt(Math.trunc($*Number(this.ATTO_FACTOR)))}static inflationaryToDemurrage($,J){return this.mulU(this.pow64(this.GAMMA_64,J),$)}static demurrageToInflationary($,J){return this.mulU(this.pow64(this.BETA_64,J),$)}static dayFromTimestamp($){return($-this.INFLATION_DAY_ZERO_UNIX)/this.SECONDS_PER_DAY}static attoCirclesToAttoStaticCircles($,J=BigInt(Math.floor(Date.now()/1000))){return this.demurrageToInflationary($,this.dayFromTimestamp(J))}static attoStaticCirclesToAttoCircles($,J=BigInt(Math.floor(Date.now()/1000))){return this.inflationaryToDemurrage($,this.dayFromTimestamp(J))}static inflationaryToDemurrageExact($,J){let Q=this.pow36(this.GAMMA_36,J);return $*Q/this.ONE_36}static demurrageToInflationaryExact($,J){let Q=this.pow36(this.BETA_36,J);return $*Q/this.ONE_36}static attoCirclesToAttoStaticCirclesExact($,J=BigInt(Math.floor(Date.now()/1000))){let Q=this.dayFromTimestamp(J);return this.demurrageToInflationaryExact($,Q)}static attoStaticCirclesToAttoCirclesExact($,J=BigInt(Math.floor(Date.now()/1000))){let Q=this.dayFromTimestamp(J);return this.inflationaryToDemurrageExact($,Q)}static truncateToInt64($){let J=$/this.FACTOR_1E12,Q=9223372036854775807n;return J>Q?Q:J}static blowUpToBigInt($){return $*this.FACTOR_1E12}static truncateToSixDecimals($){return this.blowUpToBigInt(this.truncateToInt64($))}static v1InflateFactor($){if($===0n)return this.V1_ACCURACY;return this.V1_ACCURACY*this.V1_INFLATION_PCT_NUM**$/this.V1_INFLATION_PCT_DEN**$}static attoCrcToAttoCircles($,J){let Q=J-this.INFLATION_DAY_ZERO_UNIX,Y=Q/this.PERIOD_SEC,G=Q%this.PERIOD_SEC,Z=this.v1InflateFactor(Y),K=this.v1InflateFactor(Y+1n);return this.v1ToDemurrage($,Z,K,G,this.PERIOD_SEC)}static attoCirclesToAttoCrc($,J){let Q=J-this.INFLATION_DAY_ZERO_UNIX,Y=Q/this.PERIOD_SEC,G=Q%this.PERIOD_SEC,Z=this.v1InflateFactor(Y),K=this.v1InflateFactor(Y+1n),X=Z*(this.PERIOD_SEC-G)+K*G;return $*3n*this.V1_ACCURACY*this.PERIOD_SEC/X}static v1ToDemurrage($,J,Q,Y,G){let Z=J*(G-Y)+Q*Y;return $*3n*this.V1_ACCURACY*G/Z}}class A0{client;constructor($){this.client=$}async getTotalBalance($,J=!0){let Q=await this.client.call("circlesV2_getTotalBalance",[B($),J]);return i.circlesToAttoCircles(Q)}async getTokenBalances($){let Q=(await this.client.call("circles_getTokenBalances",[B($)])).map((Y)=>j0(Y));return v(Q)}}class K${client;constructor($){this.client=$}async getAvatarInfo($){let J=await this.getAvatarInfoBatch([$]);return J.length>0?J[0]:void 0}async getAvatarInfoBatch($){if($.length===0)return[];let J=$.map((Y)=>B(Y)),Q=await this.client.call("circles_getAvatarInfoBatch",[J]);return v(Q)}async getNetworkSnapshot(){let $=await this.client.call("circles_getNetworkSnapshot",[]);return v($)}}class X${client;constructor($){this.client=$}async getProfileByCid($){return this.client.call("circles_getProfileByCid",[$])}async getProfileByCidBatch($){return this.client.call("circles_getProfileByCidBatch",[$])}async getProfileByAddress($){return this.client.call("circles_getProfileByAddress",[B($)])}async getProfileByAddressBatch($){return this.client.call("circles_getProfileByAddressBatch",[$.map((J)=>J===null?null:B(J))])}async searchProfiles($,J=10,Q=0,Y){return this.client.call("circles_searchProfiles",[$.toLowerCase(),J,Q,Y])}async searchByAddressOrName($,J=10,Q=0,Y){let G=[],Z=/^0x[a-fA-F0-9]{40}$/.test($);if(Z)try{let K=await this.getProfileByAddress($);if(K){let X={...K,address:$};if(!Y||!X.avatarType||Y.includes(X.avatarType))G.push(X)}}catch(K){console.warn("Failed to get profile by address:",K)}try{let K=await this.searchProfiles($,J,Q,Y);if(Z&&G.length>0){let X=$.toLowerCase(),q=K.filter((M)=>M.address?.toLowerCase()!==X);G.push(...q)}else G.push(...K)}catch(K){console.warn("Failed to search profiles by text:",K)}return G.slice(0,J)}}class q${client;constructor($){this.client=$}async getTokenInfo($){let J=await this.getTokenInfoBatch([$]);return J.length>0?J[0]:void 0}async getTokenInfoBatch($){if($.length===0)return[];let J=$.map((G)=>B(G)),Y=(await this.client.call("circles_getTokenInfoBatch",[J])).map((G)=>j0(G));return v(Y)}getTokenHolders($,J=100,Q="DESC"){let Y=B($);return new Q0(this.client,{namespace:"V_CrcV2",table:"BalancesByAccountAndToken",columns:["account","tokenAddress","demurragedTotalBalance"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"tokenAddress",Value:Y}],cursorColumns:[{name:"demurragedTotalBalance",sortOrder:Q},{name:"account",sortOrder:"ASC"}],orderColumns:[{Column:"demurragedTotalBalance",SortOrder:Q},{Column:"account",SortOrder:"ASC"}],limit:J,sortOrder:Q},(G)=>({account:G.account,tokenAddress:G.tokenAddress,demurragedTotalBalance:G.demurragedTotalBalance}))}}class M${client;constructor($){this.client=$}transformQueryResponse($){let{columns:J,rows:Q}=$;return Q.map((Y)=>{let G={};return J.forEach((Z,K)=>{G[Z]=Y[K]}),G})}async getInvitedBy($){let J=B($),Q=await this.client.call("circles_query",[{Namespace:"CrcV2",Table:"RegisterHuman",Columns:["inviter"],Filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"avatar",Value:J}],Order:[{Column:"blockNumber",SortOrder:"DESC"}],Limit:1}]);if(Q.length>0)return v(Q[0].inviter);return}async getInvitations($){let J=B($),Q=96,Y=await this.client.call("circles_getAvatarInfoBatch",[[J]]);if((Y.length>0?Y[0]:void 0)?.version===2)return[];let Z=await this.client.call("circles_query",[{Namespace:"V_Crc",Table:"TrustRelations",Columns:["truster","trustee"],Filter:[{Type:"Conjunction",ConjunctionType:"And",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"version",Value:2},{Type:"FilterPredicate",FilterType:"Equals",Column:"trustee",Value:J}]}],Order:[]}]),X=this.transformQueryResponse(Z).map((j)=>j.truster);if(X.length===0)return[];let q=await this.client.call("circles_getAvatarInfoBatch",[X]),M=[];for(let j of q){if(!j?.isHuman)continue;let N=(await this.client.call("circles_getTokenBalances",[j.avatar])).find((D)=>B(D.tokenAddress)===B(j.avatar));if(N&&N.circles>=96)M.push(j)}return v(M)}async getInvitationsFrom($,J=!1){let Q=B($);if(J){let Y=await this.client.call("circles_query",[{Namespace:"CrcV2",Table:"RegisterHuman",Columns:["avatar"],Filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"inviter",Value:Q}],Order:[{Column:"blockNumber",SortOrder:"DESC"}]}]),Z=this.transformQueryResponse(Y).map((K)=>K.avatar);return v(Z)}else{let Y=await this.client.call("circles_query",[{Namespace:"V_Crc",Table:"TrustRelations",Columns:["trustee","truster"],Filter:[{Type:"Conjunction",ConjunctionType:"And",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"version",Value:2},{Type:"FilterPredicate",FilterType:"Equals",Column:"truster",Value:Q}]}],Order:[]}]),Z=this.transformQueryResponse(Y).map((M)=>M.trustee);if(Z.length===0)return[];let K=await this.client.call("circles_getAvatarInfoBatch",[Z]),X=new Set(K.filter((M)=>M!==null).map((M)=>B(M.avatar))),q=Z.filter((M)=>!X.has(B(M)));return v(q)}}}function ZQ($,J){let Q=BigInt($),Y=i.attoCirclesToCircles(Q),G=i.attoCirclesToAttoCrc(Q,BigInt(J)),Z=i.attoCirclesToCircles(G),K=i.attoCirclesToAttoStaticCircles(Q,BigInt(J)),X=i.attoCirclesToCircles(K);return{attoCircles:Q,circles:Y,staticAttoCircles:K,staticCircles:X,attoCrc:G,crc:Z}}class j${client;constructor($){this.client=$}getTransactionHistory($,J=50,Q="DESC"){let Y=B($),G=[{Type:"Conjunction",ConjunctionType:"And",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"version",Value:2},{Type:"Conjunction",ConjunctionType:"Or",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"from",Value:Y},{Type:"FilterPredicate",FilterType:"Equals",Column:"to",Value:Y}]}]}];return new Q0(this.client,{namespace:"V_Crc",table:"TransferSummary",sortOrder:Q,columns:[],filter:G,limit:J},(Z)=>{let K=ZQ(Z.value,Z.timestamp),X={...Z,...K};return v(X)})}}class w0{client;constructor($){this.client=$}async findGroups($=50,J){let Q=this.getGroups($,J,"DESC"),Y=[];while(await Q.queryNextPage()){if(Y.push(...Q.currentPage.results),Y.length>=$)break;if(!Q.currentPage.hasMore)break}return Y.slice(0,$)}getGroupMemberships($,J=50,Q="DESC"){let Y=B($);return new Q0(this.client,{namespace:"V_CrcV2",table:"GroupMemberships",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","member","expiryTime"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"member",Value:Y}],limit:J},(G)=>v(G))}getGroupHolders($,J=100){let Q=B($);return new Q0(this.client,{namespace:"V_CrcV2",table:"GroupTokenHoldersBalance",sortOrder:"DESC",columns:["group","holder","totalBalance","demurragedTotalBalance","fractionOwnership"],cursorColumns:[{name:"holder",sortOrder:"ASC"}],orderColumns:[{Column:"totalBalance",SortOrder:"DESC"},{Column:"holder",SortOrder:"ASC"}],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:Q}],limit:J,rowTransformer:(Y)=>{let G={...Y,totalBalance:BigInt(Y.totalBalance),demurragedTotalBalance:BigInt(Y.demurragedTotalBalance)};return v(G)}})}getGroupMembers($,J=100,Q="DESC"){let Y=B($);return new Q0(this.client,{namespace:"V_CrcV2",table:"GroupMemberships",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","member","expiryTime"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:Y}],limit:J},(G)=>v(G))}getGroups($=50,J,Q="DESC"){let Y=[];if(J){if(J.nameStartsWith)Y.push({Type:"FilterPredicate",FilterType:"Like",Column:"name",Value:J.nameStartsWith+"%"});if(J.symbolStartsWith)Y.push({Type:"FilterPredicate",FilterType:"Like",Column:"symbol",Value:J.symbolStartsWith+"%"});if(J.groupAddressIn&&J.groupAddressIn.length>0){let Z=J.groupAddressIn.map((K)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:B(K)}));if(Z.length===1)Y.push(Z[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:Z})}if(J.groupTypeIn&&J.groupTypeIn.length>0){let Z=J.groupTypeIn.map((K)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"type",Value:K}));if(Z.length===1)Y.push(Z[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:Z})}if(J.ownerIn&&J.ownerIn.length>0){let Z=J.ownerIn.map((K)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"owner",Value:B(K)}));if(Z.length===1)Y.push(Z[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:Z})}if(J.mintHandlerEquals)Y.push({Type:"FilterPredicate",FilterType:"Equals",Column:"mintHandler",Value:B(J.mintHandlerEquals)});if(J.treasuryEquals)Y.push({Type:"FilterPredicate",FilterType:"Equals",Column:"treasury",Value:B(J.treasuryEquals)})}let G=Y.length>1?[{Type:"Conjunction",ConjunctionType:"And",Predicates:Y}]:Y;return new Q0(this.client,{namespace:"V_CrcV2",table:"Groups",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","type","owner","mintPolicy","mintHandler","treasury","service","feeCollection","memberCount","name","symbol","cidV0Digest","erc20WrapperDemurraged","erc20WrapperStatic"],filter:G,limit:$},(Z)=>v(Z))}}class x${client;_pathfinder;_query;_trust;_balance;_avatar;_profile;_token;_invitation;_transaction;_group;constructor($="https://rpc.circlesubi.network/"){this.client=new R0($)}get pathfinder(){if(!this._pathfinder)this._pathfinder=new W0(this.client);return this._pathfinder}get query(){if(!this._query)this._query=new Z$(this.client);return this._query}get trust(){if(!this._trust)this._trust=new k0(this.client);return this._trust}get balance(){if(!this._balance)this._balance=new A0(this.client);return this._balance}get avatar(){if(!this._avatar)this._avatar=new K$(this.client);return this._avatar}get profile(){if(!this._profile)this._profile=new X$(this.client);return this._profile}get token(){if(!this._token)this._token=new q$(this.client);return this._token}get invitation(){if(!this._invitation)this._invitation=new M$(this.client);return this._invitation}get transaction(){if(!this._transaction)this._transaction=new j$(this.client);return this._transaction}get group(){if(!this._group)this._group=new w0(this.client);return this._group}setRpcUrl($){this.client.setRpcUrl($)}getRpcUrl(){return this.client.getRpcUrl()}}class G0{address;abi;rpcUrl;constructor($){this.address=$.address,this.abi=$.abi,this.rpcUrl=$.rpcUrl}async read($,J,Q){let Y=T$({abi:this.abi,functionName:$,args:J}),G={to:this.address,data:Y,...Q?.from&&{from:Q.from}},K=await(await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[G,"latest"]})})).json();if(K.error)throw Error(`RPC Error: ${K.error.message}`);if(!K.result)throw Error("No result returned from RPC call");return c$({abi:this.abi,functionName:$,data:K.result})}encodeWrite($,J){return T$({abi:this.abi,functionName:$,args:J})}}var oJ=[{type:"function",name:"operateFlowMatrix",inputs:[{name:"_flowVertices",type:"address[]"},{name:"_flow",type:"tuple[]",components:[{name:"streamSinkId",type:"uint16"},{name:"amount",type:"uint192"}]},{name:"_streams",type:"tuple[]",components:[{name:"sourceCoordinate",type:"uint16"},{name:"flowEdgeIds",type:"uint16[]"},{name:"data",type:"bytes"}]},{name:"_packedCoordinates",type:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"isApprovedForAll",inputs:[{name:"_account",type:"address"},{name:"_operator",type:"address"}],outputs:[{type:"bool"}],stateMutability:"view"},{type:"function",name:"setApprovalForAll",inputs:[{name:"_operator",type:"address"},{name:"_approved",type:"bool"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"wrap",inputs:[{name:"_avatar",type:"address"},{name:"_amount",type:"uint256"},{name:"_type",type:"uint8"}],outputs:[{type:"address"}],stateMutability:"nonpayable"},{type:"function",name:"trust",inputs:[{name:"_trustReceiver",type:"address"},{name:"_expiry",type:"uint96"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"isTrusted",inputs:[{name:"_truster",type:"address"},{name:"_trustee",type:"address"}],outputs:[{type:"bool"}],stateMutability:"view"},{type:"function",name:"toTokenId",inputs:[{name:"_avatar",type:"address"}],outputs:[{type:"uint256"}],stateMutability:"pure"},{type:"function",name:"safeTransferFrom",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_id",type:"uint256"},{name:"_value",type:"uint256"},{name:"_data",type:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"isHuman",inputs:[{name:"_human",type:"address"}],outputs:[{type:"bool"}],stateMutability:"view"},{type:"function",name:"safeBatchTransferFrom",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_ids",type:"uint256[]"},{name:"_values",type:"uint256[]"},{name:"_data",type:"bytes"}],outputs:[],stateMutability:"nonpayable"}];class B0 extends G0{constructor($){super({address:$.address,abi:oJ,rpcUrl:$.rpcUrl})}async isTrusted($,J){return this.read("isTrusted",[$,J])}async isApprovedForAll($,J){return this.read("isApprovedForAll",[$,J])}async toTokenId($){return this.read("toTokenId",[$])}trust($,J){return{to:this.address,data:this.encodeWrite("trust",[$,J]),value:0n}}setApprovalForAll($,J){return{to:this.address,data:this.encodeWrite("setApprovalForAll",[$,J]),value:0n}}wrap($,J,Q){return{to:this.address,data:this.encodeWrite("wrap",[$,J,Q]),value:0n}}safeTransferFrom($,J,Q,Y,G="0x"){return{to:this.address,data:this.encodeWrite("safeTransferFrom",[$,J,Q,Y,G]),value:0n}}operateFlowMatrix($,J,Q,Y){return{to:this.address,data:this.encodeWrite("operateFlowMatrix",[$,J,Q,Y]),value:0n}}async isHuman($){return this.read("isHuman",[$])}safeBatchTransferFrom($,J,Q,Y,G="0x"){return{to:this.address,data:this.encodeWrite("safeBatchTransferFrom",[$,J,Q,Y,G]),value:0n}}}var tJ=[{type:"function",name:"erc20Circles",inputs:[{name:"_circlesType",type:"uint8"},{name:"_avatar",type:"address"}],outputs:[{type:"address"}],stateMutability:"view"}];class E$ extends G0{constructor($){super({address:$.address,abi:tJ,rpcUrl:$.rpcUrl})}async erc20Circles($,J){return this.read("erc20Circles",[$,J])}}var i$=[{type:"function",name:"unwrap",inputs:[{name:"_amount",type:"uint256"}],outputs:[],stateMutability:"nonpayable"}];class d0 extends G0{constructor($){super({address:$.address,abi:i$,rpcUrl:$.rpcUrl})}unwrap($){return{to:this.address,data:this.encodeWrite("unwrap",[$]),value:0n}}}class i0 extends G0{constructor($){super({address:$.address,abi:i$,rpcUrl:$.rpcUrl})}unwrap($){return{to:this.address,data:this.encodeWrite("unwrap",[$]),value:0n}}}var n$=[{type:"function",name:"createAccount",inputs:[{name:"signer",type:"address"}],outputs:[{name:"account",type:"address"}],stateMutability:"nonpayable"},{type:"function",name:"createAccounts",inputs:[{name:"signers",type:"address[]"}],outputs:[{name:"_accounts",type:"address[]"}],stateMutability:"nonpayable"}];var o$=[{type:"function",name:"claimInvite",inputs:[],outputs:[{name:"id",type:"uint256"}],stateMutability:"nonpayable"},{type:"function",name:"claimInvites",inputs:[{name:"numberOfInvites",type:"uint256"}],outputs:[{name:"ids",type:"uint256[]"}],stateMutability:"nonpayable"},{type:"function",name:"inviterQuota",inputs:[{name:"",type:"address"}],outputs:[{type:"uint256"}],stateMutability:"view"},{type:"function",name:"INVITATION_FEE",inputs:[],outputs:[{type:"uint256"}],stateMutability:"view"},{type:"function",name:"invitationModule",inputs:[],outputs:[{type:"address"}],stateMutability:"view"}];class n0 extends G0{constructor($){super({address:$.address,abi:n$,rpcUrl:$.rpcUrl})}createAccount($){return{to:this.address,data:this.encodeWrite("createAccount",[$]),value:0n}}createAccounts($){return{to:this.address,data:this.encodeWrite("createAccounts",[$]),value:0n}}}class o0 extends G0{constructor($){super({address:$.address,abi:o$,rpcUrl:$.rpcUrl})}claimInvite(){return{to:this.address,data:this.encodeWrite("claimInvite",[]),value:0n}}claimInvites($){return{to:this.address,data:this.encodeWrite("claimInvites",[$]),value:0n}}async inviterQuota($){return this.read("inviterQuota",[$])}async invitationFee(){return this.read("INVITATION_FEE")}async invitationModule(){return this.read("invitationModule")}}class k$ extends Error{name;code;source;cause;context;constructor($,J,Q){super(J);if(this.name=$,this.code=Q?.code,this.source=Q?.source??"UNKNOWN",this.cause=Q?.cause,this.context=Q?.context,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,source:this.source,context:this.context,cause:this.cause instanceof Error?{name:this.cause.name,message:this.cause.message}:this.cause,stack:this.stack}}toString(){let $=`[${this.source}] ${this.name}: ${this.message}`;if(this.code)$+=` (Code: ${this.code})`;if(this.context)$+=`
|
|
3
|
-
Context: ${JSON.stringify(this.context,null,2)}`;return $}}function KQ($,J,Q,Y){if(typeof $.setBigUint64==="function")return $.setBigUint64(J,Q,Y);let G=BigInt(32),Z=BigInt(4294967295),K=Number(Q>>G&Z),X=Number(Q&Z),q=Y?4:0,M=Y?0:4;$.setUint32(J+q,K,Y),$.setUint32(J+M,X,Y)}function aJ($,J,Q){return $&J^~$&Q}function sJ($,J,Q){return $&J^$&Q^J&Q}class t$ extends x0{constructor($,J,Q,Y){super();this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=$,this.outputLen=J,this.padOffset=Q,this.isLE=Y,this.buffer=new Uint8Array($),this.view=P$(this.buffer)}update($){M0(this),$=_0($),K0($);let{view:J,buffer:Q,blockLen:Y}=this,G=$.length;for(let Z=0;Z<G;){let K=Math.min(Y-this.pos,G-Z);if(K===Y){let X=P$($);for(;Y<=G-Z;Z+=Y)this.process(X,Z);continue}if(Q.set($.subarray(Z,Z+K),this.pos),this.pos+=K,Z+=K,this.pos===Y)this.process(J,0),this.pos=0}return this.length+=$.length,this.roundClean(),this}digestInto($){M0(this),C$($,this),this.finished=!0;let{buffer:J,view:Q,blockLen:Y,isLE:G}=this,{pos:Z}=this;if(J[Z++]=128,X0(this.buffer.subarray(Z)),this.padOffset>Y-Z)this.process(Q,0),Z=0;for(let j=Z;j<Y;j++)J[j]=0;KQ(Q,Y-8,BigInt(this.length*8),G),this.process(Q,0);let K=P$($),X=this.outputLen;if(X%4)throw Error("_sha2: outputLen should be aligned to 32bit");let q=X/4,M=this.get();if(q>M.length)throw Error("_sha2: outputLen bigger than state");for(let j=0;j<q;j++)K.setUint32(4*j,M[j],G)}digest(){let{buffer:$,outputLen:J}=this;this.digestInto($);let Q=$.slice(0,J);return this.destroy(),Q}_cloneInto($){$||($=new this.constructor),$.set(...this.get());let{blockLen:J,buffer:Q,length:Y,finished:G,destroyed:Z,pos:K}=this;if($.destroyed=Z,$.finished=G,$.length=Y,$.pos=K,Y%J)$.buffer.set(Q);return $}clone(){return this._cloneInto()}}var U0=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var XQ=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),L0=new Uint32Array(64);class rJ extends t${constructor($=32){super(64,$,8,!1);this.A=U0[0]|0,this.B=U0[1]|0,this.C=U0[2]|0,this.D=U0[3]|0,this.E=U0[4]|0,this.F=U0[5]|0,this.G=U0[6]|0,this.H=U0[7]|0}get(){let{A:$,B:J,C:Q,D:Y,E:G,F:Z,G:K,H:X}=this;return[$,J,Q,Y,G,Z,K,X]}set($,J,Q,Y,G,Z,K,X){this.A=$|0,this.B=J|0,this.C=Q|0,this.D=Y|0,this.E=G|0,this.F=Z|0,this.G=K|0,this.H=X|0}process($,J){for(let j=0;j<16;j++,J+=4)L0[j]=$.getUint32(J,!1);for(let j=16;j<64;j++){let z=L0[j-15],N=L0[j-2],D=Z0(z,7)^Z0(z,18)^z>>>3,P=Z0(N,17)^Z0(N,19)^N>>>10;L0[j]=P+L0[j-7]+D+L0[j-16]|0}let{A:Q,B:Y,C:G,D:Z,E:K,F:X,G:q,H:M}=this;for(let j=0;j<64;j++){let z=Z0(K,6)^Z0(K,11)^Z0(K,25),N=M+z+aJ(K,X,q)+XQ[j]+L0[j]|0,P=(Z0(Q,2)^Z0(Q,13)^Z0(Q,22))+sJ(Q,Y,G)|0;M=q,q=X,X=K,K=Z+N|0,Z=G,G=Y,Y=Q,Q=N+P|0}Q=Q+this.A|0,Y=Y+this.B|0,G=G+this.C|0,Z=Z+this.D|0,K=K+this.E|0,X=X+this.F|0,q=q+this.G|0,M=M+this.H|0,this.set(Q,Y,G,Z,K,X,q,M)}roundClean(){X0(L0)}destroy(){this.set(0,0,0,0,0,0,0,0),X0(this.buffer)}}var eJ=B$(()=>new rJ);class a$ extends x0{constructor($,J){super();this.finished=!1,this.destroyed=!1,FJ($);let Q=_0(J);if(this.iHash=$.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let Y=this.blockLen,G=new Uint8Array(Y);G.set(Q.length>Y?$.create().update(Q).digest():Q);for(let Z=0;Z<G.length;Z++)G[Z]^=54;this.iHash.update(G),this.oHash=$.create();for(let Z=0;Z<G.length;Z++)G[Z]^=106;this.oHash.update(G),X0(G)}update($){return M0(this),this.iHash.update($),this}digestInto($){M0(this),K0($,this.outputLen),this.finished=!0,this.iHash.digestInto($),this.oHash.update($),this.oHash.digestInto($),this.destroy()}digest(){let $=new Uint8Array(this.oHash.outputLen);return this.digestInto($),$}_cloneInto($){$||($=Object.create(Object.getPrototypeOf(this),{}));let{oHash:J,iHash:Q,finished:Y,destroyed:G,blockLen:Z,outputLen:K}=this;return $=$,$.finished=Y,$.destroyed=G,$.blockLen=Z,$.outputLen=K,$.oHash=J._cloneInto($.oHash),$.iHash=Q._cloneInto($.iHash),$}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var s$=($,J,Q)=>new a$($,J).update(Q).digest();s$.create=($,J)=>new a$($,J);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var JJ=BigInt(0),$J=BigInt(1);function t0($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function QJ($){if(!t0($))throw Error("Uint8Array expected")}function a0($,J){if(typeof J!=="boolean")throw Error($+" boolean expected, got "+J)}function W$($){let J=$.toString(16);return J.length&1?"0"+J:J}function Q8($){if(typeof $!=="string")throw Error("hex string expected, got "+typeof $);return $===""?JJ:BigInt("0x"+$)}var Y8=typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function",qQ=Array.from({length:256},($,J)=>J.toString(16).padStart(2,"0"));function s0($){if(QJ($),Y8)return $.toHex();let J="";for(let Q=0;Q<$.length;Q++)J+=qQ[$[Q]];return J}var z0={_0:48,_9:57,A:65,F:70,a:97,f:102};function $8($){if($>=z0._0&&$<=z0._9)return $-z0._0;if($>=z0.A&&$<=z0.F)return $-(z0.A-10);if($>=z0.a&&$<=z0.f)return $-(z0.a-10);return}function U$($){if(typeof $!=="string")throw Error("hex string expected, got "+typeof $);if(Y8)return Uint8Array.fromHex($);let J=$.length,Q=J/2;if(J%2)throw Error("hex string expected, got unpadded hex of length "+J);let Y=new Uint8Array(Q);for(let G=0,Z=0;G<Q;G++,Z+=2){let K=$8($.charCodeAt(Z)),X=$8($.charCodeAt(Z+1));if(K===void 0||X===void 0){let q=$[Z]+$[Z+1];throw Error('hex string expected, got non-hex character "'+q+'" at index '+Z)}Y[G]=K*16+X}return Y}function N0($){return Q8(s0($))}function YJ($){return QJ($),Q8(s0(Uint8Array.from($).reverse()))}function y0($,J){return U$($.toString(16).padStart(J*2,"0"))}function GJ($,J){return y0($,J).reverse()}function $0($,J,Q){let Y;if(typeof J==="string")try{Y=U$(J)}catch(Z){throw Error($+" must be hex string or Uint8Array, cause: "+Z)}else if(t0(J))Y=Uint8Array.from(J);else throw Error($+" must be hex string or Uint8Array");let G=Y.length;if(typeof Q==="number"&&G!==Q)throw Error($+" of length "+Q+" expected, got "+G);return Y}function z$(...$){let J=0;for(let Y=0;Y<$.length;Y++){let G=$[Y];QJ(G),J+=G.length}let Q=new Uint8Array(J);for(let Y=0,G=0;Y<$.length;Y++){let Z=$[Y];Q.set(Z,G),G+=Z.length}return Q}var r$=($)=>typeof $==="bigint"&&JJ<=$;function A$($,J,Q){return r$($)&&r$(J)&&r$(Q)&&J<=$&&$<Q}function b0($,J,Q,Y){if(!A$(J,Q,Y))throw Error("expected valid "+$+": "+Q+" <= n < "+Y+", got "+J)}function G8($){let J;for(J=0;$>JJ;$>>=$J,J+=1);return J}var F0=($)=>($J<<BigInt($))-$J,e$=($)=>new Uint8Array($),J8=($)=>Uint8Array.from($);function Z8($,J,Q){if(typeof $!=="number"||$<2)throw Error("hashLen must be a number");if(typeof J!=="number"||J<2)throw Error("qByteLen must be a number");if(typeof Q!=="function")throw Error("hmacFn must be a function");let Y=e$($),G=e$($),Z=0,K=()=>{Y.fill(1),G.fill(0),Z=0},X=(...z)=>Q(G,Y,...z),q=(z=e$(0))=>{if(G=X(J8([0]),z),Y=X(),z.length===0)return;G=X(J8([1]),z),Y=X()},M=()=>{if(Z++>=1000)throw Error("drbg: tried 1000 values");let z=0,N=[];while(z<J){Y=X();let D=Y.slice();N.push(D),z+=Y.length}return z$(...N)};return(z,N)=>{K(),q(z);let D=void 0;while(!(D=N(M())))q();return K(),D}}var MQ={bigint:($)=>typeof $==="bigint",function:($)=>typeof $==="function",boolean:($)=>typeof $==="boolean",string:($)=>typeof $==="string",stringOrUint8Array:($)=>typeof $==="string"||t0($),isSafeInteger:($)=>Number.isSafeInteger($),array:($)=>Array.isArray($),field:($,J)=>J.Fp.isValid($),hash:($)=>typeof $==="function"&&Number.isSafeInteger($.outputLen)};function g0($,J,Q={}){let Y=(G,Z,K)=>{let X=MQ[Z];if(typeof X!=="function")throw Error("invalid validator function");let q=$[G];if(K&&q===void 0)return;if(!X(q,$))throw Error("param "+String(G)+" is invalid. Expected "+Z+", got "+q)};for(let[G,Z]of Object.entries(J))Y(G,Z,!1);for(let[G,Z]of Object.entries(Q))Y(G,Z,!0);return $}function ZJ($){let J=new WeakMap;return(Q,...Y)=>{let G=J.get(Q);if(G!==void 0)return G;let Z=$(Q,...Y);return J.set(Q,Z),Z}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var s=BigInt(0),o=BigInt(1),f0=BigInt(2),jQ=BigInt(3),X8=BigInt(4),q8=BigInt(5),M8=BigInt(8);function n($,J){let Q=$%J;return Q>=s?Q:J+Q}function Y0($,J,Q){let Y=$;while(J-- >s)Y*=Y,Y%=Q;return Y}function w$($,J){if($===s)throw Error("invert: expected non-zero number");if(J<=s)throw Error("invert: expected positive modulus, got "+J);let Q=n($,J),Y=J,G=s,Z=o,K=o,X=s;while(Q!==s){let M=Y/Q,j=Y%Q,z=G-K*M,N=Z-X*M;Y=Q,Q=j,G=K,Z=X,K=z,X=N}if(Y!==o)throw Error("invert: does not exist");return n(G,J)}function j8($,J){let Q=($.ORDER+o)/X8,Y=$.pow(J,Q);if(!$.eql($.sqr(Y),J))throw Error("Cannot find square root");return Y}function WQ($,J){let Q=($.ORDER-q8)/M8,Y=$.mul(J,f0),G=$.pow(Y,Q),Z=$.mul(J,G),K=$.mul($.mul(Z,f0),G),X=$.mul(Z,$.sub(K,$.ONE));if(!$.eql($.sqr(X),J))throw Error("Cannot find square root");return X}function UQ($){if($<BigInt(3))throw Error("sqrt is not defined for small field");let J=$-o,Q=0;while(J%f0===s)J/=f0,Q++;let Y=f0,G=N$($);while(K8(G,Y)===1)if(Y++>1000)throw Error("Cannot find square root: probably non-prime P");if(Q===1)return j8;let Z=G.pow(Y,J),K=(J+o)/f0;return function(q,M){if(q.is0(M))return M;if(K8(q,M)!==1)throw Error("Cannot find square root");let j=Q,z=q.mul(q.ONE,Z),N=q.pow(M,J),D=q.pow(M,K);while(!q.eql(N,q.ONE)){if(q.is0(N))return q.ZERO;let P=1,V=q.sqr(N);while(!q.eql(V,q.ONE))if(P++,V=q.sqr(V),P===j)throw Error("Cannot find square root");let y=o<<BigInt(j-P-1),_=q.pow(z,y);j=P,z=q.sqr(_),N=q.mul(N,z),D=q.mul(D,_)}return D}}function zQ($){if($%X8===jQ)return j8;if($%M8===q8)return WQ;return UQ($)}var NQ=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function KJ($){let J={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},Q=NQ.reduce((Y,G)=>{return Y[G]="function",Y},J);return g0($,Q)}function DQ($,J,Q){if(Q<s)throw Error("invalid exponent, negatives unsupported");if(Q===s)return $.ONE;if(Q===o)return J;let Y=$.ONE,G=J;while(Q>s){if(Q&o)Y=$.mul(Y,G);G=$.sqr(G),Q>>=o}return Y}function XJ($,J,Q=!1){let Y=Array(J.length).fill(Q?$.ZERO:void 0),G=J.reduce((K,X,q)=>{if($.is0(X))return K;return Y[q]=K,$.mul(K,X)},$.ONE),Z=$.inv(G);return J.reduceRight((K,X,q)=>{if($.is0(X))return K;return Y[q]=$.mul(K,Y[q]),$.mul(K,X)},Z),Y}function K8($,J){let Q=($.ORDER-o)/f0,Y=$.pow(J,Q),G=$.eql(Y,$.ONE),Z=$.eql(Y,$.ZERO),K=$.eql(Y,$.neg($.ONE));if(!G&&!Z&&!K)throw Error("invalid Legendre symbol result");return G?1:Z?0:-1}function qJ($,J){if(J!==void 0)T0(J);let Q=J!==void 0?J:$.toString(2).length,Y=Math.ceil(Q/8);return{nBitLength:Q,nByteLength:Y}}function N$($,J,Q=!1,Y={}){if($<=s)throw Error("invalid field: expected ORDER > 0, got "+$);let{nBitLength:G,nByteLength:Z}=qJ($,J);if(Z>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");let K,X=Object.freeze({ORDER:$,isLE:Q,BITS:G,BYTES:Z,MASK:F0(G),ZERO:s,ONE:o,create:(q)=>n(q,$),isValid:(q)=>{if(typeof q!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof q);return s<=q&&q<$},is0:(q)=>q===s,isOdd:(q)=>(q&o)===o,neg:(q)=>n(-q,$),eql:(q,M)=>q===M,sqr:(q)=>n(q*q,$),add:(q,M)=>n(q+M,$),sub:(q,M)=>n(q-M,$),mul:(q,M)=>n(q*M,$),pow:(q,M)=>DQ(X,q,M),div:(q,M)=>n(q*w$(M,$),$),sqrN:(q)=>q*q,addN:(q,M)=>q+M,subN:(q,M)=>q-M,mulN:(q,M)=>q*M,inv:(q)=>w$(q,$),sqrt:Y.sqrt||((q)=>{if(!K)K=zQ($);return K(X,q)}),toBytes:(q)=>Q?GJ(q,Z):y0(q,Z),fromBytes:(q)=>{if(q.length!==Z)throw Error("Field.fromBytes: expected "+Z+" bytes, got "+q.length);return Q?YJ(q):N0(q)},invertBatch:(q)=>XJ(X,q),cmov:(q,M,j)=>j?M:q});return Object.freeze(X)}function W8($){if(typeof $!=="bigint")throw Error("field order must be bigint");let J=$.toString(2).length;return Math.ceil(J/8)}function MJ($){let J=W8($);return J+Math.ceil(J/2)}function U8($,J,Q=!1){let Y=$.length,G=W8(J),Z=MJ(J);if(Y<16||Y<Z||Y>1024)throw Error("expected "+Z+"-1024 bytes of input, got "+Y);let K=Q?YJ($):N0($),X=n(K,J-o)+o;return Q?GJ(X,G):y0(X,G)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var z8=BigInt(0),NJ=BigInt(1);function jJ($,J){let Q=J.negate();return $?Q:J}function D8($,J){if(!Number.isSafeInteger($)||$<=0||$>J)throw Error("invalid window size, expected [1.."+J+"], got W="+$)}function WJ($,J){D8($,J);let Q=Math.ceil(J/$)+1,Y=2**($-1),G=2**$,Z=F0($),K=BigInt($);return{windows:Q,windowSize:Y,mask:Z,maxNumber:G,shiftBy:K}}function N8($,J,Q){let{windowSize:Y,mask:G,maxNumber:Z,shiftBy:K}=Q,X=Number($&G),q=$>>K;if(X>Y)X-=Z,q+=NJ;let M=J*Y,j=M+Math.abs(X)-1,z=X===0,N=X<0,D=J%2!==0;return{nextN:q,offset:j,isZero:z,isNeg:N,isNegF:D,offsetF:M}}function VQ($,J){if(!Array.isArray($))throw Error("array expected");$.forEach((Q,Y)=>{if(!(Q instanceof J))throw Error("invalid point at index "+Y)})}function OQ($,J){if(!Array.isArray($))throw Error("array of scalars expected");$.forEach((Q,Y)=>{if(!J.isValid(Q))throw Error("invalid scalar at index "+Y)})}var UJ=new WeakMap,V8=new WeakMap;function zJ($){return V8.get($)||1}function O8($,J){return{constTimeNegate:jJ,hasPrecomputes(Q){return zJ(Q)!==1},unsafeLadder(Q,Y,G=$.ZERO){let Z=Q;while(Y>z8){if(Y&NJ)G=G.add(Z);Z=Z.double(),Y>>=NJ}return G},precomputeWindow(Q,Y){let{windows:G,windowSize:Z}=WJ(Y,J),K=[],X=Q,q=X;for(let M=0;M<G;M++){q=X,K.push(q);for(let j=1;j<Z;j++)q=q.add(X),K.push(q);X=q.double()}return K},wNAF(Q,Y,G){let{ZERO:Z,BASE:K}=$,X=WJ(Q,J);for(let q=0;q<X.windows;q++){let{nextN:M,offset:j,isZero:z,isNeg:N,isNegF:D,offsetF:P}=N8(G,q,X);if(G=M,z)K=K.add(jJ(D,Y[P]));else Z=Z.add(jJ(N,Y[j]))}return{p:Z,f:K}},wNAFUnsafe(Q,Y,G,Z=$.ZERO){let K=WJ(Q,J);for(let X=0;X<K.windows;X++){if(G===z8)break;let{nextN:q,offset:M,isZero:j,isNeg:z}=N8(G,X,K);if(G=q,j)continue;else{let N=Y[M];Z=Z.add(z?N.negate():N)}}return Z},getPrecomputes(Q,Y,G){let Z=UJ.get(Y);if(!Z){if(Z=this.precomputeWindow(Y,Q),Q!==1)UJ.set(Y,G(Z))}return Z},wNAFCached(Q,Y,G){let Z=zJ(Q);return this.wNAF(Z,this.getPrecomputes(Z,Q,G),Y)},wNAFCachedUnsafe(Q,Y,G,Z){let K=zJ(Q);if(K===1)return this.unsafeLadder(Q,Y,Z);return this.wNAFUnsafe(K,this.getPrecomputes(K,Q,G),Y,Z)},setWindowSize(Q,Y){D8(Y,J),V8.set(Q,Y),UJ.delete(Q)}}}function R8($,J,Q,Y){VQ(Q,$),OQ(Y,J);let G=Q.length,Z=Y.length;if(G!==Z)throw Error("arrays of points and scalars must have equal length");let K=$.ZERO,X=G8(BigInt(G)),q=1;if(X>12)q=X-3;else if(X>4)q=X-2;else if(X>0)q=2;let M=F0(q),j=Array(Number(M)+1).fill(K),z=Math.floor((J.BITS-1)/q)*q,N=K;for(let D=z;D>=0;D-=q){j.fill(K);for(let V=0;V<Z;V++){let y=Y[V],_=Number(y>>BigInt(D)&M);j[_]=j[_].add(Q[V])}let P=K;for(let V=j.length-1,y=K;V>0;V--)y=y.add(j[V]),P=P.add(y);if(N=N.add(P),D!==0)for(let V=0;V<q;V++)N=N.double()}return N}function DJ($){return KJ($.Fp),g0($,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...qJ($.n,$.nBitLength),...$,...{p:$.Fp.ORDER}})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function C8($){if($.lowS!==void 0)a0("lowS",$.lowS);if($.prehash!==void 0)a0("prehash",$.prehash)}function RQ($){let J=DJ($);g0(J,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:Q,Fp:Y,a:G}=J;if(Q){if(!Y.eql(G,Y.ZERO))throw Error("invalid endo: CURVE.a must be 0");if(typeof Q!=="object"||typeof Q.beta!=="bigint"||typeof Q.splitScalar!=="function")throw Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...J})}class P8 extends Error{constructor($=""){super($)}}var D0={Err:P8,_tlv:{encode:($,J)=>{let{Err:Q}=D0;if($<0||$>256)throw new Q("tlv.encode: wrong tag");if(J.length&1)throw new Q("tlv.encode: unpadded data");let Y=J.length/2,G=W$(Y);if(G.length/2&128)throw new Q("tlv.encode: long form length too big");let Z=Y>127?W$(G.length/2|128):"";return W$($)+Z+G+J},decode($,J){let{Err:Q}=D0,Y=0;if($<0||$>256)throw new Q("tlv.encode: wrong tag");if(J.length<2||J[Y++]!==$)throw new Q("tlv.decode: wrong tlv");let G=J[Y++],Z=!!(G&128),K=0;if(!Z)K=G;else{let q=G&127;if(!q)throw new Q("tlv.decode(long): indefinite length not supported");if(q>4)throw new Q("tlv.decode(long): byte length is too big");let M=J.subarray(Y,Y+q);if(M.length!==q)throw new Q("tlv.decode: length bytes not complete");if(M[0]===0)throw new Q("tlv.decode(long): zero leftmost byte");for(let j of M)K=K<<8|j;if(Y+=q,K<128)throw new Q("tlv.decode(long): not minimal encoding")}let X=J.subarray(Y,Y+K);if(X.length!==K)throw new Q("tlv.decode: wrong value length");return{v:X,l:J.subarray(Y+K)}}},_int:{encode($){let{Err:J}=D0;if($<V0)throw new J("integer: negative integers are not allowed");let Q=W$($);if(Number.parseInt(Q[0],16)&8)Q="00"+Q;if(Q.length&1)throw new J("unexpected DER parsing assertion: unpadded hex");return Q},decode($){let{Err:J}=D0;if($[0]&128)throw new J("invalid signature integer: negative");if($[0]===0&&!($[1]&128))throw new J("invalid signature integer: unnecessary leading zero");return N0($)}},toSig($){let{Err:J,_int:Q,_tlv:Y}=D0,G=$0("signature",$),{v:Z,l:K}=Y.decode(48,G);if(K.length)throw new J("invalid signature: left bytes after parsing");let{v:X,l:q}=Y.decode(2,Z),{v:M,l:j}=Y.decode(2,q);if(j.length)throw new J("invalid signature: left bytes after parsing");return{r:Q.decode(X),s:Q.decode(M)}},hexFromSig($){let{_tlv:J,_int:Q}=D0,Y=J.encode(2,Q.encode($.r)),G=J.encode(2,Q.encode($.s)),Z=Y+G;return J.encode(48,Z)}};function VJ($,J){return s0(y0($,J))}var V0=BigInt(0),d=BigInt(1),MG=BigInt(2),OJ=BigInt(3),CQ=BigInt(4);function PQ($){let J=RQ($),{Fp:Q}=J,Y=N$(J.n,J.nBitLength),G=J.toBytes||((W,O,L)=>{let S=O.toAffine();return z$(Uint8Array.from([4]),Q.toBytes(S.x),Q.toBytes(S.y))}),Z=J.fromBytes||((W)=>{let O=W.subarray(1),L=Q.fromBytes(O.subarray(0,Q.BYTES)),S=Q.fromBytes(O.subarray(Q.BYTES,2*Q.BYTES));return{x:L,y:S}});function K(W){let{a:O,b:L}=J,S=Q.sqr(W),w=Q.mul(S,W);return Q.add(Q.add(w,Q.mul(W,O)),L)}function X(W,O){let L=Q.sqr(O),S=K(W);return Q.eql(L,S)}if(!X(J.Gx,J.Gy))throw Error("bad curve params: generator point");let q=Q.mul(Q.pow(J.a,OJ),CQ),M=Q.mul(Q.sqr(J.b),BigInt(27));if(Q.is0(Q.add(q,M)))throw Error("bad curve params: a or b");function j(W){return A$(W,d,J.n)}function z(W){let{allowedPrivateKeyLengths:O,nByteLength:L,wrapPrivateKey:S,n:w}=J;if(O&&typeof W!=="bigint"){if(t0(W))W=s0(W);if(typeof W!=="string"||!O.includes(W.length))throw Error("invalid private key");W=W.padStart(L*2,"0")}let E;try{E=typeof W==="bigint"?W:N0($0("private key",W,L))}catch(b){throw Error("invalid private key, expected hex or "+L+" bytes, got "+typeof W)}if(S)E=n(E,w);return b0("private key",E,d,w),E}function N(W){if(!(W instanceof V))throw Error("ProjectivePoint expected")}let D=ZJ((W,O)=>{let{px:L,py:S,pz:w}=W;if(Q.eql(w,Q.ONE))return{x:L,y:S};let E=W.is0();if(O==null)O=E?Q.ONE:Q.inv(w);let b=Q.mul(L,O),x=Q.mul(S,O),A=Q.mul(w,O);if(E)return{x:Q.ZERO,y:Q.ZERO};if(!Q.eql(A,Q.ONE))throw Error("invZ was invalid");return{x:b,y:x}}),P=ZJ((W)=>{if(W.is0()){if(J.allowInfinityPoint&&!Q.is0(W.py))return;throw Error("bad point: ZERO")}let{x:O,y:L}=W.toAffine();if(!Q.isValid(O)||!Q.isValid(L))throw Error("bad point: x or y not FE");if(!X(O,L))throw Error("bad point: equation left != right");if(!W.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});class V{constructor(W,O,L){if(W==null||!Q.isValid(W))throw Error("x required");if(O==null||!Q.isValid(O)||Q.is0(O))throw Error("y required");if(L==null||!Q.isValid(L))throw Error("z required");this.px=W,this.py=O,this.pz=L,Object.freeze(this)}static fromAffine(W){let{x:O,y:L}=W||{};if(!W||!Q.isValid(O)||!Q.isValid(L))throw Error("invalid affine point");if(W instanceof V)throw Error("projective point not allowed");let S=(w)=>Q.eql(w,Q.ZERO);if(S(O)&&S(L))return V.ZERO;return new V(O,L,Q.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(W){let O=XJ(Q,W.map((L)=>L.pz));return W.map((L,S)=>L.toAffine(O[S])).map(V.fromAffine)}static fromHex(W){let O=V.fromAffine(Z($0("pointHex",W)));return O.assertValidity(),O}static fromPrivateKey(W){return V.BASE.multiply(z(W))}static msm(W,O){return R8(V,Y,W,O)}_setWindowSize(W){H.setWindowSize(this,W)}assertValidity(){P(this)}hasEvenY(){let{y:W}=this.toAffine();if(Q.isOdd)return!Q.isOdd(W);throw Error("Field doesn't support isOdd")}equals(W){N(W);let{px:O,py:L,pz:S}=this,{px:w,py:E,pz:b}=W,x=Q.eql(Q.mul(O,b),Q.mul(w,S)),A=Q.eql(Q.mul(L,b),Q.mul(E,S));return x&&A}negate(){return new V(this.px,Q.neg(this.py),this.pz)}double(){let{a:W,b:O}=J,L=Q.mul(O,OJ),{px:S,py:w,pz:E}=this,b=Q.ZERO,x=Q.ZERO,A=Q.ZERO,k=Q.mul(S,S),c=Q.mul(w,w),h=Q.mul(E,E),U=Q.mul(S,w);return U=Q.add(U,U),A=Q.mul(S,E),A=Q.add(A,A),b=Q.mul(W,A),x=Q.mul(L,h),x=Q.add(b,x),b=Q.sub(c,x),x=Q.add(c,x),x=Q.mul(b,x),b=Q.mul(U,b),A=Q.mul(L,A),h=Q.mul(W,h),U=Q.sub(k,h),U=Q.mul(W,U),U=Q.add(U,A),A=Q.add(k,k),k=Q.add(A,k),k=Q.add(k,h),k=Q.mul(k,U),x=Q.add(x,k),h=Q.mul(w,E),h=Q.add(h,h),k=Q.mul(h,U),b=Q.sub(b,k),A=Q.mul(h,c),A=Q.add(A,A),A=Q.add(A,A),new V(b,x,A)}add(W){N(W);let{px:O,py:L,pz:S}=this,{px:w,py:E,pz:b}=W,x=Q.ZERO,A=Q.ZERO,k=Q.ZERO,c=J.a,h=Q.mul(J.b,OJ),U=Q.mul(O,w),C=Q.mul(L,E),I=Q.mul(S,b),F=Q.add(O,L),T=Q.add(w,E);F=Q.mul(F,T),T=Q.add(U,C),F=Q.sub(F,T),T=Q.add(O,S);let R=Q.add(w,b);return T=Q.mul(T,R),R=Q.add(U,I),T=Q.sub(T,R),R=Q.add(L,S),x=Q.add(E,b),R=Q.mul(R,x),x=Q.add(C,I),R=Q.sub(R,x),k=Q.mul(c,T),x=Q.mul(h,I),k=Q.add(x,k),x=Q.sub(C,k),k=Q.add(C,k),A=Q.mul(x,k),C=Q.add(U,U),C=Q.add(C,U),I=Q.mul(c,I),T=Q.mul(h,T),C=Q.add(C,I),I=Q.sub(U,I),I=Q.mul(c,I),T=Q.add(T,I),U=Q.mul(C,T),A=Q.add(A,U),U=Q.mul(R,T),x=Q.mul(F,x),x=Q.sub(x,U),U=Q.mul(F,C),k=Q.mul(R,k),k=Q.add(k,U),new V(x,A,k)}subtract(W){return this.add(W.negate())}is0(){return this.equals(V.ZERO)}wNAF(W){return H.wNAFCached(this,W,V.normalizeZ)}multiplyUnsafe(W){let{endo:O,n:L}=J;b0("scalar",W,V0,L);let S=V.ZERO;if(W===V0)return S;if(this.is0()||W===d)return this;if(!O||H.hasPrecomputes(this))return H.wNAFCachedUnsafe(this,W,V.normalizeZ);let{k1neg:w,k1:E,k2neg:b,k2:x}=O.splitScalar(W),A=S,k=S,c=this;while(E>V0||x>V0){if(E&d)A=A.add(c);if(x&d)k=k.add(c);c=c.double(),E>>=d,x>>=d}if(w)A=A.negate();if(b)k=k.negate();return k=new V(Q.mul(k.px,O.beta),k.py,k.pz),A.add(k)}multiply(W){let{endo:O,n:L}=J;b0("scalar",W,d,L);let S,w;if(O){let{k1neg:E,k1:b,k2neg:x,k2:A}=O.splitScalar(W),{p:k,f:c}=this.wNAF(b),{p:h,f:U}=this.wNAF(A);k=H.constTimeNegate(E,k),h=H.constTimeNegate(x,h),h=new V(Q.mul(h.px,O.beta),h.py,h.pz),S=k.add(h),w=c.add(U)}else{let{p:E,f:b}=this.wNAF(W);S=E,w=b}return V.normalizeZ([S,w])[0]}multiplyAndAddUnsafe(W,O,L){let S=V.BASE,w=(b,x)=>x===V0||x===d||!b.equals(S)?b.multiplyUnsafe(x):b.multiply(x),E=w(this,O).add(w(W,L));return E.is0()?void 0:E}toAffine(W){return D(this,W)}isTorsionFree(){let{h:W,isTorsionFree:O}=J;if(W===d)return!0;if(O)return O(V,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:W,clearCofactor:O}=J;if(W===d)return this;if(O)return O(V,this);return this.multiplyUnsafe(J.h)}toRawBytes(W=!0){return a0("isCompressed",W),this.assertValidity(),G(V,this,W)}toHex(W=!0){return a0("isCompressed",W),s0(this.toRawBytes(W))}}V.BASE=new V(J.Gx,J.Gy,Q.ONE),V.ZERO=new V(Q.ZERO,Q.ONE,Q.ZERO);let{endo:y,nBitLength:_}=J,H=O8(V,y?Math.ceil(_/2):_);return{CURVE:J,ProjectivePoint:V,normPrivateKeyToScalar:z,weierstrassEquation:K,isWithinCurveOrder:j}}function BQ($){let J=DJ($);return g0(J,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...J})}function B8($){let J=BQ($),{Fp:Q,n:Y,nByteLength:G,nBitLength:Z}=J,K=Q.BYTES+1,X=2*Q.BYTES+1;function q(U){return n(U,Y)}function M(U){return w$(U,Y)}let{ProjectivePoint:j,normPrivateKeyToScalar:z,weierstrassEquation:N,isWithinCurveOrder:D}=PQ({...J,toBytes(U,C,I){let F=C.toAffine(),T=Q.toBytes(F.x),R=z$;if(a0("isCompressed",I),I)return R(Uint8Array.from([C.hasEvenY()?2:3]),T);else return R(Uint8Array.from([4]),T,Q.toBytes(F.y))},fromBytes(U){let C=U.length,I=U[0],F=U.subarray(1);if(C===K&&(I===2||I===3)){let T=N0(F);if(!A$(T,d,Q.ORDER))throw Error("Point is not on curve");let R=N(T),f;try{f=Q.sqrt(R)}catch(r){let e=r instanceof Error?": "+r.message:"";throw Error("Point is not on curve"+e)}let m=(f&d)===d;if((I&1)===1!==m)f=Q.neg(f);return{x:T,y:f}}else if(C===X&&I===4){let T=Q.fromBytes(F.subarray(0,Q.BYTES)),R=Q.fromBytes(F.subarray(Q.BYTES,2*Q.BYTES));return{x:T,y:R}}else{let T=K,R=X;throw Error("invalid Point, expected length of "+T+", or uncompressed "+R+", got "+C)}}});function P(U){let C=Y>>d;return U>C}function V(U){return P(U)?q(-U):U}let y=(U,C,I)=>N0(U.slice(C,I));class _{constructor(U,C,I){if(b0("r",U,d,Y),b0("s",C,d,Y),this.r=U,this.s=C,I!=null)this.recovery=I;Object.freeze(this)}static fromCompact(U){let C=G;return U=$0("compactSignature",U,C*2),new _(y(U,0,C),y(U,C,2*C))}static fromDER(U){let{r:C,s:I}=D0.toSig($0("DER",U));return new _(C,I)}assertValidity(){}addRecoveryBit(U){return new _(this.r,this.s,U)}recoverPublicKey(U){let{r:C,s:I,recovery:F}=this,T=w($0("msgHash",U));if(F==null||![0,1,2,3].includes(F))throw Error("recovery id invalid");let R=F===2||F===3?C+J.n:C;if(R>=Q.ORDER)throw Error("recovery id 2 or 3 invalid");let f=(F&1)===0?"02":"03",m=j.fromHex(f+VJ(R,Q.BYTES)),l=M(R),r=q(-T*l),e=q(I*l),O0=j.BASE.multiplyAndAddUnsafe(m,r,e);if(!O0)throw Error("point at infinify");return O0.assertValidity(),O0}hasHighS(){return P(this.s)}normalizeS(){return this.hasHighS()?new _(this.r,q(-this.s),this.recovery):this}toDERRawBytes(){return U$(this.toDERHex())}toDERHex(){return D0.hexFromSig(this)}toCompactRawBytes(){return U$(this.toCompactHex())}toCompactHex(){let U=G;return VJ(this.r,U)+VJ(this.s,U)}}let H={isValidPrivateKey(U){try{return z(U),!0}catch(C){return!1}},normPrivateKeyToScalar:z,randomPrivateKey:()=>{let U=MJ(J.n);return U8(J.randomBytes(U),J.n)},precompute(U=8,C=j.BASE){return C._setWindowSize(U),C.multiply(BigInt(3)),C}};function W(U,C=!0){return j.fromPrivateKey(U).toRawBytes(C)}function O(U){if(typeof U==="bigint")return!1;if(U instanceof j)return!0;let I=$0("key",U).length,F=Q.BYTES,T=F+1,R=2*F+1;if(J.allowedPrivateKeyLengths||G===T)return;else return I===T||I===R}function L(U,C,I=!0){if(O(U)===!0)throw Error("first arg must be private key");if(O(C)===!1)throw Error("second arg must be public key");return j.fromHex(C).multiply(z(U)).toRawBytes(I)}let S=J.bits2int||function(U){if(U.length>8192)throw Error("input is too large");let C=N0(U),I=U.length*8-Z;return I>0?C>>BigInt(I):C},w=J.bits2int_modN||function(U){return q(S(U))},E=F0(Z);function b(U){return b0("num < 2^"+Z,U,V0,E),y0(U,G)}function x(U,C,I=A){if(["recovered","canonical"].some((H0)=>(H0 in I)))throw Error("sign() legacy options not supported");let{hash:F,randomBytes:T}=J,{lowS:R,prehash:f,extraEntropy:m}=I;if(R==null)R=!0;if(U=$0("msgHash",U),C8(I),f)U=$0("prehashed msgHash",F(U));let l=w(U),r=z(C),e=[b(r),b(l)];if(m!=null&&m!==!1){let H0=m===!0?T(Q.BYTES):m;e.push($0("extraEntropy",H0))}let O0=z$(...e),V$=l;function g$(H0){let h0=S(H0);if(!D(h0))return;let f$=M(h0),r0=j.BASE.multiply(h0).toAffine(),S0=q(r0.x);if(S0===V0)return;let e0=q(f$*q(V$+S0*r));if(e0===V0)return;let m0=(r0.x===S0?0:2)|Number(r0.y&d),_J=e0;if(R&&P(e0))_J=V(e0),m0^=1;return new _(S0,_J,m0)}return{seed:O0,k2sig:g$}}let A={lowS:J.lowS,prehash:!1},k={lowS:J.lowS,prehash:!1};function c(U,C,I=A){let{seed:F,k2sig:T}=x(U,C,I),R=J;return Z8(R.hash.outputLen,R.nByteLength,R.hmac)(F,T)}j.BASE._setWindowSize(8);function h(U,C,I,F=k){let T=U;C=$0("msgHash",C),I=$0("publicKey",I);let{lowS:R,prehash:f,format:m}=F;if(C8(F),"strict"in F)throw Error("options.strict was renamed to lowS");if(m!==void 0&&m!=="compact"&&m!=="der")throw Error("format must be compact or der");let l=typeof T==="string"||t0(T),r=!l&&!m&&typeof T==="object"&&T!==null&&typeof T.r==="bigint"&&typeof T.s==="bigint";if(!l&&!r)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");let e=void 0,O0;try{if(r)e=new _(T.r,T.s);if(l){try{if(m!=="compact")e=_.fromDER(T)}catch(m0){if(!(m0 instanceof D0.Err))throw m0}if(!e&&m!=="der")e=_.fromCompact(T)}O0=j.fromHex(I)}catch(m0){return!1}if(!e)return!1;if(R&&e.hasHighS())return!1;if(f)C=J.hash(C);let{r:V$,s:g$}=e,H0=w(C),h0=M(g$),f$=q(H0*h0),r0=q(V$*h0),S0=j.BASE.multiplyAndAddUnsafe(O0,f$,r0)?.toAffine();if(!S0)return!1;return q(S0.x)===V$}return{CURVE:J,getPublicKey:W,getSharedSecret:L,sign:c,verify:h,ProjectivePoint:j,Signature:_,utils:H}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function LQ($){return{hash:$,hmac:(J,...Q)=>s$($,J,fJ(...Q)),randomBytes:vJ}}function L8($,J){let Q=(Y)=>B8({...$,...LQ(Y)});return{...Q(J),create:Q}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var I8=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),H8=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),HQ=BigInt(0),SQ=BigInt(1),RJ=BigInt(2),S8=($,J)=>($+J/RJ)/J;function IQ($){let J=I8,Q=BigInt(3),Y=BigInt(6),G=BigInt(11),Z=BigInt(22),K=BigInt(23),X=BigInt(44),q=BigInt(88),M=$*$*$%J,j=M*M*$%J,z=Y0(j,Q,J)*j%J,N=Y0(z,Q,J)*j%J,D=Y0(N,RJ,J)*M%J,P=Y0(D,G,J)*D%J,V=Y0(P,Z,J)*P%J,y=Y0(V,X,J)*V%J,_=Y0(y,q,J)*y%J,H=Y0(_,X,J)*V%J,W=Y0(H,Q,J)*j%J,O=Y0(W,K,J)*P%J,L=Y0(O,Y,J)*M%J,S=Y0(L,RJ,J);if(!CJ.eql(CJ.sqr(S),$))throw Error("Cannot find square root");return S}var CJ=N$(I8,void 0,void 0,{sqrt:IQ}),PJ=L8({a:HQ,b:BigInt(7),Fp:CJ,n:H8,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:($)=>{let J=H8,Q=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),Y=-SQ*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),G=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),Z=Q,K=BigInt("0x100000000000000000000000000000000"),X=S8(Z*$,J),q=S8(-Y*$,J),M=n($-X*Q-q*G,J),j=n(-X*Y-q*Z,J),z=M>K,N=j>K;if(z)M=J-M;if(N)j=J-j;if(M>K||j>K)throw Error("splitScalar: Endomorphism failed, k="+$);return{k1neg:z,k1:M,k2neg:N,k2:j}}}},eJ);function y$(){let $=PJ.utils.randomPrivateKey();return"0x"+Buffer.from($).toString("hex")}function b$($){let J=$.startsWith("0x")?$.slice(2):$,Q=Buffer.from(J,"hex"),Y=PJ.getPublicKey(Q,!1),Z=c0(Y.slice(1)).slice(-20),K="0x"+Buffer.from(Z).toString("hex");return P0(K)}function F$($){let J;if(typeof $==="string"){let Y=$.startsWith("0x")?$.slice(2):$;J=Buffer.from(Y,"hex")}else J=$;let Q=c0(J);return"0x"+Buffer.from(Q).toString("hex")}class g extends k${constructor($,J){super("InvitationError",$,{...J,source:J?.source||"INVITATIONS"})}static noPathFound($,J,Q){return new g(`No valid invitation path found from ${$} to ${J}. ${Q||"The inviter may not have enough balance of the proxy inviter's token or there's no trust connection."}`,{code:"INVITATION_NO_PATH",source:"PATHFINDING",context:{from:$,to:J,reason:Q}})}static noProxyInviters($){return new g(`No proxy inviters found for ${$}. The inviter must have mutual trust connections with users who are also trusted by the invitation module, and these users must have sufficient balance.`,{code:"INVITATION_NO_PROXY_INVITERS",source:"VALIDATION",context:{inviter:$}})}static insufficientBalance($,J,Q,Y,G,Z){let K=Number(Q)/1000000000000000000,X=Number(Y)/1000000000000000000;return new g(`Insufficient balance for ${$} invitation(s). Can only afford ${J} invitation(s). Requested: ${K.toFixed(6)} CRC, Available: ${X.toFixed(6)} CRC.`,{code:"INVITATION_INSUFFICIENT_BALANCE",source:"VALIDATION",context:{from:G,to:Z,requestedInvites:$,availableInvites:J,requested:Q.toString(),available:Y.toString(),requestedCrc:K,availableCrc:X}})}static inviteeAlreadyRegistered($,J){return new g(`Invitee ${J} is already registered as a human in Circles Hub. Cannot invite an already registered user.`,{code:"INVITATION_INVITEE_ALREADY_REGISTERED",source:"VALIDATION",context:{inviter:$,invitee:J}})}static noAddressesProvided(){return new g("At least one address must be provided for invitation.",{code:"INVITATION_NO_ADDRESSES_PROVIDED",source:"VALIDATION"})}}var T8=[];for(let $=0;$<256;$++)T8[$]=$.toString(16).padStart(2,"0");function D$($){let J="0x";for(let Q=0;Q<$.length;Q++)J+=T8[$[Q]];return J}function _8($){let J=new Uint8Array($.length*2);return $.forEach((Q,Y)=>{let G=Q>>8,Z=Q&255,K=2*Y;J[K]=G,J[K+1]=Z}),D$(J)}function x8($,J,Q){let Y=new Set([J.toLowerCase(),Q.toLowerCase()]);$.forEach((K)=>{Y.add(K.from.toLowerCase()),Y.add(K.to.toLowerCase()),Y.add(K.tokenOwner.toLowerCase())});let G=[...Y].sort((K,X)=>{let q=BigInt(K),M=BigInt(X),j=q<M,z=q>M;return j?-1:z?1:0}),Z={};return G.forEach((K,X)=>{Z[K]=X}),{sorted:G,idx:Z}}function TQ($,J){let Q=new Set,Y=[],G=null;if($.forEach((Z,K)=>{let X=Z.from.toLowerCase(),q=Z.to.toLowerCase();if(X===J&&q===J)G=K;else if(q===J)Y.push(K)}),G!==null)Q.add(G);else Y.forEach((Z)=>Q.add(Z));return Q}function BJ($,J,Q,Y){let G=$.toLowerCase(),Z=J.toLowerCase(),{sorted:K,idx:X}=x8(Y,G,Z),q=TQ(Y,Z),M=Y.map((_,H)=>{return{streamSinkId:q.has(H)?1:0,amount:_.value}});if(q.size===0)throw Error(`No terminal edges detected. Flow must have at least one edge delivering to receiver ${Z}`);let j=Array.from(q),z=[{sourceCoordinate:X[G],flowEdgeIds:j,data:new Uint8Array(0)}],N=[];Y.forEach((_)=>{N.push(X[_.tokenOwner.toLowerCase()]),N.push(X[_.from.toLowerCase()]),N.push(X[_.to.toLowerCase()])});let D=_8(N),P=BigInt(Q),V=M.filter((_)=>_.streamSinkId===1).reduce((_,H)=>_+BigInt(H.amount.toString()),BigInt(0));if(V!==P)throw Error(`Terminal sum ${V} does not equal expected ${P}`);return{flowVertices:K,flowEdges:M,streams:z,packedCoordinates:D,sourceCoordinate:X[G]}}function LJ($,J){let Q=$.streams.map((Y)=>({sourceCoordinate:Y.sourceCoordinate,flowEdgeIds:Y.flowEdgeIds,data:Y.data instanceof Uint8Array?D$(Y.data):Y.data}));if(J&&Q.length>0)Q[0].data=J instanceof Uint8Array?D$(J):J;return Q}async function HJ($,J,Q){let Y=new Map,G=new Set;return Q.transfers.forEach((X)=>{if($.toLowerCase()===X.from.toLowerCase())G.add(X.tokenOwner.toLowerCase())}),(await new x$(J).token.getTokenInfoBatch(Array.from(G))).forEach((X)=>{if(X.isWrapped&&!X.isInflationary)X.tokenType="CrcV2_ERC20WrapperDeployed_Demurraged";Y.set(X.tokenAddress.toLowerCase(),X)}),Y}function SJ($,J){let Q={};return $.transfers.forEach((Y)=>{let G=J.get(Y.tokenOwner.toLowerCase());if(G&&G.tokenType.startsWith("CrcV2_ERC20WrapperDeployed")){if(!Q[Y.tokenOwner])Q[Y.tokenOwner]=[BigInt(0),G.tokenType];Q[Y.tokenOwner][0]+=BigInt(Y.value)}}),Q}function IJ($,J){let Q=$.transfers.map((Y)=>{let G=J.get(Y.tokenOwner.toLowerCase());if(G&&G.tokenType.startsWith("CrcV2_ERC20WrapperDeployed"))return{...Y,tokenOwner:G.tokenOwner};return Y});return{...$,transfers:Q}}class t extends J${constructor($,J){super("TransferError",$,{...J,source:J?.source||"TRANSFERS"})}static noPathFound($,J,Q){return new t(`No valid transfer path found from ${$} to ${J}. ${Q||"This could mean there's no trust connection, insufficient balance, or the tokens are not transferable."}`,{code:"TRANSFER_NO_PATH",source:"PATHFINDING",context:{from:$,to:J,reason:Q}})}static insufficientBalance($,J,Q,Y){let G=Number($)/1000000000000000000,Z=Number(J)/1000000000000000000;return new t(`Insufficient balance for transfer. Requested: ${G.toFixed(6)} CRC, Available: ${Z.toFixed(6)} CRC.`,{code:"TRANSFER_INSUFFICIENT_BALANCE",source:"VALIDATION",context:{from:Q,to:Y,requested:$.toString(),available:J.toString(),requestedCrc:G,availableCrc:Z}})}static wrappedTokensRequired(){return new t("Insufficient unwrapped token balance for transfer. Your balance contains wrapped tokens (ERC20 wrappers), but useWrappedBalances option is not enabled. Please enable it by passing { useWrappedBalances: true } in the transfer options.",{code:"TRANSFER_WRAPPED_TOKENS_REQUIRED",source:"VALIDATION"})}static unregisteredAvatars($){return new t(`Flow matrix contains ${$.length} unregistered avatar(s): ${$.join(", ")}. All addresses in the flow must be registered Circles avatars (human or group).`,{code:"TRANSFER_UNREGISTERED_AVATARS",source:"FLOW_MATRIX",context:{unregisteredAddresses:$,count:$.length}})}static flowMatrixMismatch($,J){return new t(`Flow matrix terminal sum (${$}) does not equal expected amount (${J})`,{code:"TRANSFER_FLOW_MATRIX_MISMATCH",source:"FLOW_MATRIX",context:{terminalSum:$.toString(),expected:J.toString()}})}static emptyPath($,J){return new t(`Transfer path is empty for route from ${$} to ${J}`,{code:"TRANSFER_EMPTY_PATH",source:"PATHFINDING",context:{from:$,to:J}})}}class v0{config;hubV2;liftERC20;rpcClient;pathfinder;balance;group;constructor($){this.config=$,this.hubV2=new B0({address:$.v2HubAddress,rpcUrl:$.circlesRpcUrl}),this.liftERC20=new E$({address:$.liftERC20Address,rpcUrl:$.circlesRpcUrl}),this.rpcClient=new R0($.circlesRpcUrl),this.pathfinder=new W0(this.rpcClient),this.balance=new A0(this.rpcClient),this.group=new w0(this.rpcClient)}async buildFlowMatrixTx($,J,Q,Y,G=!1){let Z=$.toLowerCase(),K=J.toLowerCase();if(!Q.transfers||Q.transfers.length===0)throw t.noPathFound(Z,K);let X={...Q};if(G&&Y?.toTokens?.length===1){let H=Y.toTokens[0].toLowerCase();if(Q.maxFlow>0n)X.transfers.push({from:K,to:K,tokenOwner:H,value:Q.maxFlow})}let q=await HJ(Z,this.config.circlesRpcUrl,X),M=SJ(X,q),j=Object.keys(M).length>0;if(j&&!Y?.useWrappedBalances)throw t.wrappedTokensRequired();let z=[],N=[];if(j){let H=await this._getTokenBalanceMap(Z),W=this._createDemurragedUnwrapCalls(M),{unwrapCalls:O,wrapCalls:L}=this._createInflationaryUnwrapAndWrapCalls(M,q,H);z=[...W,...O],N=L,X=IJ(X,q)}let D=BJ(Z,K,X.maxFlow,X.transfers),P=LJ(D,Y?.txData),V=this.hubV2.operateFlowMatrix(D.flowVertices,D.flowEdges,P,D.packedCoordinates),y=!1;try{y=await this.hubV2.isApprovedForAll(Z,Z)}catch(H){console.warn("Failed to check approval status, including approval transaction:",H)}return[...y?[]:[this.hubV2.setApprovalForAll(Z,!0)],...z,V,...N]}async constructAdvancedTransfer($,J,Q,Y,G=!1){let Z=$.toLowerCase(),K=J.toLowerCase(),X=BigInt(Q);if(Z===K&&Y?.fromTokens?.length===1&&Y?.toTokens?.length===1){let D=Y.fromTokens[0],P=Y.toTokens[0],[V,y]=await Promise.all([this.liftERC20.erc20Circles(0,P),this.liftERC20.erc20Circles(1,P)]);if(D.toLowerCase()===V.toLowerCase()&&V!==_$){let H=new d0({address:D,rpcUrl:this.config.circlesRpcUrl}).unwrap(X);return[{to:H.to,data:H.data,value:H.value??0n}]}if(D.toLowerCase()===y.toLowerCase()&&y!==_$){let _=new i0({address:D,rpcUrl:this.config.circlesRpcUrl}),H=i.attoCirclesToAttoStaticCircles(X),W=_.unwrap(H);return[{to:W.to,data:W.data,value:W.value??0n}]}}let q=this._truncateToSixDecimals(X),M=await this._getDefaultTokenExcludeList(K,Y?.excludeFromTokens),{...j}=Y||{},z={...j,...M?{excludeFromTokens:M}:{}},N=await this.pathfinder.findPath({from:Z,to:K,targetFlow:q,...z});if(!N.transfers||N.transfers.length===0)throw t.noPathFound(Z,K);if(N.maxFlow<q)throw t.insufficientBalance(q,N.maxFlow,Z,K);return this.buildFlowMatrixTx(Z,K,N,Y,G)}async constructReplenish($,J,Q,Y){let G=$.toLowerCase(),Z=J.toLowerCase(),K=(Y||$).toLowerCase(),X=BigInt(Q),M=(await this.balance.getTokenBalances(G)).filter((R)=>R.tokenOwner.toLowerCase()===Z),j=0n,z=0n,N=0n,D=null,P=null;for(let R of M)if(R.isWrapped)if(R.tokenType.includes("Demurrage"))z=BigInt(R.attoCircles),D=R.tokenAddress;else N=BigInt(R.staticAttoCircles),P=R.tokenAddress;else j=BigInt(R.attoCircles);let V=j+z+i.attoStaticCirclesToAttoCircles(N),y=[];if(j>=X){if(console.log(`✓ Already have ${Number(j)/1000000000000000000} CRC unwrapped (target: ${Number(X)/1000000000000000000} CRC). No replenish needed.`),K!==G){let R=await this.hubV2.toTokenId(Z),f=this.hubV2.safeTransferFrom(G,K,R,X);y.push({to:f.to,data:f.data,value:f.value??0n})}return y}let _=X-j;if(console.log(`Current unwrapped: ${Number(j)/1000000000000000000} CRC`),console.log(`Target amount: ${Number(X)/1000000000000000000} CRC`),console.log(`Need to acquire: ${Number(_)/1000000000000000000} CRC`),V>=X){let R=_;if(z>0n&&D&&R>0n){let f=R>z?z:R,l=new d0({address:D,rpcUrl:this.config.circlesRpcUrl}).unwrap(f);y.push({to:l.to,data:l.data,value:l.value??0n}),R-=f}if(N>0n&&P&&R>0n){let f=i.attoCirclesToAttoStaticCircles(R),m=f>N?N:f,r=new i0({address:P,rpcUrl:this.config.circlesRpcUrl}).unwrap(m);y.push({to:r.to,data:r.data,value:r.value??0n})}if(K!==G){let f=await this.hubV2.toTokenId(Z),m=this.hubV2.safeTransferFrom(G,K,f,X);y.push({to:m.to,data:m.data,value:m.value??0n})}return y}let W=!await this.hubV2.isTrusted(G,Z),O=BigInt(Math.floor(Date.now()/1000)+31536000),L=i.truncateToInt64(_),S=_%i.FACTOR_1E12!==0n,w=i.blowUpToBigInt(S?L+1n:L),E;try{E=await this.pathfinder.findPath({from:G,to:K,targetFlow:w,toTokens:[Z],useWrappedBalances:!0,simulatedTrusts:W?[{truster:G,trustee:Z}]:void 0})}catch(R){let f=Number(V)/1000000000000000000,m=Number(X)/1000000000000000000,l=Number(_)/1000000000000000000;throw new t(`Insufficient tokens to replenish. Target: ${m.toFixed(6)} CRC, Current unwrapped: ${Number(j)/1000000000000000000} CRC, Need: ${l.toFixed(6)} CRC, Available (including all paths): ${f.toFixed(6)} CRC. Cannot acquire the remaining ${(Number(_-(V-j))/1000000000000000000).toFixed(6)} CRC.`,{code:"REPLENISH_INSUFFICIENT_TOKENS",source:"VALIDATION",context:{from:G,tokenId:Z,target:X.toString(),unwrapped:j.toString(),deficit:_.toString(),available:V.toString(),targetCrc:m,unwrappedCrc:Number(j)/1000000000000000000,deficitCrc:l,availableCrc:f}})}if(!E.transfers||E.transfers.length===0)throw t.noPathFound(G,K,`No path to acquire token ${Z}`);if(E.maxFlow<w){let R=Number(E.maxFlow)/1000000000000000000,f=Number(w)/1000000000000000000;throw new t(`Pathfinder can only provide ${R.toFixed(6)} CRC of the ${f.toFixed(6)} CRC deficit needed for token ${Z}.`,{code:"REPLENISH_INSUFFICIENT_PATH_FLOW",source:"PATHFINDING",context:{from:G,tokenId:Z,deficit:w.toString(),pathFlow:E.maxFlow.toString(),deficitCrc:f,pathFlowCrc:R}})}if(W){let R=this.hubV2.trust(Z,O);y.push({to:R.to,data:R.data,value:R.value??0n})}let b=await HJ(G,this.config.circlesRpcUrl,E),x=SJ(E,b),A=Object.keys(x).length>0,k=[],c=[];if(A){let R=await this._getTokenBalanceMap(G),f=this._createDemurragedUnwrapCalls(x),{unwrapCalls:m,wrapCalls:l}=this._createInflationaryUnwrapAndWrapCalls(x,b,R);k=[...f,...m],c=l,E=IJ(E,b)}let h=BJ(G,K,E.maxFlow,E.transfers),U=LJ(h),C=this.hubV2.operateFlowMatrix(h.flowVertices,h.flowEdges,U,h.packedCoordinates),I={to:C.to,data:C.data,value:C.value??0n},F=!1;try{F=await this.hubV2.isApprovedForAll(G,G)}catch(R){console.warn("Failed to check approval status, including approval transaction:",R)}if(W){let R=this.hubV2.trust(Z,0n);c.push({to:R.to,data:R.data,value:R.value??0n})}let T=F?[]:[{to:this.hubV2.setApprovalForAll(G,!0).to,data:this.hubV2.setApprovalForAll(G,!0).data,value:0n}];return y.push(...T,...k,I,...c),y}async _getTokenBalanceMap($){let J=await this.balance.getTokenBalances($),Q=new Map;return J.forEach((Y)=>{Q.set(Y.tokenAddress.toLowerCase(),Y.staticAttoCircles)}),Q}_createDemurragedUnwrapCalls($){let J=[];for(let[Q,[Y,G]]of Object.entries($)){if(G!=="CrcV2_ERC20WrapperDeployed_Demurraged")continue;let K=new d0({address:Q,rpcUrl:this.config.circlesRpcUrl}).unwrap(Y);J.push({to:K.to,data:K.data,value:K.value??0n})}return J}_createInflationaryUnwrapAndWrapCalls($,J,Q){let Y=[],G=[];for(let[Z,[K,X]]of Object.entries($)){if(X!=="CrcV2_ERC20WrapperDeployed_Inflationary")continue;let q=J.get(Z.toLowerCase()),M=Q.get(Z.toLowerCase())||0n;if(M===0n)continue;let z=new i0({address:Z,rpcUrl:this.config.circlesRpcUrl}).unwrap(M);Y.push({to:z.to,data:z.data,value:z.value??0n});let N=q?.tokenOwner,D=i.attoStaticCirclesToAttoCircles(M)-K;if(D>0n){let P=this.hubV2.wrap(N,D,1);G.push({to:P.to,data:P.data,value:P.value??0n})}}return{unwrapCalls:Y,wrapCalls:G}}_truncateToSixDecimals($){let J=BigInt(1e6),Q=BigInt(10)**BigInt(18);return $/(Q/J)*(Q/J)}async _getDefaultTokenExcludeList($,J){let Q=await this.group.findGroups(1,{mintHandlerEquals:$}),Y=new Set;if(Q.length>0){let G=Q[0];if(Y.add(G.group.toLowerCase()),G.erc20WrapperDemurraged)Y.add(G.erc20WrapperDemurraged.toLowerCase());if(G.erc20WrapperStatic)Y.add(G.erc20WrapperStatic.toLowerCase())}if(J?.forEach((G)=>Y.add(G.toLowerCase())),Y.size===0)return;return Array.from(Y)}}var E8=p0;class TJ{config;rpcClient;pathfinder;trust;hubV2;referralsModule;invitationFarm;constructor($){if(!$.referralsServiceUrl)throw new g("referralsServiceUrl is required in config",{code:"INVITATION_MISSING_CONFIG",source:"INVITATIONS",context:{missingField:"referralsServiceUrl"}});this.config=$,this.rpcClient=new R0($.circlesRpcUrl),this.pathfinder=new W0(this.rpcClient),this.trust=new k0(this.rpcClient),this.hubV2=new B0({address:$.v2HubAddress,rpcUrl:$.circlesRpcUrl}),this.referralsModule=new n0({address:$.referralsModuleAddress,rpcUrl:$.circlesRpcUrl}),this.invitationFarm=new o0({address:$.invitationFarmAddress,rpcUrl:$.circlesRpcUrl})}async saveReferralData($,J){try{let Q=await fetch(`${this.config.referralsServiceUrl}/store`,{method:"POST",headers:{accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({privateKey:J,inviter:$})});if(!Q.ok)throw new g(`HTTP error! status: ${Q.status}`,{code:"INVITATION_HTTP_ERROR",source:"INVITATIONS",context:{status:Q.status,url:`${this.config.referralsServiceUrl}/store`}})}catch(Q){throw new g(`Failed to save referral data: ${Q instanceof Error?Q.message:"Unknown error"}`,{code:"INVITATION_SAVE_REFERRAL_FAILED",source:"INVITATIONS",cause:Q})}}async listReferrals($,J=10,Q=0){try{let Y=new URL(`${this.config.referralsServiceUrl}/list/${$}`);Y.searchParams.set("limit",String(J)),Y.searchParams.set("offset",String(Q));let G=await fetch(Y.toString(),{method:"GET",headers:{accept:"application/json"}});if(!G.ok)throw new g(`HTTP error! status: ${G.status}`,{code:"INVITATION_HTTP_ERROR",source:"INVITATIONS",context:{status:G.status,url:Y.toString()}});return await G.json()}catch(Y){if(Y instanceof g)throw Y;throw new g(`Failed to list referrals: ${Y instanceof Error?Y.message:"Unknown error"}`,{code:"INVITATION_LIST_REFERRALS_FAILED",source:"INVITATIONS",cause:Y})}}orderRealInviters($,J){let Q=J.toLowerCase();return $.sort((Y,G)=>{let Z=Y.address.toLowerCase()===Q,K=G.address.toLowerCase()===Q;if(Z&&!K)return-1;if(!Z&&K)return 1;return 0})}async generateInvite($,J){let Q=$.toLowerCase(),Y=J.toLowerCase();if(await this.hubV2.isHuman(Y))throw g.inviteeAlreadyRegistered(Q,Y);let Z=await this.getRealInviters(Q),K=[];if(Z.length>0){console.log("[generateInvite] Using STANDARD PATH (proxy inviters available)");let X=Z[0].address,q=await this.findInvitePath(Q,X),M=await this.generateInviteData([Y],!1),z=await new v0(this.config).buildFlowMatrixTx(Q,this.config.invitationModuleAddress,q,{toTokens:[X],useWrappedBalances:!0,txData:H$(M)},!0);K.push(...z)}else{console.log("[generateInvite] Using FARM FALLBACK PATH (no proxy inviters available)");let X=new v0(this.config),q=await this.findFarmInvitePath(Q),M=await X.buildFlowMatrixTx(Q,E0,q,{toTokens:[p0],useWrappedBalances:!0},!0);K.push(...M);let j="0x20EcD8bDeb2F48d8a7c94E542aA4feC5790D9676",z=await this.invitationFarm.read("claimInvite",[],{from:j}),N=this.invitationFarm.claimInvite();K.push(N);let D=await this.invitationFarm.invitationModule(),P=J0(["address"],[Y]),V=this.hubV2.safeTransferFrom(Q,D,z,p,P);K.push(V)}return K}async findInvitePath($,J){let Q=$.toLowerCase(),Y;if(J)Y=J.toLowerCase();else{let Z=await this.getRealInviters(Q);if(Z.length===0)throw g.noPathFound(Q,this.config.invitationModuleAddress);Y=Z[0].address}let G=await this.pathfinder.findPath({from:Q,to:this.config.invitationModuleAddress,targetFlow:p,toTokens:[Y],useWrappedBalances:!0});if(!G.transfers||G.transfers.length===0)throw g.noPathFound(Q,this.config.invitationModuleAddress);if(G.maxFlow<p){let K=Number(G.maxFlow/p);throw g.insufficientBalance(1,K,p,G.maxFlow,Q,this.config.invitationModuleAddress)}return G}async findFarmInvitePath($){let J=$.toLowerCase(),Q=await this.pathfinder.findPath({from:J,to:E0,targetFlow:p,toTokens:[E8],useWrappedBalances:!0});if(!Q.transfers||Q.transfers.length===0)throw g.noPathFound(J,E0);if(Q.maxFlow<p){let G=Number(Q.maxFlow/p);throw g.insufficientBalance(1,G,p,Q.maxFlow,J,E0)}return Q}async getRealInviters($){console.log("[getRealInviters] Finding valid proxy inviters for:",$);let J=$.toLowerCase(),Q=await this.trust.getTrustedBy(J),Y=await this.trust.getMutualTrusts(J),G=new Set([...Q.map((H)=>H.objectAvatar.toLowerCase()),...Y.map((H)=>H.objectAvatar.toLowerCase())]),[Z,K]=await Promise.all([this.trust.getTrusts(this.config.invitationModuleAddress),this.trust.getMutualTrusts(this.config.invitationModuleAddress)]),X=new Set([...Z.map((H)=>H.objectAvatar.toLowerCase()),...K.map((H)=>H.objectAvatar.toLowerCase())]),q=new Set;if(p0!=="0x0000000000000000000000000000000000000000"){let H=await this.trust.getTrusts(p0);q=new Set([...H.map((W)=>W.objectAvatar.toLowerCase())])}if(!X.has(J))throw new g("Inviter must enable the invitation module before creating invitations",{code:"INVITATION_MODULE_NOT_ENABLED",source:"INVITATIONS",context:{inviter:J,invitationModule:this.config.invitationModuleAddress}});let j=[];for(let H of G)if(X.has(H)&&!q.has(H))j.push(H);let z=[...j];if(!q.has(J))z.push(J);if(z.length===0)return[];let D=await this.pathfinder.findPath({from:J,to:this.config.invitationModuleAddress,useWrappedBalances:!0,targetFlow:G$,toTokens:z});if(!D.transfers||D.transfers.length===0)return[];let P=new Map,V=this.config.invitationModuleAddress.toLowerCase();for(let H of D.transfers)if(H.to.toLowerCase()===V){let W=H.tokenOwner.toLowerCase(),O=P.get(W)||BigInt(0);P.set(W,O+H.value)}let y=[];for(let[H,W]of P.entries()){let O=Number(W/p);if(O>=1)y.push({address:H,possibleInvites:O})}let _=this.orderRealInviters(y,J);console.log("[getRealInviters] Final result:",_.length,"valid proxy inviters");for(let H of _);return _}async generateReferral($){let J=$.toLowerCase(),Q=y$(),Y=b$(Q),G=await this.getRealInviters(J),Z=[];if(G.length>0){console.log("[generateReferral] Using STANDARD PATH (proxy inviters available)");let K=new v0(this.config),X=await this.generateInviteData([Y],!0),q=G[0].address,M=await this.findInvitePath(J,q),j=await K.buildFlowMatrixTx(J,this.config.invitationModuleAddress,M,{toTokens:[q],useWrappedBalances:!0,txData:H$(X)},!0);Z.push(...j)}else{console.log("[generateReferral] Using FARM FALLBACK PATH (no proxy inviters available)");let K=new v0(this.config),X=await this.findFarmInvitePath(J),q=await K.buildFlowMatrixTx(J,E0,X,{toTokens:[E8],useWrappedBalances:!0},!0);Z.push(...q);let M="0x20EcD8bDeb2F48d8a7c94E542aA4feC5790D9676",j=await this.invitationFarm.read("claimInvite",[],{from:M}),z=this.invitationFarm.claimInvite();Z.push(z);let N=await this.invitationFarm.invitationModule(),D=this.referralsModule.createAccount(Y).data,P=J0(["address","bytes"],[this.config.referralsModuleAddress,D]),V=this.hubV2.safeTransferFrom(J,N,j,p,P);Z.push(V)}return{transactions:Z,privateKey:Q}}async generateInviteData($,J=!0){if($.length===0)throw g.noAddressesProvided();if(!J)if($.length===1)return J0(["address"],[$[0]]);else return J0(["address[]"],[$]);if($.length===1){let Y=this.referralsModule.createAccount($[0]).data;return J0(["address","bytes"],[this.config.referralsModuleAddress,Y])}else{let Y=this.referralsModule.createAccounts($).data;return J0(["address","bytes"],[this.config.referralsModuleAddress,Y])}}computeAddress($){let Q=$.toLowerCase().replace("0x","").padStart(64,"0"),Y=p$.replace("0x","")+Q,G=F$("0x"+Y),Z="ff",K=l$.toLowerCase().replace("0x",""),X=G.replace("0x",""),q=d$.replace("0x",""),M="ff"+K+X+q,z="0x"+F$("0x"+M).slice(-40);return P0(z)}generateSecrets($){return Array.from({length:$},()=>{let J=y$(),Q=b$(J).toLowerCase();return{secret:J,signer:Q}})}}class xQ{referralsModuleAddress;invitations;invitationFarm;referralsModule;hubV2;constructor($){this.referralsModuleAddress=$.referralsModuleAddress,this.invitations=new TJ($),this.invitationFarm=new o0({address:$.invitationFarmAddress,rpcUrl:$.circlesRpcUrl}),this.referralsModule=new n0({address:$.referralsModuleAddress,rpcUrl:$.circlesRpcUrl}),this.hubV2=new B0({address:$.v2HubAddress,rpcUrl:$.circlesRpcUrl})}async getQuota($){return this.invitationFarm.inviterQuota($)}async getInvitationFee(){return this.invitationFarm.invitationFee()}async getInvitationModule(){return this.invitationFarm.invitationModule()}async generateReferrals($,J){if(J<=0)throw new g("Count must be greater than 0",{code:"INVITATION_INVALID_COUNT",source:"VALIDATION",context:{count:J}});let Q=$.toLowerCase(),Y=J===1,G=await this.simulateClaim(Q,J);if(!G.length)throw new g("No invitation IDs returned from claim",{code:"INVITATION_NO_IDS",source:"INVITATIONS",context:{inviter:Q,count:J}});let Z=this.invitations.generateSecrets(J),K=Z.map((j)=>j.signer),X=await this.invitationFarm.invitationModule(),q=Y?this.invitationFarm.claimInvite():this.invitationFarm.claimInvites(BigInt(J)),M=Y?this.buildReferralTransfer(Q,X,G[0],K[0]):this.buildBatchReferralTransfer(Q,X,G,K);return{referrals:Z,transactions:[q,M]}}async generateInvites($,J){if(J.length===0)throw new g("At least one invitee address must be provided",{code:"INVITATION_INVALID_COUNT",source:"VALIDATION",context:{count:0}});let Q=$.toLowerCase(),Y=J.map((j)=>j.toLowerCase()),G=Y.length,Z=G===1,K=await this.simulateClaim(Q,G);if(!K.length)throw new g("No invitation IDs returned from claim",{code:"INVITATION_NO_IDS",source:"INVITATIONS",context:{inviter:Q,count:G}});let X=await this.invitationFarm.invitationModule(),q=Z?this.invitationFarm.claimInvite():this.invitationFarm.claimInvites(BigInt(G)),M=Z?this.buildInviteTransfer(Q,X,K[0],Y[0]):this.buildBatchInviteTransfer(Q,X,K,Y);return{invitees:Y,transactions:[q,M]}}async listReferrals($,J=10,Q=0){return this.invitations.listReferrals($,J,Q)}async simulateClaim($,J){if(J===1)return[await this.invitationFarm.read("claimInvite",[],{from:$})];return this.invitationFarm.read("claimInvites",[BigInt(J)],{from:$})}buildReferralTransfer($,J,Q,Y){let G=this.referralsModule.createAccount(Y).data,Z=J0(["address","bytes"],[this.referralsModuleAddress,G]);return this.hubV2.safeTransferFrom($,J,Q,p,Z)}buildBatchReferralTransfer($,J,Q,Y){let G=this.referralsModule.createAccounts(Y).data,Z=J0(["address","bytes"],[this.referralsModuleAddress,G]),K=Q.map(()=>p);return this.hubV2.safeBatchTransferFrom($,J,Q,K,Z)}buildInviteTransfer($,J,Q,Y){let G=J0(["address"],[Y]);return this.hubV2.safeTransferFrom($,J,Q,p,G)}buildBatchInviteTransfer($,J,Q,Y){let G=J0(["address[]"],[Y]),Z=Q.map(()=>p);return this.hubV2.safeBatchTransferFrom($,J,Q,Z,G)}}class EQ{baseUrl;getToken;constructor($,J){this.baseUrl=$;this.getToken=J}getBaseUrl(){return this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}async getAuthHeaders(){if(!this.getToken)return{"Content-Type":"application/json"};return{"Content-Type":"application/json",Authorization:`Bearer ${await this.getToken()}`}}async retrieve($){try{let J=`${this.getBaseUrl()}/retrieve?key=${encodeURIComponent($)}`,Q=await fetch(J);if(!Q.ok){let Y=`HTTP error! status: ${Q.status}`;try{Y=(await Q.json()).error||Y}catch{Y=Q.statusText||Y}throw new g(Y,{code:"INVITATION_RETRIEVE_FAILED",source:"INVITATIONS",context:{status:Q.status,url:J,privateKey:$}})}return Q.json()}catch(J){if(J instanceof g)throw J;throw new g(`Failed to retrieve referral: ${J instanceof Error?J.message:"Unknown error"}`,{code:"INVITATION_RETRIEVE_ERROR",source:"INVITATIONS",cause:J,context:{privateKey:$}})}}async listMine(){if(!this.getToken)throw new g("Authentication required to list referrals",{code:"INVITATION_AUTH_REQUIRED",source:"INVITATIONS"});try{let $=`${this.getBaseUrl()}/my-referrals`,J=await this.getAuthHeaders(),Q=await fetch($,{headers:J});if(!Q.ok){let Y=`HTTP error! status: ${Q.status}`;try{Y=(await Q.json()).error||Y}catch{Y=Q.statusText||Y}throw new g(Y,{code:"INVITATION_LIST_FAILED",source:"INVITATIONS",context:{status:Q.status,url:$}})}return Q.json()}catch($){if($ instanceof g)throw $;throw new g(`Failed to list referrals: ${$ instanceof Error?$.message:"Unknown error"}`,{code:"INVITATION_LIST_ERROR",source:"INVITATIONS",cause:$})}}}export{EQ as Referrals,xQ as InviteFarm,TJ as Invitations,g as InvitationError};
|
|
1
|
+
var wJ=($)=>BigInt($),$$=($)=>parseInt($,16),b8=($)=>{if($.startsWith("0x"))$=$.slice(2);if($.length%2!==0)throw Error("Invalid hex string");let J=new Uint8Array($.length/2);for(let Q=0;Q<$.length;Q+=2)J[Q/2]=parseInt($.substr(Q,2),16);return J};function F8($,J){if(typeof J==="string"&&J.startsWith("0x")){let Q=J.slice(2);if(Q.length===40)return J;if(Q.length===64){if($.toLowerCase().includes("digest")||$.toLowerCase().includes("data")||$.toLowerCase().includes("bytes"))return b8(J);try{return wJ(J)}catch{return J}}try{let Y=$$(J);if(Y<Number.MAX_SAFE_INTEGER)return Y;return wJ(J)}catch{return J}}if(J==="true")return!0;if(J==="false")return!1;return J}function m$($){let{event:J,values:Q}=$,Y={$event:J,blockNumber:Q.blockNumber?$$(Q.blockNumber):0,timestamp:Q.timestamp?$$(Q.timestamp):void 0,transactionIndex:Q.transactionIndex?$$(Q.transactionIndex):0,logIndex:Q.logIndex?$$(Q.logIndex):0,transactionHash:Q.transactionHash};for(let[G,Z]of Object.entries(Q)){if(["blockNumber","timestamp","transactionIndex","logIndex","transactionHash"].includes(G))continue;Y[G]=F8(G,Z)}return Y}function O$($){return $.map(m$)}class u0{_subscribers=[];subscribe($){return this._subscribers.push($),()=>{let J=this._subscribers.indexOf($);if(J>-1)this._subscribers.splice(J,1)}}constructor(){this._subscribers=[]}emit($){this._subscribers.forEach((J)=>J($))}static create(){let $=new u0;return{property:$,emit:(J)=>$.emit(J)}}}class J$ extends Error{name;code;source;cause;context;constructor($,J,Q){super(J);if(this.name=$,this.code=Q?.code,this.source=Q?.source??"UNKNOWN",this.cause=Q?.cause,this.context=Q?.context,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,source:this.source,context:this.context,cause:this.cause instanceof Error?{name:this.cause.name,message:this.cause.message}:this.cause,stack:this.stack}}toString(){let $=`[${this.source}] ${this.name}: ${this.message}`;if(this.code)$+=` (Code: ${this.code})`;if(this.context)$+=`
|
|
2
|
+
Context: ${JSON.stringify(this.context,null,2)}`;return $}}class s extends J${constructor($,J){super("RpcError",$,{...J,source:J?.source??"RPC_REQUEST"})}static connectionFailed($,J){return new s("Failed to connect to RPC endpoint",{code:"RPC_CONNECTION_FAILED",source:"RPC_CONNECTION",cause:J,context:{url:$}})}static timeout($,J){return new s("RPC request timed out",{code:"RPC_TIMEOUT",source:"RPC_TIMEOUT",context:{method:$,timeout:J}})}static invalidResponse($,J){return new s("Invalid RPC response",{code:"RPC_INVALID_RESPONSE",source:"RPC_RESPONSE",context:{method:$,response:J}})}static fromJsonRpcError($){return new s($.message,{code:$.code,source:"RPC_RESPONSE",context:{data:$.data}})}static websocketError($,J){return new s($,{code:"RPC_WEBSOCKET_ERROR",source:"RPC_WEBSOCKET",cause:J})}}class R0{rpcUrl;requestId=0;websocket=null;websocketConnected=!1;pendingResponses={};subscriptionListeners={};reconnectAttempt=0;initialBackoff=2000;maxBackoff=120000;constructor($){this.rpcUrl=$}async call($,J){this.requestId++;let Q={jsonrpc:"2.0",id:this.requestId,method:$,params:J};try{let Y=await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)});if(!Y.ok)throw s.connectionFailed(this.rpcUrl,Error(`HTTP ${Y.status}: ${Y.statusText}`));let G=await Y.json();if(G.error)throw s.fromJsonRpcError(G.error);if(G.result===void 0)throw s.invalidResponse($,G);return G.result}catch(Y){if(Y instanceof s)throw Y;throw s.connectionFailed(this.rpcUrl,Y)}}setRpcUrl($){this.rpcUrl=$}getRpcUrl(){return this.rpcUrl}connect(){return new Promise(($)=>{let J=this.rpcUrl.replace("http","ws");if(J.endsWith("/"))J+="ws";else J+="/ws";this.websocket=new WebSocket(J),this.websocket.onopen=()=>{console.log("WebSocket connected"),this.websocketConnected=!0,this.reconnectAttempt=0,$()},this.websocket.onmessage=(Q)=>{let Y=JSON.parse(Q.data),{id:G,method:Z,params:K}=Y;if(G!==void 0&&this.pendingResponses[G])this.pendingResponses[G].resolve(Y),delete this.pendingResponses[G];if(Z==="eth_subscription"&&K){let{subscription:X,result:q}=K;if(this.subscriptionListeners[X])this.subscriptionListeners[X].forEach((M)=>M(q))}},this.websocket.onclose=()=>{console.warn("WebSocket closed"),this.websocketConnected=!1},this.websocket.onerror=(Q)=>{console.error("WebSocket error:",Q),this.websocketConnected=!1,this.scheduleReconnect()}})}scheduleReconnect(){let $=Math.min(this.initialBackoff*Math.pow(2,this.reconnectAttempt),this.maxBackoff),J=$*(Math.random()*0.5),Q=$+J;console.log(`Reconnecting in ${Math.round(Q)}ms (attempt #${this.reconnectAttempt+1})`),this.reconnectAttempt++,setTimeout(()=>{this.reconnect()},Q)}async reconnect(){if(this.websocketConnected)return;try{await this.connect(),console.log("Reconnection successful")}catch($){console.error("Reconnection attempt failed:",$),this.scheduleReconnect()}}sendMessage($,J,Q=5000){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return Promise.reject(s.connectionFailed(this.rpcUrl));let Y=this.requestId++,G={jsonrpc:"2.0",method:$,params:J,id:Y};return new Promise((Z,K)=>{this.pendingResponses[Y]={resolve:Z,reject:K},this.websocket.send(JSON.stringify(G)),setTimeout(()=>{if(this.pendingResponses[Y])this.pendingResponses[Y].reject(s.timeout($,Q)),delete this.pendingResponses[Y]},Q)})}async subscribe($){let J=$?.toLowerCase();if(!this.websocketConnected)await this.connect();let Q=u0.create(),Y=JSON.stringify(J?{address:J}:{}),Z=(await this.sendMessage("eth_subscribe",["circles",Y])).result;if(!this.subscriptionListeners[Z])this.subscriptionListeners[Z]=[];return this.subscriptionListeners[Z].push((K)=>{O$(K).forEach((X)=>Q.emit(X))}),Q.property}}var R$=BigInt(4294967295),yJ=BigInt(32);function f8($,J=!1){if(J)return{h:Number($&R$),l:Number($>>yJ&R$)};return{h:Number($>>yJ&R$)|0,l:Number($&R$)|0}}function bJ($,J=!1){let Q=$.length,Y=new Uint32Array(Q),G=new Uint32Array(Q);for(let Z=0;Z<Q;Z++){let{h:K,l:X}=f8($[Z],J);[Y[Z],G[Z]]=[K,X]}return[Y,G]}var FJ=($,J,Q)=>$<<Q|J>>>32-Q,gJ=($,J,Q)=>J<<Q|$>>>32-Q,fJ=($,J,Q)=>J<<Q-32|$>>>64-Q,vJ=($,J,Q)=>$<<Q-32|J>>>64-Q;var I0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function v8($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function T0($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function K0($,...J){if(!v8($))throw Error("Uint8Array expected");if(J.length>0&&!J.includes($.length))throw Error("Uint8Array expected of length "+J+", got length="+$.length)}function hJ($){if(typeof $!=="function"||typeof $.create!=="function")throw Error("Hash should be wrapped by utils.createHasher");T0($.outputLen),T0($.blockLen)}function M0($,J=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(J&&$.finished)throw Error("Hash#digest() has already been called")}function C$($,J){K0($);let Q=J.outputLen;if($.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function mJ($){return new Uint32Array($.buffer,$.byteOffset,Math.floor($.byteLength/4))}function X0(...$){for(let J=0;J<$.length;J++)$[J].fill(0)}function B$($){return new DataView($.buffer,$.byteOffset,$.byteLength)}function Z0($,J){return $<<32-J|$>>>J}var h8=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function m8($){return $<<24&4278190080|$<<8&16711680|$>>>8&65280|$>>>24&255}function u8($){for(let J=0;J<$.length;J++)$[J]=m8($[J]);return $}var u$=h8?($)=>$:u8;function c8($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function _0($){if(typeof $==="string")$=c8($);return K0($),$}function uJ(...$){let J=0;for(let Y=0;Y<$.length;Y++){let G=$[Y];K0(G),J+=G.length}let Q=new Uint8Array(J);for(let Y=0,G=0;Y<$.length;Y++){let Z=$[Y];Q.set(Z,G),G+=Z.length}return Q}class x0{}function P$($){let J=(Y)=>$().update(_0(Y)).digest(),Q=$();return J.outputLen=Q.outputLen,J.blockLen=Q.blockLen,J.create=()=>$(),J}function cJ($=32){if(I0&&typeof I0.getRandomValues==="function")return I0.getRandomValues(new Uint8Array($));if(I0&&typeof I0.randomBytes==="function")return Uint8Array.from(I0.randomBytes($));throw Error("crypto.getRandomValues must be defined")}var l8=BigInt(0),Q$=BigInt(1),p8=BigInt(2),d8=BigInt(7),i8=BigInt(256),n8=BigInt(113),dJ=[],iJ=[],nJ=[];for(let $=0,J=Q$,Q=1,Y=0;$<24;$++){[Q,Y]=[Y,(2*Q+3*Y)%5],dJ.push(2*(5*Y+Q)),iJ.push(($+1)*($+2)/2%64);let G=l8;for(let Z=0;Z<7;Z++)if(J=(J<<Q$^(J>>d8)*n8)%i8,J&p8)G^=Q$<<(Q$<<BigInt(Z))-Q$;nJ.push(G)}var oJ=bJ(nJ,!0),o8=oJ[0],t8=oJ[1],lJ=($,J,Q)=>Q>32?fJ($,J,Q):FJ($,J,Q),pJ=($,J,Q)=>Q>32?vJ($,J,Q):gJ($,J,Q);function a8($,J=24){let Q=new Uint32Array(10);for(let Y=24-J;Y<24;Y++){for(let K=0;K<10;K++)Q[K]=$[K]^$[K+10]^$[K+20]^$[K+30]^$[K+40];for(let K=0;K<10;K+=2){let X=(K+8)%10,q=(K+2)%10,M=Q[q],j=Q[q+1],z=lJ(M,j,1)^Q[X],N=pJ(M,j,1)^Q[X+1];for(let D=0;D<50;D+=10)$[K+D]^=z,$[K+D+1]^=N}let G=$[2],Z=$[3];for(let K=0;K<24;K++){let X=iJ[K],q=lJ(G,Z,X),M=pJ(G,Z,X),j=dJ[K];G=$[j],Z=$[j+1],$[j]=q,$[j+1]=M}for(let K=0;K<50;K+=10){for(let X=0;X<10;X++)Q[X]=$[K+X];for(let X=0;X<10;X++)$[K+X]^=~Q[(X+2)%10]&Q[(X+4)%10]}$[0]^=o8[Y],$[1]^=t8[Y]}X0(Q)}class c$ extends x0{constructor($,J,Q,Y=!1,G=24){super();if(this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=$,this.suffix=J,this.outputLen=Q,this.enableXOF=Y,this.rounds=G,T0(Q),!(0<$&&$<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=mJ(this.state)}clone(){return this._cloneInto()}keccak(){u$(this.state32),a8(this.state32,this.rounds),u$(this.state32),this.posOut=0,this.pos=0}update($){M0(this),$=_0($),K0($);let{blockLen:J,state:Q}=this,Y=$.length;for(let G=0;G<Y;){let Z=Math.min(J-this.pos,Y-G);for(let K=0;K<Z;K++)Q[this.pos++]^=$[G++];if(this.pos===J)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:$,suffix:J,pos:Q,blockLen:Y}=this;if($[Q]^=J,(J&128)!==0&&Q===Y-1)this.keccak();$[Y-1]^=128,this.keccak()}writeInto($){M0(this,!1),K0($),this.finish();let J=this.state,{blockLen:Q}=this;for(let Y=0,G=$.length;Y<G;){if(this.posOut>=Q)this.keccak();let Z=Math.min(Q-this.posOut,G-Y);$.set(J.subarray(this.posOut,this.posOut+Z),Y),this.posOut+=Z,Y+=Z}return $}xofInto($){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto($)}xof($){return T0($),this.xofInto(new Uint8Array($))}digestInto($){if(C$($,this),this.finished)throw Error("digest() was already called");return this.writeInto($),this.destroy(),$}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,X0(this.state)}_cloneInto($){let{blockLen:J,suffix:Q,outputLen:Y,rounds:G,enableXOF:Z}=this;return $||($=new c$(J,Q,Y,Z,G)),$.state32.set(this.state32),$.pos=this.pos,$.posOut=this.posOut,$.finished=this.finished,$.rounds=G,$.suffix=Q,$.outputLen=Y,$.enableXOF=Z,$.destroyed=this.destroyed,$}}var s8=($,J,Q)=>P$(()=>new c$(J,$,Q));var c0=(()=>s8(1,136,32))();var tJ=[];for(let $=0;$<256;$++)tJ[$]=$.toString(16).padStart(2,"0");function L$($){let J="0x";for(let Q=0;Q<$.length;Q++)J+=tJ[$[Q]];return J}function H$($){let J=$.startsWith("0x")?$.slice(2):$,Q=new Uint8Array(J.length/2);for(let Y=0;Y<J.length;Y+=2)Q[Y/2]=parseInt(J.slice(Y,Y+2),16);return Q}var u=64,I$=32,S$=($)=>$.startsWith("0x")?$.slice(2):$;var q0=($)=>$.toString(16).padStart(u,"0");function B0($){let J=$.toLowerCase().replace("0x",""),Q=L$(c0(new TextEncoder().encode(J))).slice(2),Y="0x";for(let G=0;G<J.length;G++)Y+=parseInt(Q[G],16)>=8?J[G].toUpperCase():J[G];return Y}function l$($,J){if($==="tuple"&&J)return`(${J.map((G)=>l$(G.type,G.components)).join(",")})`;let Q=$.match(/^tuple(\[\d*\])$/);if(Q&&J)return`${l$("tuple",J)}${Q[1]}`;return $}function r8($){let Q=($.inputs||[]).map((Y)=>l$(Y.type,Y.components));return`${$.name}(${Q.join(",")})`}function e8($){let J=r8($),Q=c0(new TextEncoder().encode(J));return L$(Q.slice(0,4))}function l0($,J){if($==="string"||$==="bytes")return!0;if($.includes("[")){let Q=$.slice(0,$.indexOf("["));if($.endsWith("[]"))return!0;if(Q==="tuple")return aJ(J);return l0(Q)}if($==="tuple")return aJ(J);return!1}function aJ($){return $?.some((J)=>l0(J.type,J.components))??!1}function C0($,J,Q){if($==="tuple"&&Q)return JQ(Q,J);if($.includes("["))return $Q($,J,Q);return QQ($,J)}function $Q($,J,Q){let Y=$.slice(0,$.indexOf("[")),G=$.endsWith("[]"),Z=l0(Y,Q),K;if(Z){let X=J.map((j)=>C0(Y,j,Q)),q=J.length*I$;K=X.map((j)=>{let z=q;return q+=j.length/2,q0(z)}).join("")+X.join("")}else K=J.map((X)=>C0(Y,X,Q)).join("");return G?q0(J.length)+K:K}function JQ($,J){let Q=Array.isArray(J),Y=[],G=[],Z=[];for(let K=0;K<$.length;K++){let X=$[K],q=Q?J[K]:J[X.name||""],M=l0(X.type,X.components);if(Z.push(M),M)Y.push(""),G.push(C0(X.type,q,X.components));else Y.push(C0(X.type,q,X.components))}if(G.length>0){let K=Y.reduce((M,j,z)=>M+(Z[z]?I$:j.length/2),0),X="",q=0;for(let M=0;M<$.length;M++)if(Z[M])X+=q0(K),K+=G[q].length/2,q++;else X+=Y[M];return X+G.join("")}return Y.join("")}function QQ($,J){if($==="address")return S$(J).toLowerCase().padStart(u,"0");if($==="bool")return q0(J?1:0);if($.startsWith("uint")){let Q=typeof J==="bigint"?J:BigInt(J);return q0(Q)}if($.startsWith("int")){let Q=typeof J==="bigint"?J:BigInt(J);if(Q<0n){let Y=$==="int"?256:parseInt($.slice(3));Q=(1n<<BigInt(Y))+Q}return q0(Q)}if($.startsWith("bytes")&&$!=="bytes")return S$(J).padEnd(u,"0");if($==="bytes"){let Q=S$(J),Y=q0(Q.length/2),G=Q.padEnd(Math.ceil(Q.length/u)*u,"0");return Y+G}if($==="string"){let Q=Array.from(new TextEncoder().encode(J)).map((Z)=>Z.toString(16).padStart(2,"0")).join(""),Y=q0(Q.length/2),G=Q.padEnd(Math.ceil(Q.length/u)*u,"0");return Y+G}throw Error(`Unsupported type: ${$}`)}function Y$($,J,Q=0,Y){if($==="tuple"&&Y)return GQ(Y,J,Q);if($.includes("["))return YQ($,J,Q,Y);return ZQ($,J,Q)}function YQ($,J,Q,Y){let G=$.slice(0,$.indexOf("[")),Z=J.slice(Q,Q+u);if($.endsWith("[]")){let X=parseInt(Z,16)*2,q=parseInt(J.slice(X,X+u),16),M=[],j=X+u;for(let z=0;z<q;z++){let N=Y$(G,J,j,Y);M.push(N.value),j+=N.consumed}return{value:M,consumed:u}}let K=$.match(/\[(\d+)\]$/);if(K){let X=parseInt(K[1]),q=[],M=0;for(let j=0;j<X;j++){let z=Y$(G,J,Q+M,Y);q.push(z.value),M+=z.consumed}return{value:q,consumed:M}}throw Error(`Invalid array type: ${$}`)}function GQ($,J,Q){let Y=[],G=Q;for(let Z of $){let K=Y$(Z.type,J,G,Z.components);Y.push(K.value),G+=K.consumed}return{value:Y,consumed:G-Q}}function ZQ($,J,Q){let Y=J.slice(Q,Q+u);if($==="address")return{value:B0("0x"+Y.slice(24)),consumed:u};if($==="bool")return{value:parseInt(Y,16)!==0,consumed:u};if($.startsWith("uint"))return{value:BigInt("0x"+Y),consumed:u};if($.startsWith("int")){let G=BigInt("0x"+Y),Z=$==="int"?256:parseInt($.slice(3)),K=1n<<BigInt(Z-1);return{value:G>=K?G-(1n<<BigInt(Z)):G,consumed:u}}if($.startsWith("bytes")&&$!=="bytes"){let G=parseInt($.match(/^bytes(\d+)$/)[1]);return{value:"0x"+Y.slice(0,G*2),consumed:u}}if($==="bytes"){let G=parseInt(Y,16)*2,Z=parseInt(J.slice(G,G+u),16)*2;return{value:"0x"+J.slice(G+u,G+u+Z),consumed:u}}if($==="string"){let G=parseInt(Y,16)*2,Z=parseInt(J.slice(G,G+u),16)*2,K=J.slice(G+u,G+u+Z),X=new Uint8Array(K.match(/.{2}/g)?.map((q)=>parseInt(q,16))||[]);return{value:new TextDecoder().decode(X),consumed:u}}throw Error(`Unsupported type: ${$}`)}function T$($){let{abi:J,functionName:Q,args:Y=[]}=$,G=J.find((D)=>D.type==="function"&&D.name===Q);if(!G)throw Error(`Function "${Q}" not found in ABI`);let Z=e8(G),K=G.inputs||[];if(K.length===0)return Z;if(Y.length!==K.length)throw Error(`Expected ${K.length} arguments, got ${Y.length}`);let X=[],q=[],M=[];for(let D=0;D<K.length;D++){let P=K[D],V=P.components,k=l0(P.type,V);if(M.push(k),k)X.push(""),q.push(C0(P.type,Y[D],V));else X.push(C0(P.type,Y[D],V))}if(q.length===0)return Z+X.join("");let j=X.reduce((D,P,V)=>D+(M[V]?I$:P.length/2),0),z="",N=0;for(let D=0;D<K.length;D++)if(M[D])z+=q0(j),j+=q[N].length/2,N++;else z+=X[D];return Z+z+q.join("")}function p$($){let{abi:J,functionName:Q,data:Y}=$,G=J.find((M)=>M.type==="function"&&M.name===Q);if(!G)throw Error(`Function "${Q}" not found in ABI`);let Z=G.outputs||[];if(Z.length===0)return;let K=S$(Y);if(Z.length===1)return Y$(Z[0].type,K,0,Z[0].components).value;let X=[],q=0;for(let M of Z){let j=Y$(M.type,K,q,M.components);X.push(j.value),q+=j.consumed}return X}function Q0($,J){if($.length!==J.length)throw Error(`Type/value length mismatch: ${$.length} types, ${J.length} values`);let Q=[],Y=[],G=[];for(let q=0;q<$.length;q++){let M=$[q],j=l0(M);if(G.push(j),j)Q.push(""),Y.push(C0(M,J[q]));else Q.push(C0(M,J[q]))}if(Y.length===0)return"0x"+Q.join("");let Z=Q.reduce((q,M,j)=>q+(G[j]?I$:M.length/2),0),K="",X=0;for(let q=0;q<$.length;q++)if(G[q])K+=q0(Z),Z+=Y[X].length/2,X++;else K+=Q[q];return"0x"+K+Y.join("")}function L($){return $.toLowerCase()}function KQ($){return B0($)}function XQ($){if(typeof $!=="string")return!1;let J=$.replace("0x","");return J.length===40&&/^[0-9a-fA-F]{40}$/.test(J)}function f($){if($===null||$===void 0)return $;if(XQ($))return KQ($);if(Array.isArray($))return $.map((J)=>f(J));if(typeof $==="object"&&$!==null){let J={};for(let Q in $)if(Object.prototype.hasOwnProperty.call($,Q))J[Q]=f($[Q]);return J}return $}function sJ($){return{Source:L($.from),Sink:L($.to),TargetFlow:$.targetFlow.toString(),WithWrap:$.useWrappedBalances,FromTokens:$.fromTokens?.map(L),ToTokens:$.toTokens?.map(L),ExcludedFromTokens:$.excludeFromTokens?.map(L),ExcludedToTokens:$.excludeToTokens?.map(L),SimulatedBalances:$.simulatedBalances?.map((J)=>({Holder:L(J.holder),Token:L(J.token),Amount:J.amount.toString(),IsWrapped:J.isWrapped,IsStatic:J.isStatic})),SimulatedTrusts:$.simulatedTrusts?.map((J)=>({Truster:L(J.truster),Trustee:L(J.trustee)})),MaxTransfers:$.maxTransfers}}function j0($){let J={};for(let Q in $){let Y=$[Q];if(Y===null||Y===void 0)J[Q]=Y;else if(typeof Y==="string"&&/^\d+$/.test(Y))J[Q]=BigInt(Y);else if(typeof Y==="object"&&!Array.isArray(Y))J[Q]=j0(Y);else if(Array.isArray(Y))J[Q]=Y.map((G)=>typeof G==="object"&&G!==null?j0(G):G);else J[Q]=Y}return J}var _$="0x0000000000000000000000000000000000000000",p=BigInt(96)*BigInt(1000000000000000000),G$=BigInt("9999999999999999999999999999999999999"),d$="0x4e1DCf7AD4e460CfD30791CCC4F9c8a4f820ec67",i$="0x89867a67674bd4bf33165a653cde826b696ab7d050166b71066dfa0b9b6f90f4",n$="0xe298282cefe913ab5d282047161268a8222e4bd4ed106300c547894bbefd31ee",p0="0xc19bc204eb1c1d5b3fe500e5e5dfabab625f286c",E0="0x9Eb51E6A39B3F17bB1883B80748b56170039ff1d";class W0{client;constructor($){this.client=$}async findPath($){let J=sJ($),Q=await this.client.call("circlesV2_findPath",[J]),Y=j0(Q);return f(Y)}async findMaxFlow($){let J=await this.findPath({...$,targetFlow:G$});return BigInt(J.maxFlow)}}class Z${client;constructor($){this.client=$}async query($){let J=await this.client.call("circles_query",[$]);return f(J)}async tables(){return this.client.call("circles_tables",[])}async events($,J,Q=null,Y=null,G=!1){let Z=await this.client.call("circles_events",[$,J,Q,Y,G]);return f(Z)}}var qQ=[{name:"blockNumber",sortOrder:"DESC"},{name:"transactionIndex",sortOrder:"DESC"},{name:"logIndex",sortOrder:"DESC"}];class Y0{params;client;rowTransformer;cursorColumns;orderColumns;get currentPage(){return this._currentPage}_currentPage;constructor($,J,Q){this.client=$,this.params=J,this.rowTransformer=Q||J.rowTransformer,this.orderColumns=J.orderColumns,this.cursorColumns=J.cursorColumns||this.buildEventCursorColumns()}buildEventCursorColumns(){let $=qQ.map((J)=>({...J,sortOrder:this.params.sortOrder}));if(this.params.table==="TransferBatch")$.push({name:"batchIndex",sortOrder:this.params.sortOrder});return $}transformCursorValue($,J){if(J)return J($);if(typeof $==="bigint")return $.toString();return $}createEqualityPredicate($,J){return{Type:"FilterPredicate",FilterType:"Equals",Column:$.name,Value:this.transformCursorValue(J,$.toValue)}}createComparisonPredicate($,J){return{Type:"FilterPredicate",FilterType:$.sortOrder==="ASC"?"GreaterThan":"LessThan",Column:$.name,Value:this.transformCursorValue(J,$.toValue)}}buildCursorFilter($){if(!$)return[];let J=[];for(let Q=0;Q<this.cursorColumns.length;Q++){let Y=this.cursorColumns[Q],G=$[Y.name];if(G===void 0)continue;if(Q===0)J.push(this.createComparisonPredicate(Y,G));else{let Z=[];for(let K=0;K<Q;K++){let X=this.cursorColumns[K],q=$[X.name];if(q!==void 0)Z.push(this.createEqualityPredicate(X,q))}Z.push(this.createComparisonPredicate(Y,G)),J.push({Type:"Conjunction",ConjunctionType:"And",Predicates:Z})}}if(J.length===0)return[];return[{Type:"Conjunction",ConjunctionType:"Or",Predicates:J}]}buildOrderBy(){if(this.orderColumns&&this.orderColumns.length>0)return this.orderColumns;return this.cursorColumns.map(($)=>({Column:$.name,SortOrder:$.sortOrder}))}combineFilters($,J){if(!$?.length&&!J?.length)return[];if(!$?.length)return J||[];if(!J?.length)return $;return[{Type:"Conjunction",ConjunctionType:"And",Predicates:[...$,...J]}]}rowsToObjects($){let{columns:J,rows:Q}=$;return Q.map((Y)=>{let G={};return J.forEach((Z,K)=>{G[Z]=Y[K]}),this.rowTransformer?this.rowTransformer(G):G})}rowToCursor($){let J={};for(let Q of this.cursorColumns)J[Q.name]=$[Q.name];return J}getCursors($){if($.length===0)return{};return{first:this.rowToCursor($[0]),last:this.rowToCursor($[$.length-1])}}async queryNextPage(){let $=this.buildCursorFilter(this._currentPage?.lastCursor),J=this.combineFilters(this.params.filter,$),Q={Namespace:this.params.namespace,Table:this.params.table,Columns:this.params.columns,Filter:J,Order:this.buildOrderBy(),Limit:this.params.limit},Y=await this.client.call("circles_query",[Q]),G=this.rowsToObjects(Y),Z=this.getCursors(G);return this._currentPage={limit:this.params.limit,size:G.length,firstCursor:Z.first,lastCursor:Z.last,sortOrder:this.params.sortOrder,hasMore:G.length===this.params.limit,results:G},G.length>0}reset(){this._currentPage=void 0}}class k0{client;constructor($){this.client=$}transformQueryResponse($){let{columns:J,rows:Q}=$;return Q.map((Y)=>{let G={};return J.forEach((Z,K)=>{G[Z]=Y[K]}),G})}async getCommonTrust($,J){let Q=await this.client.call("circles_getCommonTrust",[L($),L(J)]);return f(Q)}getTrustRelations($,J=100,Q="DESC"){let Y=L($),G=[{Type:"Conjunction",ConjunctionType:"And",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"version",Value:2},{Type:"Conjunction",ConjunctionType:"Or",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"trustee",Value:Y},{Type:"FilterPredicate",FilterType:"Equals",Column:"truster",Value:Y}]}]}];return new Y0(this.client,{namespace:"V_Crc",table:"TrustRelations",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","version","trustee","truster","expiryTime"],filter:G,limit:J},(Z)=>f(Z))}async getAggregatedTrustRelations($){let J=L($),Q=this.getTrustRelations(J,1000),Y=[];while(await Q.queryNextPage())if(Y.push(...Q.currentPage.results),!Q.currentPage.hasMore)break;let G={};Y.forEach((K)=>{let X=L(K.truster),q=L(K.trustee),M=X!==J?K.truster:K.trustee;if(!G[M])G[M]=[];G[M].push(K)});let Z=Object.entries(G).filter(([K])=>L(K)!==J).map(([K,X])=>{let q=Math.max(...X.map((j)=>j.timestamp)),M;if(X.length===2)M="mutuallyTrusts";else if(L(X[0]?.trustee)===J)M="trustedBy";else if(L(X[0]?.truster)===J)M="trusts";else throw Error("Unexpected trust list row. Couldn't determine trust relation.");return{subjectAvatar:J,relation:M,objectAvatar:K,timestamp:q}});return f(Z)}async getTrustedBy($){let J=L($),Y=(await this.getAggregatedTrustRelations(J)).filter((G)=>G.relation==="trustedBy");return f(Y)}async getTrusts($){let J=L($),Y=(await this.getAggregatedTrustRelations(J)).filter((G)=>G.relation==="trusts");return f(Y)}async getMutualTrusts($){let J=L($),Y=(await this.getAggregatedTrustRelations(J)).filter((G)=>G.relation==="mutuallyTrusts");return f(Y)}}class i{static ONE_64=1n<<64n;static GAMMA_64=18443079296116538654n;static BETA_64=18450409579521241655n;static SECONDS_PER_DAY=86400n;static INFLATION_DAY_ZERO_UNIX=1602720000n;static ATTO_FACTOR=1000000000000000000n;static FACTOR_1E12=1000000000000n;static V1_ACCURACY=100000000n;static V1_INFLATION_PCT_NUM=107n;static V1_INFLATION_PCT_DEN=100n;static PERIOD_SEC=31556952n;static mul64($,J){return $*J>>64n}static mulU($,J){return $*J>>64n}static pow64($,J){let Q=$,Y=J,G=this.ONE_64;while(Y>0n){if((Y&1n)===1n)G=this.mul64(G,Q);Q=this.mul64(Q,Q),Y>>=1n}return G}static ONE_36=1000000000000000000000000000000000000000n;static GAMMA_36=999801332008598957430613406568191166n;static BETA_36=1000198707468214629156271489013303962n;static mul36($,J){return $*J/this.ONE_36}static pow36($,J){let Q=this.ONE_36,Y=$,G=J;while(G>0n){if((G&1n)===1n)Q=this.mul36(Q,Y);Y=this.mul36(Y,Y),G>>=1n}return Q}static attoCirclesToCircles($){if($===0n)return 0;let J=$/this.ATTO_FACTOR,Q=$%this.ATTO_FACTOR,Y=BigInt(Number.MAX_SAFE_INTEGER);if(J>Y||J<-Y)throw RangeError("Atto value’s integer component exceeds JS double precision.");return Number(J)+Number(Q)/Number(this.ATTO_FACTOR)}static circlesToAttoCircles($){return BigInt(Math.trunc($*Number(this.ATTO_FACTOR)))}static inflationaryToDemurrage($,J){return this.mulU(this.pow64(this.GAMMA_64,J),$)}static demurrageToInflationary($,J){return this.mulU(this.pow64(this.BETA_64,J),$)}static dayFromTimestamp($){return($-this.INFLATION_DAY_ZERO_UNIX)/this.SECONDS_PER_DAY}static attoCirclesToAttoStaticCircles($,J=BigInt(Math.floor(Date.now()/1000))){return this.demurrageToInflationary($,this.dayFromTimestamp(J))}static attoStaticCirclesToAttoCircles($,J=BigInt(Math.floor(Date.now()/1000))){return this.inflationaryToDemurrage($,this.dayFromTimestamp(J))}static inflationaryToDemurrageExact($,J){let Q=this.pow36(this.GAMMA_36,J);return $*Q/this.ONE_36}static demurrageToInflationaryExact($,J){let Q=this.pow36(this.BETA_36,J);return $*Q/this.ONE_36}static attoCirclesToAttoStaticCirclesExact($,J=BigInt(Math.floor(Date.now()/1000))){let Q=this.dayFromTimestamp(J);return this.demurrageToInflationaryExact($,Q)}static attoStaticCirclesToAttoCirclesExact($,J=BigInt(Math.floor(Date.now()/1000))){let Q=this.dayFromTimestamp(J);return this.inflationaryToDemurrageExact($,Q)}static truncateToInt64($){let J=$/this.FACTOR_1E12,Q=9223372036854775807n;return J>Q?Q:J}static blowUpToBigInt($){return $*this.FACTOR_1E12}static truncateToSixDecimals($){return this.blowUpToBigInt(this.truncateToInt64($))}static v1InflateFactor($){if($===0n)return this.V1_ACCURACY;return this.V1_ACCURACY*this.V1_INFLATION_PCT_NUM**$/this.V1_INFLATION_PCT_DEN**$}static attoCrcToAttoCircles($,J){let Q=J-this.INFLATION_DAY_ZERO_UNIX,Y=Q/this.PERIOD_SEC,G=Q%this.PERIOD_SEC,Z=this.v1InflateFactor(Y),K=this.v1InflateFactor(Y+1n);return this.v1ToDemurrage($,Z,K,G,this.PERIOD_SEC)}static attoCirclesToAttoCrc($,J){let Q=J-this.INFLATION_DAY_ZERO_UNIX,Y=Q/this.PERIOD_SEC,G=Q%this.PERIOD_SEC,Z=this.v1InflateFactor(Y),K=this.v1InflateFactor(Y+1n),X=Z*(this.PERIOD_SEC-G)+K*G;return $*3n*this.V1_ACCURACY*this.PERIOD_SEC/X}static v1ToDemurrage($,J,Q,Y,G){let Z=J*(G-Y)+Q*Y;return $*3n*this.V1_ACCURACY*G/Z}}class A0{client;constructor($){this.client=$}async getTotalBalance($,J=!0){let Q=await this.client.call("circlesV2_getTotalBalance",[L($),J]);return i.circlesToAttoCircles(Q)}async getTokenBalances($){let Q=(await this.client.call("circles_getTokenBalances",[L($)])).map((Y)=>j0(Y));return f(Q)}}class K${client;constructor($){this.client=$}async getAvatarInfo($){let J=await this.getAvatarInfoBatch([$]);return J.length>0?J[0]:void 0}async getAvatarInfoBatch($){if($.length===0)return[];let J=$.map((Y)=>L(Y)),Q=await this.client.call("circles_getAvatarInfoBatch",[J]);return f(Q)}async getNetworkSnapshot(){let $=await this.client.call("circles_getNetworkSnapshot",[]);return f($)}}class X${client;constructor($){this.client=$}async getProfileByCid($){return this.client.call("circles_getProfileByCid",[$])}async getProfileByCidBatch($){return this.client.call("circles_getProfileByCidBatch",[$])}async getProfileByAddress($){return this.client.call("circles_getProfileByAddress",[L($)])}async getProfileByAddressBatch($){return this.client.call("circles_getProfileByAddressBatch",[$.map((J)=>J===null?null:L(J))])}async searchProfiles($,J=10,Q=0,Y){return this.client.call("circles_searchProfiles",[$.toLowerCase(),J,Q,Y])}async searchByAddressOrName($,J=10,Q=0,Y){let G=[],Z=/^0x[a-fA-F0-9]{40}$/.test($);if(Z)try{let K=await this.getProfileByAddress($);if(K){let X={...K,address:$};if(!Y||!X.avatarType||Y.includes(X.avatarType))G.push(X)}}catch(K){console.warn("Failed to get profile by address:",K)}try{let K=await this.searchProfiles($,J,Q,Y);if(Z&&G.length>0){let X=$.toLowerCase(),q=K.filter((M)=>M.address?.toLowerCase()!==X);G.push(...q)}else G.push(...K)}catch(K){console.warn("Failed to search profiles by text:",K)}return G.slice(0,J)}}class q${client;constructor($){this.client=$}async getTokenInfo($){let J=await this.getTokenInfoBatch([$]);return J.length>0?J[0]:void 0}async getTokenInfoBatch($){if($.length===0)return[];let J=$.map((G)=>L(G)),Y=(await this.client.call("circles_getTokenInfoBatch",[J])).map((G)=>j0(G));return f(Y)}getTokenHolders($,J=100,Q="DESC"){let Y=L($);return new Y0(this.client,{namespace:"V_CrcV2",table:"BalancesByAccountAndToken",columns:["account","tokenAddress","demurragedTotalBalance"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"tokenAddress",Value:Y}],cursorColumns:[{name:"demurragedTotalBalance",sortOrder:Q},{name:"account",sortOrder:"ASC"}],orderColumns:[{Column:"demurragedTotalBalance",SortOrder:Q},{Column:"account",SortOrder:"ASC"}],limit:J,sortOrder:Q},(G)=>({account:G.account,tokenAddress:G.tokenAddress,demurragedTotalBalance:G.demurragedTotalBalance}))}}class M${client;constructor($){this.client=$}transformQueryResponse($){let{columns:J,rows:Q}=$;return Q.map((Y)=>{let G={};return J.forEach((Z,K)=>{G[Z]=Y[K]}),G})}async getInvitedBy($){let J=L($),Q=await this.client.call("circles_query",[{Namespace:"CrcV2",Table:"RegisterHuman",Columns:["inviter"],Filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"avatar",Value:J}],Order:[{Column:"blockNumber",SortOrder:"DESC"}],Limit:1}]);if(Q.length>0)return f(Q[0].inviter);return}async getInvitations($){let J=L($),Q=96,Y=await this.client.call("circles_getAvatarInfoBatch",[[J]]);if((Y.length>0?Y[0]:void 0)?.version===2)return[];let Z=await this.client.call("circles_query",[{Namespace:"V_Crc",Table:"TrustRelations",Columns:["truster","trustee"],Filter:[{Type:"Conjunction",ConjunctionType:"And",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"version",Value:2},{Type:"FilterPredicate",FilterType:"Equals",Column:"trustee",Value:J}]}],Order:[]}]),X=this.transformQueryResponse(Z).map((j)=>j.truster);if(X.length===0)return[];let q=await this.client.call("circles_getAvatarInfoBatch",[X]),M=[];for(let j of q){if(!j?.isHuman)continue;let N=(await this.client.call("circles_getTokenBalances",[j.avatar])).find((D)=>L(D.tokenAddress)===L(j.avatar));if(N&&N.circles>=96)M.push(j)}return f(M)}async getInvitationsFrom($,J=!1){let Q=L($);if(J){let Y=await this.client.call("circles_query",[{Namespace:"CrcV2",Table:"RegisterHuman",Columns:["avatar"],Filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"inviter",Value:Q}],Order:[{Column:"blockNumber",SortOrder:"DESC"}]}]),Z=this.transformQueryResponse(Y).map((K)=>K.avatar);return f(Z)}else{let Y=await this.client.call("circles_query",[{Namespace:"V_Crc",Table:"TrustRelations",Columns:["trustee","truster"],Filter:[{Type:"Conjunction",ConjunctionType:"And",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"version",Value:2},{Type:"FilterPredicate",FilterType:"Equals",Column:"truster",Value:Q}]}],Order:[]}]),Z=this.transformQueryResponse(Y).map((M)=>M.trustee);if(Z.length===0)return[];let K=await this.client.call("circles_getAvatarInfoBatch",[Z]),X=new Set(K.filter((M)=>M!==null).map((M)=>L(M.avatar))),q=Z.filter((M)=>!X.has(L(M)));return f(q)}}}function MQ($,J){let Q=BigInt($),Y=i.attoCirclesToCircles(Q),G=i.attoCirclesToAttoCrc(Q,BigInt(J)),Z=i.attoCirclesToCircles(G),K=i.attoCirclesToAttoStaticCircles(Q,BigInt(J)),X=i.attoCirclesToCircles(K);return{attoCircles:Q,circles:Y,staticAttoCircles:K,staticCircles:X,attoCrc:G,crc:Z}}class j${client;constructor($){this.client=$}getTransactionHistory($,J=50,Q="DESC"){let Y=L($),G=[{Type:"Conjunction",ConjunctionType:"And",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"version",Value:2},{Type:"Conjunction",ConjunctionType:"Or",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"from",Value:Y},{Type:"FilterPredicate",FilterType:"Equals",Column:"to",Value:Y}]}]}];return new Y0(this.client,{namespace:"V_Crc",table:"TransferSummary",sortOrder:Q,columns:[],filter:G,limit:J},(Z)=>{let K=MQ(Z.value,Z.timestamp),X={...Z,...K};return f(X)})}}class w0{client;constructor($){this.client=$}async findGroups($=50,J){let Q=this.getGroups($,J,"DESC"),Y=[];while(await Q.queryNextPage()){if(Y.push(...Q.currentPage.results),Y.length>=$)break;if(!Q.currentPage.hasMore)break}return Y.slice(0,$)}getGroupMemberships($,J=50,Q="DESC"){let Y=L($);return new Y0(this.client,{namespace:"V_CrcV2",table:"GroupMemberships",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","member","expiryTime"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"member",Value:Y}],limit:J},(G)=>f(G))}getGroupHolders($,J=100){let Q=L($);return new Y0(this.client,{namespace:"V_CrcV2",table:"GroupTokenHoldersBalance",sortOrder:"DESC",columns:["group","holder","totalBalance","demurragedTotalBalance","fractionOwnership"],cursorColumns:[{name:"holder",sortOrder:"ASC"}],orderColumns:[{Column:"totalBalance",SortOrder:"DESC"},{Column:"holder",SortOrder:"ASC"}],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:Q}],limit:J,rowTransformer:(Y)=>{let G={...Y,totalBalance:BigInt(Y.totalBalance),demurragedTotalBalance:BigInt(Y.demurragedTotalBalance)};return f(G)}})}getGroupMembers($,J=100,Q="DESC"){let Y=L($);return new Y0(this.client,{namespace:"V_CrcV2",table:"GroupMemberships",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","member","expiryTime"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:Y}],limit:J},(G)=>f(G))}getGroups($=50,J,Q="DESC"){let Y=[];if(J){if(J.nameStartsWith)Y.push({Type:"FilterPredicate",FilterType:"Like",Column:"name",Value:J.nameStartsWith+"%"});if(J.symbolStartsWith)Y.push({Type:"FilterPredicate",FilterType:"Like",Column:"symbol",Value:J.symbolStartsWith+"%"});if(J.groupAddressIn&&J.groupAddressIn.length>0){let Z=J.groupAddressIn.map((K)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:L(K)}));if(Z.length===1)Y.push(Z[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:Z})}if(J.groupTypeIn&&J.groupTypeIn.length>0){let Z=J.groupTypeIn.map((K)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"type",Value:K}));if(Z.length===1)Y.push(Z[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:Z})}if(J.ownerIn&&J.ownerIn.length>0){let Z=J.ownerIn.map((K)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"owner",Value:L(K)}));if(Z.length===1)Y.push(Z[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:Z})}if(J.mintHandlerEquals)Y.push({Type:"FilterPredicate",FilterType:"Equals",Column:"mintHandler",Value:L(J.mintHandlerEquals)});if(J.treasuryEquals)Y.push({Type:"FilterPredicate",FilterType:"Equals",Column:"treasury",Value:L(J.treasuryEquals)})}let G=Y.length>1?[{Type:"Conjunction",ConjunctionType:"And",Predicates:Y}]:Y;return new Y0(this.client,{namespace:"V_CrcV2",table:"Groups",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","type","owner","mintPolicy","mintHandler","treasury","service","feeCollection","memberCount","name","symbol","cidV0Digest","erc20WrapperDemurraged","erc20WrapperStatic"],filter:G,limit:$},(Z)=>f(Z))}}class x${client;_pathfinder;_query;_trust;_balance;_avatar;_profile;_token;_invitation;_transaction;_group;constructor($="https://rpc.circlesubi.network/"){this.client=new R0($)}get pathfinder(){if(!this._pathfinder)this._pathfinder=new W0(this.client);return this._pathfinder}get query(){if(!this._query)this._query=new Z$(this.client);return this._query}get trust(){if(!this._trust)this._trust=new k0(this.client);return this._trust}get balance(){if(!this._balance)this._balance=new A0(this.client);return this._balance}get avatar(){if(!this._avatar)this._avatar=new K$(this.client);return this._avatar}get profile(){if(!this._profile)this._profile=new X$(this.client);return this._profile}get token(){if(!this._token)this._token=new q$(this.client);return this._token}get invitation(){if(!this._invitation)this._invitation=new M$(this.client);return this._invitation}get transaction(){if(!this._transaction)this._transaction=new j$(this.client);return this._transaction}get group(){if(!this._group)this._group=new w0(this.client);return this._group}setRpcUrl($){this.client.setRpcUrl($)}getRpcUrl(){return this.client.getRpcUrl()}}class n{address;abi;rpcUrl;constructor($){this.address=$.address,this.abi=$.abi,this.rpcUrl=$.rpcUrl}async read($,J,Q){let Y=T$({abi:this.abi,functionName:$,args:J}),G={to:this.address,data:Y,...Q?.from&&{from:Q.from}},K=await(await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[G,"latest"]})})).json();if(K.error)throw Error(`RPC Error: ${K.error.message}`);if(!K.result)throw Error("No result returned from RPC call");return p$({abi:this.abi,functionName:$,data:K.result})}encodeWrite($,J){return T$({abi:this.abi,functionName:$,args:J})}}var rJ=[{type:"function",name:"operateFlowMatrix",inputs:[{name:"_flowVertices",type:"address[]"},{name:"_flow",type:"tuple[]",components:[{name:"streamSinkId",type:"uint16"},{name:"amount",type:"uint192"}]},{name:"_streams",type:"tuple[]",components:[{name:"sourceCoordinate",type:"uint16"},{name:"flowEdgeIds",type:"uint16[]"},{name:"data",type:"bytes"}]},{name:"_packedCoordinates",type:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"isApprovedForAll",inputs:[{name:"_account",type:"address"},{name:"_operator",type:"address"}],outputs:[{type:"bool"}],stateMutability:"view"},{type:"function",name:"setApprovalForAll",inputs:[{name:"_operator",type:"address"},{name:"_approved",type:"bool"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"wrap",inputs:[{name:"_avatar",type:"address"},{name:"_amount",type:"uint256"},{name:"_type",type:"uint8"}],outputs:[{type:"address"}],stateMutability:"nonpayable"},{type:"function",name:"trust",inputs:[{name:"_trustReceiver",type:"address"},{name:"_expiry",type:"uint96"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"isTrusted",inputs:[{name:"_truster",type:"address"},{name:"_trustee",type:"address"}],outputs:[{type:"bool"}],stateMutability:"view"},{type:"function",name:"toTokenId",inputs:[{name:"_avatar",type:"address"}],outputs:[{type:"uint256"}],stateMutability:"pure"},{type:"function",name:"safeTransferFrom",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_id",type:"uint256"},{name:"_value",type:"uint256"},{name:"_data",type:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"isHuman",inputs:[{name:"_human",type:"address"}],outputs:[{type:"bool"}],stateMutability:"view"},{type:"function",name:"safeBatchTransferFrom",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_ids",type:"uint256[]"},{name:"_values",type:"uint256[]"},{name:"_data",type:"bytes"}],outputs:[],stateMutability:"nonpayable"}];class P0 extends n{constructor($){super({address:$.address,abi:rJ,rpcUrl:$.rpcUrl})}async isTrusted($,J){return this.read("isTrusted",[$,J])}async isApprovedForAll($,J){return this.read("isApprovedForAll",[$,J])}async toTokenId($){return this.read("toTokenId",[$])}trust($,J){return{to:this.address,data:this.encodeWrite("trust",[$,J]),value:0n}}setApprovalForAll($,J){return{to:this.address,data:this.encodeWrite("setApprovalForAll",[$,J]),value:0n}}wrap($,J,Q){return{to:this.address,data:this.encodeWrite("wrap",[$,J,Q]),value:0n}}safeTransferFrom($,J,Q,Y,G="0x"){return{to:this.address,data:this.encodeWrite("safeTransferFrom",[$,J,Q,Y,G]),value:0n}}operateFlowMatrix($,J,Q,Y){return{to:this.address,data:this.encodeWrite("operateFlowMatrix",[$,J,Q,Y]),value:0n}}async isHuman($){return this.read("isHuman",[$])}safeBatchTransferFrom($,J,Q,Y,G="0x"){return{to:this.address,data:this.encodeWrite("safeBatchTransferFrom",[$,J,Q,Y,G]),value:0n}}}var eJ=[{type:"function",name:"erc20Circles",inputs:[{name:"_circlesType",type:"uint8"},{name:"_avatar",type:"address"}],outputs:[{type:"address"}],stateMutability:"view"}];class E$ extends n{constructor($){super({address:$.address,abi:eJ,rpcUrl:$.rpcUrl})}async erc20Circles($,J){return this.read("erc20Circles",[$,J])}}var o$=[{type:"function",name:"unwrap",inputs:[{name:"_amount",type:"uint256"}],outputs:[],stateMutability:"nonpayable"}];class d0 extends n{constructor($){super({address:$.address,abi:o$,rpcUrl:$.rpcUrl})}unwrap($){return{to:this.address,data:this.encodeWrite("unwrap",[$]),value:0n}}}class i0 extends n{constructor($){super({address:$.address,abi:o$,rpcUrl:$.rpcUrl})}unwrap($){return{to:this.address,data:this.encodeWrite("unwrap",[$]),value:0n}}}var t$=[{type:"function",name:"createAccount",inputs:[{name:"signer",type:"address"}],outputs:[{name:"account",type:"address"}],stateMutability:"nonpayable"},{type:"function",name:"createAccounts",inputs:[{name:"signers",type:"address[]"}],outputs:[{name:"_accounts",type:"address[]"}],stateMutability:"nonpayable"}];var a$=[{type:"function",name:"claimInvite",inputs:[],outputs:[{name:"id",type:"uint256"}],stateMutability:"nonpayable"},{type:"function",name:"claimInvites",inputs:[{name:"numberOfInvites",type:"uint256"}],outputs:[{name:"ids",type:"uint256[]"}],stateMutability:"nonpayable"},{type:"function",name:"inviterQuota",inputs:[{name:"",type:"address"}],outputs:[{type:"uint256"}],stateMutability:"view"},{type:"function",name:"INVITATION_FEE",inputs:[],outputs:[{type:"uint256"}],stateMutability:"view"},{type:"function",name:"invitationModule",inputs:[],outputs:[{type:"address"}],stateMutability:"view"}];var s$=[{type:"function",name:"isModuleEnabled",inputs:[{name:"module",type:"address"}],outputs:[{name:"",type:"bool"}],stateMutability:"view"},{type:"function",name:"enableModule",inputs:[{name:"module",type:"address"}],outputs:[],stateMutability:"nonpayable"}];var r$=[{type:"function",name:"trustInviter",inputs:[{name:"inviter",type:"address"}],outputs:[],stateMutability:"nonpayable"}];class n0 extends n{constructor($){super({address:$.address,abi:t$,rpcUrl:$.rpcUrl})}createAccount($){return{to:this.address,data:this.encodeWrite("createAccount",[$]),value:0n}}createAccounts($){return{to:this.address,data:this.encodeWrite("createAccounts",[$]),value:0n}}}class o0 extends n{constructor($){super({address:$.address,abi:a$,rpcUrl:$.rpcUrl})}claimInvite(){return{to:this.address,data:this.encodeWrite("claimInvite",[]),value:0n}}claimInvites($){return{to:this.address,data:this.encodeWrite("claimInvites",[$]),value:0n}}async inviterQuota($){return this.read("inviterQuota",[$])}async invitationFee(){return this.read("INVITATION_FEE")}async invitationModule(){return this.read("invitationModule")}}class k$ extends n{constructor($){super({address:$.address,abi:s$,rpcUrl:$.rpcUrl})}async isModuleEnabled($){return this.read("isModuleEnabled",[$])}enableModule($){return{to:this.address,data:this.encodeWrite("enableModule",[$]),value:0n}}}class A$ extends n{constructor($){super({address:$.address,abi:r$,rpcUrl:$.rpcUrl})}trustInviter($){return{to:this.address,data:this.encodeWrite("trustInviter",[$]),value:0n}}}class w$ extends Error{name;code;source;cause;context;constructor($,J,Q){super(J);if(this.name=$,this.code=Q?.code,this.source=Q?.source??"UNKNOWN",this.cause=Q?.cause,this.context=Q?.context,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,source:this.source,context:this.context,cause:this.cause instanceof Error?{name:this.cause.name,message:this.cause.message}:this.cause,stack:this.stack}}toString(){let $=`[${this.source}] ${this.name}: ${this.message}`;if(this.code)$+=` (Code: ${this.code})`;if(this.context)$+=`
|
|
3
|
+
Context: ${JSON.stringify(this.context,null,2)}`;return $}}function jQ($,J,Q,Y){if(typeof $.setBigUint64==="function")return $.setBigUint64(J,Q,Y);let G=BigInt(32),Z=BigInt(4294967295),K=Number(Q>>G&Z),X=Number(Q&Z),q=Y?4:0,M=Y?0:4;$.setUint32(J+q,K,Y),$.setUint32(J+M,X,Y)}function $8($,J,Q){return $&J^~$&Q}function J8($,J,Q){return $&J^$&Q^J&Q}class e$ extends x0{constructor($,J,Q,Y){super();this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=$,this.outputLen=J,this.padOffset=Q,this.isLE=Y,this.buffer=new Uint8Array($),this.view=B$(this.buffer)}update($){M0(this),$=_0($),K0($);let{view:J,buffer:Q,blockLen:Y}=this,G=$.length;for(let Z=0;Z<G;){let K=Math.min(Y-this.pos,G-Z);if(K===Y){let X=B$($);for(;Y<=G-Z;Z+=Y)this.process(X,Z);continue}if(Q.set($.subarray(Z,Z+K),this.pos),this.pos+=K,Z+=K,this.pos===Y)this.process(J,0),this.pos=0}return this.length+=$.length,this.roundClean(),this}digestInto($){M0(this),C$($,this),this.finished=!0;let{buffer:J,view:Q,blockLen:Y,isLE:G}=this,{pos:Z}=this;if(J[Z++]=128,X0(this.buffer.subarray(Z)),this.padOffset>Y-Z)this.process(Q,0),Z=0;for(let j=Z;j<Y;j++)J[j]=0;jQ(Q,Y-8,BigInt(this.length*8),G),this.process(Q,0);let K=B$($),X=this.outputLen;if(X%4)throw Error("_sha2: outputLen should be aligned to 32bit");let q=X/4,M=this.get();if(q>M.length)throw Error("_sha2: outputLen bigger than state");for(let j=0;j<q;j++)K.setUint32(4*j,M[j],G)}digest(){let{buffer:$,outputLen:J}=this;this.digestInto($);let Q=$.slice(0,J);return this.destroy(),Q}_cloneInto($){$||($=new this.constructor),$.set(...this.get());let{blockLen:J,buffer:Q,length:Y,finished:G,destroyed:Z,pos:K}=this;if($.destroyed=Z,$.finished=G,$.length=Y,$.pos=K,Y%J)$.buffer.set(Q);return $}clone(){return this._cloneInto()}}var U0=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var WQ=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),L0=new Uint32Array(64);class Q8 extends e${constructor($=32){super(64,$,8,!1);this.A=U0[0]|0,this.B=U0[1]|0,this.C=U0[2]|0,this.D=U0[3]|0,this.E=U0[4]|0,this.F=U0[5]|0,this.G=U0[6]|0,this.H=U0[7]|0}get(){let{A:$,B:J,C:Q,D:Y,E:G,F:Z,G:K,H:X}=this;return[$,J,Q,Y,G,Z,K,X]}set($,J,Q,Y,G,Z,K,X){this.A=$|0,this.B=J|0,this.C=Q|0,this.D=Y|0,this.E=G|0,this.F=Z|0,this.G=K|0,this.H=X|0}process($,J){for(let j=0;j<16;j++,J+=4)L0[j]=$.getUint32(J,!1);for(let j=16;j<64;j++){let z=L0[j-15],N=L0[j-2],D=Z0(z,7)^Z0(z,18)^z>>>3,P=Z0(N,17)^Z0(N,19)^N>>>10;L0[j]=P+L0[j-7]+D+L0[j-16]|0}let{A:Q,B:Y,C:G,D:Z,E:K,F:X,G:q,H:M}=this;for(let j=0;j<64;j++){let z=Z0(K,6)^Z0(K,11)^Z0(K,25),N=M+z+$8(K,X,q)+WQ[j]+L0[j]|0,P=(Z0(Q,2)^Z0(Q,13)^Z0(Q,22))+J8(Q,Y,G)|0;M=q,q=X,X=K,K=Z+N|0,Z=G,G=Y,Y=Q,Q=N+P|0}Q=Q+this.A|0,Y=Y+this.B|0,G=G+this.C|0,Z=Z+this.D|0,K=K+this.E|0,X=X+this.F|0,q=q+this.G|0,M=M+this.H|0,this.set(Q,Y,G,Z,K,X,q,M)}roundClean(){X0(L0)}destroy(){this.set(0,0,0,0,0,0,0,0),X0(this.buffer)}}var Y8=P$(()=>new Q8);class $J extends x0{constructor($,J){super();this.finished=!1,this.destroyed=!1,hJ($);let Q=_0(J);if(this.iHash=$.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let Y=this.blockLen,G=new Uint8Array(Y);G.set(Q.length>Y?$.create().update(Q).digest():Q);for(let Z=0;Z<G.length;Z++)G[Z]^=54;this.iHash.update(G),this.oHash=$.create();for(let Z=0;Z<G.length;Z++)G[Z]^=106;this.oHash.update(G),X0(G)}update($){return M0(this),this.iHash.update($),this}digestInto($){M0(this),K0($,this.outputLen),this.finished=!0,this.iHash.digestInto($),this.oHash.update($),this.oHash.digestInto($),this.destroy()}digest(){let $=new Uint8Array(this.oHash.outputLen);return this.digestInto($),$}_cloneInto($){$||($=Object.create(Object.getPrototypeOf(this),{}));let{oHash:J,iHash:Q,finished:Y,destroyed:G,blockLen:Z,outputLen:K}=this;return $=$,$.finished=Y,$.destroyed=G,$.blockLen=Z,$.outputLen=K,$.oHash=J._cloneInto($.oHash),$.iHash=Q._cloneInto($.iHash),$}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var JJ=($,J,Q)=>new $J($,J).update(Q).digest();JJ.create=($,J)=>new $J($,J);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var ZJ=BigInt(0),GJ=BigInt(1);function t0($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function KJ($){if(!t0($))throw Error("Uint8Array expected")}function a0($,J){if(typeof J!=="boolean")throw Error($+" boolean expected, got "+J)}function W$($){let J=$.toString(16);return J.length&1?"0"+J:J}function K8($){if(typeof $!=="string")throw Error("hex string expected, got "+typeof $);return $===""?ZJ:BigInt("0x"+$)}var X8=typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function",UQ=Array.from({length:256},($,J)=>J.toString(16).padStart(2,"0"));function s0($){if(KJ($),X8)return $.toHex();let J="";for(let Q=0;Q<$.length;Q++)J+=UQ[$[Q]];return J}var z0={_0:48,_9:57,A:65,F:70,a:97,f:102};function G8($){if($>=z0._0&&$<=z0._9)return $-z0._0;if($>=z0.A&&$<=z0.F)return $-(z0.A-10);if($>=z0.a&&$<=z0.f)return $-(z0.a-10);return}function U$($){if(typeof $!=="string")throw Error("hex string expected, got "+typeof $);if(X8)return Uint8Array.fromHex($);let J=$.length,Q=J/2;if(J%2)throw Error("hex string expected, got unpadded hex of length "+J);let Y=new Uint8Array(Q);for(let G=0,Z=0;G<Q;G++,Z+=2){let K=G8($.charCodeAt(Z)),X=G8($.charCodeAt(Z+1));if(K===void 0||X===void 0){let q=$[Z]+$[Z+1];throw Error('hex string expected, got non-hex character "'+q+'" at index '+Z)}Y[G]=K*16+X}return Y}function N0($){return K8(s0($))}function XJ($){return KJ($),K8(s0(Uint8Array.from($).reverse()))}function y0($,J){return U$($.toString(16).padStart(J*2,"0"))}function qJ($,J){return y0($,J).reverse()}function J0($,J,Q){let Y;if(typeof J==="string")try{Y=U$(J)}catch(Z){throw Error($+" must be hex string or Uint8Array, cause: "+Z)}else if(t0(J))Y=Uint8Array.from(J);else throw Error($+" must be hex string or Uint8Array");let G=Y.length;if(typeof Q==="number"&&G!==Q)throw Error($+" of length "+Q+" expected, got "+G);return Y}function z$(...$){let J=0;for(let Y=0;Y<$.length;Y++){let G=$[Y];KJ(G),J+=G.length}let Q=new Uint8Array(J);for(let Y=0,G=0;Y<$.length;Y++){let Z=$[Y];Q.set(Z,G),G+=Z.length}return Q}var QJ=($)=>typeof $==="bigint"&&ZJ<=$;function y$($,J,Q){return QJ($)&&QJ(J)&&QJ(Q)&&J<=$&&$<Q}function b0($,J,Q,Y){if(!y$(J,Q,Y))throw Error("expected valid "+$+": "+Q+" <= n < "+Y+", got "+J)}function q8($){let J;for(J=0;$>ZJ;$>>=GJ,J+=1);return J}var F0=($)=>(GJ<<BigInt($))-GJ,YJ=($)=>new Uint8Array($),Z8=($)=>Uint8Array.from($);function M8($,J,Q){if(typeof $!=="number"||$<2)throw Error("hashLen must be a number");if(typeof J!=="number"||J<2)throw Error("qByteLen must be a number");if(typeof Q!=="function")throw Error("hmacFn must be a function");let Y=YJ($),G=YJ($),Z=0,K=()=>{Y.fill(1),G.fill(0),Z=0},X=(...z)=>Q(G,Y,...z),q=(z=YJ(0))=>{if(G=X(Z8([0]),z),Y=X(),z.length===0)return;G=X(Z8([1]),z),Y=X()},M=()=>{if(Z++>=1000)throw Error("drbg: tried 1000 values");let z=0,N=[];while(z<J){Y=X();let D=Y.slice();N.push(D),z+=Y.length}return z$(...N)};return(z,N)=>{K(),q(z);let D=void 0;while(!(D=N(M())))q();return K(),D}}var zQ={bigint:($)=>typeof $==="bigint",function:($)=>typeof $==="function",boolean:($)=>typeof $==="boolean",string:($)=>typeof $==="string",stringOrUint8Array:($)=>typeof $==="string"||t0($),isSafeInteger:($)=>Number.isSafeInteger($),array:($)=>Array.isArray($),field:($,J)=>J.Fp.isValid($),hash:($)=>typeof $==="function"&&Number.isSafeInteger($.outputLen)};function g0($,J,Q={}){let Y=(G,Z,K)=>{let X=zQ[Z];if(typeof X!=="function")throw Error("invalid validator function");let q=$[G];if(K&&q===void 0)return;if(!X(q,$))throw Error("param "+String(G)+" is invalid. Expected "+Z+", got "+q)};for(let[G,Z]of Object.entries(J))Y(G,Z,!1);for(let[G,Z]of Object.entries(Q))Y(G,Z,!0);return $}function MJ($){let J=new WeakMap;return(Q,...Y)=>{let G=J.get(Q);if(G!==void 0)return G;let Z=$(Q,...Y);return J.set(Q,Z),Z}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var r=BigInt(0),t=BigInt(1),f0=BigInt(2),NQ=BigInt(3),W8=BigInt(4),U8=BigInt(5),z8=BigInt(8);function o($,J){let Q=$%J;return Q>=r?Q:J+Q}function G0($,J,Q){let Y=$;while(J-- >r)Y*=Y,Y%=Q;return Y}function b$($,J){if($===r)throw Error("invert: expected non-zero number");if(J<=r)throw Error("invert: expected positive modulus, got "+J);let Q=o($,J),Y=J,G=r,Z=t,K=t,X=r;while(Q!==r){let M=Y/Q,j=Y%Q,z=G-K*M,N=Z-X*M;Y=Q,Q=j,G=K,Z=X,K=z,X=N}if(Y!==t)throw Error("invert: does not exist");return o(G,J)}function N8($,J){let Q=($.ORDER+t)/W8,Y=$.pow(J,Q);if(!$.eql($.sqr(Y),J))throw Error("Cannot find square root");return Y}function DQ($,J){let Q=($.ORDER-U8)/z8,Y=$.mul(J,f0),G=$.pow(Y,Q),Z=$.mul(J,G),K=$.mul($.mul(Z,f0),G),X=$.mul(Z,$.sub(K,$.ONE));if(!$.eql($.sqr(X),J))throw Error("Cannot find square root");return X}function VQ($){if($<BigInt(3))throw Error("sqrt is not defined for small field");let J=$-t,Q=0;while(J%f0===r)J/=f0,Q++;let Y=f0,G=N$($);while(j8(G,Y)===1)if(Y++>1000)throw Error("Cannot find square root: probably non-prime P");if(Q===1)return N8;let Z=G.pow(Y,J),K=(J+t)/f0;return function(q,M){if(q.is0(M))return M;if(j8(q,M)!==1)throw Error("Cannot find square root");let j=Q,z=q.mul(q.ONE,Z),N=q.pow(M,J),D=q.pow(M,K);while(!q.eql(N,q.ONE)){if(q.is0(N))return q.ZERO;let P=1,V=q.sqr(N);while(!q.eql(V,q.ONE))if(P++,V=q.sqr(V),P===j)throw Error("Cannot find square root");let k=t<<BigInt(j-P-1),C=q.pow(z,k);j=P,z=q.sqr(C),N=q.mul(N,z),D=q.mul(D,C)}return D}}function OQ($){if($%W8===NQ)return N8;if($%z8===U8)return DQ;return VQ($)}var RQ=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function jJ($){let J={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},Q=RQ.reduce((Y,G)=>{return Y[G]="function",Y},J);return g0($,Q)}function CQ($,J,Q){if(Q<r)throw Error("invalid exponent, negatives unsupported");if(Q===r)return $.ONE;if(Q===t)return J;let Y=$.ONE,G=J;while(Q>r){if(Q&t)Y=$.mul(Y,G);G=$.sqr(G),Q>>=t}return Y}function WJ($,J,Q=!1){let Y=Array(J.length).fill(Q?$.ZERO:void 0),G=J.reduce((K,X,q)=>{if($.is0(X))return K;return Y[q]=K,$.mul(K,X)},$.ONE),Z=$.inv(G);return J.reduceRight((K,X,q)=>{if($.is0(X))return K;return Y[q]=$.mul(K,Y[q]),$.mul(K,X)},Z),Y}function j8($,J){let Q=($.ORDER-t)/f0,Y=$.pow(J,Q),G=$.eql(Y,$.ONE),Z=$.eql(Y,$.ZERO),K=$.eql(Y,$.neg($.ONE));if(!G&&!Z&&!K)throw Error("invalid Legendre symbol result");return G?1:Z?0:-1}function UJ($,J){if(J!==void 0)T0(J);let Q=J!==void 0?J:$.toString(2).length,Y=Math.ceil(Q/8);return{nBitLength:Q,nByteLength:Y}}function N$($,J,Q=!1,Y={}){if($<=r)throw Error("invalid field: expected ORDER > 0, got "+$);let{nBitLength:G,nByteLength:Z}=UJ($,J);if(Z>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");let K,X=Object.freeze({ORDER:$,isLE:Q,BITS:G,BYTES:Z,MASK:F0(G),ZERO:r,ONE:t,create:(q)=>o(q,$),isValid:(q)=>{if(typeof q!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof q);return r<=q&&q<$},is0:(q)=>q===r,isOdd:(q)=>(q&t)===t,neg:(q)=>o(-q,$),eql:(q,M)=>q===M,sqr:(q)=>o(q*q,$),add:(q,M)=>o(q+M,$),sub:(q,M)=>o(q-M,$),mul:(q,M)=>o(q*M,$),pow:(q,M)=>CQ(X,q,M),div:(q,M)=>o(q*b$(M,$),$),sqrN:(q)=>q*q,addN:(q,M)=>q+M,subN:(q,M)=>q-M,mulN:(q,M)=>q*M,inv:(q)=>b$(q,$),sqrt:Y.sqrt||((q)=>{if(!K)K=OQ($);return K(X,q)}),toBytes:(q)=>Q?qJ(q,Z):y0(q,Z),fromBytes:(q)=>{if(q.length!==Z)throw Error("Field.fromBytes: expected "+Z+" bytes, got "+q.length);return Q?XJ(q):N0(q)},invertBatch:(q)=>WJ(X,q),cmov:(q,M,j)=>j?M:q});return Object.freeze(X)}function D8($){if(typeof $!=="bigint")throw Error("field order must be bigint");let J=$.toString(2).length;return Math.ceil(J/8)}function zJ($){let J=D8($);return J+Math.ceil(J/2)}function V8($,J,Q=!1){let Y=$.length,G=D8(J),Z=zJ(J);if(Y<16||Y<Z||Y>1024)throw Error("expected "+Z+"-1024 bytes of input, got "+Y);let K=Q?XJ($):N0($),X=o(K,J-t)+t;return Q?qJ(X,G):y0(X,G)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var O8=BigInt(0),RJ=BigInt(1);function NJ($,J){let Q=J.negate();return $?Q:J}function C8($,J){if(!Number.isSafeInteger($)||$<=0||$>J)throw Error("invalid window size, expected [1.."+J+"], got W="+$)}function DJ($,J){C8($,J);let Q=Math.ceil(J/$)+1,Y=2**($-1),G=2**$,Z=F0($),K=BigInt($);return{windows:Q,windowSize:Y,mask:Z,maxNumber:G,shiftBy:K}}function R8($,J,Q){let{windowSize:Y,mask:G,maxNumber:Z,shiftBy:K}=Q,X=Number($&G),q=$>>K;if(X>Y)X-=Z,q+=RJ;let M=J*Y,j=M+Math.abs(X)-1,z=X===0,N=X<0,D=J%2!==0;return{nextN:q,offset:j,isZero:z,isNeg:N,isNegF:D,offsetF:M}}function BQ($,J){if(!Array.isArray($))throw Error("array expected");$.forEach((Q,Y)=>{if(!(Q instanceof J))throw Error("invalid point at index "+Y)})}function PQ($,J){if(!Array.isArray($))throw Error("array of scalars expected");$.forEach((Q,Y)=>{if(!J.isValid(Q))throw Error("invalid scalar at index "+Y)})}var VJ=new WeakMap,B8=new WeakMap;function OJ($){return B8.get($)||1}function P8($,J){return{constTimeNegate:NJ,hasPrecomputes(Q){return OJ(Q)!==1},unsafeLadder(Q,Y,G=$.ZERO){let Z=Q;while(Y>O8){if(Y&RJ)G=G.add(Z);Z=Z.double(),Y>>=RJ}return G},precomputeWindow(Q,Y){let{windows:G,windowSize:Z}=DJ(Y,J),K=[],X=Q,q=X;for(let M=0;M<G;M++){q=X,K.push(q);for(let j=1;j<Z;j++)q=q.add(X),K.push(q);X=q.double()}return K},wNAF(Q,Y,G){let{ZERO:Z,BASE:K}=$,X=DJ(Q,J);for(let q=0;q<X.windows;q++){let{nextN:M,offset:j,isZero:z,isNeg:N,isNegF:D,offsetF:P}=R8(G,q,X);if(G=M,z)K=K.add(NJ(D,Y[P]));else Z=Z.add(NJ(N,Y[j]))}return{p:Z,f:K}},wNAFUnsafe(Q,Y,G,Z=$.ZERO){let K=DJ(Q,J);for(let X=0;X<K.windows;X++){if(G===O8)break;let{nextN:q,offset:M,isZero:j,isNeg:z}=R8(G,X,K);if(G=q,j)continue;else{let N=Y[M];Z=Z.add(z?N.negate():N)}}return Z},getPrecomputes(Q,Y,G){let Z=VJ.get(Y);if(!Z){if(Z=this.precomputeWindow(Y,Q),Q!==1)VJ.set(Y,G(Z))}return Z},wNAFCached(Q,Y,G){let Z=OJ(Q);return this.wNAF(Z,this.getPrecomputes(Z,Q,G),Y)},wNAFCachedUnsafe(Q,Y,G,Z){let K=OJ(Q);if(K===1)return this.unsafeLadder(Q,Y,Z);return this.wNAFUnsafe(K,this.getPrecomputes(K,Q,G),Y,Z)},setWindowSize(Q,Y){C8(Y,J),B8.set(Q,Y),VJ.delete(Q)}}}function L8($,J,Q,Y){BQ(Q,$),PQ(Y,J);let G=Q.length,Z=Y.length;if(G!==Z)throw Error("arrays of points and scalars must have equal length");let K=$.ZERO,X=q8(BigInt(G)),q=1;if(X>12)q=X-3;else if(X>4)q=X-2;else if(X>0)q=2;let M=F0(q),j=Array(Number(M)+1).fill(K),z=Math.floor((J.BITS-1)/q)*q,N=K;for(let D=z;D>=0;D-=q){j.fill(K);for(let V=0;V<Z;V++){let k=Y[V],C=Number(k>>BigInt(D)&M);j[C]=j[C].add(Q[V])}let P=K;for(let V=j.length-1,k=K;V>0;V--)k=k.add(j[V]),P=P.add(k);if(N=N.add(P),D!==0)for(let V=0;V<q;V++)N=N.double()}return N}function CJ($){return jJ($.Fp),g0($,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...UJ($.n,$.nBitLength),...$,...{p:$.Fp.ORDER}})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function H8($){if($.lowS!==void 0)a0("lowS",$.lowS);if($.prehash!==void 0)a0("prehash",$.prehash)}function LQ($){let J=CJ($);g0(J,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:Q,Fp:Y,a:G}=J;if(Q){if(!Y.eql(G,Y.ZERO))throw Error("invalid endo: CURVE.a must be 0");if(typeof Q!=="object"||typeof Q.beta!=="bigint"||typeof Q.splitScalar!=="function")throw Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...J})}class S8 extends Error{constructor($=""){super($)}}var D0={Err:S8,_tlv:{encode:($,J)=>{let{Err:Q}=D0;if($<0||$>256)throw new Q("tlv.encode: wrong tag");if(J.length&1)throw new Q("tlv.encode: unpadded data");let Y=J.length/2,G=W$(Y);if(G.length/2&128)throw new Q("tlv.encode: long form length too big");let Z=Y>127?W$(G.length/2|128):"";return W$($)+Z+G+J},decode($,J){let{Err:Q}=D0,Y=0;if($<0||$>256)throw new Q("tlv.encode: wrong tag");if(J.length<2||J[Y++]!==$)throw new Q("tlv.decode: wrong tlv");let G=J[Y++],Z=!!(G&128),K=0;if(!Z)K=G;else{let q=G&127;if(!q)throw new Q("tlv.decode(long): indefinite length not supported");if(q>4)throw new Q("tlv.decode(long): byte length is too big");let M=J.subarray(Y,Y+q);if(M.length!==q)throw new Q("tlv.decode: length bytes not complete");if(M[0]===0)throw new Q("tlv.decode(long): zero leftmost byte");for(let j of M)K=K<<8|j;if(Y+=q,K<128)throw new Q("tlv.decode(long): not minimal encoding")}let X=J.subarray(Y,Y+K);if(X.length!==K)throw new Q("tlv.decode: wrong value length");return{v:X,l:J.subarray(Y+K)}}},_int:{encode($){let{Err:J}=D0;if($<V0)throw new J("integer: negative integers are not allowed");let Q=W$($);if(Number.parseInt(Q[0],16)&8)Q="00"+Q;if(Q.length&1)throw new J("unexpected DER parsing assertion: unpadded hex");return Q},decode($){let{Err:J}=D0;if($[0]&128)throw new J("invalid signature integer: negative");if($[0]===0&&!($[1]&128))throw new J("invalid signature integer: unnecessary leading zero");return N0($)}},toSig($){let{Err:J,_int:Q,_tlv:Y}=D0,G=J0("signature",$),{v:Z,l:K}=Y.decode(48,G);if(K.length)throw new J("invalid signature: left bytes after parsing");let{v:X,l:q}=Y.decode(2,Z),{v:M,l:j}=Y.decode(2,q);if(j.length)throw new J("invalid signature: left bytes after parsing");return{r:Q.decode(X),s:Q.decode(M)}},hexFromSig($){let{_tlv:J,_int:Q}=D0,Y=J.encode(2,Q.encode($.r)),G=J.encode(2,Q.encode($.s)),Z=Y+G;return J.encode(48,Z)}};function BJ($,J){return s0(y0($,J))}var V0=BigInt(0),d=BigInt(1),IG=BigInt(2),PJ=BigInt(3),HQ=BigInt(4);function SQ($){let J=LQ($),{Fp:Q}=J,Y=N$(J.n,J.nBitLength),G=J.toBytes||((W,R,H)=>{let S=R.toAffine();return z$(Uint8Array.from([4]),Q.toBytes(S.x),Q.toBytes(S.y))}),Z=J.fromBytes||((W)=>{let R=W.subarray(1),H=Q.fromBytes(R.subarray(0,Q.BYTES)),S=Q.fromBytes(R.subarray(Q.BYTES,2*Q.BYTES));return{x:H,y:S}});function K(W){let{a:R,b:H}=J,S=Q.sqr(W),w=Q.mul(S,W);return Q.add(Q.add(w,Q.mul(W,R)),H)}function X(W,R){let H=Q.sqr(R),S=K(W);return Q.eql(H,S)}if(!X(J.Gx,J.Gy))throw Error("bad curve params: generator point");let q=Q.mul(Q.pow(J.a,PJ),HQ),M=Q.mul(Q.sqr(J.b),BigInt(27));if(Q.is0(Q.add(q,M)))throw Error("bad curve params: a or b");function j(W){return y$(W,d,J.n)}function z(W){let{allowedPrivateKeyLengths:R,nByteLength:H,wrapPrivateKey:S,n:w}=J;if(R&&typeof W!=="bigint"){if(t0(W))W=s0(W);if(typeof W!=="string"||!R.includes(W.length))throw Error("invalid private key");W=W.padStart(H*2,"0")}let x;try{x=typeof W==="bigint"?W:N0(J0("private key",W,H))}catch(y){throw Error("invalid private key, expected hex or "+H+" bytes, got "+typeof W)}if(S)x=o(x,w);return b0("private key",x,d,w),x}function N(W){if(!(W instanceof V))throw Error("ProjectivePoint expected")}let D=MJ((W,R)=>{let{px:H,py:S,pz:w}=W;if(Q.eql(w,Q.ONE))return{x:H,y:S};let x=W.is0();if(R==null)R=x?Q.ONE:Q.inv(w);let y=Q.mul(H,R),_=Q.mul(S,R),A=Q.mul(w,R);if(x)return{x:Q.ZERO,y:Q.ZERO};if(!Q.eql(A,Q.ONE))throw Error("invZ was invalid");return{x:y,y:_}}),P=MJ((W)=>{if(W.is0()){if(J.allowInfinityPoint&&!Q.is0(W.py))return;throw Error("bad point: ZERO")}let{x:R,y:H}=W.toAffine();if(!Q.isValid(R)||!Q.isValid(H))throw Error("bad point: x or y not FE");if(!X(R,H))throw Error("bad point: equation left != right");if(!W.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});class V{constructor(W,R,H){if(W==null||!Q.isValid(W))throw Error("x required");if(R==null||!Q.isValid(R)||Q.is0(R))throw Error("y required");if(H==null||!Q.isValid(H))throw Error("z required");this.px=W,this.py=R,this.pz=H,Object.freeze(this)}static fromAffine(W){let{x:R,y:H}=W||{};if(!W||!Q.isValid(R)||!Q.isValid(H))throw Error("invalid affine point");if(W instanceof V)throw Error("projective point not allowed");let S=(w)=>Q.eql(w,Q.ZERO);if(S(R)&&S(H))return V.ZERO;return new V(R,H,Q.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(W){let R=WJ(Q,W.map((H)=>H.pz));return W.map((H,S)=>H.toAffine(R[S])).map(V.fromAffine)}static fromHex(W){let R=V.fromAffine(Z(J0("pointHex",W)));return R.assertValidity(),R}static fromPrivateKey(W){return V.BASE.multiply(z(W))}static msm(W,R){return L8(V,Y,W,R)}_setWindowSize(W){b.setWindowSize(this,W)}assertValidity(){P(this)}hasEvenY(){let{y:W}=this.toAffine();if(Q.isOdd)return!Q.isOdd(W);throw Error("Field doesn't support isOdd")}equals(W){N(W);let{px:R,py:H,pz:S}=this,{px:w,py:x,pz:y}=W,_=Q.eql(Q.mul(R,y),Q.mul(w,S)),A=Q.eql(Q.mul(H,y),Q.mul(x,S));return _&&A}negate(){return new V(this.px,Q.neg(this.py),this.pz)}double(){let{a:W,b:R}=J,H=Q.mul(R,PJ),{px:S,py:w,pz:x}=this,y=Q.ZERO,_=Q.ZERO,A=Q.ZERO,E=Q.mul(S,S),c=Q.mul(w,w),h=Q.mul(x,x),U=Q.mul(S,w);return U=Q.add(U,U),A=Q.mul(S,x),A=Q.add(A,A),y=Q.mul(W,A),_=Q.mul(H,h),_=Q.add(y,_),y=Q.sub(c,_),_=Q.add(c,_),_=Q.mul(y,_),y=Q.mul(U,y),A=Q.mul(H,A),h=Q.mul(W,h),U=Q.sub(E,h),U=Q.mul(W,U),U=Q.add(U,A),A=Q.add(E,E),E=Q.add(A,E),E=Q.add(E,h),E=Q.mul(E,U),_=Q.add(_,E),h=Q.mul(w,x),h=Q.add(h,h),E=Q.mul(h,U),y=Q.sub(y,E),A=Q.mul(h,c),A=Q.add(A,A),A=Q.add(A,A),new V(y,_,A)}add(W){N(W);let{px:R,py:H,pz:S}=this,{px:w,py:x,pz:y}=W,_=Q.ZERO,A=Q.ZERO,E=Q.ZERO,c=J.a,h=Q.mul(J.b,PJ),U=Q.mul(R,w),B=Q.mul(H,x),I=Q.mul(S,y),F=Q.add(R,H),T=Q.add(w,x);F=Q.mul(F,T),T=Q.add(U,B),F=Q.sub(F,T),T=Q.add(R,S);let O=Q.add(w,y);return T=Q.mul(T,O),O=Q.add(U,I),T=Q.sub(T,O),O=Q.add(H,S),_=Q.add(x,y),O=Q.mul(O,_),_=Q.add(B,I),O=Q.sub(O,_),E=Q.mul(c,T),_=Q.mul(h,I),E=Q.add(_,E),_=Q.sub(B,E),E=Q.add(B,E),A=Q.mul(_,E),B=Q.add(U,U),B=Q.add(B,U),I=Q.mul(c,I),T=Q.mul(h,T),B=Q.add(B,I),I=Q.sub(U,I),I=Q.mul(c,I),T=Q.add(T,I),U=Q.mul(B,T),A=Q.add(A,U),U=Q.mul(O,T),_=Q.mul(F,_),_=Q.sub(_,U),U=Q.mul(F,B),E=Q.mul(O,E),E=Q.add(E,U),new V(_,A,E)}subtract(W){return this.add(W.negate())}is0(){return this.equals(V.ZERO)}wNAF(W){return b.wNAFCached(this,W,V.normalizeZ)}multiplyUnsafe(W){let{endo:R,n:H}=J;b0("scalar",W,V0,H);let S=V.ZERO;if(W===V0)return S;if(this.is0()||W===d)return this;if(!R||b.hasPrecomputes(this))return b.wNAFCachedUnsafe(this,W,V.normalizeZ);let{k1neg:w,k1:x,k2neg:y,k2:_}=R.splitScalar(W),A=S,E=S,c=this;while(x>V0||_>V0){if(x&d)A=A.add(c);if(_&d)E=E.add(c);c=c.double(),x>>=d,_>>=d}if(w)A=A.negate();if(y)E=E.negate();return E=new V(Q.mul(E.px,R.beta),E.py,E.pz),A.add(E)}multiply(W){let{endo:R,n:H}=J;b0("scalar",W,d,H);let S,w;if(R){let{k1neg:x,k1:y,k2neg:_,k2:A}=R.splitScalar(W),{p:E,f:c}=this.wNAF(y),{p:h,f:U}=this.wNAF(A);E=b.constTimeNegate(x,E),h=b.constTimeNegate(_,h),h=new V(Q.mul(h.px,R.beta),h.py,h.pz),S=E.add(h),w=c.add(U)}else{let{p:x,f:y}=this.wNAF(W);S=x,w=y}return V.normalizeZ([S,w])[0]}multiplyAndAddUnsafe(W,R,H){let S=V.BASE,w=(y,_)=>_===V0||_===d||!y.equals(S)?y.multiplyUnsafe(_):y.multiply(_),x=w(this,R).add(w(W,H));return x.is0()?void 0:x}toAffine(W){return D(this,W)}isTorsionFree(){let{h:W,isTorsionFree:R}=J;if(W===d)return!0;if(R)return R(V,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:W,clearCofactor:R}=J;if(W===d)return this;if(R)return R(V,this);return this.multiplyUnsafe(J.h)}toRawBytes(W=!0){return a0("isCompressed",W),this.assertValidity(),G(V,this,W)}toHex(W=!0){return a0("isCompressed",W),s0(this.toRawBytes(W))}}V.BASE=new V(J.Gx,J.Gy,Q.ONE),V.ZERO=new V(Q.ZERO,Q.ONE,Q.ZERO);let{endo:k,nBitLength:C}=J,b=P8(V,k?Math.ceil(C/2):C);return{CURVE:J,ProjectivePoint:V,normPrivateKeyToScalar:z,weierstrassEquation:K,isWithinCurveOrder:j}}function IQ($){let J=CJ($);return g0(J,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...J})}function I8($){let J=IQ($),{Fp:Q,n:Y,nByteLength:G,nBitLength:Z}=J,K=Q.BYTES+1,X=2*Q.BYTES+1;function q(U){return o(U,Y)}function M(U){return b$(U,Y)}let{ProjectivePoint:j,normPrivateKeyToScalar:z,weierstrassEquation:N,isWithinCurveOrder:D}=SQ({...J,toBytes(U,B,I){let F=B.toAffine(),T=Q.toBytes(F.x),O=z$;if(a0("isCompressed",I),I)return O(Uint8Array.from([B.hasEvenY()?2:3]),T);else return O(Uint8Array.from([4]),T,Q.toBytes(F.y))},fromBytes(U){let B=U.length,I=U[0],F=U.subarray(1);if(B===K&&(I===2||I===3)){let T=N0(F);if(!y$(T,d,Q.ORDER))throw Error("Point is not on curve");let O=N(T),g;try{g=Q.sqrt(O)}catch(e){let $0=e instanceof Error?": "+e.message:"";throw Error("Point is not on curve"+$0)}let m=(g&d)===d;if((I&1)===1!==m)g=Q.neg(g);return{x:T,y:g}}else if(B===X&&I===4){let T=Q.fromBytes(F.subarray(0,Q.BYTES)),O=Q.fromBytes(F.subarray(Q.BYTES,2*Q.BYTES));return{x:T,y:O}}else{let T=K,O=X;throw Error("invalid Point, expected length of "+T+", or uncompressed "+O+", got "+B)}}});function P(U){let B=Y>>d;return U>B}function V(U){return P(U)?q(-U):U}let k=(U,B,I)=>N0(U.slice(B,I));class C{constructor(U,B,I){if(b0("r",U,d,Y),b0("s",B,d,Y),this.r=U,this.s=B,I!=null)this.recovery=I;Object.freeze(this)}static fromCompact(U){let B=G;return U=J0("compactSignature",U,B*2),new C(k(U,0,B),k(U,B,2*B))}static fromDER(U){let{r:B,s:I}=D0.toSig(J0("DER",U));return new C(B,I)}assertValidity(){}addRecoveryBit(U){return new C(this.r,this.s,U)}recoverPublicKey(U){let{r:B,s:I,recovery:F}=this,T=w(J0("msgHash",U));if(F==null||![0,1,2,3].includes(F))throw Error("recovery id invalid");let O=F===2||F===3?B+J.n:B;if(O>=Q.ORDER)throw Error("recovery id 2 or 3 invalid");let g=(F&1)===0?"02":"03",m=j.fromHex(g+BJ(O,Q.BYTES)),l=M(O),e=q(-T*l),$0=q(I*l),O0=j.BASE.multiplyAndAddUnsafe(m,e,$0);if(!O0)throw Error("point at infinify");return O0.assertValidity(),O0}hasHighS(){return P(this.s)}normalizeS(){return this.hasHighS()?new C(this.r,q(-this.s),this.recovery):this}toDERRawBytes(){return U$(this.toDERHex())}toDERHex(){return D0.hexFromSig(this)}toCompactRawBytes(){return U$(this.toCompactHex())}toCompactHex(){let U=G;return BJ(this.r,U)+BJ(this.s,U)}}let b={isValidPrivateKey(U){try{return z(U),!0}catch(B){return!1}},normPrivateKeyToScalar:z,randomPrivateKey:()=>{let U=zJ(J.n);return V8(J.randomBytes(U),J.n)},precompute(U=8,B=j.BASE){return B._setWindowSize(U),B.multiply(BigInt(3)),B}};function W(U,B=!0){return j.fromPrivateKey(U).toRawBytes(B)}function R(U){if(typeof U==="bigint")return!1;if(U instanceof j)return!0;let I=J0("key",U).length,F=Q.BYTES,T=F+1,O=2*F+1;if(J.allowedPrivateKeyLengths||G===T)return;else return I===T||I===O}function H(U,B,I=!0){if(R(U)===!0)throw Error("first arg must be private key");if(R(B)===!1)throw Error("second arg must be public key");return j.fromHex(B).multiply(z(U)).toRawBytes(I)}let S=J.bits2int||function(U){if(U.length>8192)throw Error("input is too large");let B=N0(U),I=U.length*8-Z;return I>0?B>>BigInt(I):B},w=J.bits2int_modN||function(U){return q(S(U))},x=F0(Z);function y(U){return b0("num < 2^"+Z,U,V0,x),y0(U,G)}function _(U,B,I=A){if(["recovered","canonical"].some((H0)=>(H0 in I)))throw Error("sign() legacy options not supported");let{hash:F,randomBytes:T}=J,{lowS:O,prehash:g,extraEntropy:m}=I;if(O==null)O=!0;if(U=J0("msgHash",U),H8(I),g)U=J0("prehashed msgHash",F(U));let l=w(U),e=z(B),$0=[y(e),y(l)];if(m!=null&&m!==!1){let H0=m===!0?T(Q.BYTES):m;$0.push(J0("extraEntropy",H0))}let O0=z$(...$0),V$=l;function v$(H0){let h0=S(H0);if(!D(h0))return;let h$=M(h0),r0=j.BASE.multiply(h0).toAffine(),S0=q(r0.x);if(S0===V0)return;let e0=q(h$*q(V$+S0*e));if(e0===V0)return;let m0=(r0.x===S0?0:2)|Number(r0.y&d),AJ=e0;if(O&&P(e0))AJ=V(e0),m0^=1;return new C(S0,AJ,m0)}return{seed:O0,k2sig:v$}}let A={lowS:J.lowS,prehash:!1},E={lowS:J.lowS,prehash:!1};function c(U,B,I=A){let{seed:F,k2sig:T}=_(U,B,I),O=J;return M8(O.hash.outputLen,O.nByteLength,O.hmac)(F,T)}j.BASE._setWindowSize(8);function h(U,B,I,F=E){let T=U;B=J0("msgHash",B),I=J0("publicKey",I);let{lowS:O,prehash:g,format:m}=F;if(H8(F),"strict"in F)throw Error("options.strict was renamed to lowS");if(m!==void 0&&m!=="compact"&&m!=="der")throw Error("format must be compact or der");let l=typeof T==="string"||t0(T),e=!l&&!m&&typeof T==="object"&&T!==null&&typeof T.r==="bigint"&&typeof T.s==="bigint";if(!l&&!e)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");let $0=void 0,O0;try{if(e)$0=new C(T.r,T.s);if(l){try{if(m!=="compact")$0=C.fromDER(T)}catch(m0){if(!(m0 instanceof D0.Err))throw m0}if(!$0&&m!=="der")$0=C.fromCompact(T)}O0=j.fromHex(I)}catch(m0){return!1}if(!$0)return!1;if(O&&$0.hasHighS())return!1;if(g)B=J.hash(B);let{r:V$,s:v$}=$0,H0=w(B),h0=M(v$),h$=q(H0*h0),r0=q(V$*h0),S0=j.BASE.multiplyAndAddUnsafe(O0,h$,r0)?.toAffine();if(!S0)return!1;return q(S0.x)===V$}return{CURVE:J,getPublicKey:W,getSharedSecret:H,sign:c,verify:h,ProjectivePoint:j,Signature:C,utils:b}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function TQ($){return{hash:$,hmac:(J,...Q)=>JJ($,J,uJ(...Q)),randomBytes:cJ}}function T8($,J){let Q=(Y)=>I8({...$,...TQ(Y)});return{...Q(J),create:Q}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var E8=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),_8=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),_Q=BigInt(0),xQ=BigInt(1),LJ=BigInt(2),x8=($,J)=>($+J/LJ)/J;function EQ($){let J=E8,Q=BigInt(3),Y=BigInt(6),G=BigInt(11),Z=BigInt(22),K=BigInt(23),X=BigInt(44),q=BigInt(88),M=$*$*$%J,j=M*M*$%J,z=G0(j,Q,J)*j%J,N=G0(z,Q,J)*j%J,D=G0(N,LJ,J)*M%J,P=G0(D,G,J)*D%J,V=G0(P,Z,J)*P%J,k=G0(V,X,J)*V%J,C=G0(k,q,J)*k%J,b=G0(C,X,J)*V%J,W=G0(b,Q,J)*j%J,R=G0(W,K,J)*P%J,H=G0(R,Y,J)*M%J,S=G0(H,LJ,J);if(!HJ.eql(HJ.sqr(S),$))throw Error("Cannot find square root");return S}var HJ=N$(E8,void 0,void 0,{sqrt:EQ}),SJ=T8({a:_Q,b:BigInt(7),Fp:HJ,n:_8,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:($)=>{let J=_8,Q=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),Y=-xQ*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),G=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),Z=Q,K=BigInt("0x100000000000000000000000000000000"),X=x8(Z*$,J),q=x8(-Y*$,J),M=o($-X*Q-q*G,J),j=o(-X*Y-q*Z,J),z=M>K,N=j>K;if(z)M=J-M;if(N)j=J-j;if(M>K||j>K)throw Error("splitScalar: Endomorphism failed, k="+$);return{k1neg:z,k1:M,k2neg:N,k2:j}}}},Y8);function F$(){let $=SJ.utils.randomPrivateKey();return"0x"+Buffer.from($).toString("hex")}function g$($){let J=$.startsWith("0x")?$.slice(2):$,Q=Buffer.from(J,"hex"),Y=SJ.getPublicKey(Q,!1),Z=c0(Y.slice(1)).slice(-20),K="0x"+Buffer.from(Z).toString("hex");return B0(K)}function f$($){let J;if(typeof $==="string"){let Y=$.startsWith("0x")?$.slice(2):$;J=Buffer.from(Y,"hex")}else J=$;let Q=c0(J);return"0x"+Buffer.from(Q).toString("hex")}class v extends w${constructor($,J){super("InvitationError",$,{...J,source:J?.source||"INVITATIONS"})}static noPathFound($,J,Q){return new v(`No valid invitation path found from ${$} to ${J}. ${Q||"The inviter may not have enough balance of the proxy inviter's token or there's no trust connection."}`,{code:"INVITATION_NO_PATH",source:"PATHFINDING",context:{from:$,to:J,reason:Q}})}static noProxyInviters($){return new v(`No proxy inviters found for ${$}. The inviter must have mutual trust connections with users who are also trusted by the invitation module, and these users must have sufficient balance.`,{code:"INVITATION_NO_PROXY_INVITERS",source:"VALIDATION",context:{inviter:$}})}static insufficientBalance($,J,Q,Y,G,Z){let K=Number(Q)/1000000000000000000,X=Number(Y)/1000000000000000000;return new v(`Insufficient balance for ${$} invitation(s). Can only afford ${J} invitation(s). Requested: ${K.toFixed(6)} CRC, Available: ${X.toFixed(6)} CRC.`,{code:"INVITATION_INSUFFICIENT_BALANCE",source:"VALIDATION",context:{from:G,to:Z,requestedInvites:$,availableInvites:J,requested:Q.toString(),available:Y.toString(),requestedCrc:K,availableCrc:X}})}static inviteeAlreadyRegistered($,J){return new v(`Invitee ${J} is already registered as a human in Circles Hub. Cannot invite an already registered user.`,{code:"INVITATION_INVITEE_ALREADY_REGISTERED",source:"VALIDATION",context:{inviter:$,invitee:J}})}static noAddressesProvided(){return new v("At least one address must be provided for invitation.",{code:"INVITATION_NO_ADDRESSES_PROVIDED",source:"VALIDATION"})}}var k8=[];for(let $=0;$<256;$++)k8[$]=$.toString(16).padStart(2,"0");function D$($){let J="0x";for(let Q=0;Q<$.length;Q++)J+=k8[$[Q]];return J}function A8($){let J=new Uint8Array($.length*2);return $.forEach((Q,Y)=>{let G=Q>>8,Z=Q&255,K=2*Y;J[K]=G,J[K+1]=Z}),D$(J)}function w8($,J,Q){let Y=new Set([J.toLowerCase(),Q.toLowerCase()]);$.forEach((K)=>{Y.add(K.from.toLowerCase()),Y.add(K.to.toLowerCase()),Y.add(K.tokenOwner.toLowerCase())});let G=[...Y].sort((K,X)=>{let q=BigInt(K),M=BigInt(X),j=q<M,z=q>M;return j?-1:z?1:0}),Z={};return G.forEach((K,X)=>{Z[K]=X}),{sorted:G,idx:Z}}function kQ($,J){let Q=new Set,Y=[],G=null;if($.forEach((Z,K)=>{let X=Z.from.toLowerCase(),q=Z.to.toLowerCase();if(X===J&&q===J)G=K;else if(q===J)Y.push(K)}),G!==null)Q.add(G);else Y.forEach((Z)=>Q.add(Z));return Q}function IJ($,J,Q,Y){let G=$.toLowerCase(),Z=J.toLowerCase(),{sorted:K,idx:X}=w8(Y,G,Z),q=kQ(Y,Z),M=Y.map((C,b)=>{return{streamSinkId:q.has(b)?1:0,amount:C.value}});if(q.size===0)throw Error(`No terminal edges detected. Flow must have at least one edge delivering to receiver ${Z}`);let j=Array.from(q),z=[{sourceCoordinate:X[G],flowEdgeIds:j,data:new Uint8Array(0)}],N=[];Y.forEach((C)=>{N.push(X[C.tokenOwner.toLowerCase()]),N.push(X[C.from.toLowerCase()]),N.push(X[C.to.toLowerCase()])});let D=A8(N),P=BigInt(Q),V=M.filter((C)=>C.streamSinkId===1).reduce((C,b)=>C+BigInt(b.amount.toString()),BigInt(0));if(V!==P)throw Error(`Terminal sum ${V} does not equal expected ${P}`);return{flowVertices:K,flowEdges:M,streams:z,packedCoordinates:D,sourceCoordinate:X[G]}}function TJ($,J){let Q=$.streams.map((Y)=>({sourceCoordinate:Y.sourceCoordinate,flowEdgeIds:Y.flowEdgeIds,data:Y.data instanceof Uint8Array?D$(Y.data):Y.data}));if(J&&Q.length>0)Q[0].data=J instanceof Uint8Array?D$(J):J;return Q}async function _J($,J,Q){let Y=new Map,G=new Set;return Q.transfers.forEach((X)=>{if($.toLowerCase()===X.from.toLowerCase())G.add(X.tokenOwner.toLowerCase())}),(await new x$(J).token.getTokenInfoBatch(Array.from(G))).forEach((X)=>{if(X.isWrapped&&!X.isInflationary)X.tokenType="CrcV2_ERC20WrapperDeployed_Demurraged";Y.set(X.tokenAddress.toLowerCase(),X)}),Y}function xJ($,J){let Q={};return $.transfers.forEach((Y)=>{let G=J.get(Y.tokenOwner.toLowerCase());if(G&&G.tokenType.startsWith("CrcV2_ERC20WrapperDeployed")){if(!Q[Y.tokenOwner])Q[Y.tokenOwner]=[BigInt(0),G.tokenType];Q[Y.tokenOwner][0]+=BigInt(Y.value)}}),Q}function EJ($,J){let Q=$.transfers.map((Y)=>{let G=J.get(Y.tokenOwner.toLowerCase());if(G&&G.tokenType.startsWith("CrcV2_ERC20WrapperDeployed"))return{...Y,tokenOwner:G.tokenOwner};return Y});return{...$,transfers:Q}}class a extends J${constructor($,J){super("TransferError",$,{...J,source:J?.source||"TRANSFERS"})}static noPathFound($,J,Q){return new a(`No valid transfer path found from ${$} to ${J}. ${Q||"This could mean there's no trust connection, insufficient balance, or the tokens are not transferable."}`,{code:"TRANSFER_NO_PATH",source:"PATHFINDING",context:{from:$,to:J,reason:Q}})}static insufficientBalance($,J,Q,Y){let G=Number($)/1000000000000000000,Z=Number(J)/1000000000000000000;return new a(`Insufficient balance for transfer. Requested: ${G.toFixed(6)} CRC, Available: ${Z.toFixed(6)} CRC.`,{code:"TRANSFER_INSUFFICIENT_BALANCE",source:"VALIDATION",context:{from:Q,to:Y,requested:$.toString(),available:J.toString(),requestedCrc:G,availableCrc:Z}})}static wrappedTokensRequired(){return new a("Insufficient unwrapped token balance for transfer. Your balance contains wrapped tokens (ERC20 wrappers), but useWrappedBalances option is not enabled. Please enable it by passing { useWrappedBalances: true } in the transfer options.",{code:"TRANSFER_WRAPPED_TOKENS_REQUIRED",source:"VALIDATION"})}static unregisteredAvatars($){return new a(`Flow matrix contains ${$.length} unregistered avatar(s): ${$.join(", ")}. All addresses in the flow must be registered Circles avatars (human or group).`,{code:"TRANSFER_UNREGISTERED_AVATARS",source:"FLOW_MATRIX",context:{unregisteredAddresses:$,count:$.length}})}static flowMatrixMismatch($,J){return new a(`Flow matrix terminal sum (${$}) does not equal expected amount (${J})`,{code:"TRANSFER_FLOW_MATRIX_MISMATCH",source:"FLOW_MATRIX",context:{terminalSum:$.toString(),expected:J.toString()}})}static emptyPath($,J){return new a(`Transfer path is empty for route from ${$} to ${J}`,{code:"TRANSFER_EMPTY_PATH",source:"PATHFINDING",context:{from:$,to:J}})}}class v0{config;hubV2;liftERC20;rpcClient;pathfinder;balance;group;constructor($){this.config=$,this.hubV2=new P0({address:$.v2HubAddress,rpcUrl:$.circlesRpcUrl}),this.liftERC20=new E$({address:$.liftERC20Address,rpcUrl:$.circlesRpcUrl}),this.rpcClient=new R0($.circlesRpcUrl),this.pathfinder=new W0(this.rpcClient),this.balance=new A0(this.rpcClient),this.group=new w0(this.rpcClient)}async buildFlowMatrixTx($,J,Q,Y,G=!1){let Z=$.toLowerCase(),K=J.toLowerCase();if(!Q.transfers||Q.transfers.length===0)throw a.noPathFound(Z,K);let X={...Q};if(G&&Y?.toTokens?.length===1){let b=Y.toTokens[0].toLowerCase();if(Q.maxFlow>0n)X.transfers.push({from:K,to:K,tokenOwner:b,value:Q.maxFlow})}let q=await _J(Z,this.config.circlesRpcUrl,X),M=xJ(X,q),j=Object.keys(M).length>0;if(j&&!Y?.useWrappedBalances)throw a.wrappedTokensRequired();let z=[],N=[];if(j){let b=await this._getTokenBalanceMap(Z),W=this._createDemurragedUnwrapCalls(M),{unwrapCalls:R,wrapCalls:H}=this._createInflationaryUnwrapAndWrapCalls(M,q,b);z=[...W,...R],N=H,X=EJ(X,q)}let D=IJ(Z,K,X.maxFlow,X.transfers),P=TJ(D,Y?.txData),V=this.hubV2.operateFlowMatrix(D.flowVertices,D.flowEdges,P,D.packedCoordinates),k=!1;try{k=await this.hubV2.isApprovedForAll(Z,Z)}catch(b){console.warn("Failed to check approval status, including approval transaction:",b)}return[...k?[]:[this.hubV2.setApprovalForAll(Z,!0)],...z,V,...N]}async constructAdvancedTransfer($,J,Q,Y,G=!1){let Z=$.toLowerCase(),K=J.toLowerCase(),X=BigInt(Q);if(Z===K&&Y?.fromTokens?.length===1&&Y?.toTokens?.length===1){let D=Y.fromTokens[0],P=Y.toTokens[0],[V,k]=await Promise.all([this.liftERC20.erc20Circles(0,P),this.liftERC20.erc20Circles(1,P)]);if(D.toLowerCase()===V.toLowerCase()&&V!==_$){let b=new d0({address:D,rpcUrl:this.config.circlesRpcUrl}).unwrap(X);return[{to:b.to,data:b.data,value:b.value??0n}]}if(D.toLowerCase()===k.toLowerCase()&&k!==_$){let C=new i0({address:D,rpcUrl:this.config.circlesRpcUrl}),b=i.attoCirclesToAttoStaticCircles(X),W=C.unwrap(b);return[{to:W.to,data:W.data,value:W.value??0n}]}}let q=this._truncateToSixDecimals(X),M=await this._getDefaultTokenExcludeList(K,Y?.excludeFromTokens),{...j}=Y||{},z={...j,...M?{excludeFromTokens:M}:{}},N=await this.pathfinder.findPath({from:Z,to:K,targetFlow:q,...z});if(!N.transfers||N.transfers.length===0)throw a.noPathFound(Z,K);if(N.maxFlow<q)throw a.insufficientBalance(q,N.maxFlow,Z,K);return this.buildFlowMatrixTx(Z,K,N,Y,G)}async constructReplenish($,J,Q,Y){let G=$.toLowerCase(),Z=J.toLowerCase(),K=(Y||$).toLowerCase(),X=BigInt(Q),M=(await this.balance.getTokenBalances(G)).filter((O)=>O.tokenOwner.toLowerCase()===Z),j=0n,z=0n,N=0n,D=null,P=null;for(let O of M)if(O.isWrapped)if(O.tokenType.includes("Demurrage"))z=BigInt(O.attoCircles),D=O.tokenAddress;else N=BigInt(O.staticAttoCircles),P=O.tokenAddress;else j=BigInt(O.attoCircles);let V=j+z+i.attoStaticCirclesToAttoCircles(N),k=[];if(j>=X){if(console.log(`✓ Already have ${Number(j)/1000000000000000000} CRC unwrapped (target: ${Number(X)/1000000000000000000} CRC). No replenish needed.`),K!==G){let O=await this.hubV2.toTokenId(Z),g=this.hubV2.safeTransferFrom(G,K,O,X);k.push({to:g.to,data:g.data,value:g.value??0n})}return k}let C=X-j;if(console.log(`Current unwrapped: ${Number(j)/1000000000000000000} CRC`),console.log(`Target amount: ${Number(X)/1000000000000000000} CRC`),console.log(`Need to acquire: ${Number(C)/1000000000000000000} CRC`),V>=X){let O=C;if(z>0n&&D&&O>0n){let g=O>z?z:O,l=new d0({address:D,rpcUrl:this.config.circlesRpcUrl}).unwrap(g);k.push({to:l.to,data:l.data,value:l.value??0n}),O-=g}if(N>0n&&P&&O>0n){let g=i.attoCirclesToAttoStaticCircles(O),m=g>N?N:g,e=new i0({address:P,rpcUrl:this.config.circlesRpcUrl}).unwrap(m);k.push({to:e.to,data:e.data,value:e.value??0n})}if(K!==G){let g=await this.hubV2.toTokenId(Z),m=this.hubV2.safeTransferFrom(G,K,g,X);k.push({to:m.to,data:m.data,value:m.value??0n})}return k}let W=!await this.hubV2.isTrusted(G,Z),R=BigInt(Math.floor(Date.now()/1000)+31536000),H=i.truncateToInt64(C),S=C%i.FACTOR_1E12!==0n,w=i.blowUpToBigInt(S?H+1n:H),x;try{x=await this.pathfinder.findPath({from:G,to:K,targetFlow:w,toTokens:[Z],useWrappedBalances:!0,simulatedTrusts:W?[{truster:G,trustee:Z}]:void 0})}catch(O){let g=Number(V)/1000000000000000000,m=Number(X)/1000000000000000000,l=Number(C)/1000000000000000000;throw new a(`Insufficient tokens to replenish. Target: ${m.toFixed(6)} CRC, Current unwrapped: ${Number(j)/1000000000000000000} CRC, Need: ${l.toFixed(6)} CRC, Available (including all paths): ${g.toFixed(6)} CRC. Cannot acquire the remaining ${(Number(C-(V-j))/1000000000000000000).toFixed(6)} CRC.`,{code:"REPLENISH_INSUFFICIENT_TOKENS",source:"VALIDATION",context:{from:G,tokenId:Z,target:X.toString(),unwrapped:j.toString(),deficit:C.toString(),available:V.toString(),targetCrc:m,unwrappedCrc:Number(j)/1000000000000000000,deficitCrc:l,availableCrc:g}})}if(!x.transfers||x.transfers.length===0)throw a.noPathFound(G,K,`No path to acquire token ${Z}`);if(x.maxFlow<w){let O=Number(x.maxFlow)/1000000000000000000,g=Number(w)/1000000000000000000;throw new a(`Pathfinder can only provide ${O.toFixed(6)} CRC of the ${g.toFixed(6)} CRC deficit needed for token ${Z}.`,{code:"REPLENISH_INSUFFICIENT_PATH_FLOW",source:"PATHFINDING",context:{from:G,tokenId:Z,deficit:w.toString(),pathFlow:x.maxFlow.toString(),deficitCrc:g,pathFlowCrc:O}})}if(W){let O=this.hubV2.trust(Z,R);k.push({to:O.to,data:O.data,value:O.value??0n})}let y=await _J(G,this.config.circlesRpcUrl,x),_=xJ(x,y),A=Object.keys(_).length>0,E=[],c=[];if(A){let O=await this._getTokenBalanceMap(G),g=this._createDemurragedUnwrapCalls(_),{unwrapCalls:m,wrapCalls:l}=this._createInflationaryUnwrapAndWrapCalls(_,y,O);E=[...g,...m],c=l,x=EJ(x,y)}let h=IJ(G,K,x.maxFlow,x.transfers),U=TJ(h),B=this.hubV2.operateFlowMatrix(h.flowVertices,h.flowEdges,U,h.packedCoordinates),I={to:B.to,data:B.data,value:B.value??0n},F=!1;try{F=await this.hubV2.isApprovedForAll(G,G)}catch(O){console.warn("Failed to check approval status, including approval transaction:",O)}if(W){let O=this.hubV2.trust(Z,0n);c.push({to:O.to,data:O.data,value:O.value??0n})}let T=F?[]:[{to:this.hubV2.setApprovalForAll(G,!0).to,data:this.hubV2.setApprovalForAll(G,!0).data,value:0n}];return k.push(...T,...E,I,...c),k}async _getTokenBalanceMap($){let J=await this.balance.getTokenBalances($),Q=new Map;return J.forEach((Y)=>{Q.set(Y.tokenAddress.toLowerCase(),Y.staticAttoCircles)}),Q}_createDemurragedUnwrapCalls($){let J=[];for(let[Q,[Y,G]]of Object.entries($)){if(G!=="CrcV2_ERC20WrapperDeployed_Demurraged")continue;let K=new d0({address:Q,rpcUrl:this.config.circlesRpcUrl}).unwrap(Y);J.push({to:K.to,data:K.data,value:K.value??0n})}return J}_createInflationaryUnwrapAndWrapCalls($,J,Q){let Y=[],G=[];for(let[Z,[K,X]]of Object.entries($)){if(X!=="CrcV2_ERC20WrapperDeployed_Inflationary")continue;let q=J.get(Z.toLowerCase()),M=Q.get(Z.toLowerCase())||0n;if(M===0n)continue;let z=new i0({address:Z,rpcUrl:this.config.circlesRpcUrl}).unwrap(M);Y.push({to:z.to,data:z.data,value:z.value??0n});let N=q?.tokenOwner,D=i.attoStaticCirclesToAttoCircles(M)-K;if(D>0n){let P=this.hubV2.wrap(N,D,1);G.push({to:P.to,data:P.data,value:P.value??0n})}}return{unwrapCalls:Y,wrapCalls:G}}_truncateToSixDecimals($){let J=BigInt(1e6),Q=BigInt(10)**BigInt(18);return $/(Q/J)*(Q/J)}async _getDefaultTokenExcludeList($,J){let Q=await this.group.findGroups(1,{mintHandlerEquals:$}),Y=new Set;if(Q.length>0){let G=Q[0];if(Y.add(G.group.toLowerCase()),G.erc20WrapperDemurraged)Y.add(G.erc20WrapperDemurraged.toLowerCase());if(G.erc20WrapperStatic)Y.add(G.erc20WrapperStatic.toLowerCase())}if(J?.forEach((G)=>Y.add(G.toLowerCase())),Y.size===0)return;return Array.from(Y)}}var y8=p0;class kJ{config;rpcClient;pathfinder;trust;hubV2;referralsModule;invitationFarm;invitationModuleContract;constructor($){if(!$.referralsServiceUrl)throw new v("referralsServiceUrl is required in config",{code:"INVITATION_MISSING_CONFIG",source:"INVITATIONS",context:{missingField:"referralsServiceUrl"}});this.config=$,this.rpcClient=new R0($.circlesRpcUrl),this.pathfinder=new W0(this.rpcClient),this.trust=new k0(this.rpcClient),this.hubV2=new P0({address:$.v2HubAddress,rpcUrl:$.circlesRpcUrl}),this.referralsModule=new n0({address:$.referralsModuleAddress,rpcUrl:$.circlesRpcUrl}),this.invitationFarm=new o0({address:$.invitationFarmAddress,rpcUrl:$.circlesRpcUrl}),this.invitationModuleContract=new A$({address:$.invitationModuleAddress,rpcUrl:$.circlesRpcUrl})}async ensureInviterSetup($){let J=$.toLowerCase(),Q=this.config.invitationModuleAddress,Y=[],G=new k$({address:J,rpcUrl:this.config.circlesRpcUrl});if(!await G.isModuleEnabled(Q))Y.push(G.enableModule(Q)),Y.push(this.invitationModuleContract.trustInviter(J));else if(!await this.hubV2.isTrusted(Q,J))Y.push(this.invitationModuleContract.trustInviter(J));return Y}async saveReferralData($,J){try{let Q=await fetch(`${this.config.referralsServiceUrl}/store`,{method:"POST",headers:{accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({privateKey:J,inviter:$})});if(!Q.ok)throw new v(`HTTP error! status: ${Q.status}`,{code:"INVITATION_HTTP_ERROR",source:"INVITATIONS",context:{status:Q.status,url:`${this.config.referralsServiceUrl}/store`}})}catch(Q){throw new v(`Failed to save referral data: ${Q instanceof Error?Q.message:"Unknown error"}`,{code:"INVITATION_SAVE_REFERRAL_FAILED",source:"INVITATIONS",cause:Q})}}async listReferrals($,J=10,Q=0){try{let Y=new URL(`${this.config.referralsServiceUrl}/list/${$}`);Y.searchParams.set("limit",String(J)),Y.searchParams.set("offset",String(Q));let G=await fetch(Y.toString(),{method:"GET",headers:{accept:"application/json"}});if(!G.ok)throw new v(`HTTP error! status: ${G.status}`,{code:"INVITATION_HTTP_ERROR",source:"INVITATIONS",context:{status:G.status,url:Y.toString()}});return await G.json()}catch(Y){if(Y instanceof v)throw Y;throw new v(`Failed to list referrals: ${Y instanceof Error?Y.message:"Unknown error"}`,{code:"INVITATION_LIST_REFERRALS_FAILED",source:"INVITATIONS",cause:Y})}}orderRealInviters($,J){let Q=J.toLowerCase();return $.sort((Y,G)=>{let Z=Y.address.toLowerCase()===Q,K=G.address.toLowerCase()===Q;if(Z&&!K)return-1;if(!Z&&K)return 1;return 0})}async generateInvite($,J){let Q=$.toLowerCase(),Y=J.toLowerCase();if(await this.hubV2.isHuman(Y))throw v.inviteeAlreadyRegistered(Q,Y);let Z=await this.ensureInviterSetup(Q),K=await this.getRealInviters(Q),X=[...Z];if(K.length>0){console.log("[generateInvite] Using STANDARD PATH (proxy inviters available)");let q=K[0].address,M=await this.findInvitePath(Q,q),j=await this.generateInviteData([Y],!1),N=await new v0(this.config).buildFlowMatrixTx(Q,this.config.invitationModuleAddress,M,{toTokens:[q],useWrappedBalances:!0,txData:H$(j)},!0);X.push(...N)}else{console.log("[generateInvite] Using FARM FALLBACK PATH (no proxy inviters available)");let q=new v0(this.config),M=await this.findFarmInvitePath(Q),j=await q.buildFlowMatrixTx(Q,E0,M,{toTokens:[p0],useWrappedBalances:!0},!0);X.push(...j);let z="0x20EcD8bDeb2F48d8a7c94E542aA4feC5790D9676",N=await this.invitationFarm.read("claimInvite",[],{from:z}),D=this.invitationFarm.claimInvite();X.push(D);let P=await this.invitationFarm.invitationModule(),V=Q0(["address"],[Y]),k=this.hubV2.safeTransferFrom(Q,P,N,p,V);X.push(k)}return X}async findInvitePath($,J){let Q=$.toLowerCase(),Y;if(J)Y=J.toLowerCase();else{let Z=await this.getRealInviters(Q);if(Z.length===0)throw v.noPathFound(Q,this.config.invitationModuleAddress);Y=Z[0].address}let G=await this.pathfinder.findPath({from:Q,to:this.config.invitationModuleAddress,targetFlow:p,toTokens:[Y],useWrappedBalances:!0});if(!G.transfers||G.transfers.length===0)throw v.noPathFound(Q,this.config.invitationModuleAddress);if(G.maxFlow<p){let K=Number(G.maxFlow/p);throw v.insufficientBalance(1,K,p,G.maxFlow,Q,this.config.invitationModuleAddress)}return G}async findFarmInvitePath($){let J=$.toLowerCase(),Q=await this.pathfinder.findPath({from:J,to:E0,targetFlow:p,toTokens:[y8],useWrappedBalances:!0});if(!Q.transfers||Q.transfers.length===0)throw v.noPathFound(J,E0);if(Q.maxFlow<p){let G=Number(Q.maxFlow/p);throw v.insufficientBalance(1,G,p,Q.maxFlow,J,E0)}return Q}async getRealInviters($){console.log("[getRealInviters] Finding valid proxy inviters for:",$);let J=$.toLowerCase(),Q=await this.trust.getTrustedBy(J),Y=await this.trust.getMutualTrusts(J),G=new Set([...Q.map((C)=>C.objectAvatar.toLowerCase()),...Y.map((C)=>C.objectAvatar.toLowerCase())]),[Z,K]=await Promise.all([this.trust.getTrusts(this.config.invitationModuleAddress),this.trust.getMutualTrusts(this.config.invitationModuleAddress)]),X=new Set([...Z.map((C)=>C.objectAvatar.toLowerCase()),...K.map((C)=>C.objectAvatar.toLowerCase())]),q=new Set;if(p0!=="0x0000000000000000000000000000000000000000"){let C=await this.trust.getTrusts(p0);q=new Set([...C.map((b)=>b.objectAvatar.toLowerCase())])}let M=[];for(let C of G)if(X.has(C)&&!q.has(C))M.push(C);let j=[...M];if(!q.has(J))j.push(J);if(j.length===0)return[];let N=await this.pathfinder.findPath({from:J,to:this.config.invitationModuleAddress,useWrappedBalances:!0,targetFlow:G$,toTokens:j});if(!N.transfers||N.transfers.length===0)return[];let D=new Map,P=this.config.invitationModuleAddress.toLowerCase();for(let C of N.transfers)if(C.to.toLowerCase()===P){let b=C.tokenOwner.toLowerCase(),W=D.get(b)||BigInt(0);D.set(b,W+C.value)}let V=[];for(let[C,b]of D.entries()){let W=Number(b/p);if(W>=1)V.push({address:C,possibleInvites:W})}let k=this.orderRealInviters(V,J);console.log("[getRealInviters] Final result:",k.length,"valid proxy inviters");for(let C of k);return k}async generateReferral($){let J=$.toLowerCase(),Q=F$(),Y=g$(Q),G=await this.ensureInviterSetup(J),Z=await this.getRealInviters(J),K=[...G];if(Z.length>0){console.log("[generateReferral] Using STANDARD PATH (proxy inviters available)");let X=new v0(this.config),q=await this.generateInviteData([Y],!0),M=Z[0].address,j=await this.findInvitePath(J,M),z=await X.buildFlowMatrixTx(J,this.config.invitationModuleAddress,j,{toTokens:[M],useWrappedBalances:!0,txData:H$(q)},!0);K.push(...z)}else{console.log("[generateReferral] Using FARM FALLBACK PATH (no proxy inviters available)");let X=new v0(this.config),q=await this.findFarmInvitePath(J),M=await X.buildFlowMatrixTx(J,E0,q,{toTokens:[y8],useWrappedBalances:!0},!0);K.push(...M);let j="0x20EcD8bDeb2F48d8a7c94E542aA4feC5790D9676",z=await this.invitationFarm.read("claimInvite",[],{from:j}),N=this.invitationFarm.claimInvite();K.push(N);let D=await this.invitationFarm.invitationModule(),P=this.referralsModule.createAccount(Y).data,V=Q0(["address","bytes"],[this.config.referralsModuleAddress,P]),k=this.hubV2.safeTransferFrom(J,D,z,p,V);K.push(k)}return{transactions:K,privateKey:Q}}async generateInviteData($,J=!0){if($.length===0)throw v.noAddressesProvided();if(!J)if($.length===1)return Q0(["address"],[$[0]]);else return Q0(["address[]"],[$]);if($.length===1){let Y=this.referralsModule.createAccount($[0]).data;return Q0(["address","bytes"],[this.config.referralsModuleAddress,Y])}else{let Y=this.referralsModule.createAccounts($).data;return Q0(["address","bytes"],[this.config.referralsModuleAddress,Y])}}computeAddress($){let Q=$.toLowerCase().replace("0x","").padStart(64,"0"),Y=i$.replace("0x","")+Q,G=f$("0x"+Y),Z="ff",K=d$.toLowerCase().replace("0x",""),X=G.replace("0x",""),q=n$.replace("0x",""),M="ff"+K+X+q,z="0x"+f$("0x"+M).slice(-40);return B0(z)}generateSecrets($){return Array.from({length:$},()=>{let J=F$(),Q=g$(J).toLowerCase();return{secret:J,signer:Q}})}}class wQ{referralsModuleAddress;invitations;invitationFarm;referralsModule;hubV2;constructor($){this.referralsModuleAddress=$.referralsModuleAddress,this.invitations=new kJ($),this.invitationFarm=new o0({address:$.invitationFarmAddress,rpcUrl:$.circlesRpcUrl}),this.referralsModule=new n0({address:$.referralsModuleAddress,rpcUrl:$.circlesRpcUrl}),this.hubV2=new P0({address:$.v2HubAddress,rpcUrl:$.circlesRpcUrl})}async getQuota($){return this.invitationFarm.inviterQuota($)}async getInvitationFee(){return this.invitationFarm.invitationFee()}async getInvitationModule(){return this.invitationFarm.invitationModule()}async generateReferrals($,J){if(J<=0)throw new v("Count must be greater than 0",{code:"INVITATION_INVALID_COUNT",source:"VALIDATION",context:{count:J}});let Q=$.toLowerCase(),Y=J===1,G=await this.simulateClaim(Q,J);if(!G.length)throw new v("No invitation IDs returned from claim",{code:"INVITATION_NO_IDS",source:"INVITATIONS",context:{inviter:Q,count:J}});let Z=this.invitations.generateSecrets(J),K=Z.map((j)=>j.signer),X=await this.invitationFarm.invitationModule(),q=Y?this.invitationFarm.claimInvite():this.invitationFarm.claimInvites(BigInt(J)),M=Y?this.buildReferralTransfer(Q,X,G[0],K[0]):this.buildBatchReferralTransfer(Q,X,G,K);return{referrals:Z,transactions:[q,M]}}async generateInvites($,J){if(J.length===0)throw new v("At least one invitee address must be provided",{code:"INVITATION_INVALID_COUNT",source:"VALIDATION",context:{count:0}});let Q=$.toLowerCase(),Y=J.map((j)=>j.toLowerCase()),G=Y.length,Z=G===1,K=await this.simulateClaim(Q,G);if(!K.length)throw new v("No invitation IDs returned from claim",{code:"INVITATION_NO_IDS",source:"INVITATIONS",context:{inviter:Q,count:G}});let X=await this.invitationFarm.invitationModule(),q=Z?this.invitationFarm.claimInvite():this.invitationFarm.claimInvites(BigInt(G)),M=Z?this.buildInviteTransfer(Q,X,K[0],Y[0]):this.buildBatchInviteTransfer(Q,X,K,Y);return{invitees:Y,transactions:[q,M]}}async listReferrals($,J=10,Q=0){return this.invitations.listReferrals($,J,Q)}async simulateClaim($,J){if(J===1)return[await this.invitationFarm.read("claimInvite",[],{from:$})];return this.invitationFarm.read("claimInvites",[BigInt(J)],{from:$})}buildReferralTransfer($,J,Q,Y){let G=this.referralsModule.createAccount(Y).data,Z=Q0(["address","bytes"],[this.referralsModuleAddress,G]);return this.hubV2.safeTransferFrom($,J,Q,p,Z)}buildBatchReferralTransfer($,J,Q,Y){let G=this.referralsModule.createAccounts(Y).data,Z=Q0(["address","bytes"],[this.referralsModuleAddress,G]),K=Q.map(()=>p);return this.hubV2.safeBatchTransferFrom($,J,Q,K,Z)}buildInviteTransfer($,J,Q,Y){let G=Q0(["address"],[Y]);return this.hubV2.safeTransferFrom($,J,Q,p,G)}buildBatchInviteTransfer($,J,Q,Y){let G=Q0(["address[]"],[Y]),Z=Q.map(()=>p);return this.hubV2.safeBatchTransferFrom($,J,Q,Z,G)}}class yQ{baseUrl;getToken;constructor($,J){this.baseUrl=$;this.getToken=J}getBaseUrl(){return this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}async getAuthHeaders(){if(!this.getToken)return{"Content-Type":"application/json"};return{"Content-Type":"application/json",Authorization:`Bearer ${await this.getToken()}`}}async retrieve($){try{let J=`${this.getBaseUrl()}/retrieve?key=${encodeURIComponent($)}`,Q=await fetch(J);if(!Q.ok){let Y=`HTTP error! status: ${Q.status}`;try{Y=(await Q.json()).error||Y}catch{Y=Q.statusText||Y}throw new v(Y,{code:"INVITATION_RETRIEVE_FAILED",source:"INVITATIONS",context:{status:Q.status,url:J,privateKey:$}})}return Q.json()}catch(J){if(J instanceof v)throw J;throw new v(`Failed to retrieve referral: ${J instanceof Error?J.message:"Unknown error"}`,{code:"INVITATION_RETRIEVE_ERROR",source:"INVITATIONS",cause:J,context:{privateKey:$}})}}async listMine(){if(!this.getToken)throw new v("Authentication required to list referrals",{code:"INVITATION_AUTH_REQUIRED",source:"INVITATIONS"});try{let $=`${this.getBaseUrl()}/my-referrals`,J=await this.getAuthHeaders(),Q=await fetch($,{headers:J});if(!Q.ok){let Y=`HTTP error! status: ${Q.status}`;try{Y=(await Q.json()).error||Y}catch{Y=Q.statusText||Y}throw new v(Y,{code:"INVITATION_LIST_FAILED",source:"INVITATIONS",context:{status:Q.status,url:$}})}return Q.json()}catch($){if($ instanceof v)throw $;throw new v(`Failed to list referrals: ${$ instanceof Error?$.message:"Unknown error"}`,{code:"INVITATION_LIST_ERROR",source:"INVITATIONS",cause:$})}}}export{yQ as Referrals,wQ as InviteFarm,kJ as Invitations,v as InvitationError};
|