@aboutcircles/sdk-rpc 0.1.16 → 0.1.18
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/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
function i(J){return J&&typeof J==="object"&&typeof J.$event==="string"&&typeof J.blockNumber==="number"&&typeof J.transactionIndex==="number"&&typeof J.logIndex==="number"}var n=(J)=>BigInt(J),I=(J)=>parseInt(J,16),DJ=(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 PJ(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 DJ(Z);try{return n(Z)}catch{return Z}}try{let G=I(Z);if(G<Number.MAX_SAFE_INTEGER)return G;return n(Z)}catch{return Z}}if(Z==="true")return!0;if(Z==="false")return!1;return Z}function f(J){let{event:Z,values:$}=J,G={$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[Y,W]of Object.entries($)){if(["blockNumber","timestamp","transactionIndex","logIndex","transactionHash"].includes(Y))continue;G[Y]=PJ(Y,W)}return G}function x(J){return J.map(f)}class O{_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 O;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 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 A{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)=>{x(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-$,s=(J,Z,$)=>Z<<$|J>>>32-$,r=(J,Z,$)=>Z<<$-32|J>>>64-$,e=(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 y(J){if(!Number.isSafeInteger(J)||J<0)throw Error("positive integer expected, got "+J)}function L(J,...Z){if(!IJ(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){L(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 LJ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function zJ(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]=zJ(J[Z]);return J}var p=LJ?(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 L(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),z=BigInt(1),TJ=BigInt(2),EJ=BigInt(7),SJ=BigInt(256),HJ=BigInt(113),WJ=[],KJ=[],QJ=[];for(let J=0,Z=z,$=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<<z^(Z>>EJ)*HJ)%SJ,Z&TJ)Y^=z<<(z<<BigInt(W))-z;QJ.push(Y)}var MJ=t(QJ,!0),kJ=MJ[0],wJ=MJ[1],GJ=(J,Z,$)=>$>32?r(J,Z,$):a(J,Z,$),YJ=(J,Z,$)=>$>32?e(J,Z,$):s(J,Z,$);function CJ(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 P=0;P<50;P+=10)J[K+P]^=d,J[K+P+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]^=wJ[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),CJ(this.state32,this.rounds),p(this.state32),this.posOut=0,this.pos=0}update(J){h(this),J=u(J),L(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),L(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 xJ(J){return J.map((Z)=>Q(Z))}function AJ(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 AJ(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 F(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[$]=F(G);else if(Array.isArray(G))Z[$]=G.map((Y)=>typeof Y==="object"&&Y!==null?F(Y):Y);else Z[$]=G}return Z}var VZ=BigInt(96)*BigInt(1000000000000000000),jJ=BigInt("9999999999999999999999999999999999999");class _{client;constructor(J){this.client=J}async findPath(J){let Z=XJ(J),$=await this.client.call("circlesV2_findPath",[Z]),G=F($);return V(G)}async findMaxFlow(J){let Z=await this.findPath({...J,targetFlow:jJ});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 j{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 j(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 D{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 D.circlesToAttoCircles($)}async getTokenBalances(J){let $=(await this.client.call("circles_getTokenBalances",[Q(J)])).map((G)=>F(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)=>F(Y));return V(G)}getTokenHolders(J,Z=100,$="DESC"){let G=Q(J);return new j(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((P)=>Q(P.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=D.attoCirclesToCircles($),Y=D.attoCirclesToAttoCrc($,BigInt(Z)),W=D.attoCirclesToCircles(Y),K=D.attoCirclesToAttoStaticCircles($,BigInt(Z)),M=D.attoCirclesToCircles(K);return{attoCircles:$,circles:G,staticAttoCircles:K,staticCircles:M,attoCrc:Y,crc:W}}class w{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 j(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 C{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 j(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 j(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 j(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 j(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 FJ{client;_pathfinder;_query;_trust;_balance;_avatar;_profile;_token;_invitation;_transaction;_group;constructor(J="https://rpc.circlesubi.network/"){this.client=new A(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 w(this.client);return this._transaction}get group(){if(!this._group)this._group=new C(this.client);return this._group}setRpcUrl(J){this.client.setRpcUrl(J)}getRpcUrl(){return this.client.getRpcUrl()}}export{F as parseStringsToBigInt,x as parseRpcSubscriptionMessage,f as parseRpcEvent,xJ as normalizeAddresses,Q as normalizeAddress,i as isCirclesEvent,R as TrustMethods,w as TransactionMethods,H as TokenMethods,X as RpcError,A as RpcClient,B as QueryMethods,S as ProfileMethods,_ as PathfinderMethods,j as PagedQuery,O as Observable,k as InvitationMethods,C as GroupMethods,FJ as CirclesRpc,T as BalanceMethods,E as AvatarMethods};
|
|
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 A{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)=>{x(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-$,s=(J,Z,$)=>Z<<$|J>>>32-$,r=(J,Z,$)=>Z<<$-32|J>>>64-$,e=(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 y(J){if(!Number.isSafeInteger(J)||J<0)throw Error("positive integer expected, got "+J)}function L(J,...Z){if(!IJ(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){L(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 LJ=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function zJ(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]=zJ(J[Z]);return J}var p=LJ?(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 L(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),z=BigInt(1),TJ=BigInt(2),EJ=BigInt(7),SJ=BigInt(256),HJ=BigInt(113),WJ=[],KJ=[],QJ=[];for(let J=0,Z=z,$=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<<z^(Z>>EJ)*HJ)%SJ,Z&TJ)Y^=z<<(z<<BigInt(W))-z;QJ.push(Y)}var MJ=t(QJ,!0),wJ=MJ[0],kJ=MJ[1],GJ=(J,Z,$)=>$>32?r(J,Z,$):a(J,Z,$),YJ=(J,Z,$)=>$>32?e(J,Z,$):s(J,Z,$);function CJ(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 P=0;P<50;P+=10)J[K+P]^=d,J[K+P+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]^=wJ[G],J[1]^=kJ[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),CJ(this.state32,this.rounds),p(this.state32),this.posOut=0,this.pos=0}update(J){h(this),J=u(J),L(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),L(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 xJ(J){return J.map((Z)=>Q(Z))}function AJ(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 AJ(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 F(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[$]=F(G);else if(Array.isArray(G))Z[$]=G.map((Y)=>typeof Y==="object"&&Y!==null?F(Y):Y);else Z[$]=G}return Z}var VZ=BigInt(96)*BigInt(1000000000000000000),jJ=BigInt("9999999999999999999999999999999999999");class _{client;constructor(J){this.client=J}async findPath(J){let Z=XJ(J),$=await this.client.call("circlesV2_findPath",[Z]),G=F($);return V(G)}async findMaxFlow(J){let Z=await this.findPath({...J,targetFlow:jJ});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 j{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 j(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 D{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 D.circlesToAttoCircles($)}async getTokenBalances(J){let $=(await this.client.call("circles_getTokenBalances",[Q(J)])).map((G)=>F(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)=>F(Y));return V(G)}getTokenHolders(J,Z=100,$="DESC"){let G=Q(J);return new j(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 w{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((P)=>Q(P.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=D.attoCirclesToCircles($),Y=D.attoCirclesToAttoCrc($,BigInt(Z)),W=D.attoCirclesToCircles(Y),K=D.attoCirclesToAttoStaticCircles($,BigInt(Z)),M=D.attoCirclesToCircles(K);return{attoCircles:$,circles:G,staticAttoCircles:K,staticCircles:M,attoCrc:Y,crc:W}}class k{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 j(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 C{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 j(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 j(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 j(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 j(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 FJ{client;_pathfinder;_query;_trust;_balance;_avatar;_profile;_token;_invitation;_transaction;_group;constructor(J="https://rpc.circlesubi.network/"){this.client=new A(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 w(this.client);return this._invitation}get transaction(){if(!this._transaction)this._transaction=new k(this.client);return this._transaction}get group(){if(!this._group)this._group=new C(this.client);return this._group}setRpcUrl(J){this.client.setRpcUrl(J)}getRpcUrl(){return this.client.getRpcUrl()}}export{F as parseStringsToBigInt,x as parseRpcSubscriptionMessage,f as parseRpcEvent,xJ as normalizeAddresses,Q as normalizeAddress,i as isCirclesEvent,R as TrustMethods,k as TransactionMethods,H as TokenMethods,X as RpcError,A as RpcClient,B as QueryMethods,S as ProfileMethods,_ as PathfinderMethods,j as PagedQuery,O as Observable,w as InvitationMethods,C as GroupMethods,FJ as CirclesRpc,T as BalanceMethods,E as AvatarMethods};
|