@aboutcircles/sdk-rpc 0.1.28 → 0.1.29
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.map +1 -1
- package/dist/client.js +20 -11
- package/dist/index.js +2 -2
- package/dist/methods/group.d.ts +30 -60
- package/dist/methods/group.d.ts.map +1 -1
- package/dist/methods/group.js +86 -160
- package/dist/methods/index.d.ts +1 -0
- package/dist/methods/index.d.ts.map +1 -1
- package/dist/methods/index.js +1 -0
- package/dist/methods/invitation.d.ts +99 -5
- package/dist/methods/invitation.d.ts.map +1 -1
- package/dist/methods/invitation.js +130 -164
- package/dist/methods/profile.d.ts +12 -4
- package/dist/methods/profile.d.ts.map +1 -1
- package/dist/methods/profile.js +16 -43
- package/dist/methods/query.d.ts +38 -9
- package/dist/methods/query.d.ts.map +1 -1
- package/dist/methods/query.js +38 -13
- package/dist/methods/sdk.d.ts +142 -0
- package/dist/methods/sdk.d.ts.map +1 -0
- package/dist/methods/sdk.js +165 -0
- package/dist/methods/token.d.ts +9 -15
- package/dist/methods/token.d.ts.map +1 -1
- package/dist/methods/token.js +14 -39
- package/dist/methods/transaction.d.ts +20 -21
- package/dist/methods/transaction.d.ts.map +1 -1
- package/dist/methods/transaction.js +32 -89
- package/dist/methods/trust.d.ts +30 -6
- package/dist/methods/trust.d.ts.map +1 -1
- package/dist/methods/trust.js +46 -50
- package/dist/pagedQuery.d.ts +7 -49
- package/dist/pagedQuery.d.ts.map +1 -1
- package/dist/pagedQuery.js +17 -146
- package/dist/rpc.d.ts +8 -3
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +14 -4
- package/dist/types.d.ts +4 -5
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/client.d.ts.map
CHANGED
|
@@ -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;
|
|
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"}
|
package/dist/client.js
CHANGED
|
@@ -74,13 +74,13 @@ export class RpcClient {
|
|
|
74
74
|
* @private
|
|
75
75
|
*/
|
|
76
76
|
connect() {
|
|
77
|
-
return new Promise((resolve) => {
|
|
77
|
+
return new Promise((resolve, reject) => {
|
|
78
78
|
let wsUrl = this.rpcUrl.replace('http', 'ws');
|
|
79
79
|
if (wsUrl.endsWith('/')) {
|
|
80
|
-
wsUrl += 'ws';
|
|
80
|
+
wsUrl += 'ws/subscribe';
|
|
81
81
|
}
|
|
82
82
|
else {
|
|
83
|
-
wsUrl += '/ws';
|
|
83
|
+
wsUrl += '/ws/subscribe';
|
|
84
84
|
}
|
|
85
85
|
this.websocket = new WebSocket(wsUrl);
|
|
86
86
|
this.websocket.onopen = () => {
|
|
@@ -97,21 +97,29 @@ export class RpcClient {
|
|
|
97
97
|
this.pendingResponses[id].resolve(message);
|
|
98
98
|
delete this.pendingResponses[id];
|
|
99
99
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
100
|
+
// Handle server event push: { method: "circles_subscription", params: { result: [...] } }
|
|
101
|
+
if (method === 'circles_subscription' && params?.result) {
|
|
102
|
+
// Server broadcasts to all subscribers, so notify all listeners
|
|
103
|
+
Object.values(this.subscriptionListeners).forEach(listeners => {
|
|
104
|
+
listeners.forEach(listener => listener(params.result));
|
|
105
|
+
});
|
|
105
106
|
}
|
|
106
107
|
};
|
|
107
108
|
this.websocket.onclose = () => {
|
|
108
109
|
console.warn('WebSocket closed');
|
|
110
|
+
const wasConnected = this.websocketConnected;
|
|
109
111
|
this.websocketConnected = false;
|
|
112
|
+
// Reconnect after a previously-established connection drops
|
|
113
|
+
if (wasConnected) {
|
|
114
|
+
this.scheduleReconnect();
|
|
115
|
+
}
|
|
110
116
|
};
|
|
111
117
|
this.websocket.onerror = (error) => {
|
|
112
118
|
console.error('WebSocket error:', error);
|
|
113
119
|
this.websocketConnected = false;
|
|
114
|
-
//
|
|
120
|
+
// Reject the initial connection promise so callers don't hang forever.
|
|
121
|
+
// Reconnect attempts happen in the background via scheduleReconnect().
|
|
122
|
+
reject(RpcError.connectionFailed(this.rpcUrl, error instanceof Error ? error : new Error('WebSocket connection failed')));
|
|
115
123
|
this.scheduleReconnect();
|
|
116
124
|
};
|
|
117
125
|
});
|
|
@@ -180,8 +188,9 @@ export class RpcClient {
|
|
|
180
188
|
await this.connect();
|
|
181
189
|
}
|
|
182
190
|
const observable = Observable.create();
|
|
183
|
-
|
|
184
|
-
const
|
|
191
|
+
// Server expects: { method: "circles_subscribe", params: { address: "0x..." } }
|
|
192
|
+
const subscriptionParams = normalizedAddress ? { address: normalizedAddress } : {};
|
|
193
|
+
const response = await this.sendMessage('circles_subscribe', subscriptionParams);
|
|
185
194
|
const subscriptionId = response.result;
|
|
186
195
|
if (!this.subscriptionListeners[subscriptionId]) {
|
|
187
196
|
this.subscriptionListeners[subscriptionId] = [];
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function
|
|
2
|
-
Context: ${JSON.stringify(this.context,null,2)}`;return J}}class X extends v{constructor(J,Z){super("RpcError",J,{...Z,source:Z?.source??"RPC_REQUEST"})}static connectionFailed(J,Z){return new X("Failed to connect to RPC endpoint",{code:"RPC_CONNECTION_FAILED",source:"RPC_CONNECTION",cause:Z,context:{url:J}})}static timeout(J,Z){return new X("RPC request timed out",{code:"RPC_TIMEOUT",source:"RPC_TIMEOUT",context:{method:J,timeout:Z}})}static invalidResponse(J,Z){return new X("Invalid RPC response",{code:"RPC_INVALID_RESPONSE",source:"RPC_RESPONSE",context:{method:J,response:Z}})}static fromJsonRpcError(J){return new X(J.message,{code:J.code,source:"RPC_RESPONSE",context:{data:J.data}})}static websocketError(J,Z){return new X(J,{code:"RPC_WEBSOCKET_ERROR",source:"RPC_WEBSOCKET",cause:Z})}}class x{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 G=await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify($)});if(!G.ok)throw X.connectionFailed(this.rpcUrl,Error(`HTTP ${G.status}: ${G.statusText}`));let Y=await G.json();if(Y.error)throw X.fromJsonRpcError(Y.error);if(Y.result===void 0)throw X.invalidResponse(J,Y);return Y.result}catch(G){if(G instanceof X)throw G;throw X.connectionFailed(this.rpcUrl,G)}}setRpcUrl(J){this.rpcUrl=J}getRpcUrl(){return this.rpcUrl}connect(){return new Promise((J)=>{let Z=this.rpcUrl.replace("http","ws");if(Z.endsWith("/"))Z+="ws";else Z+="/ws";this.websocket=new WebSocket(Z),this.websocket.onopen=()=>{console.log("WebSocket connected"),this.websocketConnected=!0,this.reconnectAttempt=0,J()},this.websocket.onmessage=($)=>{let G=JSON.parse($.data),{id:Y,method:W,params:K}=G;if(Y!==void 0&&this.pendingResponses[Y])this.pendingResponses[Y].resolve(G),delete this.pendingResponses[Y];if(W==="eth_subscription"&&K){let{subscription:M,result:N}=K;if(this.subscriptionListeners[M])this.subscriptionListeners[M].forEach((q)=>q(N))}},this.websocket.onclose=()=>{console.warn("WebSocket closed"),this.websocketConnected=!1},this.websocket.onerror=($)=>{console.error("WebSocket error:",$),this.websocketConnected=!1,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(X.connectionFailed(this.rpcUrl));let G=this.requestId++,Y={jsonrpc:"2.0",method:J,params:Z,id:G};return new Promise((W,K)=>{this.pendingResponses[G]={resolve:W,reject:K},this.websocket.send(JSON.stringify(Y)),setTimeout(()=>{if(this.pendingResponses[G])this.pendingResponses[G].reject(X.timeout(J,$)),delete this.pendingResponses[G]},$)})}async subscribe(J){let Z=J?.toLowerCase();if(!this.websocketConnected)await this.connect();let $=O.create(),G=JSON.stringify(Z?{address:Z}:{}),W=(await this.sendMessage("eth_subscribe",["circles",G])).result;if(!this.subscriptionListeners[W])this.subscriptionListeners[W]=[];return this.subscriptionListeners[W].push((K)=>{A(K).forEach((M)=>$.emit(M))}),$.property}}var b=BigInt(4294967295),o=BigInt(32);function OJ(J,Z=!1){if(Z)return{h:Number(J&b),l:Number(J>>o&b)};return{h:Number(J>>o&b)|0,l:Number(J&b)|0}}function t(J,Z=!1){let $=J.length,G=new Uint32Array($),Y=new Uint32Array($);for(let W=0;W<$;W++){let{h:K,l:M}=OJ(J[W],Z);[G[W],Y[W]]=[K,M]}return[G,Y]}var a=(J,Z,$)=>J<<$|Z>>>32-$,r=(J,Z,$)=>Z<<$|J>>>32-$,s=(J,Z,$)=>Z<<$-32|J>>>64-$,e=(J,Z,$)=>J<<$-32|Z>>>64-$;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function LJ(J){return J instanceof Uint8Array||ArrayBuffer.isView(J)&&J.constructor.name==="Uint8Array"}function y(J){if(!Number.isSafeInteger(J)||J<0)throw Error("positive integer expected, got "+J)}function z(J,...Z){if(!LJ(J))throw Error("Uint8Array expected");if(Z.length>0&&!Z.includes(J.length))throw Error("Uint8Array expected of length "+Z+", got length="+J.length)}function h(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 JJ(J,Z){z(J);let $=Z.outputLen;if(J.length<$)throw Error("digestInto() expects output buffer of length at least "+$)}function ZJ(J){return new Uint32Array(J.buffer,J.byteOffset,Math.floor(J.byteLength/4))}function m(...J){for(let Z=0;Z<J.length;Z++)J[Z].fill(0)}var zJ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function IJ(J){return J<<24&4278190080|J<<8&16711680|J>>>8&65280|J>>>24&255}function _J(J){for(let Z=0;Z<J.length;Z++)J[Z]=IJ(J[Z]);return J}var p=zJ?(J)=>J:_J;function BJ(J){if(typeof J!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(J))}function u(J){if(typeof J==="string")J=BJ(J);return z(J),J}class c{}function $J(J){let Z=(G)=>J().update(u(G)).digest(),$=J();return Z.outputLen=$.outputLen,Z.blockLen=$.blockLen,Z.create=()=>J(),Z}var RJ=BigInt(0),I=BigInt(1),TJ=BigInt(2),EJ=BigInt(7),SJ=BigInt(256),HJ=BigInt(113),WJ=[],KJ=[],QJ=[];for(let J=0,Z=I,$=1,G=0;J<24;J++){[$,G]=[G,(2*$+3*G)%5],WJ.push(2*(5*G+$)),KJ.push((J+1)*(J+2)/2%64);let Y=RJ;for(let W=0;W<7;W++)if(Z=(Z<<I^(Z>>EJ)*HJ)%SJ,Z&TJ)Y^=I<<(I<<BigInt(W))-I;QJ.push(Y)}var MJ=t(QJ,!0),kJ=MJ[0],CJ=MJ[1],GJ=(J,Z,$)=>$>32?s(J,Z,$):a(J,Z,$),YJ=(J,Z,$)=>$>32?e(J,Z,$):r(J,Z,$);function wJ(J,Z=24){let $=new Uint32Array(10);for(let G=24-Z;G<24;G++){for(let K=0;K<10;K++)$[K]=J[K]^J[K+10]^J[K+20]^J[K+30]^J[K+40];for(let K=0;K<10;K+=2){let M=(K+8)%10,N=(K+2)%10,q=$[N],U=$[N+1],d=GJ(q,U,1)^$[M],g=YJ(q,U,1)^$[M+1];for(let j=0;j<50;j+=10)J[K+j]^=d,J[K+j+1]^=g}let Y=J[2],W=J[3];for(let K=0;K<24;K++){let M=KJ[K],N=GJ(Y,W,M),q=YJ(Y,W,M),U=WJ[K];Y=J[U],W=J[U+1],J[U]=N,J[U+1]=q}for(let K=0;K<50;K+=10){for(let M=0;M<10;M++)$[M]=J[K+M];for(let M=0;M<10;M++)J[K+M]^=~$[(M+2)%10]&$[(M+4)%10]}J[0]^=kJ[G],J[1]^=CJ[G]}m($)}class l extends c{constructor(J,Z,$,G=!1,Y=24){super();if(this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=J,this.suffix=Z,this.outputLen=$,this.enableXOF=G,this.rounds=Y,y($),!(0<J&&J<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ZJ(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){h(this),J=u(J),z(J);let{blockLen:Z,state:$}=this,G=J.length;for(let Y=0;Y<G;){let W=Math.min(Z-this.pos,G-Y);for(let K=0;K<W;K++)$[this.pos++]^=J[Y++];if(this.pos===Z)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:J,suffix:Z,pos:$,blockLen:G}=this;if(J[$]^=Z,(Z&128)!==0&&$===G-1)this.keccak();J[G-1]^=128,this.keccak()}writeInto(J){h(this,!1),z(J),this.finish();let Z=this.state,{blockLen:$}=this;for(let G=0,Y=J.length;G<Y;){if(this.posOut>=$)this.keccak();let W=Math.min($-this.posOut,Y-G);J.set(Z.subarray(this.posOut,this.posOut+W),G),this.posOut+=W,G+=W}return J}xofInto(J){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(J)}xof(J){return y(J),this.xofInto(new Uint8Array(J))}digestInto(J){if(JJ(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,m(this.state)}_cloneInto(J){let{blockLen:Z,suffix:$,outputLen:G,rounds:Y,enableXOF:W}=this;return J||(J=new l(Z,$,G,W,Y)),J.state32.set(this.state32),J.pos=this.pos,J.posOut=this.posOut,J.finished=this.finished,J.rounds=Y,J.suffix=$,J.outputLen=G,J.enableXOF=W,J.destroyed=this.destroyed,J}}var gJ=(J,Z,$)=>$J(()=>new l(Z,J,$));var VJ=(()=>gJ(1,136,32))();var qJ=[];for(let J=0;J<256;J++)qJ[J]=J.toString(16).padStart(2,"0");function NJ(J){let Z="0x";for(let $=0;$<J.length;$++)Z+=qJ[J[$]];return Z}function UJ(J){let Z=J.toLowerCase().replace("0x",""),$=NJ(VJ(new TextEncoder().encode(Z))).slice(2),G="0x";for(let Y=0;Y<Z.length;Y++)G+=parseInt($[Y],16)>=8?Z[Y].toUpperCase():Z[Y];return G}function Q(J){return J.toLowerCase()}function AJ(J){return J.map((Z)=>Q(Z))}function xJ(J){return UJ(J)}function bJ(J){if(typeof J!=="string")return!1;let Z=J.replace("0x","");return Z.length===40&&/^[0-9a-fA-F]{40}$/.test(Z)}function V(J){if(J===null||J===void 0)return J;if(bJ(J))return xJ(J);if(Array.isArray(J))return J.map((Z)=>V(Z));if(typeof J==="object"&&J!==null){let Z={};for(let $ in J)if(Object.prototype.hasOwnProperty.call(J,$))Z[$]=V(J[$]);return Z}return J}function XJ(J){return{Source:Q(J.from),Sink:Q(J.to),TargetFlow:J.targetFlow.toString(),WithWrap:J.useWrappedBalances,FromTokens:J.fromTokens?.map(Q),ToTokens:J.toTokens?.map(Q),ExcludedFromTokens:J.excludeFromTokens?.map(Q),ExcludedToTokens:J.excludeToTokens?.map(Q),SimulatedBalances:J.simulatedBalances?.map((Z)=>({Holder:Q(Z.holder),Token:Q(Z.token),Amount:Z.amount.toString(),IsWrapped:Z.isWrapped,IsStatic:Z.isStatic})),SimulatedTrusts:J.simulatedTrusts?.map((Z)=>({Truster:Q(Z.truster),Trustee:Q(Z.trustee)})),MaxTransfers:J.maxTransfers}}function D(J){let Z={};for(let $ in J){let G=J[$];if(G===null||G===void 0)Z[$]=G;else if(typeof G==="string"&&/^\d+$/.test(G))Z[$]=BigInt(G);else if(typeof G==="object"&&!Array.isArray(G))Z[$]=D(G);else if(Array.isArray(G))Z[$]=G.map((Y)=>typeof Y==="object"&&Y!==null?D(Y):Y);else Z[$]=G}return Z}var VZ=BigInt(96)*BigInt(1000000000000000000),FJ=BigInt("9999999999999999999999999999999999999");class _{client;constructor(J){this.client=J}async findPath(J){let Z=XJ(J),$=await this.client.call("circlesV2_findPath",[Z]),G=D($);return V(G)}async findMaxFlow(J){let Z=await this.findPath({...J,targetFlow:FJ});return BigInt(Z.maxFlow)}}class B{client;constructor(J){this.client=J}async query(J){let Z=await this.client.call("circles_query",[J]);return V(Z)}async tables(){return this.client.call("circles_tables",[])}async events(J,Z,$=null,G=null,Y=!1){let W=await this.client.call("circles_events",[J,Z,$,G,Y]);return V(W)}}var fJ=[{name:"blockNumber",sortOrder:"DESC"},{name:"transactionIndex",sortOrder:"DESC"},{name:"logIndex",sortOrder:"DESC"}];class F{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=fJ.map((Z)=>({...Z,sortOrder:this.params.sortOrder}));if(this.params.table==="TransferBatch")J.push({name:"batchIndex",sortOrder:this.params.sortOrder});return J}transformCursorValue(J,Z){if(Z)return Z(J);if(typeof J==="bigint")return J.toString();return J}createEqualityPredicate(J,Z){return{Type:"FilterPredicate",FilterType:"Equals",Column:J.name,Value:this.transformCursorValue(Z,J.toValue)}}createComparisonPredicate(J,Z){return{Type:"FilterPredicate",FilterType:J.sortOrder==="ASC"?"GreaterThan":"LessThan",Column:J.name,Value:this.transformCursorValue(Z,J.toValue)}}buildCursorFilter(J){if(!J)return[];let Z=[];for(let $=0;$<this.cursorColumns.length;$++){let G=this.cursorColumns[$],Y=J[G.name];if(Y===void 0)continue;if($===0)Z.push(this.createComparisonPredicate(G,Y));else{let W=[];for(let K=0;K<$;K++){let M=this.cursorColumns[K],N=J[M.name];if(N!==void 0)W.push(this.createEqualityPredicate(M,N))}W.push(this.createComparisonPredicate(G,Y)),Z.push({Type:"Conjunction",ConjunctionType:"And",Predicates:W})}}if(Z.length===0)return[];return[{Type:"Conjunction",ConjunctionType:"Or",Predicates:Z}]}buildOrderBy(){if(this.orderColumns&&this.orderColumns.length>0)return this.orderColumns;return this.cursorColumns.map((J)=>({Column:J.name,SortOrder:J.sortOrder}))}combineFilters(J,Z){if(!J?.length&&!Z?.length)return[];if(!J?.length)return Z||[];if(!Z?.length)return J;return[{Type:"Conjunction",ConjunctionType:"And",Predicates:[...J,...Z]}]}rowsToObjects(J){let{columns:Z,rows:$}=J;return $.map((G)=>{let Y={};return Z.forEach((W,K)=>{Y[W]=G[K]}),this.rowTransformer?this.rowTransformer(Y):Y})}rowToCursor(J){let Z={};for(let $ of this.cursorColumns)Z[$.name]=J[$.name];return Z}getCursors(J){if(J.length===0)return{};return{first:this.rowToCursor(J[0]),last:this.rowToCursor(J[J.length-1])}}async queryNextPage(){let J=this.buildCursorFilter(this._currentPage?.lastCursor),Z=this.combineFilters(this.params.filter,J),$={Namespace:this.params.namespace,Table:this.params.table,Columns:this.params.columns,Filter:Z,Order:this.buildOrderBy(),Limit:this.params.limit},G=await this.client.call("circles_query",[$]),Y=this.rowsToObjects(G),W=this.getCursors(Y);return this._currentPage={limit:this.params.limit,size:Y.length,firstCursor:W.first,lastCursor:W.last,sortOrder:this.params.sortOrder,hasMore:Y.length===this.params.limit,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((G)=>{let Y={};return Z.forEach((W,K)=>{Y[W]=G[K]}),Y})}async getCommonTrust(J,Z){let $=await this.client.call("circles_getCommonTrust",[Q(J),Q(Z)]);return V($)}getTrustRelations(J,Z=100,$="DESC"){let G=Q(J),Y=[{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:G},{Type:"FilterPredicate",FilterType:"Equals",Column:"truster",Value:G}]}]}];return new F(this.client,{namespace:"V_Crc",table:"TrustRelations",sortOrder:$,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","version","trustee","truster","expiryTime"],filter:Y,limit:Z},(W)=>V(W))}async getAggregatedTrustRelations(J){let Z=Q(J),$=this.getTrustRelations(Z,1000),G=[];while(await $.queryNextPage())if(G.push(...$.currentPage.results),!$.currentPage.hasMore)break;let Y={};G.forEach((K)=>{let M=Q(K.truster),N=Q(K.trustee),q=M!==Z?K.truster:K.trustee;if(!Y[q])Y[q]=[];Y[q].push(K)});let W=Object.entries(Y).filter(([K])=>Q(K)!==Z).map(([K,M])=>{let N=Math.max(...M.map((U)=>U.timestamp)),q;if(M.length===2)q="mutuallyTrusts";else if(Q(M[0]?.trustee)===Z)q="trustedBy";else if(Q(M[0]?.truster)===Z)q="trusts";else throw Error("Unexpected trust list row. Couldn't determine trust relation.");return{subjectAvatar:Z,relation:q,objectAvatar:K,timestamp:N}});return V(W)}async getTrustedBy(J){let Z=Q(J),G=(await this.getAggregatedTrustRelations(Z)).filter((Y)=>Y.relation==="trustedBy");return V(G)}async getTrusts(J){let Z=Q(J),G=(await this.getAggregatedTrustRelations(Z)).filter((Y)=>Y.relation==="trusts");return V(G)}async getMutualTrusts(J){let Z=Q(J),G=(await this.getAggregatedTrustRelations(Z)).filter((Y)=>Y.relation==="mutuallyTrusts");return V(G)}}class P{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,G=Z,Y=this.ONE_64;while(G>0n){if((G&1n)===1n)Y=this.mul64(Y,$);$=this.mul64($,$),G>>=1n}return Y}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,G=J,Y=Z;while(Y>0n){if((Y&1n)===1n)$=this.mul36($,G);G=this.mul36(G,G),Y>>=1n}return $}static attoCirclesToCircles(J){if(J===0n)return 0;let Z=J/this.ATTO_FACTOR,$=J%this.ATTO_FACTOR,G=BigInt(Number.MAX_SAFE_INTEGER);if(Z>G||Z<-G)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,G=$/this.PERIOD_SEC,Y=$%this.PERIOD_SEC,W=this.v1InflateFactor(G),K=this.v1InflateFactor(G+1n);return this.v1ToDemurrage(J,W,K,Y,this.PERIOD_SEC)}static attoCirclesToAttoCrc(J,Z){let $=Z-this.INFLATION_DAY_ZERO_UNIX,G=$/this.PERIOD_SEC,Y=$%this.PERIOD_SEC,W=this.v1InflateFactor(G),K=this.v1InflateFactor(G+1n),M=W*(this.PERIOD_SEC-Y)+K*Y;return J*3n*this.V1_ACCURACY*this.PERIOD_SEC/M}static v1ToDemurrage(J,Z,$,G,Y){let W=Z*(Y-G)+$*G;return J*3n*this.V1_ACCURACY*Y/W}}class T{client;constructor(J){this.client=J}async getTotalBalance(J,Z=!0){let $=await this.client.call("circlesV2_getTotalBalance",[Q(J),Z]);return P.circlesToAttoCircles($)}async getTokenBalances(J){let $=(await this.client.call("circles_getTokenBalances",[Q(J)])).map((G)=>D(G));return V($)}}class E{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((G)=>Q(G)),$=await this.client.call("circles_getAvatarInfoBatch",[Z]);return V($)}async getNetworkSnapshot(){let J=await this.client.call("circles_getNetworkSnapshot",[]);return V(J)}}class S{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",[Q(J)])}async getProfileByAddressBatch(J){return this.client.call("circles_getProfileByAddressBatch",[J.map((Z)=>Z===null?null:Q(Z))])}async searchProfiles(J,Z=10,$=0,G){return this.client.call("circles_searchProfiles",[J.toLowerCase(),Z,$,G])}async searchByAddressOrName(J,Z=10,$=0,G){let Y=[],W=/^0x[a-fA-F0-9]{40}$/.test(J);if(W)try{let K=await this.getProfileByAddress(J);if(K){let M={...K,address:J};if(!G||!M.avatarType||G.includes(M.avatarType))Y.push(M)}}catch(K){console.warn("Failed to get profile by address:",K)}try{let K=await this.searchProfiles(J,Z,$,G);if(W&&Y.length>0){let M=J.toLowerCase(),N=K.filter((q)=>q.address?.toLowerCase()!==M);Y.push(...N)}else Y.push(...K)}catch(K){console.warn("Failed to search profiles by text:",K)}return Y.slice(0,Z)}}class H{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((Y)=>Q(Y)),G=(await this.client.call("circles_getTokenInfoBatch",[Z])).map((Y)=>D(Y));return V(G)}getTokenHolders(J,Z=100,$="DESC"){let G=Q(J);return new F(this.client,{namespace:"V_CrcV2",table:"BalancesByAccountAndToken",columns:["account","tokenAddress","demurragedTotalBalance"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"tokenAddress",Value:G}],cursorColumns:[{name:"demurragedTotalBalance",sortOrder:$},{name:"account",sortOrder:"ASC"}],orderColumns:[{Column:"demurragedTotalBalance",SortOrder:$},{Column:"account",SortOrder:"ASC"}],limit:Z,sortOrder:$},(Y)=>({account:Y.account,tokenAddress:Y.tokenAddress,demurragedTotalBalance:Y.demurragedTotalBalance}))}}class k{client;constructor(J){this.client=J}transformQueryResponse(J){let{columns:Z,rows:$}=J;return $.map((G)=>{let Y={};return Z.forEach((W,K)=>{Y[W]=G[K]}),Y})}async getInvitedBy(J){let Z=Q(J),$=await this.client.call("circles_query",[{Namespace:"CrcV2",Table:"RegisterHuman",Columns:["inviter"],Filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"avatar",Value:Z}],Order:[{Column:"blockNumber",SortOrder:"DESC"}],Limit:1}]);if($.length>0)return V($[0].inviter);return}async getInvitations(J){let Z=Q(J),$=96,G=await this.client.call("circles_getAvatarInfoBatch",[[Z]]);if((G.length>0?G[0]:void 0)?.version===2)return[];let W=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:Z}]}],Order:[]}]),M=this.transformQueryResponse(W).map((U)=>U.truster);if(M.length===0)return[];let N=await this.client.call("circles_getAvatarInfoBatch",[M]),q=[];for(let U of N){if(!U?.isHuman)continue;let g=(await this.client.call("circles_getTokenBalances",[U.avatar])).find((j)=>Q(j.tokenAddress)===Q(U.avatar));if(g&&g.circles>=96)q.push(U)}return V(q)}async getInvitationsFrom(J,Z=!1){let $=Q(J);if(Z){let G=await this.client.call("circles_query",[{Namespace:"CrcV2",Table:"RegisterHuman",Columns:["avatar"],Filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"inviter",Value:$}],Order:[{Column:"blockNumber",SortOrder:"DESC"}]}]),W=this.transformQueryResponse(G).map((K)=>K.avatar);return V(W)}else{let G=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:$}]}],Order:[]}]),W=this.transformQueryResponse(G).map((q)=>q.trustee);if(W.length===0)return[];let K=await this.client.call("circles_getAvatarInfoBatch",[W]),M=new Set(K.filter((q)=>q!==null).map((q)=>Q(q.avatar))),N=W.filter((q)=>!M.has(Q(q)));return V(N)}}}function vJ(J,Z){let $=BigInt(J),G=P.attoCirclesToCircles($),Y=P.attoCirclesToAttoCrc($,BigInt(Z)),W=P.attoCirclesToCircles(Y),K=P.attoCirclesToAttoStaticCircles($,BigInt(Z)),M=P.attoCirclesToCircles(K);return{attoCircles:$,circles:G,staticAttoCircles:K,staticCircles:M,attoCrc:Y,crc:W}}class C{client;constructor(J){this.client=J}getTransactionHistory(J,Z=50,$="DESC"){let G=Q(J),Y=[{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:G},{Type:"FilterPredicate",FilterType:"Equals",Column:"to",Value:G}]}]}];return new F(this.client,{namespace:"V_Crc",table:"TransferSummary",sortOrder:$,columns:[],filter:Y,limit:Z},(W)=>{let K=vJ(W.value,W.timestamp),M={...W,...K};return V(M)})}}class w{client;constructor(J){this.client=J}async findGroups(J=50,Z){let $=this.getGroups(J,Z,"DESC"),G=[];while(await $.queryNextPage()){if(G.push(...$.currentPage.results),G.length>=J)break;if(!$.currentPage.hasMore)break}return G.slice(0,J)}getGroupMemberships(J,Z=50,$="DESC"){let G=Q(J);return new F(this.client,{namespace:"V_CrcV2",table:"GroupMemberships",sortOrder:$,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","member","expiryTime"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"member",Value:G}],limit:Z},(Y)=>V(Y))}getGroupHolders(J,Z=100){let $=Q(J);return new F(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:$}],limit:Z,rowTransformer:(G)=>{let Y={...G,totalBalance:BigInt(G.totalBalance),demurragedTotalBalance:BigInt(G.demurragedTotalBalance)};return V(Y)}})}getGroupMembers(J,Z=100,$="DESC"){let G=Q(J);return new F(this.client,{namespace:"V_CrcV2",table:"GroupMemberships",sortOrder:$,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","member","expiryTime"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:G}],limit:Z},(Y)=>V(Y))}getGroups(J=50,Z,$="DESC"){let G=[];if(Z){if(Z.nameStartsWith)G.push({Type:"FilterPredicate",FilterType:"Like",Column:"name",Value:Z.nameStartsWith+"%"});if(Z.symbolStartsWith)G.push({Type:"FilterPredicate",FilterType:"Like",Column:"symbol",Value:Z.symbolStartsWith+"%"});if(Z.groupAddressIn&&Z.groupAddressIn.length>0){let W=Z.groupAddressIn.map((K)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:Q(K)}));if(W.length===1)G.push(W[0]);else G.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:W})}if(Z.groupTypeIn&&Z.groupTypeIn.length>0){let W=Z.groupTypeIn.map((K)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"type",Value:K}));if(W.length===1)G.push(W[0]);else G.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:W})}if(Z.ownerIn&&Z.ownerIn.length>0){let W=Z.ownerIn.map((K)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"owner",Value:Q(K)}));if(W.length===1)G.push(W[0]);else G.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:W})}if(Z.mintHandlerEquals)G.push({Type:"FilterPredicate",FilterType:"Equals",Column:"mintHandler",Value:Q(Z.mintHandlerEquals)});if(Z.treasuryEquals)G.push({Type:"FilterPredicate",FilterType:"Equals",Column:"treasury",Value:Q(Z.treasuryEquals)})}let Y=G.length>1?[{Type:"Conjunction",ConjunctionType:"And",Predicates:G}]:G;return new F(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:Y,limit:J},(W)=>V(W))}}class DJ{client;_pathfinder;_query;_trust;_balance;_avatar;_profile;_token;_invitation;_transaction;_group;constructor(J="https://rpc.circlesubi.network/"){this.client=new x(J)}get pathfinder(){if(!this._pathfinder)this._pathfinder=new _(this.client);return this._pathfinder}get query(){if(!this._query)this._query=new B(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 T(this.client);return this._balance}get avatar(){if(!this._avatar)this._avatar=new E(this.client);return this._avatar}get profile(){if(!this._profile)this._profile=new S(this.client);return this._profile}get token(){if(!this._token)this._token=new H(this.client);return this._token}get invitation(){if(!this._invitation)this._invitation=new k(this.client);return this._invitation}get transaction(){if(!this._transaction)this._transaction=new C(this.client);return this._transaction}get group(){if(!this._group)this._group=new w(this.client);return this._group}setRpcUrl(J){this.client.setRpcUrl(J)}getRpcUrl(){return this.client.getRpcUrl()}}export{D as parseStringsToBigInt,A as parseRpcSubscriptionMessage,f as parseRpcEvent,AJ as normalizeAddresses,Q as normalizeAddress,i as isCirclesEvent,R as TrustMethods,C as TransactionMethods,H as TokenMethods,X as RpcError,x as RpcClient,B as QueryMethods,S as ProfileMethods,_ as PathfinderMethods,F as PagedQuery,O as Observable,k as InvitationMethods,w as GroupMethods,DJ as CirclesRpc,T as BalanceMethods,E 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),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};
|
package/dist/methods/group.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { RpcClient } from '../client.js';
|
|
2
|
-
import type { Address, GroupRow, GroupMembershipRow, GroupQueryParams } from '@aboutcircles/sdk-types';
|
|
2
|
+
import type { Address, GroupRow, GroupMembershipRow, GroupQueryParams, PagedResponse } from '@aboutcircles/sdk-types';
|
|
3
3
|
import type { GroupTokenHolderRow } from '../types.js';
|
|
4
4
|
import { PagedQuery } from '../pagedQuery.js';
|
|
5
5
|
/**
|
|
@@ -11,8 +11,8 @@ export declare class GroupMethods {
|
|
|
11
11
|
/**
|
|
12
12
|
* Find groups with optional filters
|
|
13
13
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
14
|
+
* Uses the native RPC method for efficient server-side filtering and pagination.
|
|
15
|
+
* Fetches all results using cursor-based pagination up to the specified limit.
|
|
16
16
|
*
|
|
17
17
|
* @param limit - Maximum number of groups to return (default: 50)
|
|
18
18
|
* @param params - Optional query parameters to filter groups
|
|
@@ -39,82 +39,44 @@ export declare class GroupMethods {
|
|
|
39
39
|
* });
|
|
40
40
|
* ```
|
|
41
41
|
*/
|
|
42
|
-
findGroups(limit?: number, params?: GroupQueryParams): Promise<GroupRow
|
|
42
|
+
findGroups(limit?: number, params?: GroupQueryParams, cursor?: string | null): Promise<PagedResponse<GroupRow>>;
|
|
43
43
|
/**
|
|
44
|
-
* Get group memberships for an avatar
|
|
44
|
+
* Get group memberships for an avatar
|
|
45
|
+
*
|
|
46
|
+
* Uses the native RPC method for efficient server-side queries.
|
|
47
|
+
* Fetches all results using cursor-based pagination up to the specified limit.
|
|
45
48
|
*
|
|
46
49
|
* @param avatar - Avatar address to query group memberships for
|
|
47
|
-
* @param limit -
|
|
48
|
-
* @
|
|
49
|
-
* @returns PagedQuery instance for iterating through memberships
|
|
50
|
+
* @param limit - Maximum number of memberships to return (default: 50)
|
|
51
|
+
* @returns Array of group membership rows
|
|
50
52
|
*
|
|
51
53
|
* @example
|
|
52
54
|
* ```typescript
|
|
53
|
-
* const
|
|
55
|
+
* const memberships = await rpc.group.getGroupMemberships(
|
|
54
56
|
* '0xde374ece6fa50e781e81aac78e811b33d16912c7',
|
|
55
57
|
* 50
|
|
56
58
|
* );
|
|
57
|
-
*
|
|
58
|
-
* console.log(query.currentPage.results);
|
|
59
|
-
* ```
|
|
60
|
-
*/
|
|
61
|
-
getGroupMemberships(avatar: Address, limit?: number, sortOrder?: 'ASC' | 'DESC'): PagedQuery<GroupMembershipRow>;
|
|
62
|
-
/**
|
|
63
|
-
* Get holders of a group token using cursor-based pagination
|
|
64
|
-
*
|
|
65
|
-
* Returns a PagedQuery instance that can be used to fetch holders page by page.
|
|
66
|
-
* Results are ordered by totalBalance DESC (highest first), with holder address as tie-breaker.
|
|
67
|
-
*
|
|
68
|
-
* Note: Pagination uses holder address as cursor because totalBalance (BigInt) values
|
|
69
|
-
* cannot be reliably passed through JSON-RPC filters. This means pagination boundaries
|
|
70
|
-
* are based on holder addresses, not balances.
|
|
71
|
-
*
|
|
72
|
-
* @param groupAddress - The address of the group token
|
|
73
|
-
* @param limit - Number of holders per page (default: 100)
|
|
74
|
-
* @returns PagedQuery instance for iterating through group token holders
|
|
75
|
-
*
|
|
76
|
-
* @example
|
|
77
|
-
* ```typescript
|
|
78
|
-
* const query = rpc.group.getGroupHolders('0xGroupAddress...', 50);
|
|
79
|
-
*
|
|
80
|
-
* // Get first page (ordered by totalBalance DESC)
|
|
81
|
-
* await query.queryNextPage();
|
|
82
|
-
* console.log(query.currentPage.results[0]); // Holder with highest balance
|
|
83
|
-
*
|
|
84
|
-
* // Get next page if available
|
|
85
|
-
* if (query.currentPage.hasMore) {
|
|
86
|
-
* await query.queryNextPage();
|
|
87
|
-
* }
|
|
59
|
+
* console.log(memberships);
|
|
88
60
|
* ```
|
|
89
61
|
*/
|
|
90
|
-
|
|
62
|
+
getGroupMemberships(avatar: Address, limit?: number, cursor?: string | null): Promise<PagedResponse<GroupMembershipRow>>;
|
|
91
63
|
/**
|
|
92
|
-
* Get members of a group
|
|
64
|
+
* Get members of a group
|
|
93
65
|
*
|
|
94
|
-
*
|
|
95
|
-
* using cursor-based pagination.
|
|
66
|
+
* Uses the native RPC method for efficient server-side queries.
|
|
67
|
+
* Fetches all results using cursor-based pagination up to the specified limit.
|
|
96
68
|
*
|
|
97
|
-
* @param groupAddress -
|
|
98
|
-
* @param limit -
|
|
99
|
-
* @
|
|
100
|
-
* @returns PagedQuery instance for iterating through group members
|
|
69
|
+
* @param groupAddress - Group address to query members for
|
|
70
|
+
* @param limit - Maximum number of members to return (default: 100)
|
|
71
|
+
* @returns Array of group membership rows (members of the group)
|
|
101
72
|
*
|
|
102
73
|
* @example
|
|
103
74
|
* ```typescript
|
|
104
|
-
* const
|
|
105
|
-
*
|
|
106
|
-
* // Get first page
|
|
107
|
-
* await query.queryNextPage();
|
|
108
|
-
* console.log(query.currentPage.results);
|
|
109
|
-
*
|
|
110
|
-
* // Get next page if available
|
|
111
|
-
* if (query.currentPage.hasMore) {
|
|
112
|
-
* await query.queryNextPage();
|
|
113
|
-
* console.log(query.currentPage.results);
|
|
114
|
-
* }
|
|
75
|
+
* const members = await rpc.group.getGroupMembers('0xGroupAddress...', 100);
|
|
76
|
+
* console.log(`Group has ${members.length} members`);
|
|
115
77
|
* ```
|
|
116
78
|
*/
|
|
117
|
-
getGroupMembers(groupAddress: Address, limit?: number,
|
|
79
|
+
getGroupMembers(groupAddress: Address, limit?: number, cursor?: string | null): Promise<PagedResponse<GroupMembershipRow>>;
|
|
118
80
|
/**
|
|
119
81
|
* Get groups using cursor-based pagination
|
|
120
82
|
*
|
|
@@ -141,5 +103,13 @@ export declare class GroupMethods {
|
|
|
141
103
|
* ```
|
|
142
104
|
*/
|
|
143
105
|
getGroups(limit?: number, params?: GroupQueryParams, sortOrder?: 'ASC' | 'DESC'): PagedQuery<GroupRow>;
|
|
106
|
+
/**
|
|
107
|
+
* Get holders of a group token
|
|
108
|
+
*
|
|
109
|
+
* @param groupAddress - Group address (which is also the token address)
|
|
110
|
+
* @param limit - Maximum number of holders to return (default: 100)
|
|
111
|
+
* @returns PagedQuery instance for iterating through holders
|
|
112
|
+
*/
|
|
113
|
+
getGroupHolders(groupAddress: Address, limit?: number): PagedQuery<GroupTokenHolderRow>;
|
|
144
114
|
}
|
|
145
115
|
//# sourceMappingURL=group.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"group.d.ts","sourceRoot":"","sources":["../../src/methods/group.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"group.d.ts","sourceRoot":"","sources":["../../src/methods/group.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,KAAK,EACV,OAAO,EACP,QAAQ,EACR,kBAAkB,EAClB,gBAAgB,EAEhB,aAAa,EACd,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAEvD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C;;GAEG;AACH,qBAAa,YAAY;IACX,OAAO,CAAC,MAAM;gBAAN,MAAM,EAAE,SAAS;IAErC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA8BG;IACG,UAAU,CACd,KAAK,GAAE,MAAW,EAClB,MAAM,CAAC,EAAE,gBAAgB,EACzB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GACrB,OAAO,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;IA6BnC;;;;;;;;;;;;;;;;;;OAkBG;IACG,mBAAmB,CACvB,MAAM,EAAE,OAAO,EACf,KAAK,GAAE,MAAW,EAClB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GACrB,OAAO,CAAC,aAAa,CAAC,kBAAkB,CAAC,CAAC;IAa7C;;;;;;;;;;;;;;;OAeG;IACG,eAAe,CACnB,YAAY,EAAE,OAAO,EACrB,KAAK,GAAE,MAAY,EACnB,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GACrB,OAAO,CAAC,aAAa,CAAC,kBAAkB,CAAC,CAAC;IAa7C;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH,SAAS,CACP,KAAK,GAAE,MAAW,EAClB,MAAM,CAAC,EAAE,gBAAgB,EACzB,SAAS,GAAE,KAAK,GAAG,MAAe,GACjC,UAAU,CAAC,QAAQ,CAAC;IAkJvB;;;;;;OAMG;IACH,eAAe,CACb,YAAY,EAAE,OAAO,EACrB,KAAK,GAAE,MAAY,GAClB,UAAU,CAAC,mBAAmB,CAAC;CAiCnC"}
|