@aboutcircles/sdk-invitations 0.1.19 → 0.1.20

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.
@@ -13,6 +13,7 @@ export declare class Invitations {
13
13
  private rpcClient;
14
14
  private pathfinder;
15
15
  private trust;
16
+ private token;
16
17
  private hubV2;
17
18
  private referralsModule;
18
19
  private invitationFarm;
@@ -108,16 +109,15 @@ export declare class Invitations {
108
109
  *
109
110
  * @description
110
111
  * This function:
111
- * 1. Gets all addresses that trust the inviter (set1) - includes both one-way trusts and mutual trusts
112
- * 2. Gets all addresses trusted by the invitation module (set2) - includes both one-way trusts and mutual trusts
113
- * 3. Gets all addresses trusted by the gnosis group (set3) - these will be excluded
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)
112
+ * @description
113
+ * set1 = addresses trusted by the Gnosis group (excluded from proxy inviters)
114
+ * set2 = addresses that trust the inviter (potential token sources)
115
+ * set3 = addresses trusted by the invitation module (can receive those tokens)
116
+ * Proxy inviters = (set2 set3) set1
117
+ *
118
+ * Only (set2 set3) set1 addresses are passed to the pathfinder as toTokens.
119
+ * Wrapped ERC20 token addresses returned by the pathfinder are resolved back to their real
120
+ * human avatar owners via getTokenInfoBatch before amounts are summed.
121
121
  */
122
122
  getRealInviters(inviter: Address): Promise<ProxyInviter[]>;
123
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;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"}
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,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;IA+BjC;;;;;;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;IAmDpE;;;;;;;;;OASG;IACG,kBAAkB,CAAC,OAAO,EAAE,OAAO;IAkCzC;;;;;;;;;;;;;;;;;OAiBG;IACG,eAAe,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;IAqGhE;;;;;;;;;;;;;;;;;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"}
@@ -1,4 +1,4 @@
1
- import { RpcClient, PathfinderMethods, TrustMethods } from '@aboutcircles/sdk-rpc';
1
+ import { RpcClient, PathfinderMethods, TrustMethods, TokenMethods } from '@aboutcircles/sdk-rpc';
2
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';
@@ -16,6 +16,7 @@ export class Invitations {
16
16
  rpcClient;
17
17
  pathfinder;
18
18
  trust;
19
+ token;
19
20
  hubV2;
20
21
  referralsModule;
21
22
  invitationFarm;
@@ -32,6 +33,7 @@ export class Invitations {
32
33
  this.rpcClient = new RpcClient(config.circlesRpcUrl);
33
34
  this.pathfinder = new PathfinderMethods(this.rpcClient);
34
35
  this.trust = new TrustMethods(this.rpcClient);
36
+ this.token = new TokenMethods(this.rpcClient);
35
37
  this.hubV2 = new HubV2ContractMinimal({
36
38
  address: config.v2HubAddress,
37
39
  rpcUrl: config.circlesRpcUrl,
@@ -277,13 +279,15 @@ export class Invitations {
277
279
  }
278
280
  tokenToUse = realInviters[0].address;
279
281
  }
280
- // Find path using the selected token
282
+ // Find path using the selected token.
283
+ // Simulate the module trusting the inviter in case enableModule/trustInviter txs are not yet on-chain.
281
284
  const path = await this.pathfinder.findPath({
282
285
  from: inviterLower,
283
286
  to: this.config.invitationModuleAddress,
284
287
  targetFlow: INVITATION_FEE,
285
288
  toTokens: [tokenToUse],
286
- useWrappedBalances: true
289
+ useWrappedBalances: true,
290
+ simulatedTrusts: [{ truster: this.config.invitationModuleAddress, trustee: inviterLower }],
287
291
  });
288
292
  if (!path.transfers || path.transfers.length === 0) {
289
293
  throw InvitationError.noPathFound(inviterLower, this.config.invitationModuleAddress);
@@ -333,108 +337,92 @@ export class Invitations {
333
337
  *
334
338
  * @description
335
339
  * This function:
336
- * 1. Gets all addresses that trust the inviter (set1) - includes both one-way trusts and mutual trusts
337
- * 2. Gets all addresses trusted by the invitation module (set2) - includes both one-way trusts and mutual trusts
338
- * 3. Gets all addresses trusted by the gnosis group (set3) - these will be excluded
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)
340
+ * @description
341
+ * set1 = addresses trusted by the Gnosis group (excluded from proxy inviters)
342
+ * set2 = addresses that trust the inviter (potential token sources)
343
+ * set3 = addresses trusted by the invitation module (can receive those tokens)
344
+ * Proxy inviters = (set2 set3) set1
345
+ *
346
+ * Only (set2 set3) set1 addresses are passed to the pathfinder as toTokens.
347
+ * Wrapped ERC20 token addresses returned by the pathfinder are resolved back to their real
348
+ * human avatar owners via getTokenInfoBatch before amounts are summed.
346
349
  */
347
350
  async getRealInviters(inviter) {
348
- console.log('[getRealInviters] Finding valid proxy inviters for:', inviter);
349
351
  const inviterLower = inviter.toLowerCase();
350
- // Step 1: Get addresses that trust the inviter (set1)
351
- const trustedByRelations = await this.trust.getTrustedBy(inviterLower);
352
- const mutualTrustRelations = await this.trust.getMutualTrusts(inviterLower);
353
- // Extract the addresses of avatars who trust the inviter
354
- // Combine both trustedBy (one-way) and mutualTrusts
355
- const trustedByInviter = new Set([
356
- ...trustedByRelations.map(relation => relation.objectAvatar.toLowerCase()),
357
- ...mutualTrustRelations.map(relation => relation.objectAvatar.toLowerCase())
358
- ]);
359
- // Step 2: Get addresses trusted by the invitation module (set2)
360
- // This includes both one-way outgoing trusts and mutual trusts
361
- // getTrusts returns only one-way outgoing trusts, so we also need getMutualTrusts
362
- // to catch addresses that trusted the module back (creating a mutual trust)
363
- const [trustsRelations, moduleMutualTrustRelations] = await Promise.all([
352
+ // set1: addresses trusted by the Gnosis group — excluded from proxy inviters
353
+ // set2: addresses that trust the inviter — potential token sources
354
+ // set3: addresses trusted by the invitation module — can receive those tokens
355
+ // Proxy inviters = (set2 set3) set1
356
+ const [gnosisGroupTrusts, trustsInviterRelations, mutualTrustRelations, moduleTrustsRelations, moduleMutualTrustRelations,] = await Promise.all([
357
+ GNOSIS_GROUP_ADDRESS !== '0x0000000000000000000000000000000000000000'
358
+ ? this.trust.getTrusts(GNOSIS_GROUP_ADDRESS)
359
+ : Promise.resolve([]),
360
+ this.trust.getTrustedBy(inviterLower),
361
+ this.trust.getMutualTrusts(inviterLower),
364
362
  this.trust.getTrusts(this.config.invitationModuleAddress),
365
363
  this.trust.getMutualTrusts(this.config.invitationModuleAddress),
366
364
  ]);
367
- const trustedByModule = new Set([
368
- ...trustsRelations.map(relation => relation.objectAvatar.toLowerCase()),
369
- ...moduleMutualTrustRelations.map(relation => relation.objectAvatar.toLowerCase()),
365
+ // set1: trusted by Gnosis group
366
+ const set1 = new Set(gnosisGroupTrusts.map(r => r.objectAvatar.toLowerCase()));
367
+ // set2: addresses that trust the inviter (one-way + mutual)
368
+ const set2 = new Set([
369
+ ...trustsInviterRelations.map(r => r.objectAvatar.toLowerCase()),
370
+ ...mutualTrustRelations.map(r => r.objectAvatar.toLowerCase()),
370
371
  ]);
371
- // Step 3: Get addresses trusted by the gnosis group (set3) - these will be excluded
372
- let trustedByGnosisGroup = new Set();
373
- if (GNOSIS_GROUP_ADDRESS !== '0x0000000000000000000000000000000000000000') {
374
- const gnosisGroupTrusts = await this.trust.getTrusts(GNOSIS_GROUP_ADDRESS);
375
- trustedByGnosisGroup = new Set([
376
- ...gnosisGroupTrusts.map(relation => relation.objectAvatar.toLowerCase()),
377
- ]);
378
- }
379
- else {
380
- }
381
- // Step 4: Find intersection - addresses that trust inviter AND are trusted by invitation module
382
- // AND are NOT trusted by the gnosis group
383
- const intersection = [];
384
- for (const address of trustedByInviter) {
385
- if (trustedByModule.has(address) && !trustedByGnosisGroup.has(address)) {
386
- intersection.push(address);
387
- }
388
- }
389
- // Step 5: Add the inviter's own address to the list of possible tokens
390
- const tokensToUse = [...intersection];
391
- const inviterExcluded = trustedByGnosisGroup.has(inviterLower);
392
- if (!inviterExcluded) {
393
- tokensToUse.push(inviterLower);
394
- }
395
- // If no tokens available at all, return empty
372
+ // set3: addresses trusted by the invitation module (one-way + mutual)
373
+ const set3 = new Set([
374
+ ...moduleTrustsRelations.map(r => r.objectAvatar.toLowerCase()),
375
+ ...moduleMutualTrustRelations.map(r => r.objectAvatar.toLowerCase()),
376
+ ]);
377
+ // (set2 set3) − set1: trust the inviter, trusted by the module, not in the Gnosis group
378
+ const intersection = [...set2].filter(a => set3.has(a) && !set1.has(a));
379
+ const tokensToUse = [...intersection, inviterLower];
396
380
  if (tokensToUse.length === 0) {
397
381
  return [];
398
382
  }
399
- // Step 6: Build path from inviter to invitation module
400
383
  const path = await this.pathfinder.findPath({
401
384
  from: inviterLower,
402
385
  to: this.config.invitationModuleAddress,
403
386
  useWrappedBalances: true,
404
387
  targetFlow: MAX_FLOW,
405
388
  toTokens: tokensToUse,
389
+ simulatedTrusts: [{ truster: this.config.invitationModuleAddress, trustee: inviterLower }],
406
390
  });
407
391
  if (!path.transfers || path.transfers.length === 0) {
408
392
  return [];
409
393
  }
410
- // Step 7: Sum up transferred token amounts by tokenOwner (only terminal transfers to invitation module)
411
- const tokenOwnerAmounts = new Map();
394
+ // Only count transfers arriving at the invitation module (terminal transfers)
412
395
  const invitationModuleLower = this.config.invitationModuleAddress.toLowerCase();
413
- for (const transfer of path.transfers) {
414
- // Only count transfers that go to the invitation module (terminal transfers)
415
- if (transfer.to.toLowerCase() === invitationModuleLower) {
416
- const tokenOwnerLower = transfer.tokenOwner.toLowerCase();
417
- const currentAmount = tokenOwnerAmounts.get(tokenOwnerLower) || BigInt(0);
418
- tokenOwnerAmounts.set(tokenOwnerLower, currentAmount + transfer.value);
396
+ const terminalTransfers = path.transfers.filter(t => t.to.toLowerCase() === invitationModuleLower);
397
+ // Resolve wrapped ERC20 token addresses to their real human avatar owners.
398
+ // The pathfinder uses the wrapped token address as tokenOwner, but the real proxy
399
+ // inviter is the human avatar who owns the underlying ERC1155 token.
400
+ // Note: the RPC returns `tokenAddress` rather than `token` as the TokenInfo type declares.
401
+ const rawOwners = [...new Set(terminalTransfers.map(t => t.tokenOwner.toLowerCase()))];
402
+ const tokenInfos = await this.token.getTokenInfoBatch(rawOwners);
403
+ const ownerRemap = new Map();
404
+ for (const info of tokenInfos) {
405
+ const tokenAddr = (info.tokenAddress ?? info.token);
406
+ if (tokenAddr && info?.tokenOwner) {
407
+ ownerRemap.set(tokenAddr.toLowerCase(), info.tokenOwner.toLowerCase());
419
408
  }
420
409
  }
421
- // Step 8: Calculate possible invites and filter token owners
410
+ // Sum amounts by resolved (real) owner
411
+ const tokenOwnerAmounts = new Map();
412
+ for (const transfer of terminalTransfers) {
413
+ const rawOwner = transfer.tokenOwner.toLowerCase();
414
+ const resolvedOwner = ownerRemap.get(rawOwner) ?? rawOwner;
415
+ tokenOwnerAmounts.set(resolvedOwner, (tokenOwnerAmounts.get(resolvedOwner) ?? 0n) + transfer.value);
416
+ }
417
+ // Build result: require >= 1 full invite worth of flow
422
418
  const realInviters = [];
423
419
  for (const [tokenOwner, amount] of tokenOwnerAmounts.entries()) {
424
420
  const possibleInvites = Number(amount / INVITATION_FEE);
425
421
  if (possibleInvites >= 1) {
426
- realInviters.push({
427
- address: tokenOwner,
428
- possibleInvites
429
- });
422
+ realInviters.push({ address: tokenOwner, possibleInvites });
430
423
  }
431
424
  }
432
- // Step 9: Order real inviters by preference (best candidates first)
433
- const orderedRealInviters = this.orderRealInviters(realInviters, inviterLower);
434
- console.log('[getRealInviters] Final result:', orderedRealInviters.length, 'valid proxy inviters');
435
- for (const ri of orderedRealInviters) {
436
- }
437
- return orderedRealInviters;
425
+ return this.orderRealInviters(realInviters, inviterLower);
438
426
  }
439
427
  /**
440
428
  * Generate a referral for inviting a new user
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
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};
1
+ var wJ=($)=>BigInt($),J$=($)=>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$(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?J$(Q.blockNumber):0,timestamp:Q.timestamp?J$(Q.timestamp):void 0,transactionIndex:Q.transactionIndex?J$(Q.transactionIndex):0,logIndex:Q.logIndex?J$(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 c0{_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 c0;return{property:$,emit:(J)=>$.emit(J)}}}class Q$ 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 Q${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=c0.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 B$($,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 C$($){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),Y$=BigInt(1),p8=BigInt(2),d8=BigInt(7),i8=BigInt(256),n8=BigInt(113),dJ=[],iJ=[],nJ=[];for(let $=0,J=Y$,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<<Y$^(J>>d8)*n8)%i8,J&p8)G^=Y$<<(Y$<<BigInt(Z))-Y$;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],N=lJ(M,j,1)^Q[X],D=pJ(M,j,1)^Q[X+1];for(let O=0;O<50;O+=10)$[K+O]^=N,$[K+O+1]^=D}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(B$($,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 l0=(()=>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 C0($){let J=$.toLowerCase().replace("0x",""),Q=L$(l0(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=l0(new TextEncoder().encode(J));return L$(Q.slice(0,4))}function p0($,J){if($==="string"||$==="bytes")return!0;if($.includes("[")){let Q=$.slice(0,$.indexOf("["));if($.endsWith("[]"))return!0;if(Q==="tuple")return aJ(J);return p0(Q)}if($==="tuple")return aJ(J);return!1}function aJ($){return $?.some((J)=>p0(J.type,J.components))??!1}function B0($,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=p0(Y,Q),K;if(Z){let X=J.map((j)=>B0(Y,j,Q)),q=J.length*I$;K=X.map((j)=>{let N=q;return q+=j.length/2,q0(N)}).join("")+X.join("")}else K=J.map((X)=>B0(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=p0(X.type,X.components);if(Z.push(M),M)Y.push(""),G.push(B0(X.type,q,X.components));else Y.push(B0(X.type,q,X.components))}if(G.length>0){let K=Y.reduce((M,j,N)=>M+(Z[N]?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 G$($,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 N=0;N<q;N++){let D=G$(G,J,j,Y);M.push(D.value),j+=D.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 N=G$(G,J,Q+M,Y);q.push(N.value),M+=N.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=G$(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:C0("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((O)=>O.type==="function"&&O.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 O=0;O<K.length;O++){let P=K[O],V=P.components,k=p0(P.type,V);if(M.push(k),k)X.push(""),q.push(B0(P.type,Y[O],V));else X.push(B0(P.type,Y[O],V))}if(q.length===0)return Z+X.join("");let j=X.reduce((O,P,V)=>O+(M[V]?I$:P.length/2),0),N="",D=0;for(let O=0;O<K.length;O++)if(M[O])N+=q0(j),j+=q[D].length/2,D++;else N+=X[O];return Z+N+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 G$(Z[0].type,K,0,Z[0].components).value;let X=[],q=0;for(let M of Z){let j=G$(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=p0(M);if(G.push(j),j)Q.push(""),Y.push(B0(M,J[q]));else Q.push(B0(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 H($){return $.toLowerCase()}function KQ($){return C0($)}function XQ($){if(typeof $!=="string")return!1;let J=$.replace("0x","");return J.length===40&&/^[0-9a-fA-F]{40}$/.test(J)}function g($){if($===null||$===void 0)return $;if(XQ($))return KQ($);if(Array.isArray($))return $.map((J)=>g(J));if(typeof $==="object"&&$!==null){let J={};for(let Q in $)if(Object.prototype.hasOwnProperty.call($,Q))J[Q]=g($[Q]);return J}return $}function sJ($){return{Source:H($.from),Sink:H($.to),TargetFlow:$.targetFlow.toString(),WithWrap:$.useWrappedBalances,FromTokens:$.fromTokens?.map(H),ToTokens:$.toTokens?.map(H),ExcludedFromTokens:$.excludeFromTokens?.map(H),ExcludedToTokens:$.excludeToTokens?.map(H),SimulatedBalances:$.simulatedBalances?.map((J)=>({Holder:H(J.holder),Token:H(J.token),Amount:J.amount.toString(),IsWrapped:J.isWrapped,IsStatic:J.isStatic})),SimulatedTrusts:$.simulatedTrusts?.map((J)=>({Truster:H(J.truster),Trustee:H(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),Z$=BigInt("9999999999999999999999999999999999999"),d$="0x4e1DCf7AD4e460CfD30791CCC4F9c8a4f820ec67",i$="0x89867a67674bd4bf33165a653cde826b696ab7d050166b71066dfa0b9b6f90f4",n$="0xe298282cefe913ab5d282047161268a8222e4bd4ed106300c547894bbefd31ee",d0="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 g(Y)}async findMaxFlow($){let J=await this.findPath({...$,targetFlow:Z$});return BigInt(J.maxFlow)}}class K${client;constructor($){this.client=$}async query($){let J=await this.client.call("circles_query",[$]);return g(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 g(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",[H($),H(J)]);return g(Q)}getTrustRelations($,J=100,Q="DESC"){let Y=H($),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)=>g(Z))}async getAggregatedTrustRelations($){let J=H($),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=H(K.truster),q=H(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])=>H(K)!==J).map(([K,X])=>{let q=Math.max(...X.map((j)=>j.timestamp)),M;if(X.length===2)M="mutuallyTrusts";else if(H(X[0]?.trustee)===J)M="trustedBy";else if(H(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 g(Z)}async getTrustedBy($){let J=H($),Y=(await this.getAggregatedTrustRelations(J)).filter((G)=>G.relation==="trustedBy");return g(Y)}async getTrusts($){let J=H($),Y=(await this.getAggregatedTrustRelations(J)).filter((G)=>G.relation==="trusts");return g(Y)}async getMutualTrusts($){let J=H($),Y=(await this.getAggregatedTrustRelations(J)).filter((G)=>G.relation==="mutuallyTrusts");return g(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",[H($),J]);return i.circlesToAttoCircles(Q)}async getTokenBalances($){let Q=(await this.client.call("circles_getTokenBalances",[H($)])).map((Y)=>j0(Y));return g(Q)}}class X${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)=>H(Y)),Q=await this.client.call("circles_getAvatarInfoBatch",[J]);return g(Q)}async getNetworkSnapshot(){let $=await this.client.call("circles_getNetworkSnapshot",[]);return g($)}}class q${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",[H($)])}async getProfileByAddressBatch($){return this.client.call("circles_getProfileByAddressBatch",[$.map((J)=>J===null?null:H(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 w0{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)=>H(G)),Y=(await this.client.call("circles_getTokenInfoBatch",[J])).map((G)=>j0(G));return g(Y)}getTokenHolders($,J=100,Q="DESC"){let Y=H($);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=H($),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 g(Q[0].inviter);return}async getInvitations($){let J=H($),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 D=(await this.client.call("circles_getTokenBalances",[j.avatar])).find((O)=>H(O.tokenAddress)===H(j.avatar));if(D&&D.circles>=96)M.push(j)}return g(M)}async getInvitationsFrom($,J=!1){let Q=H($);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 g(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)=>H(M.avatar))),q=Z.filter((M)=>!X.has(H(M)));return g(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=H($),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 g(X)})}}class y0{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=H($);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)=>g(G))}getGroupHolders($,J=100){let Q=H($);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 g(G)}})}getGroupMembers($,J=100,Q="DESC"){let Y=H($);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)=>g(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:H(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:H(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:H(J.mintHandlerEquals)});if(J.treasuryEquals)Y.push({Type:"FilterPredicate",FilterType:"Equals",Column:"treasury",Value:H(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)=>g(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 K$(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 X$(this.client);return this._avatar}get profile(){if(!this._profile)this._profile=new q$(this.client);return this._profile}get token(){if(!this._token)this._token=new w0(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 y0(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 i0 extends n{constructor($){super({address:$.address,abi:o$,rpcUrl:$.rpcUrl})}unwrap($){return{to:this.address,data:this.encodeWrite("unwrap",[$]),value:0n}}}class n0 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 o0 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 t0 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=C$(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=C$($);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),B$($,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=C$($),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 N=L0[j-15],D=L0[j-2],O=Z0(N,7)^Z0(N,18)^N>>>3,P=Z0(D,17)^Z0(D,19)^D>>>10;L0[j]=P+L0[j-7]+O+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 N=Z0(K,6)^Z0(K,11)^Z0(K,25),D=M+N+$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+D|0,Z=G,G=Y,Y=Q,Q=D+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 a0($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function KJ($){if(!a0($))throw Error("Uint8Array expected")}function s0($,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 r0($){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(r0($))}function XJ($){return KJ($),K8(r0(Uint8Array.from($).reverse()))}function b0($,J){return U$($.toString(16).padStart(J*2,"0"))}function qJ($,J){return b0($,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(a0(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 F0($,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 g0=($)=>(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=(...N)=>Q(G,Y,...N),q=(N=YJ(0))=>{if(G=X(Z8([0]),N),Y=X(),N.length===0)return;G=X(Z8([1]),N),Y=X()},M=()=>{if(Z++>=1000)throw Error("drbg: tried 1000 values");let N=0,D=[];while(N<J){Y=X();let O=Y.slice();D.push(O),N+=Y.length}return z$(...D)};return(N,D)=>{K(),q(N);let O=void 0;while(!(O=D(M())))q();return K(),O}}var zQ={bigint:($)=>typeof $==="bigint",function:($)=>typeof $==="function",boolean:($)=>typeof $==="boolean",string:($)=>typeof $==="string",stringOrUint8Array:($)=>typeof $==="string"||a0($),isSafeInteger:($)=>Number.isSafeInteger($),array:($)=>Array.isArray($),field:($,J)=>J.Fp.isValid($),hash:($)=>typeof $==="function"&&Number.isSafeInteger($.outputLen)};function f0($,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),v0=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,N=G-K*M,D=Z-X*M;Y=Q,Q=j,G=K,Z=X,K=N,X=D}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,v0),G=$.pow(Y,Q),Z=$.mul(J,G),K=$.mul($.mul(Z,v0),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%v0===r)J/=v0,Q++;let Y=v0,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)/v0;return function(q,M){if(q.is0(M))return M;if(j8(q,M)!==1)throw Error("Cannot find square root");let j=Q,N=q.mul(q.ONE,Z),D=q.pow(M,J),O=q.pow(M,K);while(!q.eql(D,q.ONE)){if(q.is0(D))return q.ZERO;let P=1,V=q.sqr(D);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),T=q.pow(N,k);j=P,N=q.sqr(T),D=q.mul(D,N),O=q.mul(O,T)}return O}}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 f0($,Q)}function BQ($,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)/v0,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:g0(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)=>BQ(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):b0(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):b0(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 B8($,J){if(!Number.isSafeInteger($)||$<=0||$>J)throw Error("invalid window size, expected [1.."+J+"], got W="+$)}function DJ($,J){B8($,J);let Q=Math.ceil(J/$)+1,Y=2**($-1),G=2**$,Z=g0($),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,N=X===0,D=X<0,O=J%2!==0;return{nextN:q,offset:j,isZero:N,isNeg:D,isNegF:O,offsetF:M}}function CQ($,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,C8=new WeakMap;function OJ($){return C8.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:N,isNeg:D,isNegF:O,offsetF:P}=R8(G,q,X);if(G=M,N)K=K.add(NJ(O,Y[P]));else Z=Z.add(NJ(D,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:N}=R8(G,X,K);if(G=q,j)continue;else{let D=Y[M];Z=Z.add(N?D.negate():D)}}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){B8(Y,J),C8.set(Q,Y),VJ.delete(Q)}}}function L8($,J,Q,Y){CQ(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=g0(q),j=Array(Number(M)+1).fill(K),N=Math.floor((J.BITS-1)/q)*q,D=K;for(let O=N;O>=0;O-=q){j.fill(K);for(let V=0;V<Z;V++){let k=Y[V],T=Number(k>>BigInt(O)&M);j[T]=j[T].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(D=D.add(P),O!==0)for(let V=0;V<q;V++)D=D.double()}return D}function BJ($){return jJ($.Fp),f0($,{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)s0("lowS",$.lowS);if($.prehash!==void 0)s0("prehash",$.prehash)}function LQ($){let J=BJ($);f0(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 CJ($,J){return r0(b0($,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,U,C)=>{let L=U.toAffine();return z$(Uint8Array.from([4]),Q.toBytes(L.x),Q.toBytes(L.y))}),Z=J.fromBytes||((W)=>{let U=W.subarray(1),C=Q.fromBytes(U.subarray(0,Q.BYTES)),L=Q.fromBytes(U.subarray(Q.BYTES,2*Q.BYTES));return{x:C,y:L}});function K(W){let{a:U,b:C}=J,L=Q.sqr(W),w=Q.mul(L,W);return Q.add(Q.add(w,Q.mul(W,U)),C)}function X(W,U){let C=Q.sqr(U),L=K(W);return Q.eql(C,L)}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 N(W){let{allowedPrivateKeyLengths:U,nByteLength:C,wrapPrivateKey:L,n:w}=J;if(U&&typeof W!=="bigint"){if(a0(W))W=r0(W);if(typeof W!=="string"||!U.includes(W.length))throw Error("invalid private key");W=W.padStart(C*2,"0")}let x;try{x=typeof W==="bigint"?W:N0(J0("private key",W,C))}catch(y){throw Error("invalid private key, expected hex or "+C+" bytes, got "+typeof W)}if(L)x=o(x,w);return F0("private key",x,d,w),x}function D(W){if(!(W instanceof V))throw Error("ProjectivePoint expected")}let O=MJ((W,U)=>{let{px:C,py:L,pz:w}=W;if(Q.eql(w,Q.ONE))return{x:C,y:L};let x=W.is0();if(U==null)U=x?Q.ONE:Q.inv(w);let y=Q.mul(C,U),_=Q.mul(L,U),A=Q.mul(w,U);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:U,y:C}=W.toAffine();if(!Q.isValid(U)||!Q.isValid(C))throw Error("bad point: x or y not FE");if(!X(U,C))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,U,C){if(W==null||!Q.isValid(W))throw Error("x required");if(U==null||!Q.isValid(U)||Q.is0(U))throw Error("y required");if(C==null||!Q.isValid(C))throw Error("z required");this.px=W,this.py=U,this.pz=C,Object.freeze(this)}static fromAffine(W){let{x:U,y:C}=W||{};if(!W||!Q.isValid(U)||!Q.isValid(C))throw Error("invalid affine point");if(W instanceof V)throw Error("projective point not allowed");let L=(w)=>Q.eql(w,Q.ZERO);if(L(U)&&L(C))return V.ZERO;return new V(U,C,Q.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(W){let U=WJ(Q,W.map((C)=>C.pz));return W.map((C,L)=>C.toAffine(U[L])).map(V.fromAffine)}static fromHex(W){let U=V.fromAffine(Z(J0("pointHex",W)));return U.assertValidity(),U}static fromPrivateKey(W){return V.BASE.multiply(N(W))}static msm(W,U){return L8(V,Y,W,U)}_setWindowSize(W){v.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){D(W);let{px:U,py:C,pz:L}=this,{px:w,py:x,pz:y}=W,_=Q.eql(Q.mul(U,y),Q.mul(w,L)),A=Q.eql(Q.mul(C,y),Q.mul(x,L));return _&&A}negate(){return new V(this.px,Q.neg(this.py),this.pz)}double(){let{a:W,b:U}=J,C=Q.mul(U,PJ),{px:L,py:w,pz:x}=this,y=Q.ZERO,_=Q.ZERO,A=Q.ZERO,E=Q.mul(L,L),c=Q.mul(w,w),h=Q.mul(x,x),z=Q.mul(L,w);return z=Q.add(z,z),A=Q.mul(L,x),A=Q.add(A,A),y=Q.mul(W,A),_=Q.mul(C,h),_=Q.add(y,_),y=Q.sub(c,_),_=Q.add(c,_),_=Q.mul(y,_),y=Q.mul(z,y),A=Q.mul(C,A),h=Q.mul(W,h),z=Q.sub(E,h),z=Q.mul(W,z),z=Q.add(z,A),A=Q.add(E,E),E=Q.add(A,E),E=Q.add(E,h),E=Q.mul(E,z),_=Q.add(_,E),h=Q.mul(w,x),h=Q.add(h,h),E=Q.mul(h,z),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){D(W);let{px:U,py:C,pz:L}=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),z=Q.mul(U,w),B=Q.mul(C,x),S=Q.mul(L,y),b=Q.add(U,C),I=Q.add(w,x);b=Q.mul(b,I),I=Q.add(z,B),b=Q.sub(b,I),I=Q.add(U,L);let R=Q.add(w,y);return I=Q.mul(I,R),R=Q.add(z,S),I=Q.sub(I,R),R=Q.add(C,L),_=Q.add(x,y),R=Q.mul(R,_),_=Q.add(B,S),R=Q.sub(R,_),E=Q.mul(c,I),_=Q.mul(h,S),E=Q.add(_,E),_=Q.sub(B,E),E=Q.add(B,E),A=Q.mul(_,E),B=Q.add(z,z),B=Q.add(B,z),S=Q.mul(c,S),I=Q.mul(h,I),B=Q.add(B,S),S=Q.sub(z,S),S=Q.mul(c,S),I=Q.add(I,S),z=Q.mul(B,I),A=Q.add(A,z),z=Q.mul(R,I),_=Q.mul(b,_),_=Q.sub(_,z),z=Q.mul(b,B),E=Q.mul(R,E),E=Q.add(E,z),new V(_,A,E)}subtract(W){return this.add(W.negate())}is0(){return this.equals(V.ZERO)}wNAF(W){return v.wNAFCached(this,W,V.normalizeZ)}multiplyUnsafe(W){let{endo:U,n:C}=J;F0("scalar",W,V0,C);let L=V.ZERO;if(W===V0)return L;if(this.is0()||W===d)return this;if(!U||v.hasPrecomputes(this))return v.wNAFCachedUnsafe(this,W,V.normalizeZ);let{k1neg:w,k1:x,k2neg:y,k2:_}=U.splitScalar(W),A=L,E=L,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,U.beta),E.py,E.pz),A.add(E)}multiply(W){let{endo:U,n:C}=J;F0("scalar",W,d,C);let L,w;if(U){let{k1neg:x,k1:y,k2neg:_,k2:A}=U.splitScalar(W),{p:E,f:c}=this.wNAF(y),{p:h,f:z}=this.wNAF(A);E=v.constTimeNegate(x,E),h=v.constTimeNegate(_,h),h=new V(Q.mul(h.px,U.beta),h.py,h.pz),L=E.add(h),w=c.add(z)}else{let{p:x,f:y}=this.wNAF(W);L=x,w=y}return V.normalizeZ([L,w])[0]}multiplyAndAddUnsafe(W,U,C){let L=V.BASE,w=(y,_)=>_===V0||_===d||!y.equals(L)?y.multiplyUnsafe(_):y.multiply(_),x=w(this,U).add(w(W,C));return x.is0()?void 0:x}toAffine(W){return O(this,W)}isTorsionFree(){let{h:W,isTorsionFree:U}=J;if(W===d)return!0;if(U)return U(V,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:W,clearCofactor:U}=J;if(W===d)return this;if(U)return U(V,this);return this.multiplyUnsafe(J.h)}toRawBytes(W=!0){return s0("isCompressed",W),this.assertValidity(),G(V,this,W)}toHex(W=!0){return s0("isCompressed",W),r0(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:T}=J,v=P8(V,k?Math.ceil(T/2):T);return{CURVE:J,ProjectivePoint:V,normPrivateKeyToScalar:N,weierstrassEquation:K,isWithinCurveOrder:j}}function IQ($){let J=BJ($);return f0(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(z){return o(z,Y)}function M(z){return b$(z,Y)}let{ProjectivePoint:j,normPrivateKeyToScalar:N,weierstrassEquation:D,isWithinCurveOrder:O}=SQ({...J,toBytes(z,B,S){let b=B.toAffine(),I=Q.toBytes(b.x),R=z$;if(s0("isCompressed",S),S)return R(Uint8Array.from([B.hasEvenY()?2:3]),I);else return R(Uint8Array.from([4]),I,Q.toBytes(b.y))},fromBytes(z){let B=z.length,S=z[0],b=z.subarray(1);if(B===K&&(S===2||S===3)){let I=N0(b);if(!y$(I,d,Q.ORDER))throw Error("Point is not on curve");let R=D(I),F;try{F=Q.sqrt(R)}catch(e){let $0=e instanceof Error?": "+e.message:"";throw Error("Point is not on curve"+$0)}let m=(F&d)===d;if((S&1)===1!==m)F=Q.neg(F);return{x:I,y:F}}else if(B===X&&S===4){let I=Q.fromBytes(b.subarray(0,Q.BYTES)),R=Q.fromBytes(b.subarray(Q.BYTES,2*Q.BYTES));return{x:I,y:R}}else{let I=K,R=X;throw Error("invalid Point, expected length of "+I+", or uncompressed "+R+", got "+B)}}});function P(z){let B=Y>>d;return z>B}function V(z){return P(z)?q(-z):z}let k=(z,B,S)=>N0(z.slice(B,S));class T{constructor(z,B,S){if(F0("r",z,d,Y),F0("s",B,d,Y),this.r=z,this.s=B,S!=null)this.recovery=S;Object.freeze(this)}static fromCompact(z){let B=G;return z=J0("compactSignature",z,B*2),new T(k(z,0,B),k(z,B,2*B))}static fromDER(z){let{r:B,s:S}=D0.toSig(J0("DER",z));return new T(B,S)}assertValidity(){}addRecoveryBit(z){return new T(this.r,this.s,z)}recoverPublicKey(z){let{r:B,s:S,recovery:b}=this,I=w(J0("msgHash",z));if(b==null||![0,1,2,3].includes(b))throw Error("recovery id invalid");let R=b===2||b===3?B+J.n:B;if(R>=Q.ORDER)throw Error("recovery id 2 or 3 invalid");let F=(b&1)===0?"02":"03",m=j.fromHex(F+CJ(R,Q.BYTES)),l=M(R),e=q(-I*l),$0=q(S*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 T(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 z=G;return CJ(this.r,z)+CJ(this.s,z)}}let v={isValidPrivateKey(z){try{return N(z),!0}catch(B){return!1}},normPrivateKeyToScalar:N,randomPrivateKey:()=>{let z=zJ(J.n);return V8(J.randomBytes(z),J.n)},precompute(z=8,B=j.BASE){return B._setWindowSize(z),B.multiply(BigInt(3)),B}};function W(z,B=!0){return j.fromPrivateKey(z).toRawBytes(B)}function U(z){if(typeof z==="bigint")return!1;if(z instanceof j)return!0;let S=J0("key",z).length,b=Q.BYTES,I=b+1,R=2*b+1;if(J.allowedPrivateKeyLengths||G===I)return;else return S===I||S===R}function C(z,B,S=!0){if(U(z)===!0)throw Error("first arg must be private key");if(U(B)===!1)throw Error("second arg must be public key");return j.fromHex(B).multiply(N(z)).toRawBytes(S)}let L=J.bits2int||function(z){if(z.length>8192)throw Error("input is too large");let B=N0(z),S=z.length*8-Z;return S>0?B>>BigInt(S):B},w=J.bits2int_modN||function(z){return q(L(z))},x=g0(Z);function y(z){return F0("num < 2^"+Z,z,V0,x),b0(z,G)}function _(z,B,S=A){if(["recovered","canonical"].some((H0)=>(H0 in S)))throw Error("sign() legacy options not supported");let{hash:b,randomBytes:I}=J,{lowS:R,prehash:F,extraEntropy:m}=S;if(R==null)R=!0;if(z=J0("msgHash",z),H8(S),F)z=J0("prehashed msgHash",b(z));let l=w(z),e=N(B),$0=[y(e),y(l)];if(m!=null&&m!==!1){let H0=m===!0?I(Q.BYTES):m;$0.push(J0("extraEntropy",H0))}let O0=z$(...$0),V$=l;function v$(H0){let m0=L(H0);if(!O(m0))return;let h$=M(m0),e0=j.BASE.multiply(m0).toAffine(),S0=q(e0.x);if(S0===V0)return;let $$=q(h$*q(V$+S0*e));if($$===V0)return;let u0=(e0.x===S0?0:2)|Number(e0.y&d),AJ=$$;if(R&&P($$))AJ=V($$),u0^=1;return new T(S0,AJ,u0)}return{seed:O0,k2sig:v$}}let A={lowS:J.lowS,prehash:!1},E={lowS:J.lowS,prehash:!1};function c(z,B,S=A){let{seed:b,k2sig:I}=_(z,B,S),R=J;return M8(R.hash.outputLen,R.nByteLength,R.hmac)(b,I)}j.BASE._setWindowSize(8);function h(z,B,S,b=E){let I=z;B=J0("msgHash",B),S=J0("publicKey",S);let{lowS:R,prehash:F,format:m}=b;if(H8(b),"strict"in b)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 I==="string"||a0(I),e=!l&&!m&&typeof I==="object"&&I!==null&&typeof I.r==="bigint"&&typeof I.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 T(I.r,I.s);if(l){try{if(m!=="compact")$0=T.fromDER(I)}catch(u0){if(!(u0 instanceof D0.Err))throw u0}if(!$0&&m!=="der")$0=T.fromCompact(I)}O0=j.fromHex(S)}catch(u0){return!1}if(!$0)return!1;if(R&&$0.hasHighS())return!1;if(F)B=J.hash(B);let{r:V$,s:v$}=$0,H0=w(B),m0=M(v$),h$=q(H0*m0),e0=q(V$*m0),S0=j.BASE.multiplyAndAddUnsafe(O0,h$,e0)?.toAffine();if(!S0)return!1;return q(S0.x)===V$}return{CURVE:J,getPublicKey:W,getSharedSecret:C,sign:c,verify:h,ProjectivePoint:j,Signature:T,utils:v}}/*! 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,N=G0(j,Q,J)*j%J,D=G0(N,Q,J)*j%J,O=G0(D,LJ,J)*M%J,P=G0(O,G,J)*O%J,V=G0(P,Z,J)*P%J,k=G0(V,X,J)*V%J,T=G0(k,q,J)*k%J,v=G0(T,X,J)*V%J,W=G0(v,Q,J)*j%J,U=G0(W,K,J)*P%J,C=G0(U,Y,J)*M%J,L=G0(C,LJ,J);if(!HJ.eql(HJ.sqr(L),$))throw Error("Cannot find square root");return L}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),N=M>K,D=j>K;if(N)M=J-M;if(D)j=J-j;if(M>K||j>K)throw Error("splitScalar: Endomorphism failed, k="+$);return{k1neg:N,k1:M,k2neg:D,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=l0(Y.slice(1)).slice(-20),K="0x"+Buffer.from(Z).toString("hex");return C0(K)}function f$($){let J;if(typeof $==="string"){let Y=$.startsWith("0x")?$.slice(2):$;J=Buffer.from(Y,"hex")}else J=$;let Q=l0(J);return"0x"+Buffer.from(Q).toString("hex")}class f extends w${constructor($,J){super("InvitationError",$,{...J,source:J?.source||"INVITATIONS"})}static noPathFound($,J,Q){return new f(`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 f(`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 f(`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 f(`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 f("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,N=q>M;return j?-1:N?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((T,v)=>{return{streamSinkId:q.has(v)?1:0,amount:T.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),N=[{sourceCoordinate:X[G],flowEdgeIds:j,data:new Uint8Array(0)}],D=[];Y.forEach((T)=>{D.push(X[T.tokenOwner.toLowerCase()]),D.push(X[T.from.toLowerCase()]),D.push(X[T.to.toLowerCase()])});let O=A8(D),P=BigInt(Q),V=M.filter((T)=>T.streamSinkId===1).reduce((T,v)=>T+BigInt(v.amount.toString()),BigInt(0));if(V!==P)throw Error(`Terminal sum ${V} does not equal expected ${P}`);return{flowVertices:K,flowEdges:M,streams:N,packedCoordinates:O,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 Q${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 h0{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 y0(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 v=Y.toTokens[0].toLowerCase();if(Q.maxFlow>0n)X.transfers.push({from:K,to:K,tokenOwner:v,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 N=[],D=[];if(j){let v=await this._getTokenBalanceMap(Z),W=this._createDemurragedUnwrapCalls(M),{unwrapCalls:U,wrapCalls:C}=this._createInflationaryUnwrapAndWrapCalls(M,q,v);N=[...W,...U],D=C,X=EJ(X,q)}let O=IJ(Z,K,X.maxFlow,X.transfers),P=TJ(O,Y?.txData),V=this.hubV2.operateFlowMatrix(O.flowVertices,O.flowEdges,P,O.packedCoordinates),k=!1;try{k=await this.hubV2.isApprovedForAll(Z,Z)}catch(v){console.warn("Failed to check approval status, including approval transaction:",v)}return[...k?[]:[this.hubV2.setApprovalForAll(Z,!0)],...N,V,...D]}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 O=Y.fromTokens[0],P=Y.toTokens[0],[V,k]=await Promise.all([this.liftERC20.erc20Circles(0,P),this.liftERC20.erc20Circles(1,P)]);if(O.toLowerCase()===V.toLowerCase()&&V!==_$){let v=new i0({address:O,rpcUrl:this.config.circlesRpcUrl}).unwrap(X);return[{to:v.to,data:v.data,value:v.value??0n}]}if(O.toLowerCase()===k.toLowerCase()&&k!==_$){let T=new n0({address:O,rpcUrl:this.config.circlesRpcUrl}),v=i.attoCirclesToAttoStaticCircles(X),W=T.unwrap(v);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||{},N={...j,...M?{excludeFromTokens:M}:{}},D=await this.pathfinder.findPath({from:Z,to:K,targetFlow:q,...N});if(!D.transfers||D.transfers.length===0)throw a.noPathFound(Z,K);if(D.maxFlow<q)throw a.insufficientBalance(q,D.maxFlow,Z,K);return this.buildFlowMatrixTx(Z,K,D,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,N=0n,D=0n,O=null,P=null;for(let R of M)if(R.isWrapped)if(R.tokenType.includes("Demurrage"))N=BigInt(R.attoCircles),O=R.tokenAddress;else D=BigInt(R.staticAttoCircles),P=R.tokenAddress;else j=BigInt(R.attoCircles);let V=j+N+i.attoStaticCirclesToAttoCircles(D),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 R=await this.hubV2.toTokenId(Z),F=this.hubV2.safeTransferFrom(G,K,R,X);k.push({to:F.to,data:F.data,value:F.value??0n})}return k}let T=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(T)/1000000000000000000} CRC`),V>=X){let R=T;if(N>0n&&O&&R>0n){let F=R>N?N:R,l=new i0({address:O,rpcUrl:this.config.circlesRpcUrl}).unwrap(F);k.push({to:l.to,data:l.data,value:l.value??0n}),R-=F}if(D>0n&&P&&R>0n){let F=i.attoCirclesToAttoStaticCircles(R),m=F>D?D:F,e=new n0({address:P,rpcUrl:this.config.circlesRpcUrl}).unwrap(m);k.push({to:e.to,data:e.data,value:e.value??0n})}if(K!==G){let F=await this.hubV2.toTokenId(Z),m=this.hubV2.safeTransferFrom(G,K,F,X);k.push({to:m.to,data:m.data,value:m.value??0n})}return k}let W=!await this.hubV2.isTrusted(G,Z),U=BigInt(Math.floor(Date.now()/1000)+31536000),C=i.truncateToInt64(T),L=T%i.FACTOR_1E12!==0n,w=i.blowUpToBigInt(L?C+1n:C),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(R){let F=Number(V)/1000000000000000000,m=Number(X)/1000000000000000000,l=Number(T)/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): ${F.toFixed(6)} CRC. Cannot acquire the remaining ${(Number(T-(V-j))/1000000000000000000).toFixed(6)} CRC.`,{code:"REPLENISH_INSUFFICIENT_TOKENS",source:"VALIDATION",context:{from:G,tokenId:Z,target:X.toString(),unwrapped:j.toString(),deficit:T.toString(),available:V.toString(),targetCrc:m,unwrappedCrc:Number(j)/1000000000000000000,deficitCrc:l,availableCrc:F}})}if(!x.transfers||x.transfers.length===0)throw a.noPathFound(G,K,`No path to acquire token ${Z}`);if(x.maxFlow<w){let R=Number(x.maxFlow)/1000000000000000000,F=Number(w)/1000000000000000000;throw new a(`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:x.maxFlow.toString(),deficitCrc:F,pathFlowCrc:R}})}if(W){let R=this.hubV2.trust(Z,U);k.push({to:R.to,data:R.data,value:R.value??0n})}let y=await _J(G,this.config.circlesRpcUrl,x),_=xJ(x,y),A=Object.keys(_).length>0,E=[],c=[];if(A){let R=await this._getTokenBalanceMap(G),F=this._createDemurragedUnwrapCalls(_),{unwrapCalls:m,wrapCalls:l}=this._createInflationaryUnwrapAndWrapCalls(_,y,R);E=[...F,...m],c=l,x=EJ(x,y)}let h=IJ(G,K,x.maxFlow,x.transfers),z=TJ(h),B=this.hubV2.operateFlowMatrix(h.flowVertices,h.flowEdges,z,h.packedCoordinates),S={to:B.to,data:B.data,value:B.value??0n},b=!1;try{b=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 I=b?[]:[{to:this.hubV2.setApprovalForAll(G,!0).to,data:this.hubV2.setApprovalForAll(G,!0).data,value:0n}];return k.push(...I,...E,S,...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 i0({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 N=new n0({address:Z,rpcUrl:this.config.circlesRpcUrl}).unwrap(M);Y.push({to:N.to,data:N.data,value:N.value??0n});let D=q?.tokenOwner,O=i.attoStaticCirclesToAttoCircles(M)-K;if(O>0n){let P=this.hubV2.wrap(D,O,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=d0;class kJ{config;rpcClient;pathfinder;trust;token;hubV2;referralsModule;invitationFarm;invitationModuleContract;constructor($){if(!$.referralsServiceUrl)throw new f("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.token=new w0(this.rpcClient),this.hubV2=new P0({address:$.v2HubAddress,rpcUrl:$.circlesRpcUrl}),this.referralsModule=new o0({address:$.referralsModuleAddress,rpcUrl:$.circlesRpcUrl}),this.invitationFarm=new t0({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 f(`HTTP error! status: ${Q.status}`,{code:"INVITATION_HTTP_ERROR",source:"INVITATIONS",context:{status:Q.status,url:`${this.config.referralsServiceUrl}/store`}})}catch(Q){throw new f(`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 f(`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 f)throw Y;throw new f(`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 f.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),D=await new h0(this.config).buildFlowMatrixTx(Q,this.config.invitationModuleAddress,M,{toTokens:[q],useWrappedBalances:!0,txData:H$(j)},!0);X.push(...D)}else{console.log("[generateInvite] Using FARM FALLBACK PATH (no proxy inviters available)");let q=new h0(this.config),M=await this.findFarmInvitePath(Q),j=await q.buildFlowMatrixTx(Q,E0,M,{toTokens:[d0],useWrappedBalances:!0},!0);X.push(...j);let N="0x20EcD8bDeb2F48d8a7c94E542aA4feC5790D9676",D=await this.invitationFarm.read("claimInvite",[],{from:N}),O=this.invitationFarm.claimInvite();X.push(O);let P=await this.invitationFarm.invitationModule(),V=Q0(["address"],[Y]),k=this.hubV2.safeTransferFrom(Q,P,D,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 f.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,simulatedTrusts:[{truster:this.config.invitationModuleAddress,trustee:Q}]});if(!G.transfers||G.transfers.length===0)throw f.noPathFound(Q,this.config.invitationModuleAddress);if(G.maxFlow<p){let K=Number(G.maxFlow/p);throw f.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 f.noPathFound(J,E0);if(Q.maxFlow<p){let G=Number(Q.maxFlow/p);throw f.insufficientBalance(1,G,p,Q.maxFlow,J,E0)}return Q}async getRealInviters($){let J=$.toLowerCase(),[Q,Y,G,Z,K]=await Promise.all([d0!=="0x0000000000000000000000000000000000000000"?this.trust.getTrusts(d0):Promise.resolve([]),this.trust.getTrustedBy(J),this.trust.getMutualTrusts(J),this.trust.getTrusts(this.config.invitationModuleAddress),this.trust.getMutualTrusts(this.config.invitationModuleAddress)]),X=new Set(Q.map((U)=>U.objectAvatar.toLowerCase())),q=new Set([...Y.map((U)=>U.objectAvatar.toLowerCase()),...G.map((U)=>U.objectAvatar.toLowerCase())]),M=new Set([...Z.map((U)=>U.objectAvatar.toLowerCase()),...K.map((U)=>U.objectAvatar.toLowerCase())]),N=[...[...q].filter((U)=>M.has(U)&&!X.has(U)),J];if(N.length===0)return[];let D=await this.pathfinder.findPath({from:J,to:this.config.invitationModuleAddress,useWrappedBalances:!0,targetFlow:Z$,toTokens:N,simulatedTrusts:[{truster:this.config.invitationModuleAddress,trustee:J}]});if(!D.transfers||D.transfers.length===0)return[];let O=this.config.invitationModuleAddress.toLowerCase(),P=D.transfers.filter((U)=>U.to.toLowerCase()===O),V=[...new Set(P.map((U)=>U.tokenOwner.toLowerCase()))],k=await this.token.getTokenInfoBatch(V),T=new Map;for(let U of k){let C=U.tokenAddress??U.token;if(C&&U?.tokenOwner)T.set(C.toLowerCase(),U.tokenOwner.toLowerCase())}let v=new Map;for(let U of P){let C=U.tokenOwner.toLowerCase(),L=T.get(C)??C;v.set(L,(v.get(L)??0n)+U.value)}let W=[];for(let[U,C]of v.entries()){let L=Number(C/p);if(L>=1)W.push({address:U,possibleInvites:L})}return this.orderRealInviters(W,J)}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 h0(this.config),q=await this.generateInviteData([Y],!0),M=Z[0].address,j=await this.findInvitePath(J,M),N=await X.buildFlowMatrixTx(J,this.config.invitationModuleAddress,j,{toTokens:[M],useWrappedBalances:!0,txData:H$(q)},!0);K.push(...N)}else{console.log("[generateReferral] Using FARM FALLBACK PATH (no proxy inviters available)");let X=new h0(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",N=await this.invitationFarm.read("claimInvite",[],{from:j}),D=this.invitationFarm.claimInvite();K.push(D);let O=await this.invitationFarm.invitationModule(),P=this.referralsModule.createAccount(Y).data,V=Q0(["address","bytes"],[this.config.referralsModuleAddress,P]),k=this.hubV2.safeTransferFrom(J,O,N,p,V);K.push(k)}return{transactions:K,privateKey:Q}}async generateInviteData($,J=!0){if($.length===0)throw f.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,N="0x"+f$("0x"+M).slice(-40);return C0(N)}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 t0({address:$.invitationFarmAddress,rpcUrl:$.circlesRpcUrl}),this.referralsModule=new o0({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 f("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 f("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 f("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 f("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 f(Y,{code:"INVITATION_RETRIEVE_FAILED",source:"INVITATIONS",context:{status:Q.status,url:J,privateKey:$}})}return Q.json()}catch(J){if(J instanceof f)throw J;throw new f(`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 f("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 f(Y,{code:"INVITATION_LIST_FAILED",source:"INVITATIONS",context:{status:Q.status,url:$}})}return Q.json()}catch($){if($ instanceof f)throw $;throw new f(`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,f as InvitationError};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aboutcircles/sdk-invitations",
3
- "version": "0.1.19",
3
+ "version": "0.1.20",
4
4
  "description": "Circles Invitations Module SDK",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",