@aboutcircles/sdk-rpc 0.1.29 → 0.1.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.ts CHANGED
@@ -12,6 +12,7 @@ export declare class RpcClient {
12
12
  private websocketConnected;
13
13
  private pendingResponses;
14
14
  private subscriptionListeners;
15
+ private activeSubscriptions;
15
16
  private reconnectAttempt;
16
17
  private readonly initialBackoff;
17
18
  private readonly maxBackoff;
@@ -43,6 +44,14 @@ export declare class RpcClient {
43
44
  * @private
44
45
  */
45
46
  private reconnect;
47
+ /**
48
+ * Re-issues circles_subscribe for every tracked active subscription so the
49
+ * server resumes pushing events after a reconnect. Server-assigned
50
+ * subscriptionIds change on each subscribe, so we move the existing
51
+ * listeners from the old id to the new one.
52
+ * @private
53
+ */
54
+ private resubscribeActive;
46
55
  /**
47
56
  * Sends a message over WebSocket
48
57
  * @private
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAmC,OAAO,EAAE,MAAM,yBAAyB,CAAC;AACxF,OAAO,EAAE,UAAU,EAA+B,MAAM,mBAAmB,CAAC;AAC5E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAGtD;;;GAGG;AACH,qBAAa,SAAS;IACpB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,SAAS,CAAa;IAG9B,OAAO,CAAC,SAAS,CAA0B;IAC3C,OAAO,CAAC,kBAAkB,CAAS;IACnC,OAAO,CAAC,gBAAgB,CAA2B;IACnD,OAAO,CAAC,qBAAqB,CAEtB;IAGP,OAAO,CAAC,gBAAgB,CAAK;IAC7B,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAQ;IACvC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAU;gBAEzB,MAAM,EAAE,MAAM;IAI1B;;OAEG;IACG,IAAI,CAAC,OAAO,GAAG,OAAO,EAAE,EAAE,OAAO,GAAG,OAAO,EAC/C,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,OAAO,GACd,OAAO,CAAC,OAAO,CAAC;IA6CnB;;OAEG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAI/B;;OAEG;IACH,SAAS,IAAI,MAAM;IAInB;;;OAGG;IACH,OAAO,CAAC,OAAO;IAyDf;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IAqBzB;;;OAGG;YACW,SAAS;IAWvB;;;OAGG;IACH,OAAO,CAAC,WAAW;IAmBnB;;;;OAIG;IACG,SAAS,CAAC,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;CAuBtE"}
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAmC,OAAO,EAAE,MAAM,yBAAyB,CAAC;AACxF,OAAO,EAAE,UAAU,EAA+B,MAAM,mBAAmB,CAAC;AAC5E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAGtD;;;GAGG;AACH,qBAAa,SAAS;IACpB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,SAAS,CAAa;IAG9B,OAAO,CAAC,SAAS,CAA0B;IAC3C,OAAO,CAAC,kBAAkB,CAAS;IACnC,OAAO,CAAC,gBAAgB,CAA2B;IACnD,OAAO,CAAC,qBAAqB,CAEtB;IAMP,OAAO,CAAC,mBAAmB,CAA2C;IAGtE,OAAO,CAAC,gBAAgB,CAAK;IAC7B,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAQ;IACvC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAU;gBAEzB,MAAM,EAAE,MAAM;IAI1B;;OAEG;IACG,IAAI,CAAC,OAAO,GAAG,OAAO,EAAE,EAAE,OAAO,GAAG,OAAO,EAC/C,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,OAAO,GACd,OAAO,CAAC,OAAO,CAAC;IA6CnB;;OAEG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAI/B;;OAEG;IACH,SAAS,IAAI,MAAM;IAInB;;;OAGG;IACH,OAAO,CAAC,OAAO;IAyDf;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IAqBzB;;;OAGG;YACW,SAAS;IAYvB;;;;;;OAMG;YACW,iBAAiB;IA2B/B;;;OAGG;IACH,OAAO,CAAC,WAAW;IAmBnB;;;;OAIG;IACG,SAAS,CAAC,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;CAyBtE"}
package/dist/client.js CHANGED
@@ -12,6 +12,11 @@ export class RpcClient {
12
12
  websocketConnected = false;
13
13
  pendingResponses = {};
14
14
  subscriptionListeners = {};
15
+ // Track parameters of active subscriptions so we can re-issue circles_subscribe
16
+ // after a reconnect. The server forgets prior subscriptionIds when the WS
17
+ // closes, so without this the server stops pushing events even though the
18
+ // client's local listeners are still attached.
19
+ activeSubscriptions = [];
15
20
  // Backoff-related fields for reconnection
16
21
  reconnectAttempt = 0;
17
22
  initialBackoff = 2000; // 2 seconds
@@ -150,12 +155,44 @@ export class RpcClient {
150
155
  try {
151
156
  await this.connect();
152
157
  console.log('Reconnection successful');
158
+ await this.resubscribeActive();
153
159
  }
154
160
  catch (err) {
155
161
  console.error('Reconnection attempt failed:', err);
156
162
  this.scheduleReconnect();
157
163
  }
158
164
  }
165
+ /**
166
+ * Re-issues circles_subscribe for every tracked active subscription so the
167
+ * server resumes pushing events after a reconnect. Server-assigned
168
+ * subscriptionIds change on each subscribe, so we move the existing
169
+ * listeners from the old id to the new one.
170
+ * @private
171
+ */
172
+ async resubscribeActive() {
173
+ if (this.activeSubscriptions.length === 0)
174
+ return;
175
+ const previous = [...this.activeSubscriptions];
176
+ this.activeSubscriptions = [];
177
+ for (const entry of previous) {
178
+ try {
179
+ const params = entry.address ? { address: entry.address } : {};
180
+ const response = await this.sendMessage('circles_subscribe', params);
181
+ const newId = response.result;
182
+ const existingListeners = this.subscriptionListeners[entry.id];
183
+ if (existingListeners) {
184
+ this.subscriptionListeners[newId] = existingListeners;
185
+ delete this.subscriptionListeners[entry.id];
186
+ }
187
+ this.activeSubscriptions.push({ id: newId, address: entry.address });
188
+ }
189
+ catch (err) {
190
+ console.error('Failed to re-issue circles_subscribe after reconnect:', err);
191
+ // Keep the entry so a subsequent reconnect can retry it.
192
+ this.activeSubscriptions.push(entry);
193
+ }
194
+ }
195
+ }
159
196
  /**
160
197
  * Sends a message over WebSocket
161
198
  * @private
@@ -198,6 +235,7 @@ export class RpcClient {
198
235
  this.subscriptionListeners[subscriptionId].push((events) => {
199
236
  parseRpcSubscriptionMessage(events).forEach(event => observable.emit(event));
200
237
  });
238
+ this.activeSubscriptions.push({ id: subscriptionId, address: normalizedAddress });
201
239
  return observable.property;
202
240
  }
203
241
  }
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- function c(J){return J&&typeof J==="object"&&typeof J.$event==="string"&&typeof J.blockNumber==="number"&&typeof J.transactionIndex==="number"&&typeof J.logIndex==="number"}var l=(J)=>BigInt(J),I=(J)=>parseInt(J,16),OJ=(J)=>{if(J.startsWith("0x"))J=J.slice(2);if(J.length%2!==0)throw Error("Invalid hex string");let Z=new Uint8Array(J.length/2);for(let $=0;$<J.length;$+=2)Z[$/2]=parseInt(J.substr($,2),16);return Z};function DJ(J,Z){if(typeof Z==="string"&&Z.startsWith("0x")){let $=Z.slice(2);if($.length===40)return Z;if($.length===64){if(J.toLowerCase().includes("digest")||J.toLowerCase().includes("data")||J.toLowerCase().includes("bytes"))return OJ(Z);try{return l(Z)}catch{return Z}}try{let Y=I(Z);if(Y<Number.MAX_SAFE_INTEGER)return Y;return l(Z)}catch{return Z}}if(Z==="true")return!0;if(Z==="false")return!1;return Z}function b(J){let{event:Z,values:$}=J,Y={$event:Z,blockNumber:$.blockNumber?I($.blockNumber):0,timestamp:$.timestamp?I($.timestamp):void 0,transactionIndex:$.transactionIndex?I($.transactionIndex):0,logIndex:$.logIndex?I($.logIndex):0,transactionHash:$.transactionHash};for(let[W,G]of Object.entries($)){if(["blockNumber","timestamp","transactionIndex","logIndex","transactionHash"].includes(W))continue;Y[W]=DJ(W,G)}return Y}function H(J){return J.map(b)}class D{_subscribers=[];subscribe(J){return this._subscribers.push(J),()=>{let Z=this._subscribers.indexOf(J);if(Z>-1)this._subscribers.splice(Z,1)}}constructor(){this._subscribers=[]}emit(J){this._subscribers.forEach((Z)=>Z(J))}static create(){let J=new D;return{property:J,emit:(Z)=>J.emit(Z)}}}class v extends Error{name;code;source;cause;context;constructor(J,Z,$){super(Z);if(this.name=J,this.code=$?.code,this.source=$?.source??"UNKNOWN",this.cause=$?.cause,this.context=$?.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 J=`[${this.source}] ${this.name}: ${this.message}`;if(this.code)J+=` (Code: ${this.code})`;if(this.context)J+=`
2
- Context: ${JSON.stringify(this.context,null,2)}`;return J}}class q extends v{constructor(J,Z){super("RpcError",J,{...Z,source:Z?.source??"RPC_REQUEST"})}static connectionFailed(J,Z){return new q("Failed to connect to RPC endpoint",{code:"RPC_CONNECTION_FAILED",source:"RPC_CONNECTION",cause:Z,context:{url:J}})}static timeout(J,Z){return new q("RPC request timed out",{code:"RPC_TIMEOUT",source:"RPC_TIMEOUT",context:{method:J,timeout:Z}})}static invalidResponse(J,Z){return new q("Invalid RPC response",{code:"RPC_INVALID_RESPONSE",source:"RPC_RESPONSE",context:{method:J,response:Z}})}static fromJsonRpcError(J){return new q(J.message,{code:J.code,source:"RPC_RESPONSE",context:{data:J.data}})}static websocketError(J,Z){return new q(J,{code:"RPC_WEBSOCKET_ERROR",source:"RPC_WEBSOCKET",cause:Z})}}class k{rpcUrl;requestId=0;websocket=null;websocketConnected=!1;pendingResponses={};subscriptionListeners={};reconnectAttempt=0;initialBackoff=2000;maxBackoff=120000;constructor(J){this.rpcUrl=J}async call(J,Z){this.requestId++;let $={jsonrpc:"2.0",id:this.requestId,method:J,params:Z};try{let Y=await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)});if(!Y.ok)throw q.connectionFailed(this.rpcUrl,Error(`HTTP ${Y.status}: ${Y.statusText}`));let W=await Y.json();if(W.error)throw q.fromJsonRpcError(W.error);if(W.result===void 0)throw q.invalidResponse(J,W);return W.result}catch(Y){if(Y instanceof q)throw Y;throw q.connectionFailed(this.rpcUrl,Y)}}setRpcUrl(J){this.rpcUrl=J}getRpcUrl(){return this.rpcUrl}connect(){return new Promise((J,Z)=>{let $=this.rpcUrl.replace("http","ws");if($.endsWith("/"))$+="ws/subscribe";else $+="/ws/subscribe";this.websocket=new WebSocket($),this.websocket.onopen=()=>{console.log("WebSocket connected"),this.websocketConnected=!0,this.reconnectAttempt=0,J()},this.websocket.onmessage=(Y)=>{let W=JSON.parse(Y.data),{id:G,method:Q,params:M}=W;if(G!==void 0&&this.pendingResponses[G])this.pendingResponses[G].resolve(W),delete this.pendingResponses[G];if(Q==="circles_subscription"&&M?.result)Object.values(this.subscriptionListeners).forEach((F)=>{F.forEach((O)=>O(M.result))})},this.websocket.onclose=()=>{console.warn("WebSocket closed");let Y=this.websocketConnected;if(this.websocketConnected=!1,Y)this.scheduleReconnect()},this.websocket.onerror=(Y)=>{console.error("WebSocket error:",Y),this.websocketConnected=!1,Z(q.connectionFailed(this.rpcUrl,Y instanceof Error?Y:Error("WebSocket connection failed"))),this.scheduleReconnect()}})}scheduleReconnect(){let J=Math.min(this.initialBackoff*Math.pow(2,this.reconnectAttempt),this.maxBackoff),Z=J*(Math.random()*0.5),$=J+Z;console.log(`Reconnecting in ${Math.round($)}ms (attempt #${this.reconnectAttempt+1})`),this.reconnectAttempt++,setTimeout(()=>{this.reconnect()},$)}async reconnect(){if(this.websocketConnected)return;try{await this.connect(),console.log("Reconnection successful")}catch(J){console.error("Reconnection attempt failed:",J),this.scheduleReconnect()}}sendMessage(J,Z,$=5000){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return Promise.reject(q.connectionFailed(this.rpcUrl));let Y=this.requestId++,W={jsonrpc:"2.0",method:J,params:Z,id:Y};return new Promise((G,Q)=>{this.pendingResponses[Y]={resolve:G,reject:Q},this.websocket.send(JSON.stringify(W)),setTimeout(()=>{if(this.pendingResponses[Y])this.pendingResponses[Y].reject(q.timeout(J,$)),delete this.pendingResponses[Y]},$)})}async subscribe(J){let Z=J?.toLowerCase();if(!this.websocketConnected)await this.connect();let $=D.create(),Y=Z?{address:Z}:{},G=(await this.sendMessage("circles_subscribe",Y)).result;if(!this.subscriptionListeners[G])this.subscriptionListeners[G]=[];return this.subscriptionListeners[G].push((Q)=>{H(Q).forEach((M)=>$.emit(M))}),$.property}}var g=BigInt(4294967295),d=BigInt(32);function IJ(J,Z=!1){if(Z)return{h:Number(J&g),l:Number(J>>d&g)};return{h:Number(J>>d&g)|0,l:Number(J&g)|0}}function i(J,Z=!1){let $=J.length,Y=new Uint32Array($),W=new Uint32Array($);for(let G=0;G<$;G++){let{h:Q,l:M}=IJ(J[G],Z);[Y[G],W[G]]=[Q,M]}return[Y,W]}var n=(J,Z,$)=>J<<$|Z>>>32-$,o=(J,Z,$)=>Z<<$|J>>>32-$,t=(J,Z,$)=>Z<<$-32|J>>>64-$,a=(J,Z,$)=>J<<$-32|Z>>>64-$;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function jJ(J){return J instanceof Uint8Array||ArrayBuffer.isView(J)&&J.constructor.name==="Uint8Array"}function f(J,Z=""){if(!Number.isSafeInteger(J)||J<0){let $=Z&&`"${Z}" `;throw Error(`${$}expected integer >= 0, got ${J}`)}}function A(J,Z,$=""){let Y=jJ(J),W=J?.length,G=Z!==void 0;if(!Y||G&&W!==Z){let Q=$&&`"${$}" `,M=G?` of length ${Z}`:"",F=Y?`length=${W}`:`type=${typeof J}`;throw Error(Q+"expected Uint8Array"+M+", got "+F)}return J}function y(J,Z=!0){if(J.destroyed)throw Error("Hash instance has been destroyed");if(Z&&J.finished)throw Error("Hash#digest() has already been called")}function r(J,Z){A(J,void 0,"digestInto() output");let $=Z.outputLen;if(J.length<$)throw Error('"digestInto() output" expected to be of length >='+$)}function s(J){return new Uint32Array(J.buffer,J.byteOffset,Math.floor(J.byteLength/4))}function h(...J){for(let Z=0;Z<J.length;Z++)J[Z].fill(0)}var LJ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function PJ(J){return J<<24&4278190080|J<<8&16711680|J>>>8&65280|J>>>24&255}function RJ(J){for(let Z=0;Z<J.length;Z++)J[Z]=PJ(J[Z]);return J}var p=LJ?(J)=>J:RJ;function e(J,Z={}){let $=(W,G)=>J(G).update(W).digest(),Y=J(void 0);return $.outputLen=Y.outputLen,$.blockLen=Y.blockLen,$.create=(W)=>J(W),Object.assign($,Z),Object.freeze($)}var _J=BigInt(0),j=BigInt(1),zJ=BigInt(2),TJ=BigInt(7),CJ=BigInt(256),EJ=BigInt(113),$J=[],YJ=[],WJ=[];for(let J=0,Z=j,$=1,Y=0;J<24;J++){[$,Y]=[Y,(2*$+3*Y)%5],$J.push(2*(5*Y+$)),YJ.push((J+1)*(J+2)/2%64);let W=_J;for(let G=0;G<7;G++)if(Z=(Z<<j^(Z>>TJ)*EJ)%CJ,Z&zJ)W^=j<<(j<<BigInt(G))-j;WJ.push(W)}var GJ=i(WJ,!0),wJ=GJ[0],BJ=GJ[1],JJ=(J,Z,$)=>$>32?t(J,Z,$):n(J,Z,$),ZJ=(J,Z,$)=>$>32?a(J,Z,$):o(J,Z,$);function SJ(J,Z=24){let $=new Uint32Array(10);for(let Y=24-Z;Y<24;Y++){for(let Q=0;Q<10;Q++)$[Q]=J[Q]^J[Q+10]^J[Q+20]^J[Q+30]^J[Q+40];for(let Q=0;Q<10;Q+=2){let M=(Q+8)%10,F=(Q+2)%10,O=$[F],U=$[F+1],UJ=JJ(O,U,1)^$[M],NJ=ZJ(O,U,1)^$[M+1];for(let S=0;S<50;S+=10)J[Q+S]^=UJ,J[Q+S+1]^=NJ}let W=J[2],G=J[3];for(let Q=0;Q<24;Q++){let M=YJ[Q],F=JJ(W,G,M),O=ZJ(W,G,M),U=$J[Q];W=J[U],G=J[U+1],J[U]=F,J[U+1]=O}for(let Q=0;Q<50;Q+=10){for(let M=0;M<10;M++)$[M]=J[Q+M];for(let M=0;M<10;M++)J[Q+M]^=~$[(M+2)%10]&$[(M+4)%10]}J[0]^=wJ[Y],J[1]^=BJ[Y]}h($)}class m{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(J,Z,$,Y=!1,W=24){if(this.blockLen=J,this.suffix=Z,this.outputLen=$,this.enableXOF=Y,this.rounds=W,f($,"outputLen"),!(0<J&&J<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=s(this.state)}clone(){return this._cloneInto()}keccak(){p(this.state32),SJ(this.state32,this.rounds),p(this.state32),this.posOut=0,this.pos=0}update(J){y(this),A(J);let{blockLen:Z,state:$}=this,Y=J.length;for(let W=0;W<Y;){let G=Math.min(Z-this.pos,Y-W);for(let Q=0;Q<G;Q++)$[this.pos++]^=J[W++];if(this.pos===Z)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:J,suffix:Z,pos:$,blockLen:Y}=this;if(J[$]^=Z,(Z&128)!==0&&$===Y-1)this.keccak();J[Y-1]^=128,this.keccak()}writeInto(J){y(this,!1),A(J),this.finish();let Z=this.state,{blockLen:$}=this;for(let Y=0,W=J.length;Y<W;){if(this.posOut>=$)this.keccak();let G=Math.min($-this.posOut,W-Y);J.set(Z.subarray(this.posOut,this.posOut+G),Y),this.posOut+=G,Y+=G}return J}xofInto(J){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(J)}xof(J){return f(J),this.xofInto(new Uint8Array(J))}digestInto(J){if(r(J,this),this.finished)throw Error("digest() was already called");return this.writeInto(J),this.destroy(),J}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,h(this.state)}_cloneInto(J){let{blockLen:Z,suffix:$,outputLen:Y,rounds:W,enableXOF:G}=this;return J||=new m(Z,$,Y,G,W),J.state32.set(this.state32),J.pos=this.pos,J.posOut=this.posOut,J.finished=this.finished,J.rounds=W,J.suffix=$,J.outputLen=Y,J.enableXOF=G,J.destroyed=this.destroyed,J}}var HJ=(J,Z,$,Y={})=>e(()=>new m(Z,J,$),Y);var QJ=HJ(1,136,32);var VJ=[];for(let J=0;J<256;J++)VJ[J]=J.toString(16).padStart(2,"0");function KJ(J){let Z="0x";for(let $=0;$<J.length;$++)Z+=VJ[J[$]];return Z}function MJ(J){let Z=J.toLowerCase().replace("0x",""),$=KJ(QJ(new TextEncoder().encode(Z))).slice(2),Y="0x";for(let W=0;W<Z.length;W++)Y+=parseInt($[W],16)>=8?Z[W].toUpperCase():Z[W];return Y}function V(J){return J.toLowerCase()}function kJ(J){return J.map((Z)=>V(Z))}function gJ(J){return MJ(J)}function AJ(J){if(typeof J!=="string")return!1;let Z=J.replace("0x","");return Z.length===40&&/^[0-9a-fA-F]{40}$/.test(Z)}function K(J){if(J===null||J===void 0)return J;if(AJ(J))return gJ(J);if(Array.isArray(J))return J.map((Z)=>K(Z));if(typeof J==="object"&&J!==null){let Z={};for(let $ in J)if(Object.prototype.hasOwnProperty.call(J,$))Z[$]=K(J[$]);return Z}return J}function qJ(J){return{Source:V(J.from),Sink:V(J.to),TargetFlow:J.targetFlow.toString(),WithWrap:J.useWrappedBalances,FromTokens:J.fromTokens?.map(V),ToTokens:J.toTokens?.map(V),ExcludedFromTokens:J.excludeFromTokens?.map(V),ExcludedToTokens:J.excludeToTokens?.map(V),SimulatedBalances:J.simulatedBalances?.map((Z)=>({Holder:V(Z.holder),Token:V(Z.token),Amount:Z.amount.toString(),IsWrapped:Z.isWrapped,IsStatic:Z.isStatic})),SimulatedTrusts:J.simulatedTrusts?.map((Z)=>({Truster:V(Z.truster),Trustee:V(Z.trustee)})),MaxTransfers:J.maxTransfers}}function X(J){let Z={};for(let $ in J){let Y=J[$];if(Y===null||Y===void 0)Z[$]=Y;else if(typeof Y==="string"&&/^\d+$/.test(Y))Z[$]=BigInt(Y);else if(typeof Y==="object"&&!Array.isArray(Y))Z[$]=X(Y);else if(Array.isArray(Y))Z[$]=Y.map((W)=>typeof W==="object"&&W!==null?X(W):W);else Z[$]=Y}return Z}var QZ=BigInt(96)*BigInt(1000000000000000000),FJ=BigInt("9999999999999999999999999999999999999");class L{client;constructor(J){this.client=J}async findPath(J){let Z=qJ(J),$=await this.client.call("circlesV2_findPath",[Z]),Y=X($);return K(Y)}async findMaxFlow(J){let Z=await this.findPath({...J,targetFlow:FJ});return BigInt(Z.maxFlow)}}class P{client;constructor(J){this.client=J}async query(J){let Z=await this.client.call("circles_query",[J]),{columns:$,rows:Y}=Z,W=Y.map((G)=>{let Q={};return $.forEach((M,F)=>{Q[M]=G[F]}),Q});return K(W)}async tables(){return this.client.call("circles_tables",[])}async events(J=null,Z=null,$=null,Y=null,W=null,G=!1,Q=100,M=null){let F=await this.client.call("circles_events_paginated",[J,Z,$,Y,W,G,Q,M]);return{events:K(F.events),hasMore:F.hasMore,nextCursor:F.nextCursor}}}var xJ=[{name:"blockNumber",sortOrder:"DESC"},{name:"transactionIndex",sortOrder:"DESC"},{name:"logIndex",sortOrder:"DESC"}];class N{params;client;rowTransformer;cursorColumns;orderColumns;get currentPage(){return this._currentPage}_currentPage;constructor(J,Z,$){this.client=J,this.params=Z,this.rowTransformer=$||Z.rowTransformer,this.orderColumns=Z.orderColumns,this.cursorColumns=Z.cursorColumns||this.buildEventCursorColumns()}buildEventCursorColumns(){let J=xJ.map((Z)=>({...Z,sortOrder:this.params.sortOrder}));if(this.params.table==="TransferBatch")J.push({name:"batchIndex",sortOrder:this.params.sortOrder});return J}buildOrderBy(){if(this.orderColumns&&this.orderColumns.length>0)return this.orderColumns;return this.cursorColumns.map((J)=>({Column:J.name,SortOrder:J.sortOrder}))}rowsToObjects(J){let{columns:Z,rows:$}=J;return $.map((Y)=>{let W={};return Z.forEach((G,Q)=>{W[G]=Y[Q]}),this.rowTransformer?this.rowTransformer(W):W})}async queryNextPage(){let J={Namespace:this.params.namespace,Table:this.params.table,Columns:this.params.columns,Filter:this.params.filter||[],Order:this.buildOrderBy(),Limit:this.params.limit},Z=this._currentPage?.nextCursor?[J,this._currentPage.nextCursor]:[J],$=await this.client.call("circles_paginated_query",Z),Y=this.rowsToObjects($);return this._currentPage={limit:this.params.limit,size:Y.length,sortOrder:this.params.sortOrder,hasMore:$.hasMore,nextCursor:$.nextCursor??void 0,results:Y},Y.length>0}reset(){this._currentPage=void 0}}class R{client;constructor(J){this.client=J}transformQueryResponse(J){let{columns:Z,rows:$}=J;return $.map((Y)=>{let W={};return Z.forEach((G,Q)=>{W[G]=Y[Q]}),W})}async getCommonTrust(J,Z){let $=await this.client.call("circles_getCommonTrust",[V(J),V(Z)]);return K($)}getTrustRelations(J,Z=100,$="DESC"){let Y=V(J),W=[{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 N(this.client,{namespace:"V_Crc",table:"TrustRelations",sortOrder:$,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","version","trustee","truster","expiryTime"],filter:W,limit:Z},(G)=>K(G))}async getAggregatedTrustRelations(J){let Z=V(J),$=await this.client.call("circles_getAggregatedTrustRelations",[Z]);return K($)}async getTrustedBy(J){let Z=V(J),Y=(await this.getAggregatedTrustRelations(Z)).filter((W)=>W.relation==="trustedBy");return K(Y)}async getTrusts(J){let Z=V(J),Y=(await this.getAggregatedTrustRelations(Z)).filter((W)=>W.relation==="trusts");return K(Y)}async getMutualTrusts(J){let Z=V(J),Y=(await this.getAggregatedTrustRelations(Z)).filter((W)=>W.relation==="mutuallyTrusts");return K(Y)}async getTrustNetworkSummary(J,Z=2){return this.client.call("circles_getTrustNetworkSummary",[V(J),Z])}async getAggregatedTrustRelationsEnriched(J){return this.client.call("circles_getAggregatedTrustRelationsEnriched",[V(J)])}async getValidInviters(J,Z){let $=[V(J)];if(Z)$.push(Z);return this.client.call("circles_getValidInviters",$)}}class u{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,Z){return J*Z>>64n}static mulU(J,Z){return J*Z>>64n}static pow64(J,Z){let $=J,Y=Z,W=this.ONE_64;while(Y>0n){if((Y&1n)===1n)W=this.mul64(W,$);$=this.mul64($,$),Y>>=1n}return W}static ONE_36=1000000000000000000000000000000000000000n;static GAMMA_36=999801332008598957430613406568191166n;static BETA_36=1000198707468214629156271489013303962n;static mul36(J,Z){return J*Z/this.ONE_36}static pow36(J,Z){let $=this.ONE_36,Y=J,W=Z;while(W>0n){if((W&1n)===1n)$=this.mul36($,Y);Y=this.mul36(Y,Y),W>>=1n}return $}static attoCirclesToCircles(J){if(J===0n)return 0;let Z=J/this.ATTO_FACTOR,$=J%this.ATTO_FACTOR,Y=BigInt(Number.MAX_SAFE_INTEGER);if(Z>Y||Z<-Y)throw RangeError("Atto value’s integer component exceeds JS double precision.");return Number(Z)+Number($)/Number(this.ATTO_FACTOR)}static circlesToAttoCircles(J){return BigInt(Math.trunc(J*Number(this.ATTO_FACTOR)))}static inflationaryToDemurrage(J,Z){return this.mulU(this.pow64(this.GAMMA_64,Z),J)}static demurrageToInflationary(J,Z){return this.mulU(this.pow64(this.BETA_64,Z),J)}static dayFromTimestamp(J){return(J-this.INFLATION_DAY_ZERO_UNIX)/this.SECONDS_PER_DAY}static attoCirclesToAttoStaticCircles(J,Z=BigInt(Math.floor(Date.now()/1000))){return this.demurrageToInflationary(J,this.dayFromTimestamp(Z))}static attoStaticCirclesToAttoCircles(J,Z=BigInt(Math.floor(Date.now()/1000))){return this.inflationaryToDemurrage(J,this.dayFromTimestamp(Z))}static inflationaryToDemurrageExact(J,Z){let $=this.pow36(this.GAMMA_36,Z);return J*$/this.ONE_36}static demurrageToInflationaryExact(J,Z){let $=this.pow36(this.BETA_36,Z);return J*$/this.ONE_36}static attoCirclesToAttoStaticCirclesExact(J,Z=BigInt(Math.floor(Date.now()/1000))){let $=this.dayFromTimestamp(Z);return this.demurrageToInflationaryExact(J,$)}static attoStaticCirclesToAttoCirclesExact(J,Z=BigInt(Math.floor(Date.now()/1000))){let $=this.dayFromTimestamp(Z);return this.inflationaryToDemurrageExact(J,$)}static truncateToInt64(J){let Z=J/this.FACTOR_1E12,$=9223372036854775807n;return Z>$?$:Z}static blowUpToBigInt(J){return J*this.FACTOR_1E12}static truncateToSixDecimals(J){return this.blowUpToBigInt(this.truncateToInt64(J))}static v1InflateFactor(J){if(J===0n)return this.V1_ACCURACY;return this.V1_ACCURACY*this.V1_INFLATION_PCT_NUM**J/this.V1_INFLATION_PCT_DEN**J}static attoCrcToAttoCircles(J,Z){let $=Z-this.INFLATION_DAY_ZERO_UNIX,Y=$/this.PERIOD_SEC,W=$%this.PERIOD_SEC,G=this.v1InflateFactor(Y),Q=this.v1InflateFactor(Y+1n);return this.v1ToDemurrage(J,G,Q,W,this.PERIOD_SEC)}static attoCirclesToAttoCrc(J,Z){let $=Z-this.INFLATION_DAY_ZERO_UNIX,Y=$/this.PERIOD_SEC,W=$%this.PERIOD_SEC,G=this.v1InflateFactor(Y),Q=this.v1InflateFactor(Y+1n),M=G*(this.PERIOD_SEC-W)+Q*W;return J*3n*this.V1_ACCURACY*this.PERIOD_SEC/M}static v1ToDemurrage(J,Z,$,Y,W){let G=Z*(W-Y)+$*Y;return J*3n*this.V1_ACCURACY*W/G}}class _{client;constructor(J){this.client=J}async getTotalBalance(J,Z=!0){let $=await this.client.call("circlesV2_getTotalBalance",[V(J),Z]);return u.circlesToAttoCircles($)}async getTokenBalances(J){let $=(await this.client.call("circles_getTokenBalances",[V(J)])).map((Y)=>X(Y));return K($)}}class z{client;constructor(J){this.client=J}async getAvatarInfo(J){let Z=await this.getAvatarInfoBatch([J]);return Z.length>0?Z[0]:void 0}async getAvatarInfoBatch(J){if(J.length===0)return[];let Z=J.map((Y)=>V(Y)),$=await this.client.call("circles_getAvatarInfoBatch",[Z]);return K($)}async getNetworkSnapshot(){let J=await this.client.call("circles_getNetworkSnapshot",[]);return K(J)}}class T{client;constructor(J){this.client=J}async getProfileByCid(J){return this.client.call("circles_getProfileByCid",[J])}async getProfileByCidBatch(J){return this.client.call("circles_getProfileByCidBatch",[J])}async getProfileByAddress(J){return this.client.call("circles_getProfileByAddress",[V(J)])}async getProfileByAddressBatch(J){return this.client.call("circles_getProfileByAddressBatch",[J.map((Z)=>Z===null?null:V(Z))])}async searchProfiles(J,Z=10,$=0,Y){return this.client.call("circles_searchProfiles",[J.toLowerCase(),Z,$,Y])}async searchByAddressOrName(J,Z=10,$,Y){return this.client.call("circles_searchProfileByAddressOrName",Y?[J,Z,$??null,Y]:[J,Z,$??null])}async getProfileView(J){return this.client.call("circles_getProfileView",[V(J)])}}class C{client;constructor(J){this.client=J}async getTokenInfo(J){let Z=await this.getTokenInfoBatch([J]);return Z.length>0?Z[0]:void 0}async getTokenInfoBatch(J){if(J.length===0)return[];let Z=J.map((W)=>V(W)),Y=(await this.client.call("circles_getTokenInfoBatch",[Z])).map((W)=>X(W));return K(Y)}async getTokenHolders(J,Z=100,$){let Y=await this.client.call("circles_getTokenHolders",[V(J),Z,$??null]);return{hasMore:Y.hasMore,nextCursor:Y.nextCursor,results:K(Y.results)}}}class E{client;constructor(J){this.client=J}async getInvitationOrigin(J){let Z=V(J),$=await this.client.call("circles_getInvitationOrigin",[Z]);return $?K($):null}async getInvitedBy(J){let Z=await this.getInvitationOrigin(J);if(Z?.inviter)return K(Z.inviter);return}async getTrustInvitations(J,Z){let $=V(J),Y=await this.client.call("circles_getTrustInvitations",Z?[$,Z]:[$]);return K(Y)}async getInvitations(J,Z){let Y=(await this.getValidInviters(J,Z)).results.map((W)=>W.avatarInfo).filter((W)=>W!==void 0&&W!==null);return K(Y)}async getValidInviters(J,Z){let $=V(J),Y=await this.client.call("circles_getValidInviters",Z?[$,Z]:[$]);return K(Y)}async getInvitationsFrom(J,Z=!1){let $=V(J),Y=await this.client.call("circles_getInvitationsFrom",[$,Z]);return K(Y)}async getEscrowInvitations(J){let Z=V(J),$=await this.client.call("circles_getEscrowInvitations",[Z]);return K($)}async getAtScaleInvitations(J){let Z=V(J),$=await this.client.call("circles_getAtScaleInvitations",[Z]);return K($)}async getAllInvitations(J,Z){let $=V(J),Y=await this.client.call("circles_getAllInvitations",Z?[$,Z]:[$]);return K(Y)}}class w{client;constructor(J){this.client=J}async getTransactionHistory(J,Z=50,$){let Y=await this.client.call("circles_getTransactionHistory",[V(J),Z,$??null]);return{hasMore:Y.hasMore,nextCursor:Y.nextCursor,results:K(Y.results)}}async getTransactionHistoryEnriched(J,Z=0,$=null,Y=20,W){let G=await this.client.call("circles_getTransactionHistoryEnriched",[V(J),Z,$,Y,W??null]);return{hasMore:G.hasMore,nextCursor:G.nextCursor,results:K(G.results)}}}class B{client;constructor(J){this.client=J}async findGroups(J=50,Z,$){let Y=Z?{nameStartsWith:Z.nameStartsWith,symbolStartsWith:Z.symbolStartsWith,ownerIn:Z.ownerIn?.map((Q)=>V(Q))}:void 0,W=await this.client.call("circles_findGroups",[J,Y??null,$??null]),G=K(W.results).map((Q)=>{let M=Q;if(!M.owner&&M.mint)return{...M,owner:M.mint};return M});return{hasMore:W.hasMore,nextCursor:W.nextCursor,results:G}}async getGroupMemberships(J,Z=50,$){let Y=await this.client.call("circles_getGroupMemberships",[V(J),Z,$??null]);return{hasMore:Y.hasMore,nextCursor:Y.nextCursor,results:K(Y.results)}}async getGroupMembers(J,Z=100,$){let Y=await this.client.call("circles_getGroupMembers",[V(J),Z,$??null]);return{hasMore:Y.hasMore,nextCursor:Y.nextCursor,results:K(Y.results)}}getGroups(J=50,Z,$="DESC"){let Y=[];if(Z){if(Z.nameStartsWith)Y.push({Type:"FilterPredicate",FilterType:"Like",Column:"name",Value:Z.nameStartsWith+"%"});if(Z.symbolStartsWith)Y.push({Type:"FilterPredicate",FilterType:"Like",Column:"symbol",Value:Z.symbolStartsWith+"%"});if(Z.groupAddressIn&&Z.groupAddressIn.length>0){let G=Z.groupAddressIn.map((Q)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:V(Q)}));if(G.length===1)Y.push(G[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:G})}if(Z.groupTypeIn&&Z.groupTypeIn.length>0){let G=Z.groupTypeIn.map((Q)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"type",Value:Q}));if(G.length===1)Y.push(G[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:G})}if(Z.ownerIn&&Z.ownerIn.length>0){let G=Z.ownerIn.map((Q)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"owner",Value:V(Q)}));if(G.length===1)Y.push(G[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:G})}if(Z.mintHandlerEquals)Y.push({Type:"FilterPredicate",FilterType:"Equals",Column:"mintHandler",Value:V(Z.mintHandlerEquals)});if(Z.treasuryEquals)Y.push({Type:"FilterPredicate",FilterType:"Equals",Column:"treasury",Value:V(Z.treasuryEquals)})}let W=Y.length>1?[{Type:"Conjunction",ConjunctionType:"And",Predicates:Y}]:Y;return new N(this.client,{namespace:"V_CrcV2",table:"Groups",sortOrder:$,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","type","owner","mintPolicy","mintHandler","treasury","service","feeCollection","memberCount","name","symbol","cidV0Digest","erc20WrapperDemurraged","erc20WrapperStatic"],filter:W,limit:J},(G)=>K(G))}getGroupHolders(J,Z=100){let $=V(J);return new N(this.client,{namespace:"V_Crc",table:"TokenBalances",sortOrder:"DESC",columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","token","account","balance","lastChangedAt"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"token",Value:$}],limit:Z},(Y)=>K(Y))}}class x{client;constructor(J){this.client=J}async getProfileView(J){let Z=V(J);return this.client.call("circles_getProfileView",[Z])}async getTrustNetworkSummary(J,Z=2){let $=V(J);return this.client.call("circles_getTrustNetworkSummary",[$,Z])}async getAggregatedTrustRelations(J){let Z=V(J);return this.client.call("circles_getAggregatedTrustRelations",[Z])}async getValidInviters(J,Z){let $=V(J),Y=await this.client.call("circles_getValidInviters",Z?[$,Z]:[$]);return K(Y)}async getTransactionHistoryEnriched(J,Z=0,$=null,Y=50,W){let G=V(J),Q=await this.client.call("circles_getTransactionHistoryEnriched",[G,Z,$,Y,W??null]);return{hasMore:Q.hasMore,nextCursor:Q.nextCursor,results:K(Q.results)}}async searchProfileByAddressOrName(J,Z=20,$,Y){return this.client.call("circles_searchProfileByAddressOrName",Y?[J,Z,$??null,Y]:[J,Z,$??null])}}class XJ{client;_pathfinder;_query;_trust;_balance;_avatar;_profile;_token;_invitation;_transaction;_group;_sdk;constructor(J="https://rpc.aboutcircles.com/"){this.client=new k(J)}get pathfinder(){if(!this._pathfinder)this._pathfinder=new L(this.client);return this._pathfinder}get query(){if(!this._query)this._query=new P(this.client);return this._query}get trust(){if(!this._trust)this._trust=new R(this.client);return this._trust}get balance(){if(!this._balance)this._balance=new _(this.client);return this._balance}get avatar(){if(!this._avatar)this._avatar=new z(this.client);return this._avatar}get profile(){if(!this._profile)this._profile=new T(this.client);return this._profile}get token(){if(!this._token)this._token=new C(this.client);return this._token}get invitation(){if(!this._invitation)this._invitation=new E(this.client);return this._invitation}get transaction(){if(!this._transaction)this._transaction=new w(this.client);return this._transaction}get group(){if(!this._group)this._group=new B(this.client);return this._group}get sdk(){if(!this._sdk)this._sdk=new x(this.client);return this._sdk}setRpcUrl(J){this.client.setRpcUrl(J)}getRpcUrl(){return this.client.getRpcUrl()}}export{X as parseStringsToBigInt,H as parseRpcSubscriptionMessage,b as parseRpcEvent,kJ as normalizeAddresses,V as normalizeAddress,c as isCirclesEvent,R as TrustMethods,w as TransactionMethods,C as TokenMethods,q as RpcError,k as RpcClient,P as QueryMethods,T as ProfileMethods,L as PathfinderMethods,N as PagedQuery,D as Observable,E as InvitationMethods,B as GroupMethods,XJ as CirclesRpc,_ as BalanceMethods,z as AvatarMethods};
1
+ function c(J){return J&&typeof J==="object"&&typeof J.$event==="string"&&typeof J.blockNumber==="number"&&typeof J.transactionIndex==="number"&&typeof J.logIndex==="number"}var l=(J)=>BigInt(J),j=(J)=>parseInt(J,16),OJ=(J)=>{if(J.startsWith("0x"))J=J.slice(2);if(J.length%2!==0)throw Error("Invalid hex string");let Z=new Uint8Array(J.length/2);for(let $=0;$<J.length;$+=2)Z[$/2]=parseInt(J.substr($,2),16);return Z};function DJ(J,Z){if(typeof Z==="string"&&Z.startsWith("0x")){let $=Z.slice(2);if($.length===40)return Z;if($.length===64){if(J.toLowerCase().includes("digest")||J.toLowerCase().includes("data")||J.toLowerCase().includes("bytes"))return OJ(Z);try{return l(Z)}catch{return Z}}try{let Y=j(Z);if(Y<Number.MAX_SAFE_INTEGER)return Y;return l(Z)}catch{return Z}}if(Z==="true")return!0;if(Z==="false")return!1;return Z}function b(J){let{event:Z,values:$}=J,Y={$event:Z,blockNumber:$.blockNumber?j($.blockNumber):0,timestamp:$.timestamp?j($.timestamp):void 0,transactionIndex:$.transactionIndex?j($.transactionIndex):0,logIndex:$.logIndex?j($.logIndex):0,transactionHash:$.transactionHash};for(let[W,G]of Object.entries($)){if(["blockNumber","timestamp","transactionIndex","logIndex","transactionHash"].includes(W))continue;Y[W]=DJ(W,G)}return Y}function H(J){return J.map(b)}class D{_subscribers=[];subscribe(J){return this._subscribers.push(J),()=>{let Z=this._subscribers.indexOf(J);if(Z>-1)this._subscribers.splice(Z,1)}}constructor(){this._subscribers=[]}emit(J){this._subscribers.forEach((Z)=>Z(J))}static create(){let J=new D;return{property:J,emit:(Z)=>J.emit(Z)}}}class v extends Error{name;code;source;cause;context;constructor(J,Z,$){super(Z);if(this.name=J,this.code=$?.code,this.source=$?.source??"UNKNOWN",this.cause=$?.cause,this.context=$?.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 J=`[${this.source}] ${this.name}: ${this.message}`;if(this.code)J+=` (Code: ${this.code})`;if(this.context)J+=`
2
+ Context: ${JSON.stringify(this.context,null,2)}`;return J}}class q extends v{constructor(J,Z){super("RpcError",J,{...Z,source:Z?.source??"RPC_REQUEST"})}static connectionFailed(J,Z){return new q("Failed to connect to RPC endpoint",{code:"RPC_CONNECTION_FAILED",source:"RPC_CONNECTION",cause:Z,context:{url:J}})}static timeout(J,Z){return new q("RPC request timed out",{code:"RPC_TIMEOUT",source:"RPC_TIMEOUT",context:{method:J,timeout:Z}})}static invalidResponse(J,Z){return new q("Invalid RPC response",{code:"RPC_INVALID_RESPONSE",source:"RPC_RESPONSE",context:{method:J,response:Z}})}static fromJsonRpcError(J){return new q(J.message,{code:J.code,source:"RPC_RESPONSE",context:{data:J.data}})}static websocketError(J,Z){return new q(J,{code:"RPC_WEBSOCKET_ERROR",source:"RPC_WEBSOCKET",cause:Z})}}class k{rpcUrl;requestId=0;websocket=null;websocketConnected=!1;pendingResponses={};subscriptionListeners={};activeSubscriptions=[];reconnectAttempt=0;initialBackoff=2000;maxBackoff=120000;constructor(J){this.rpcUrl=J}async call(J,Z){this.requestId++;let $={jsonrpc:"2.0",id:this.requestId,method:J,params:Z};try{let Y=await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)});if(!Y.ok)throw q.connectionFailed(this.rpcUrl,Error(`HTTP ${Y.status}: ${Y.statusText}`));let W=await Y.json();if(W.error)throw q.fromJsonRpcError(W.error);if(W.result===void 0)throw q.invalidResponse(J,W);return W.result}catch(Y){if(Y instanceof q)throw Y;throw q.connectionFailed(this.rpcUrl,Y)}}setRpcUrl(J){this.rpcUrl=J}getRpcUrl(){return this.rpcUrl}connect(){return new Promise((J,Z)=>{let $=this.rpcUrl.replace("http","ws");if($.endsWith("/"))$+="ws/subscribe";else $+="/ws/subscribe";this.websocket=new WebSocket($),this.websocket.onopen=()=>{console.log("WebSocket connected"),this.websocketConnected=!0,this.reconnectAttempt=0,J()},this.websocket.onmessage=(Y)=>{let W=JSON.parse(Y.data),{id:G,method:Q,params:M}=W;if(G!==void 0&&this.pendingResponses[G])this.pendingResponses[G].resolve(W),delete this.pendingResponses[G];if(Q==="circles_subscription"&&M?.result)Object.values(this.subscriptionListeners).forEach((F)=>{F.forEach((O)=>O(M.result))})},this.websocket.onclose=()=>{console.warn("WebSocket closed");let Y=this.websocketConnected;if(this.websocketConnected=!1,Y)this.scheduleReconnect()},this.websocket.onerror=(Y)=>{console.error("WebSocket error:",Y),this.websocketConnected=!1,Z(q.connectionFailed(this.rpcUrl,Y instanceof Error?Y:Error("WebSocket connection failed"))),this.scheduleReconnect()}})}scheduleReconnect(){let J=Math.min(this.initialBackoff*Math.pow(2,this.reconnectAttempt),this.maxBackoff),Z=J*(Math.random()*0.5),$=J+Z;console.log(`Reconnecting in ${Math.round($)}ms (attempt #${this.reconnectAttempt+1})`),this.reconnectAttempt++,setTimeout(()=>{this.reconnect()},$)}async reconnect(){if(this.websocketConnected)return;try{await this.connect(),console.log("Reconnection successful"),await this.resubscribeActive()}catch(J){console.error("Reconnection attempt failed:",J),this.scheduleReconnect()}}async resubscribeActive(){if(this.activeSubscriptions.length===0)return;let J=[...this.activeSubscriptions];this.activeSubscriptions=[];for(let Z of J)try{let $=Z.address?{address:Z.address}:{},W=(await this.sendMessage("circles_subscribe",$)).result,G=this.subscriptionListeners[Z.id];if(G)this.subscriptionListeners[W]=G,delete this.subscriptionListeners[Z.id];this.activeSubscriptions.push({id:W,address:Z.address})}catch($){console.error("Failed to re-issue circles_subscribe after reconnect:",$),this.activeSubscriptions.push(Z)}}sendMessage(J,Z,$=5000){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return Promise.reject(q.connectionFailed(this.rpcUrl));let Y=this.requestId++,W={jsonrpc:"2.0",method:J,params:Z,id:Y};return new Promise((G,Q)=>{this.pendingResponses[Y]={resolve:G,reject:Q},this.websocket.send(JSON.stringify(W)),setTimeout(()=>{if(this.pendingResponses[Y])this.pendingResponses[Y].reject(q.timeout(J,$)),delete this.pendingResponses[Y]},$)})}async subscribe(J){let Z=J?.toLowerCase();if(!this.websocketConnected)await this.connect();let $=D.create(),Y=Z?{address:Z}:{},G=(await this.sendMessage("circles_subscribe",Y)).result;if(!this.subscriptionListeners[G])this.subscriptionListeners[G]=[];return this.subscriptionListeners[G].push((Q)=>{H(Q).forEach((M)=>$.emit(M))}),this.activeSubscriptions.push({id:G,address:Z}),$.property}}var g=BigInt(4294967295),d=BigInt(32);function jJ(J,Z=!1){if(Z)return{h:Number(J&g),l:Number(J>>d&g)};return{h:Number(J>>d&g)|0,l:Number(J&g)|0}}function i(J,Z=!1){let $=J.length,Y=new Uint32Array($),W=new Uint32Array($);for(let G=0;G<$;G++){let{h:Q,l:M}=jJ(J[G],Z);[Y[G],W[G]]=[Q,M]}return[Y,W]}var n=(J,Z,$)=>J<<$|Z>>>32-$,o=(J,Z,$)=>Z<<$|J>>>32-$,t=(J,Z,$)=>Z<<$-32|J>>>64-$,a=(J,Z,$)=>J<<$-32|Z>>>64-$;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function IJ(J){return J instanceof Uint8Array||ArrayBuffer.isView(J)&&J.constructor.name==="Uint8Array"}function f(J,Z=""){if(!Number.isSafeInteger(J)||J<0){let $=Z&&`"${Z}" `;throw Error(`${$}expected integer >= 0, got ${J}`)}}function A(J,Z,$=""){let Y=IJ(J),W=J?.length,G=Z!==void 0;if(!Y||G&&W!==Z){let Q=$&&`"${$}" `,M=G?` of length ${Z}`:"",F=Y?`length=${W}`:`type=${typeof J}`;throw Error(Q+"expected Uint8Array"+M+", got "+F)}return J}function y(J,Z=!0){if(J.destroyed)throw Error("Hash instance has been destroyed");if(Z&&J.finished)throw Error("Hash#digest() has already been called")}function r(J,Z){A(J,void 0,"digestInto() output");let $=Z.outputLen;if(J.length<$)throw Error('"digestInto() output" expected to be of length >='+$)}function s(J){return new Uint32Array(J.buffer,J.byteOffset,Math.floor(J.byteLength/4))}function h(...J){for(let Z=0;Z<J.length;Z++)J[Z].fill(0)}var LJ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function PJ(J){return J<<24&4278190080|J<<8&16711680|J>>>8&65280|J>>>24&255}function RJ(J){for(let Z=0;Z<J.length;Z++)J[Z]=PJ(J[Z]);return J}var p=LJ?(J)=>J:RJ;function e(J,Z={}){let $=(W,G)=>J(G).update(W).digest(),Y=J(void 0);return $.outputLen=Y.outputLen,$.blockLen=Y.blockLen,$.create=(W)=>J(W),Object.assign($,Z),Object.freeze($)}var _J=BigInt(0),I=BigInt(1),zJ=BigInt(2),TJ=BigInt(7),CJ=BigInt(256),EJ=BigInt(113),$J=[],YJ=[],WJ=[];for(let J=0,Z=I,$=1,Y=0;J<24;J++){[$,Y]=[Y,(2*$+3*Y)%5],$J.push(2*(5*Y+$)),YJ.push((J+1)*(J+2)/2%64);let W=_J;for(let G=0;G<7;G++)if(Z=(Z<<I^(Z>>TJ)*EJ)%CJ,Z&zJ)W^=I<<(I<<BigInt(G))-I;WJ.push(W)}var GJ=i(WJ,!0),BJ=GJ[0],SJ=GJ[1],JJ=(J,Z,$)=>$>32?t(J,Z,$):n(J,Z,$),ZJ=(J,Z,$)=>$>32?a(J,Z,$):o(J,Z,$);function wJ(J,Z=24){let $=new Uint32Array(10);for(let Y=24-Z;Y<24;Y++){for(let Q=0;Q<10;Q++)$[Q]=J[Q]^J[Q+10]^J[Q+20]^J[Q+30]^J[Q+40];for(let Q=0;Q<10;Q+=2){let M=(Q+8)%10,F=(Q+2)%10,O=$[F],U=$[F+1],UJ=JJ(O,U,1)^$[M],NJ=ZJ(O,U,1)^$[M+1];for(let w=0;w<50;w+=10)J[Q+w]^=UJ,J[Q+w+1]^=NJ}let W=J[2],G=J[3];for(let Q=0;Q<24;Q++){let M=YJ[Q],F=JJ(W,G,M),O=ZJ(W,G,M),U=$J[Q];W=J[U],G=J[U+1],J[U]=F,J[U+1]=O}for(let Q=0;Q<50;Q+=10){for(let M=0;M<10;M++)$[M]=J[Q+M];for(let M=0;M<10;M++)J[Q+M]^=~$[(M+2)%10]&$[(M+4)%10]}J[0]^=BJ[Y],J[1]^=SJ[Y]}h($)}class m{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(J,Z,$,Y=!1,W=24){if(this.blockLen=J,this.suffix=Z,this.outputLen=$,this.enableXOF=Y,this.rounds=W,f($,"outputLen"),!(0<J&&J<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=s(this.state)}clone(){return this._cloneInto()}keccak(){p(this.state32),wJ(this.state32,this.rounds),p(this.state32),this.posOut=0,this.pos=0}update(J){y(this),A(J);let{blockLen:Z,state:$}=this,Y=J.length;for(let W=0;W<Y;){let G=Math.min(Z-this.pos,Y-W);for(let Q=0;Q<G;Q++)$[this.pos++]^=J[W++];if(this.pos===Z)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:J,suffix:Z,pos:$,blockLen:Y}=this;if(J[$]^=Z,(Z&128)!==0&&$===Y-1)this.keccak();J[Y-1]^=128,this.keccak()}writeInto(J){y(this,!1),A(J),this.finish();let Z=this.state,{blockLen:$}=this;for(let Y=0,W=J.length;Y<W;){if(this.posOut>=$)this.keccak();let G=Math.min($-this.posOut,W-Y);J.set(Z.subarray(this.posOut,this.posOut+G),Y),this.posOut+=G,Y+=G}return J}xofInto(J){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(J)}xof(J){return f(J),this.xofInto(new Uint8Array(J))}digestInto(J){if(r(J,this),this.finished)throw Error("digest() was already called");return this.writeInto(J),this.destroy(),J}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,h(this.state)}_cloneInto(J){let{blockLen:Z,suffix:$,outputLen:Y,rounds:W,enableXOF:G}=this;return J||=new m(Z,$,Y,G,W),J.state32.set(this.state32),J.pos=this.pos,J.posOut=this.posOut,J.finished=this.finished,J.rounds=W,J.suffix=$,J.outputLen=Y,J.enableXOF=G,J.destroyed=this.destroyed,J}}var HJ=(J,Z,$,Y={})=>e(()=>new m(Z,J,$),Y);var QJ=HJ(1,136,32);var VJ=[];for(let J=0;J<256;J++)VJ[J]=J.toString(16).padStart(2,"0");function KJ(J){let Z="0x";for(let $=0;$<J.length;$++)Z+=VJ[J[$]];return Z}function MJ(J){let Z=J.toLowerCase().replace("0x",""),$=KJ(QJ(new TextEncoder().encode(Z))).slice(2),Y="0x";for(let W=0;W<Z.length;W++)Y+=parseInt($[W],16)>=8?Z[W].toUpperCase():Z[W];return Y}function V(J){return J.toLowerCase()}function kJ(J){return J.map((Z)=>V(Z))}function gJ(J){return MJ(J)}function AJ(J){if(typeof J!=="string")return!1;let Z=J.replace("0x","");return Z.length===40&&/^[0-9a-fA-F]{40}$/.test(Z)}function K(J){if(J===null||J===void 0)return J;if(AJ(J))return gJ(J);if(Array.isArray(J))return J.map((Z)=>K(Z));if(typeof J==="object"&&J!==null){let Z={};for(let $ in J)if(Object.prototype.hasOwnProperty.call(J,$))Z[$]=K(J[$]);return Z}return J}function qJ(J){return{Source:V(J.from),Sink:V(J.to),TargetFlow:J.targetFlow.toString(),WithWrap:J.useWrappedBalances,FromTokens:J.fromTokens?.map(V),ToTokens:J.toTokens?.map(V),ExcludedFromTokens:J.excludeFromTokens?.map(V),ExcludedToTokens:J.excludeToTokens?.map(V),SimulatedBalances:J.simulatedBalances?.map((Z)=>({Holder:V(Z.holder),Token:V(Z.token),Amount:Z.amount.toString(),IsWrapped:Z.isWrapped,IsStatic:Z.isStatic})),SimulatedTrusts:J.simulatedTrusts?.map((Z)=>({Truster:V(Z.truster),Trustee:V(Z.trustee)})),MaxTransfers:J.maxTransfers}}function X(J){let Z={};for(let $ in J){let Y=J[$];if(Y===null||Y===void 0)Z[$]=Y;else if(typeof Y==="string"&&/^\d+$/.test(Y))Z[$]=BigInt(Y);else if(typeof Y==="object"&&!Array.isArray(Y))Z[$]=X(Y);else if(Array.isArray(Y))Z[$]=Y.map((W)=>typeof W==="object"&&W!==null?X(W):W);else Z[$]=Y}return Z}var QZ=BigInt(96)*BigInt(1000000000000000000),FJ=BigInt("9999999999999999999999999999999999999");class L{client;constructor(J){this.client=J}async findPath(J){let Z=qJ(J),$=await this.client.call("circlesV2_findPath",[Z]),Y=X($);return K(Y)}async findMaxFlow(J){let Z=await this.findPath({...J,targetFlow:FJ});return BigInt(Z.maxFlow)}}class P{client;constructor(J){this.client=J}async query(J){let Z=await this.client.call("circles_query",[J]),{columns:$,rows:Y}=Z,W=Y.map((G)=>{let Q={};return $.forEach((M,F)=>{Q[M]=G[F]}),Q});return K(W)}async tables(){return this.client.call("circles_tables",[])}async events(J=null,Z=null,$=null,Y=null,W=null,G=!1,Q=100,M=null){let F=await this.client.call("circles_events_paginated",[J,Z,$,Y,W,G,Q,M]);return{events:K(F.events),hasMore:F.hasMore,nextCursor:F.nextCursor}}}var xJ=[{name:"blockNumber",sortOrder:"DESC"},{name:"transactionIndex",sortOrder:"DESC"},{name:"logIndex",sortOrder:"DESC"}];class N{params;client;rowTransformer;cursorColumns;orderColumns;get currentPage(){return this._currentPage}_currentPage;constructor(J,Z,$){this.client=J,this.params=Z,this.rowTransformer=$||Z.rowTransformer,this.orderColumns=Z.orderColumns,this.cursorColumns=Z.cursorColumns||this.buildEventCursorColumns()}buildEventCursorColumns(){let J=xJ.map((Z)=>({...Z,sortOrder:this.params.sortOrder}));if(this.params.table==="TransferBatch")J.push({name:"batchIndex",sortOrder:this.params.sortOrder});return J}buildOrderBy(){if(this.orderColumns&&this.orderColumns.length>0)return this.orderColumns;return this.cursorColumns.map((J)=>({Column:J.name,SortOrder:J.sortOrder}))}rowsToObjects(J){let{columns:Z,rows:$}=J;return $.map((Y)=>{let W={};return Z.forEach((G,Q)=>{W[G]=Y[Q]}),this.rowTransformer?this.rowTransformer(W):W})}async queryNextPage(){let J={Namespace:this.params.namespace,Table:this.params.table,Columns:this.params.columns,Filter:this.params.filter||[],Order:this.buildOrderBy(),Limit:this.params.limit},Z=this._currentPage?.nextCursor?[J,this._currentPage.nextCursor]:[J],$=await this.client.call("circles_paginated_query",Z),Y=this.rowsToObjects($);return this._currentPage={limit:this.params.limit,size:Y.length,sortOrder:this.params.sortOrder,hasMore:$.hasMore,nextCursor:$.nextCursor??void 0,results:Y},Y.length>0}reset(){this._currentPage=void 0}}class R{client;constructor(J){this.client=J}transformQueryResponse(J){let{columns:Z,rows:$}=J;return $.map((Y)=>{let W={};return Z.forEach((G,Q)=>{W[G]=Y[Q]}),W})}async getCommonTrust(J,Z){let $=await this.client.call("circles_getCommonTrust",[V(J),V(Z)]);return K($)}getTrustRelations(J,Z=100,$="DESC"){let Y=V(J),W=[{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 N(this.client,{namespace:"V_Crc",table:"TrustRelations",sortOrder:$,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","version","trustee","truster","expiryTime"],filter:W,limit:Z},(G)=>K(G))}async getAggregatedTrustRelations(J){let Z=V(J),$=await this.client.call("circles_getAggregatedTrustRelations",[Z]);return K($)}async getTrustedBy(J){let Z=V(J),Y=(await this.getAggregatedTrustRelations(Z)).filter((W)=>W.relation==="trustedBy");return K(Y)}async getTrusts(J){let Z=V(J),Y=(await this.getAggregatedTrustRelations(Z)).filter((W)=>W.relation==="trusts");return K(Y)}async getMutualTrusts(J){let Z=V(J),Y=(await this.getAggregatedTrustRelations(Z)).filter((W)=>W.relation==="mutuallyTrusts");return K(Y)}async getTrustNetworkSummary(J,Z=2){return this.client.call("circles_getTrustNetworkSummary",[V(J),Z])}async getAggregatedTrustRelationsEnriched(J){return this.client.call("circles_getAggregatedTrustRelationsEnriched",[V(J)])}async getValidInviters(J,Z){let $=[V(J)];if(Z)$.push(Z);return this.client.call("circles_getValidInviters",$)}}class u{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,Z){return J*Z>>64n}static mulU(J,Z){return J*Z>>64n}static pow64(J,Z){let $=J,Y=Z,W=this.ONE_64;while(Y>0n){if((Y&1n)===1n)W=this.mul64(W,$);$=this.mul64($,$),Y>>=1n}return W}static ONE_36=1000000000000000000000000000000000000000n;static GAMMA_36=999801332008598957430613406568191166n;static BETA_36=1000198707468214629156271489013303962n;static mul36(J,Z){return J*Z/this.ONE_36}static pow36(J,Z){let $=this.ONE_36,Y=J,W=Z;while(W>0n){if((W&1n)===1n)$=this.mul36($,Y);Y=this.mul36(Y,Y),W>>=1n}return $}static attoCirclesToCircles(J){if(J===0n)return 0;let Z=J/this.ATTO_FACTOR,$=J%this.ATTO_FACTOR,Y=BigInt(Number.MAX_SAFE_INTEGER);if(Z>Y||Z<-Y)throw RangeError("Atto value’s integer component exceeds JS double precision.");return Number(Z)+Number($)/Number(this.ATTO_FACTOR)}static circlesToAttoCircles(J){return BigInt(Math.trunc(J*Number(this.ATTO_FACTOR)))}static inflationaryToDemurrage(J,Z){return this.mulU(this.pow64(this.GAMMA_64,Z),J)}static demurrageToInflationary(J,Z){return this.mulU(this.pow64(this.BETA_64,Z),J)}static dayFromTimestamp(J){return(J-this.INFLATION_DAY_ZERO_UNIX)/this.SECONDS_PER_DAY}static attoCirclesToAttoStaticCircles(J,Z=BigInt(Math.floor(Date.now()/1000))){return this.demurrageToInflationary(J,this.dayFromTimestamp(Z))}static attoStaticCirclesToAttoCircles(J,Z=BigInt(Math.floor(Date.now()/1000))){return this.inflationaryToDemurrage(J,this.dayFromTimestamp(Z))}static inflationaryToDemurrageExact(J,Z){let $=this.pow36(this.GAMMA_36,Z);return J*$/this.ONE_36}static demurrageToInflationaryExact(J,Z){let $=this.pow36(this.BETA_36,Z);return J*$/this.ONE_36}static attoCirclesToAttoStaticCirclesExact(J,Z=BigInt(Math.floor(Date.now()/1000))){let $=this.dayFromTimestamp(Z);return this.demurrageToInflationaryExact(J,$)}static attoStaticCirclesToAttoCirclesExact(J,Z=BigInt(Math.floor(Date.now()/1000))){let $=this.dayFromTimestamp(Z);return this.inflationaryToDemurrageExact(J,$)}static truncateToInt64(J){let Z=J/this.FACTOR_1E12,$=9223372036854775807n;return Z>$?$:Z}static blowUpToBigInt(J){return J*this.FACTOR_1E12}static truncateToSixDecimals(J){return this.blowUpToBigInt(this.truncateToInt64(J))}static v1InflateFactor(J){if(J===0n)return this.V1_ACCURACY;return this.V1_ACCURACY*this.V1_INFLATION_PCT_NUM**J/this.V1_INFLATION_PCT_DEN**J}static attoCrcToAttoCircles(J,Z){let $=Z-this.INFLATION_DAY_ZERO_UNIX,Y=$/this.PERIOD_SEC,W=$%this.PERIOD_SEC,G=this.v1InflateFactor(Y),Q=this.v1InflateFactor(Y+1n);return this.v1ToDemurrage(J,G,Q,W,this.PERIOD_SEC)}static attoCirclesToAttoCrc(J,Z){let $=Z-this.INFLATION_DAY_ZERO_UNIX,Y=$/this.PERIOD_SEC,W=$%this.PERIOD_SEC,G=this.v1InflateFactor(Y),Q=this.v1InflateFactor(Y+1n),M=G*(this.PERIOD_SEC-W)+Q*W;return J*3n*this.V1_ACCURACY*this.PERIOD_SEC/M}static v1ToDemurrage(J,Z,$,Y,W){let G=Z*(W-Y)+$*Y;return J*3n*this.V1_ACCURACY*W/G}}class _{client;constructor(J){this.client=J}async getTotalBalance(J,Z=!0){let $=await this.client.call("circlesV2_getTotalBalance",[V(J),Z]);return u.circlesToAttoCircles($)}async getTokenBalances(J){let $=(await this.client.call("circles_getTokenBalances",[V(J)])).map((Y)=>X(Y));return K($)}}class z{client;constructor(J){this.client=J}async getAvatarInfo(J){let Z=await this.getAvatarInfoBatch([J]);return Z.length>0?Z[0]:void 0}async getAvatarInfoBatch(J){if(J.length===0)return[];let Z=J.map((Y)=>V(Y)),$=await this.client.call("circles_getAvatarInfoBatch",[Z]);return K($)}async getNetworkSnapshot(){let J=await this.client.call("circles_getNetworkSnapshot",[]);return K(J)}}class T{client;constructor(J){this.client=J}async getProfileByCid(J){return this.client.call("circles_getProfileByCid",[J])}async getProfileByCidBatch(J){return this.client.call("circles_getProfileByCidBatch",[J])}async getProfileByAddress(J){return this.client.call("circles_getProfileByAddress",[V(J)])}async getProfileByAddressBatch(J){return this.client.call("circles_getProfileByAddressBatch",[J.map((Z)=>Z===null?null:V(Z))])}async searchProfiles(J,Z=10,$=0,Y){return this.client.call("circles_searchProfiles",[J.toLowerCase(),Z,$,Y])}async searchByAddressOrName(J,Z=10,$,Y){return this.client.call("circles_searchProfileByAddressOrName",Y?[J,Z,$??null,Y]:[J,Z,$??null])}async getProfileView(J){return this.client.call("circles_getProfileView",[V(J)])}}class C{client;constructor(J){this.client=J}async getTokenInfo(J){let Z=await this.getTokenInfoBatch([J]);return Z.length>0?Z[0]:void 0}async getTokenInfoBatch(J){if(J.length===0)return[];let Z=J.map((W)=>V(W)),Y=(await this.client.call("circles_getTokenInfoBatch",[Z])).map((W)=>X(W));return K(Y)}async getTokenHolders(J,Z=100,$){let Y=await this.client.call("circles_getTokenHolders",[V(J),Z,$??null]);return{hasMore:Y.hasMore,nextCursor:Y.nextCursor,results:K(Y.results)}}}class E{client;constructor(J){this.client=J}async getInvitationOrigin(J){let Z=V(J),$=await this.client.call("circles_getInvitationOrigin",[Z]);return $?K($):null}async getInvitedBy(J){let Z=await this.getInvitationOrigin(J);if(Z?.inviter)return K(Z.inviter);return}async getTrustInvitations(J,Z){let $=V(J),Y=await this.client.call("circles_getTrustInvitations",Z?[$,Z]:[$]);return K(Y)}async getInvitations(J,Z){let Y=(await this.getValidInviters(J,Z)).results.map((W)=>W.avatarInfo).filter((W)=>W!==void 0&&W!==null);return K(Y)}async getValidInviters(J,Z){let $=V(J),Y=await this.client.call("circles_getValidInviters",Z?[$,Z]:[$]);return K(Y)}async getInvitationsFrom(J,Z=!1){let $=V(J),Y=await this.client.call("circles_getInvitationsFrom",[$,Z]);return K(Y)}async getEscrowInvitations(J){let Z=V(J),$=await this.client.call("circles_getEscrowInvitations",[Z]);return K($)}async getAtScaleInvitations(J){let Z=V(J),$=await this.client.call("circles_getAtScaleInvitations",[Z]);return K($)}async getAllInvitations(J,Z){let $=V(J),Y=await this.client.call("circles_getAllInvitations",Z?[$,Z]:[$]);return K(Y)}}class B{client;constructor(J){this.client=J}async getTransactionHistory(J,Z=50,$){let Y=await this.client.call("circles_getTransactionHistory",[V(J),Z,$??null]);return{hasMore:Y.hasMore,nextCursor:Y.nextCursor,results:K(Y.results)}}async getTransactionHistoryEnriched(J,Z=0,$=null,Y=20,W){let G=await this.client.call("circles_getTransactionHistoryEnriched",[V(J),Z,$,Y,W??null]);return{hasMore:G.hasMore,nextCursor:G.nextCursor,results:K(G.results)}}}class S{client;constructor(J){this.client=J}async findGroups(J=50,Z,$){let Y=Z?{nameStartsWith:Z.nameStartsWith,symbolStartsWith:Z.symbolStartsWith,ownerIn:Z.ownerIn?.map((Q)=>V(Q))}:void 0,W=await this.client.call("circles_findGroups",[J,Y??null,$??null]),G=K(W.results).map((Q)=>{let M=Q;if(!M.owner&&M.mint)return{...M,owner:M.mint};return M});return{hasMore:W.hasMore,nextCursor:W.nextCursor,results:G}}async getGroupMemberships(J,Z=50,$){let Y=await this.client.call("circles_getGroupMemberships",[V(J),Z,$??null]);return{hasMore:Y.hasMore,nextCursor:Y.nextCursor,results:K(Y.results)}}async getGroupMembers(J,Z=100,$){let Y=await this.client.call("circles_getGroupMembers",[V(J),Z,$??null]);return{hasMore:Y.hasMore,nextCursor:Y.nextCursor,results:K(Y.results)}}getGroups(J=50,Z,$="DESC"){let Y=[];if(Z){if(Z.nameStartsWith)Y.push({Type:"FilterPredicate",FilterType:"Like",Column:"name",Value:Z.nameStartsWith+"%"});if(Z.symbolStartsWith)Y.push({Type:"FilterPredicate",FilterType:"Like",Column:"symbol",Value:Z.symbolStartsWith+"%"});if(Z.groupAddressIn&&Z.groupAddressIn.length>0){let G=Z.groupAddressIn.map((Q)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:V(Q)}));if(G.length===1)Y.push(G[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:G})}if(Z.groupTypeIn&&Z.groupTypeIn.length>0){let G=Z.groupTypeIn.map((Q)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"type",Value:Q}));if(G.length===1)Y.push(G[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:G})}if(Z.ownerIn&&Z.ownerIn.length>0){let G=Z.ownerIn.map((Q)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"owner",Value:V(Q)}));if(G.length===1)Y.push(G[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:G})}if(Z.mintHandlerEquals)Y.push({Type:"FilterPredicate",FilterType:"Equals",Column:"mintHandler",Value:V(Z.mintHandlerEquals)});if(Z.treasuryEquals)Y.push({Type:"FilterPredicate",FilterType:"Equals",Column:"treasury",Value:V(Z.treasuryEquals)})}let W=Y.length>1?[{Type:"Conjunction",ConjunctionType:"And",Predicates:Y}]:Y;return new N(this.client,{namespace:"V_CrcV2",table:"Groups",sortOrder:$,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","type","owner","mintPolicy","mintHandler","treasury","service","feeCollection","memberCount","name","symbol","cidV0Digest","erc20WrapperDemurraged","erc20WrapperStatic"],filter:W,limit:J},(G)=>K(G))}getGroupHolders(J,Z=100){let $=V(J);return new N(this.client,{namespace:"V_Crc",table:"TokenBalances",sortOrder:"DESC",columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","token","account","balance","lastChangedAt"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"token",Value:$}],limit:Z},(Y)=>K(Y))}}class x{client;constructor(J){this.client=J}async getProfileView(J){let Z=V(J);return this.client.call("circles_getProfileView",[Z])}async getTrustNetworkSummary(J,Z=2){let $=V(J);return this.client.call("circles_getTrustNetworkSummary",[$,Z])}async getAggregatedTrustRelations(J){let Z=V(J);return this.client.call("circles_getAggregatedTrustRelations",[Z])}async getValidInviters(J,Z){let $=V(J),Y=await this.client.call("circles_getValidInviters",Z?[$,Z]:[$]);return K(Y)}async getTransactionHistoryEnriched(J,Z=0,$=null,Y=50,W){let G=V(J),Q=await this.client.call("circles_getTransactionHistoryEnriched",[G,Z,$,Y,W??null]);return{hasMore:Q.hasMore,nextCursor:Q.nextCursor,results:K(Q.results)}}async searchProfileByAddressOrName(J,Z=20,$,Y){return this.client.call("circles_searchProfileByAddressOrName",Y?[J,Z,$??null,Y]:[J,Z,$??null])}}class XJ{client;_pathfinder;_query;_trust;_balance;_avatar;_profile;_token;_invitation;_transaction;_group;_sdk;constructor(J="https://rpc.aboutcircles.com/"){this.client=new k(J)}get pathfinder(){if(!this._pathfinder)this._pathfinder=new L(this.client);return this._pathfinder}get query(){if(!this._query)this._query=new P(this.client);return this._query}get trust(){if(!this._trust)this._trust=new R(this.client);return this._trust}get balance(){if(!this._balance)this._balance=new _(this.client);return this._balance}get avatar(){if(!this._avatar)this._avatar=new z(this.client);return this._avatar}get profile(){if(!this._profile)this._profile=new T(this.client);return this._profile}get token(){if(!this._token)this._token=new C(this.client);return this._token}get invitation(){if(!this._invitation)this._invitation=new E(this.client);return this._invitation}get transaction(){if(!this._transaction)this._transaction=new B(this.client);return this._transaction}get group(){if(!this._group)this._group=new S(this.client);return this._group}get sdk(){if(!this._sdk)this._sdk=new x(this.client);return this._sdk}setRpcUrl(J){this.client.setRpcUrl(J)}getRpcUrl(){return this.client.getRpcUrl()}}export{X as parseStringsToBigInt,H as parseRpcSubscriptionMessage,b as parseRpcEvent,kJ as normalizeAddresses,V as normalizeAddress,c as isCirclesEvent,R as TrustMethods,B as TransactionMethods,C as TokenMethods,q as RpcError,k as RpcClient,P as QueryMethods,T as ProfileMethods,L as PathfinderMethods,N as PagedQuery,D as Observable,E as InvitationMethods,S as GroupMethods,XJ as CirclesRpc,_ as BalanceMethods,z as AvatarMethods};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aboutcircles/sdk-rpc",
3
- "version": "0.1.29",
3
+ "version": "0.1.30",
4
4
  "description": "Circles RPC wrapper",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",