@aboutcircles/sdk-pathfinder 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/index.js +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
Context: ${JSON.stringify(this.context,null,2)}`;return z}}class P extends i{constructor(z,j){super("RpcError",z,{...j,source:j?.source??"RPC_REQUEST"})}static connectionFailed(z,j){return new P("Failed to connect to RPC endpoint",{code:"RPC_CONNECTION_FAILED",source:"RPC_CONNECTION",cause:j,context:{url:z}})}static timeout(z,j){return new P("RPC request timed out",{code:"RPC_TIMEOUT",source:"RPC_TIMEOUT",context:{method:z,timeout:j}})}static invalidResponse(z,j){return new P("Invalid RPC response",{code:"RPC_INVALID_RESPONSE",source:"RPC_RESPONSE",context:{method:z,response:j}})}static fromJsonRpcError(z){return new P(z.message,{code:z.code,source:"RPC_RESPONSE",context:{data:z.data}})}static websocketError(z,j){return new P(z,{code:"RPC_WEBSOCKET_ERROR",source:"RPC_WEBSOCKET",cause:j})}}class s{rpcUrl;requestId=0;websocket=null;websocketConnected=!1;pendingResponses={};subscriptionListeners={};reconnectAttempt=0;initialBackoff=2000;maxBackoff=120000;constructor(z){this.rpcUrl=z}async call(z,j){this.requestId++;let B={jsonrpc:"2.0",id:this.requestId,method:z,params:j};try{let R=await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!R.ok)throw P.connectionFailed(this.rpcUrl,Error(`HTTP ${R.status}: ${R.statusText}`));let O=await R.json();if(O.error)throw P.fromJsonRpcError(O.error);if(O.result===void 0)throw P.invalidResponse(z,O);return O.result}catch(R){if(R instanceof P)throw R;throw P.connectionFailed(this.rpcUrl,R)}}setRpcUrl(z){this.rpcUrl=z}getRpcUrl(){return this.rpcUrl}connect(){return new Promise((z)=>{let j=this.rpcUrl.replace("http","ws");if(j.endsWith("/"))j+="ws";else j+="/ws";this.websocket=new WebSocket(j),this.websocket.onopen=()=>{console.log("WebSocket connected"),this.websocketConnected=!0,this.reconnectAttempt=0,z()},this.websocket.onmessage=(B)=>{let R=JSON.parse(B.data),{id:O,method:_,params:H}=R;if(O!==void 0&&this.pendingResponses[O])this.pendingResponses[O].resolve(R),delete this.pendingResponses[O];if(_==="eth_subscription"&&H){let{subscription:L,result:D}=H;if(this.subscriptionListeners[L])this.subscriptionListeners[L].forEach((F)=>F(D))}},this.websocket.onclose=()=>{console.warn("WebSocket closed"),this.websocketConnected=!1},this.websocket.onerror=(B)=>{console.error("WebSocket error:",B),this.websocketConnected=!1,this.scheduleReconnect()}})}scheduleReconnect(){let z=Math.min(this.initialBackoff*Math.pow(2,this.reconnectAttempt),this.maxBackoff),j=z*(Math.random()*0.5),B=z+j;console.log(`Reconnecting in ${Math.round(B)}ms (attempt #${this.reconnectAttempt+1})`),this.reconnectAttempt++,setTimeout(()=>{this.reconnect()},B)}async reconnect(){if(this.websocketConnected)return;try{await this.connect(),console.log("Reconnection successful")}catch(z){console.error("Reconnection attempt failed:",z),this.scheduleReconnect()}}sendMessage(z,j,B=5000){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return Promise.reject(P.connectionFailed(this.rpcUrl));let R=this.requestId++,O={jsonrpc:"2.0",method:z,params:j,id:R};return new Promise((_,H)=>{this.pendingResponses[R]={resolve:_,reject:H},this.websocket.send(JSON.stringify(O)),setTimeout(()=>{if(this.pendingResponses[R])this.pendingResponses[R].reject(P.timeout(z,B)),delete this.pendingResponses[R]},B)})}async subscribe(z){let j=z?.toLowerCase();if(!this.websocketConnected)await this.connect();let B=w.create(),R=JSON.stringify(j?{address:j}:{}),O=(await this.sendMessage("eth_subscribe",["circles",R])).result;if(!this.subscriptionListeners[O])this.subscriptionListeners[O]=[];return this.subscriptionListeners[O].push((_)=>{P1(_).forEach((H)=>B.emit(H))}),B.property}}var I=BigInt(4294967295),Y=BigInt(32);function q1(z,j=!1){if(j)return{h:Number(z&I),l:Number(z>>Y&I)};return{h:Number(z>>Y&I)|0,l:Number(z&I)|0}}function U1(z,j=!1){let B=z.length,R=new Uint32Array(B),O=new Uint32Array(B);for(let _=0;_<B;_++){let{h:H,l:L}=q1(z[_],j);[R[_],O[_]]=[H,L]}return[R,O]}var V1=(z,j,B)=>z<<B|j>>>32-B,X1=(z,j,B)=>j<<B|z>>>32-B,A1=(z,j,B)=>j<<B-32|z>>>64-B,T1=(z,j,B)=>z<<B-32|j>>>64-B;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function y1(z){return z instanceof Uint8Array||ArrayBuffer.isView(z)&&z.constructor.name==="Uint8Array"}function l(z){if(!Number.isSafeInteger(z)||z<0)throw Error("positive integer expected, got "+z)}function k(z,...j){if(!y1(z))throw Error("Uint8Array expected");if(j.length>0&&!j.includes(z.length))throw Error("Uint8Array expected of length "+j+", got length="+z.length)}function p(z,j=!0){if(z.destroyed)throw Error("Hash instance has been destroyed");if(j&&z.finished)throw Error("Hash#digest() has already been called")}function Q1(z,j){k(z);let B=j.outputLen;if(z.length<B)throw Error("digestInto() expects output buffer of length at least "+B)}function S1(z){return new Uint32Array(z.buffer,z.byteOffset,Math.floor(z.byteLength/4))}function d(...z){for(let j=0;j<z.length;j++)z[j].fill(0)}var v1=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function I1(z){return z<<24&4278190080|z<<8&16711680|z>>>8&65280|z>>>24&255}function k1(z){for(let j=0;j<z.length;j++)z[j]=I1(z[j]);return z}var G=v1?(z)=>z:k1;function g1(z){if(typeof z!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(z))}function n(z){if(typeof z==="string")z=g1(z);return k(z),z}class o{}function w1(z){let j=(R)=>z().update(n(R)).digest(),B=z();return j.outputLen=B.outputLen,j.blockLen=B.blockLen,j.create=()=>z(),j}var M1=BigInt(0),Q=BigInt(1),h1=BigInt(2),b1=BigInt(7),W1=BigInt(256),m1=BigInt(113),a=[],Z=[],t=[];for(let z=0,j=Q,B=1,R=0;z<24;z++){[B,R]=[R,(2*B+3*R)%5],a.push(2*(5*R+B)),Z.push((z+1)*(z+2)/2%64);let O=M1;for(let _=0;_<7;_++)if(j=(j<<Q^(j>>b1)*m1)%W1,j&h1)O^=Q<<(Q<<BigInt(_))-Q;t.push(O)}var r=U1(t,!0),K1=r[0],u1=r[1],c=(z,j,B)=>B>32?A1(z,j,B):V1(z,j,B),$=(z,j,B)=>B>32?T1(z,j,B):X1(z,j,B);function f1(z,j=24){let B=new Uint32Array(10);for(let R=24-j;R<24;R++){for(let H=0;H<10;H++)B[H]=z[H]^z[H+10]^z[H+20]^z[H+30]^z[H+40];for(let H=0;H<10;H+=2){let L=(H+8)%10,D=(H+2)%10,F=B[D],E=B[D+1],X=c(F,E,1)^B[L],A=$(F,E,1)^B[L+1];for(let T=0;T<50;T+=10)z[H+T]^=X,z[H+T+1]^=A}let O=z[2],_=z[3];for(let H=0;H<24;H++){let L=Z[H],D=c(O,_,L),F=$(O,_,L),E=a[H];O=z[E],_=z[E+1],z[E]=D,z[E+1]=F}for(let H=0;H<50;H+=10){for(let L=0;L<10;L++)B[L]=z[H+L];for(let L=0;L<10;L++)z[H+L]^=~B[(L+2)%10]&B[(L+4)%10]}z[0]^=K1[R],z[1]^=u1[R]}d(B)}class M extends o{constructor(z,j,B,R=!1,O=24){super();if(this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=z,this.suffix=j,this.outputLen=B,this.enableXOF=R,this.rounds=O,l(B),!(0<z&&z<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=S1(this.state)}clone(){return this._cloneInto()}keccak(){G(this.state32),f1(this.state32,this.rounds),G(this.state32),this.posOut=0,this.pos=0}update(z){p(this),z=n(z),k(z);let{blockLen:j,state:B}=this,R=z.length;for(let O=0;O<R;){let _=Math.min(j-this.pos,R-O);for(let H=0;H<_;H++)B[this.pos++]^=z[O++];if(this.pos===j)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:z,suffix:j,pos:B,blockLen:R}=this;if(z[B]^=j,(j&128)!==0&&B===R-1)this.keccak();z[R-1]^=128,this.keccak()}writeInto(z){p(this,!1),k(z),this.finish();let j=this.state,{blockLen:B}=this;for(let R=0,O=z.length;R<O;){if(this.posOut>=B)this.keccak();let _=Math.min(B-this.posOut,O-R);z.set(j.subarray(this.posOut,this.posOut+_),R),this.posOut+=_,R+=_}return z}xofInto(z){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(z)}xof(z){return l(z),this.xofInto(new Uint8Array(z))}digestInto(z){if(Q1(z,this),this.finished)throw Error("digest() was already called");return this.writeInto(z),this.destroy(),z}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,d(this.state)}_cloneInto(z){let{blockLen:j,suffix:B,outputLen:R,rounds:O,enableXOF:_}=this;return z||(z=new M(j,B,R,_,O)),z.state32.set(this.state32),z.pos=this.pos,z.posOut=this.posOut,z.finished=this.finished,z.rounds=O,z.suffix=B,z.outputLen=R,z.enableXOF=_,z.destroyed=this.destroyed,z}}var x1=(z,j,B)=>w1(()=>new M(j,z,B)),Y1=(()=>x1(1,136,32))(),e=[];for(let z=0;z<256;z++)e[z]=z.toString(16).padStart(2,"0");function l1(z){let j="0x";for(let B=0;B<z.length;B++)j+=e[z[B]];return j}function p1(z){let j=z.toLowerCase().replace("0x",""),B=l1(Y1(new TextEncoder().encode(j))).slice(2),R="0x";for(let O=0;O<j.length;O++)R+=parseInt(B[O],16)>=8?j[O].toUpperCase():j[O];return R}function C(z){return z.toLowerCase()}function G1(z){return p1(z)}function c1(z){if(typeof z!=="string")return!1;let j=z.replace("0x","");return j.length===40&&/^[0-9a-fA-F]{40}$/.test(j)}function N(z){if(z===null||z===void 0)return z;if(c1(z))return G1(z);if(Array.isArray(z))return z.map((j)=>N(j));if(typeof z==="object"&&z!==null){let j={};for(let B in z)if(Object.prototype.hasOwnProperty.call(z,B))j[B]=N(z[B]);return j}return z}function $1(z){return{Source:C(z.from),Sink:C(z.to),TargetFlow:z.targetFlow.toString(),WithWrap:z.useWrappedBalances,FromTokens:z.fromTokens?.map(C),ToTokens:z.toTokens?.map(C),ExcludedFromTokens:z.excludeFromTokens?.map(C),ExcludedToTokens:z.excludeToTokens?.map(C),SimulatedBalances:z.simulatedBalances?.map((j)=>({Holder:C(j.holder),Token:C(j.token),Amount:j.amount.toString(),IsWrapped:j.isWrapped,IsStatic:j.isStatic})),SimulatedTrusts:z.simulatedTrusts?.map((j)=>({Truster:C(j.truster),Trustee:C(j.trustee)})),MaxTransfers:z.maxTransfers}}function v(z){let j={};for(let B in z){let R=z[B];if(R===null||R===void 0)j[B]=R;else if(typeof R==="string"&&/^\d+$/.test(R))j[B]=BigInt(R);else if(typeof R==="object"&&!Array.isArray(R))j[B]=v(R);else if(Array.isArray(R))j[B]=R.map((O)=>typeof O==="object"&&O!==null?v(O):O);else j[B]=R}return j}var O3=BigInt(96)*BigInt(1000000000000000000),i1=BigInt("9999999999999999999999999999999999999");class J{client;constructor(z){this.client=z}async findPath(z){let j=$1(z),B=await this.client.call("circlesV2_findPath",[j]),R=v(B);return N(R)}async findMaxFlow(z){let j=await this.findPath({...z,targetFlow:i1});return BigInt(j.maxFlow)}}class z1{client;constructor(z){this.client=z}async query(z){let j=await this.client.call("circles_query",[z]);return N(j)}async tables(){return this.client.call("circles_tables",[])}async events(z,j,B=null,R=null,O=!1){let _=await this.client.call("circles_events",[z,j,B,R,O]);return N(_)}}var s1=[{name:"blockNumber",sortOrder:"DESC"},{name:"transactionIndex",sortOrder:"DESC"},{name:"logIndex",sortOrder:"DESC"}];class U{params;client;rowTransformer;cursorColumns;orderColumns;get currentPage(){return this._currentPage}_currentPage;constructor(z,j,B){this.client=z,this.params=j,this.rowTransformer=B||j.rowTransformer,this.orderColumns=j.orderColumns,this.cursorColumns=j.cursorColumns||this.buildEventCursorColumns()}buildEventCursorColumns(){let z=s1.map((j)=>({...j,sortOrder:this.params.sortOrder}));if(this.params.table==="TransferBatch")z.push({name:"batchIndex",sortOrder:this.params.sortOrder});return z}transformCursorValue(z,j){if(j)return j(z);if(typeof z==="bigint")return z.toString();return z}createEqualityPredicate(z,j){return{Type:"FilterPredicate",FilterType:"Equals",Column:z.name,Value:this.transformCursorValue(j,z.toValue)}}createComparisonPredicate(z,j){return{Type:"FilterPredicate",FilterType:z.sortOrder==="ASC"?"GreaterThan":"LessThan",Column:z.name,Value:this.transformCursorValue(j,z.toValue)}}buildCursorFilter(z){if(!z)return[];let j=[];for(let B=0;B<this.cursorColumns.length;B++){let R=this.cursorColumns[B],O=z[R.name];if(O===void 0)continue;if(B===0)j.push(this.createComparisonPredicate(R,O));else{let _=[];for(let H=0;H<B;H++){let L=this.cursorColumns[H],D=z[L.name];if(D!==void 0)_.push(this.createEqualityPredicate(L,D))}_.push(this.createComparisonPredicate(R,O)),j.push({Type:"Conjunction",ConjunctionType:"And",Predicates:_})}}if(j.length===0)return[];return[{Type:"Conjunction",ConjunctionType:"Or",Predicates:j}]}buildOrderBy(){if(this.orderColumns&&this.orderColumns.length>0)return this.orderColumns;return this.cursorColumns.map((z)=>({Column:z.name,SortOrder:z.sortOrder}))}combineFilters(z,j){if(!z?.length&&!j?.length)return[];if(!z?.length)return j||[];if(!j?.length)return z;return[{Type:"Conjunction",ConjunctionType:"And",Predicates:[...z,...j]}]}rowsToObjects(z){let{columns:j,rows:B}=z;return B.map((R)=>{let O={};return j.forEach((_,H)=>{O[_]=R[H]}),this.rowTransformer?this.rowTransformer(O):O})}rowToCursor(z){let j={};for(let B of this.cursorColumns)j[B.name]=z[B.name];return j}getCursors(z){if(z.length===0)return{};return{first:this.rowToCursor(z[0]),last:this.rowToCursor(z[z.length-1])}}async queryNextPage(){let z=this.buildCursorFilter(this._currentPage?.lastCursor),j=this.combineFilters(this.params.filter,z),B={Namespace:this.params.namespace,Table:this.params.table,Columns:this.params.columns,Filter:j,Order:this.buildOrderBy(),Limit:this.params.limit},R=await this.client.call("circles_query",[B]),O=this.rowsToObjects(R),_=this.getCursors(O);return this._currentPage={limit:this.params.limit,size:O.length,firstCursor:_.first,lastCursor:_.last,sortOrder:this.params.sortOrder,hasMore:O.length===this.params.limit,results:O},O.length>0}reset(){this._currentPage=void 0}}class j1{client;constructor(z){this.client=z}transformQueryResponse(z){let{columns:j,rows:B}=z;return B.map((R)=>{let O={};return j.forEach((_,H)=>{O[_]=R[H]}),O})}async getCommonTrust(z,j){let B=await this.client.call("circles_getCommonTrust",[C(z),C(j)]);return N(B)}getTrustRelations(z,j=100,B="DESC"){let R=C(z),O=[{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:R},{Type:"FilterPredicate",FilterType:"Equals",Column:"truster",Value:R}]}]}];return new U(this.client,{namespace:"V_Crc",table:"TrustRelations",sortOrder:B,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","version","trustee","truster","expiryTime"],filter:O,limit:j},(_)=>N(_))}async getAggregatedTrustRelations(z){let j=C(z),B=this.getTrustRelations(j,1000),R=[];while(await B.queryNextPage())if(R.push(...B.currentPage.results),!B.currentPage.hasMore)break;let O={};R.forEach((H)=>{let L=C(H.truster),D=C(H.trustee),F=L!==j?H.truster:H.trustee;if(!O[F])O[F]=[];O[F].push(H)});let _=Object.entries(O).filter(([H])=>C(H)!==j).map(([H,L])=>{let D=Math.max(...L.map((E)=>E.timestamp)),F;if(L.length===2)F="mutuallyTrusts";else if(C(L[0]?.trustee)===j)F="trustedBy";else if(C(L[0]?.truster)===j)F="trusts";else throw Error("Unexpected trust list row. Couldn't determine trust relation.");return{subjectAvatar:j,relation:F,objectAvatar:H,timestamp:D}});return N(_)}async getTrustedBy(z){let j=C(z),B=(await this.getAggregatedTrustRelations(j)).filter((R)=>R.relation==="trustedBy");return N(B)}async getTrusts(z){let j=C(z),B=(await this.getAggregatedTrustRelations(j)).filter((R)=>R.relation==="trusts");return N(B)}async getMutualTrusts(z){let j=C(z),B=(await this.getAggregatedTrustRelations(j)).filter((R)=>R.relation==="mutuallyTrusts");return N(B)}}class V{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(z,j){return z*j>>64n}static mulU(z,j){return z*j>>64n}static pow64(z,j){let B=z,R=j,O=this.ONE_64;while(R>0n){if((R&1n)===1n)O=this.mul64(O,B);B=this.mul64(B,B),R>>=1n}return O}static ONE_36=1000000000000000000000000000000000000000n;static GAMMA_36=999801332008598957430613406568191166n;static BETA_36=1000198707468214629156271489013303962n;static mul36(z,j){return z*j/this.ONE_36}static pow36(z,j){let B=this.ONE_36,R=z,O=j;while(O>0n){if((O&1n)===1n)B=this.mul36(B,R);R=this.mul36(R,R),O>>=1n}return B}static attoCirclesToCircles(z){if(z===0n)return 0;let j=z/this.ATTO_FACTOR,B=z%this.ATTO_FACTOR,R=BigInt(Number.MAX_SAFE_INTEGER);if(j>R||j<-R)throw RangeError("Atto value’s integer component exceeds JS double precision.");return Number(j)+Number(B)/Number(this.ATTO_FACTOR)}static circlesToAttoCircles(z){return BigInt(Math.trunc(z*Number(this.ATTO_FACTOR)))}static inflationaryToDemurrage(z,j){return this.mulU(this.pow64(this.GAMMA_64,j),z)}static demurrageToInflationary(z,j){return this.mulU(this.pow64(this.BETA_64,j),z)}static dayFromTimestamp(z){return(z-this.INFLATION_DAY_ZERO_UNIX)/this.SECONDS_PER_DAY}static attoCirclesToAttoStaticCircles(z,j=BigInt(Math.floor(Date.now()/1000))){return this.demurrageToInflationary(z,this.dayFromTimestamp(j))}static attoStaticCirclesToAttoCircles(z,j=BigInt(Math.floor(Date.now()/1000))){return this.inflationaryToDemurrage(z,this.dayFromTimestamp(j))}static inflationaryToDemurrageExact(z,j){let B=this.pow36(this.GAMMA_36,j);return z*B/this.ONE_36}static demurrageToInflationaryExact(z,j){let B=this.pow36(this.BETA_36,j);return z*B/this.ONE_36}static attoCirclesToAttoStaticCirclesExact(z,j=BigInt(Math.floor(Date.now()/1000))){let B=this.dayFromTimestamp(j);return this.demurrageToInflationaryExact(z,B)}static attoStaticCirclesToAttoCirclesExact(z,j=BigInt(Math.floor(Date.now()/1000))){let B=this.dayFromTimestamp(j);return this.inflationaryToDemurrageExact(z,B)}static truncateToInt64(z){let j=z/this.FACTOR_1E12,B=9223372036854775807n;return j>B?B:j}static blowUpToBigInt(z){return z*this.FACTOR_1E12}static truncateToSixDecimals(z){return this.blowUpToBigInt(this.truncateToInt64(z))}static v1InflateFactor(z){if(z===0n)return this.V1_ACCURACY;return this.V1_ACCURACY*this.V1_INFLATION_PCT_NUM**z/this.V1_INFLATION_PCT_DEN**z}static attoCrcToAttoCircles(z,j){let B=j-this.INFLATION_DAY_ZERO_UNIX,R=B/this.PERIOD_SEC,O=B%this.PERIOD_SEC,_=this.v1InflateFactor(R),H=this.v1InflateFactor(R+1n);return this.v1ToDemurrage(z,_,H,O,this.PERIOD_SEC)}static attoCirclesToAttoCrc(z,j){let B=j-this.INFLATION_DAY_ZERO_UNIX,R=B/this.PERIOD_SEC,O=B%this.PERIOD_SEC,_=this.v1InflateFactor(R),H=this.v1InflateFactor(R+1n),L=_*(this.PERIOD_SEC-O)+H*O;return z*3n*this.V1_ACCURACY*this.PERIOD_SEC/L}static v1ToDemurrage(z,j,B,R,O){let _=j*(O-R)+B*R;return z*3n*this.V1_ACCURACY*O/_}}class B1{client;constructor(z){this.client=z}async getTotalBalance(z,j=!0){let B=await this.client.call("circlesV2_getTotalBalance",[C(z),j]);return V.circlesToAttoCircles(B)}async getTokenBalances(z){let j=(await this.client.call("circles_getTokenBalances",[C(z)])).map((B)=>v(B));return N(j)}}class R1{client;constructor(z){this.client=z}async getAvatarInfo(z){let j=await this.getAvatarInfoBatch([z]);return j.length>0?j[0]:void 0}async getAvatarInfoBatch(z){if(z.length===0)return[];let j=z.map((R)=>C(R)),B=await this.client.call("circles_getAvatarInfoBatch",[j]);return N(B)}async getNetworkSnapshot(){let z=await this.client.call("circles_getNetworkSnapshot",[]);return N(z)}}class O1{client;constructor(z){this.client=z}async getProfileByCid(z){return this.client.call("circles_getProfileByCid",[z])}async getProfileByCidBatch(z){return this.client.call("circles_getProfileByCidBatch",[z])}async getProfileByAddress(z){return this.client.call("circles_getProfileByAddress",[C(z)])}async getProfileByAddressBatch(z){return this.client.call("circles_getProfileByAddressBatch",[z.map((j)=>j===null?null:C(j))])}async searchProfiles(z,j=10,B=0,R){return this.client.call("circles_searchProfiles",[z.toLowerCase(),j,B,R])}async searchByAddressOrName(z,j=10,B=0,R){let O=[],_=/^0x[a-fA-F0-9]{40}$/.test(z);if(_)try{let H=await this.getProfileByAddress(z);if(H){let L={...H,address:z};if(!R||!L.avatarType||R.includes(L.avatarType))O.push(L)}}catch(H){console.warn("Failed to get profile by address:",H)}try{let H=await this.searchProfiles(z,j,B,R);if(_&&O.length>0){let L=z.toLowerCase(),D=H.filter((F)=>F.address?.toLowerCase()!==L);O.push(...D)}else O.push(...H)}catch(H){console.warn("Failed to search profiles by text:",H)}return O.slice(0,j)}}class _1{client;constructor(z){this.client=z}async getTokenInfo(z){let j=await this.getTokenInfoBatch([z]);return j.length>0?j[0]:void 0}async getTokenInfoBatch(z){if(z.length===0)return[];let j=z.map((R)=>C(R)),B=(await this.client.call("circles_getTokenInfoBatch",[j])).map((R)=>v(R));return N(B)}getTokenHolders(z,j=100,B="DESC"){let R=C(z);return new U(this.client,{namespace:"V_CrcV2",table:"BalancesByAccountAndToken",columns:["account","tokenAddress","demurragedTotalBalance"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"tokenAddress",Value:R}],cursorColumns:[{name:"demurragedTotalBalance",sortOrder:B},{name:"account",sortOrder:"ASC"}],orderColumns:[{Column:"demurragedTotalBalance",SortOrder:B},{Column:"account",SortOrder:"ASC"}],limit:j,sortOrder:B},(O)=>({account:O.account,tokenAddress:O.tokenAddress,demurragedTotalBalance:O.demurragedTotalBalance}))}}class H1{client;constructor(z){this.client=z}transformQueryResponse(z){let{columns:j,rows:B}=z;return B.map((R)=>{let O={};return j.forEach((_,H)=>{O[_]=R[H]}),O})}async getInvitedBy(z){let j=C(z),B=await this.client.call("circles_query",[{Namespace:"CrcV2",Table:"RegisterHuman",Columns:["inviter"],Filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"avatar",Value:j}],Order:[{Column:"blockNumber",SortOrder:"DESC"}],Limit:1}]);if(B.length>0)return N(B[0].inviter);return}async getInvitations(z){let j=C(z),B=96,R=await this.client.call("circles_getAvatarInfoBatch",[[j]]);if((R.length>0?R[0]:void 0)?.version===2)return[];let O=await this.client.call("circles_query",[{Namespace:"V_Crc",Table:"TrustRelations",Columns:["truster","trustee"],Filter:[{Type:"Conjunction",ConjunctionType:"And",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"version",Value:2},{Type:"FilterPredicate",FilterType:"Equals",Column:"trustee",Value:j}]}],Order:[]}]),_=this.transformQueryResponse(O).map((D)=>D.truster);if(_.length===0)return[];let H=await this.client.call("circles_getAvatarInfoBatch",[_]),L=[];for(let D of H){if(!D?.isHuman)continue;let F=(await this.client.call("circles_getTokenBalances",[D.avatar])).find((E)=>C(E.tokenAddress)===C(D.avatar));if(F&&F.circles>=96)L.push(D)}return N(L)}async getInvitationsFrom(z,j=!1){let B=C(z);if(j){let R=await this.client.call("circles_query",[{Namespace:"CrcV2",Table:"RegisterHuman",Columns:["avatar"],Filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"inviter",Value:B}],Order:[{Column:"blockNumber",SortOrder:"DESC"}]}]),O=this.transformQueryResponse(R).map((_)=>_.avatar);return N(O)}else{let R=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:B}]}],Order:[]}]),O=this.transformQueryResponse(R).map((D)=>D.trustee);if(O.length===0)return[];let _=await this.client.call("circles_getAvatarInfoBatch",[O]),H=new Set(_.filter((D)=>D!==null).map((D)=>C(D.avatar))),L=O.filter((D)=>!H.has(C(D)));return N(L)}}}function d1(z,j){let B=BigInt(z),R=V.attoCirclesToCircles(B),O=V.attoCirclesToAttoCrc(B,BigInt(j)),_=V.attoCirclesToCircles(O),H=V.attoCirclesToAttoStaticCircles(B,BigInt(j)),L=V.attoCirclesToCircles(H);return{attoCircles:B,circles:R,staticAttoCircles:H,staticCircles:L,attoCrc:O,crc:_}}class L1{client;constructor(z){this.client=z}getTransactionHistory(z,j=50,B="DESC"){let R=C(z),O=[{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:R},{Type:"FilterPredicate",FilterType:"Equals",Column:"to",Value:R}]}]}];return new U(this.client,{namespace:"V_Crc",table:"TransferSummary",sortOrder:B,columns:[],filter:O,limit:j},(_)=>{let H=d1(_.value,_.timestamp),L={..._,...H};return N(L)})}}class D1{client;constructor(z){this.client=z}async findGroups(z=50,j){let B=this.getGroups(z,j,"DESC"),R=[];while(await B.queryNextPage()){if(R.push(...B.currentPage.results),R.length>=z)break;if(!B.currentPage.hasMore)break}return R.slice(0,z)}getGroupMemberships(z,j=50,B="DESC"){let R=C(z);return new U(this.client,{namespace:"V_CrcV2",table:"GroupMemberships",sortOrder:B,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","member","expiryTime"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"member",Value:R}],limit:j},(O)=>N(O))}getGroupHolders(z,j=100){let B=C(z);return new U(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:B}],limit:j,rowTransformer:(R)=>{let O={...R,totalBalance:BigInt(R.totalBalance),demurragedTotalBalance:BigInt(R.demurragedTotalBalance)};return N(O)}})}getGroupMembers(z,j=100,B="DESC"){let R=C(z);return new U(this.client,{namespace:"V_CrcV2",table:"GroupMemberships",sortOrder:B,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","member","expiryTime"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:R}],limit:j},(O)=>N(O))}getGroups(z=50,j,B="DESC"){let R=[];if(j){if(j.nameStartsWith)R.push({Type:"FilterPredicate",FilterType:"Like",Column:"name",Value:j.nameStartsWith+"%"});if(j.symbolStartsWith)R.push({Type:"FilterPredicate",FilterType:"Like",Column:"symbol",Value:j.symbolStartsWith+"%"});if(j.groupAddressIn&&j.groupAddressIn.length>0){let _=j.groupAddressIn.map((H)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:C(H)}));if(_.length===1)R.push(_[0]);else R.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:_})}if(j.groupTypeIn&&j.groupTypeIn.length>0){let _=j.groupTypeIn.map((H)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"type",Value:H}));if(_.length===1)R.push(_[0]);else R.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:_})}if(j.ownerIn&&j.ownerIn.length>0){let _=j.ownerIn.map((H)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"owner",Value:C(H)}));if(_.length===1)R.push(_[0]);else R.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:_})}if(j.mintHandlerEquals)R.push({Type:"FilterPredicate",FilterType:"Equals",Column:"mintHandler",Value:C(j.mintHandlerEquals)});if(j.treasuryEquals)R.push({Type:"FilterPredicate",FilterType:"Equals",Column:"treasury",Value:C(j.treasuryEquals)})}let O=R.length>1?[{Type:"Conjunction",ConjunctionType:"And",Predicates:R}]:R;return new U(this.client,{namespace:"V_CrcV2",table:"Groups",sortOrder:B,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","type","owner","mintPolicy","mintHandler","treasury","service","feeCollection","memberCount","name","symbol","cidV0Digest","erc20WrapperDemurraged","erc20WrapperStatic"],filter:O,limit:z},(_)=>N(_))}}class h{client;_pathfinder;_query;_trust;_balance;_avatar;_profile;_token;_invitation;_transaction;_group;constructor(z="https://rpc.circlesubi.network/"){this.client=new s(z)}get pathfinder(){if(!this._pathfinder)this._pathfinder=new J(this.client);return this._pathfinder}get query(){if(!this._query)this._query=new z1(this.client);return this._query}get trust(){if(!this._trust)this._trust=new j1(this.client);return this._trust}get balance(){if(!this._balance)this._balance=new B1(this.client);return this._balance}get avatar(){if(!this._avatar)this._avatar=new R1(this.client);return this._avatar}get profile(){if(!this._profile)this._profile=new O1(this.client);return this._profile}get token(){if(!this._token)this._token=new _1(this.client);return this._token}get invitation(){if(!this._invitation)this._invitation=new H1(this.client);return this._invitation}get transaction(){if(!this._transaction)this._transaction=new L1(this.client);return this._transaction}get group(){if(!this._group)this._group=new D1(this.client);return this._group}setRpcUrl(z){this.client.setRpcUrl(z)}getRpcUrl(){return this.client.getRpcUrl()}}class b{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(z,j){return z*j>>64n}static mulU(z,j){return z*j>>64n}static pow64(z,j){let B=z,R=j,O=this.ONE_64;while(R>0n){if((R&1n)===1n)O=this.mul64(O,B);B=this.mul64(B,B),R>>=1n}return O}static ONE_36=1000000000000000000000000000000000000000n;static GAMMA_36=999801332008598957430613406568191166n;static BETA_36=1000198707468214629156271489013303962n;static mul36(z,j){return z*j/this.ONE_36}static pow36(z,j){let B=this.ONE_36,R=z,O=j;while(O>0n){if((O&1n)===1n)B=this.mul36(B,R);R=this.mul36(R,R),O>>=1n}return B}static attoCirclesToCircles(z){if(z===0n)return 0;let j=z/this.ATTO_FACTOR,B=z%this.ATTO_FACTOR,R=BigInt(Number.MAX_SAFE_INTEGER);if(j>R||j<-R)throw RangeError("Atto value’s integer component exceeds JS double precision.");return Number(j)+Number(B)/Number(this.ATTO_FACTOR)}static circlesToAttoCircles(z){return BigInt(Math.trunc(z*Number(this.ATTO_FACTOR)))}static inflationaryToDemurrage(z,j){return this.mulU(this.pow64(this.GAMMA_64,j),z)}static demurrageToInflationary(z,j){return this.mulU(this.pow64(this.BETA_64,j),z)}static dayFromTimestamp(z){return(z-this.INFLATION_DAY_ZERO_UNIX)/this.SECONDS_PER_DAY}static attoCirclesToAttoStaticCircles(z,j=BigInt(Math.floor(Date.now()/1000))){return this.demurrageToInflationary(z,this.dayFromTimestamp(j))}static attoStaticCirclesToAttoCircles(z,j=BigInt(Math.floor(Date.now()/1000))){return this.inflationaryToDemurrage(z,this.dayFromTimestamp(j))}static inflationaryToDemurrageExact(z,j){let B=this.pow36(this.GAMMA_36,j);return z*B/this.ONE_36}static demurrageToInflationaryExact(z,j){let B=this.pow36(this.BETA_36,j);return z*B/this.ONE_36}static attoCirclesToAttoStaticCirclesExact(z,j=BigInt(Math.floor(Date.now()/1000))){let B=this.dayFromTimestamp(j);return this.demurrageToInflationaryExact(z,B)}static attoStaticCirclesToAttoCirclesExact(z,j=BigInt(Math.floor(Date.now()/1000))){let B=this.dayFromTimestamp(j);return this.inflationaryToDemurrageExact(z,B)}static truncateToInt64(z){let j=z/this.FACTOR_1E12,B=9223372036854775807n;return j>B?B:j}static blowUpToBigInt(z){return z*this.FACTOR_1E12}static truncateToSixDecimals(z){return this.blowUpToBigInt(this.truncateToInt64(z))}static v1InflateFactor(z){if(z===0n)return this.V1_ACCURACY;return this.V1_ACCURACY*this.V1_INFLATION_PCT_NUM**z/this.V1_INFLATION_PCT_DEN**z}static attoCrcToAttoCircles(z,j){let B=j-this.INFLATION_DAY_ZERO_UNIX,R=B/this.PERIOD_SEC,O=B%this.PERIOD_SEC,_=this.v1InflateFactor(R),H=this.v1InflateFactor(R+1n);return this.v1ToDemurrage(z,_,H,O,this.PERIOD_SEC)}static attoCirclesToAttoCrc(z,j){let B=j-this.INFLATION_DAY_ZERO_UNIX,R=B/this.PERIOD_SEC,O=B%this.PERIOD_SEC,_=this.v1InflateFactor(R),H=this.v1InflateFactor(R+1n),L=_*(this.PERIOD_SEC-O)+H*O;return z*3n*this.V1_ACCURACY*this.PERIOD_SEC/L}static v1ToDemurrage(z,j,B,R,O){let _=j*(O-R)+B*R;return z*3n*this.V1_ACCURACY*O/_}}async function C3(z,j,B){let R=new Map,O=new Set;return B.transfers.forEach((L)=>{if(z.toLowerCase()===L.from.toLowerCase())O.add(L.tokenOwner.toLowerCase())}),(await new h(j).token.getTokenInfoBatch(Array.from(O))).forEach((L)=>{if(L.isWrapped&&!L.isInflationary)L.tokenType="CrcV2_ERC20WrapperDeployed_Demurraged";R.set(L.tokenAddress.toLowerCase(),L)}),R}function F3(z,j){let B={};return z.transfers.forEach((R)=>{let O=j.get(R.tokenOwner.toLowerCase());if(O&&O.tokenType.startsWith("CrcV2_ERC20WrapperDeployed")){if(!B[R.tokenOwner])B[R.tokenOwner]=[BigInt(0),O.tokenType];B[R.tokenOwner][0]+=BigInt(R.value)}}),B}function N3(z,j){let B={};return Object.entries(z).forEach(([R,[O,_]])=>{let H=j.get(R.toLowerCase());if(!H)return;if(_==="CrcV2_ERC20WrapperDeployed_Demurraged")B[R]=[O,H.tokenOwner];if(_==="CrcV2_ERC20WrapperDeployed_Inflationary")B[R]=[b.attoStaticCirclesToAttoCircles(O),H.tokenOwner]}),B}function E3(z,j){let B=z.transfers.map((R)=>{let O=j.get(R.tokenOwner.toLowerCase());if(O&&O.tokenType.startsWith("CrcV2_ERC20WrapperDeployed"))return{...R,tokenOwner:O.tokenOwner};return R});return{...z,transfers:B}}function P3(z,j){let B={};Object.entries(j).forEach(([O,[,_]])=>{B[O.toLowerCase()]=_});let R=z.transfers.map((O)=>{let _=O.tokenOwner.toLowerCase(),H=B[_]||O.tokenOwner;return{...O,tokenOwner:H}});return{...z,transfers:R}}function q3(z,j,B=BigInt(999999999999)){let R=new Map,O=[],_=BigInt(1000000000000);return z.transfers.forEach((L)=>{let D=BigInt(L.value)*B/_;if(D===BigInt(0))return;O.push({...L,value:D}),R.set(L.to,(R.get(L.to)??BigInt(0))+D)}),{maxFlow:j?R.get(j.toLowerCase())??BigInt(0):BigInt(0),transfers:O}}function U3(z,j,B){let R=o1(z),{source:O,sink:_}=n1(z,j,B),H=O===_;R.forEach((L,D)=>{if(H){if(L!==BigInt(0))throw Error(`Vertex ${D} is unbalanced: ${L}`);return}let F=D===O,E=D===_;if(F&&L>=BigInt(0))throw Error(`Source ${D} should be net negative, got ${L}`);if(E&&L<=BigInt(0))throw Error(`Sink ${D} should be net positive, got ${L}`);if(!F&&!E&&L!==BigInt(0))throw Error(`Vertex ${D} is unbalanced: ${L}`)})}function n1(z,j,B){let R=new Set(z.transfers.map((L)=>L.from.toLowerCase())),O=new Set(z.transfers.map((L)=>L.to.toLowerCase())),_=[...R].find((L)=>!O.has(L)),H=[...O].find((L)=>!R.has(L));if(!(_??j)||!(H??B))throw Error("Could not determine unique source / sink");return{source:_??j,sink:H??B}}function o1(z){let j=new Map;return z.transfers.forEach(({from:B,to:R,value:O})=>{let _=BigInt(O);j.set(B.toLowerCase(),(j.get(B.toLowerCase())??BigInt(0))-_),j.set(R.toLowerCase(),(j.get(R.toLowerCase())??BigInt(0))+_)}),j}export{f as transformToFlowVertices,q3 as shrinkPathValues,E3 as replaceWrappedTokensWithAvatars,P3 as replaceWrappedTokens,B3 as prepareFlowMatrixStreams,u as packCoordinates,F3 as getWrappedTokensFromPath,C3 as getTokenInfoMapFromPath,N3 as getExpectedUnwrappedTokenTotals,j3 as createFlowMatrix,o1 as computeNettedFlow,U3 as assertNoNettedFlowMismatch};
|
|
1
|
+
var G=[];for(let z=0;z<256;z++)G[z]=z.toString(16).padStart(2,"0");function T(z){let j="0x";for(let B=0;B<z.length;B++)j+=G[z[B]];return j}function m(z){let j=new Uint8Array(z.length*2);return z.forEach((B,R)=>{let O=B>>8,H=B&255,_=2*R;j[_]=O,j[_+1]=H}),T(j)}function f(z,j,B){let R=new Set([j.toLowerCase(),B.toLowerCase()]);z.forEach((_)=>{R.add(_.from.toLowerCase()),R.add(_.to.toLowerCase()),R.add(_.tokenOwner.toLowerCase())});let O=[...R].sort((_,X)=>{let F=BigInt(_),N=BigInt(X),P=F<N,U=F>N;return P?-1:U?1:0}),H={};return O.forEach((_,X)=>{H[_]=X}),{sorted:O,idx:H}}function L1(z,j){let B=new Set,R=[],O=null;if(z.forEach((H,_)=>{let X=H.from.toLowerCase(),F=H.to.toLowerCase();if(X===j&&F===j)O=_;else if(F===j)R.push(_)}),O!==null)B.add(O);else R.forEach((H)=>B.add(H));return B}function e1(z,j,B,R){let O=z.toLowerCase(),H=j.toLowerCase(),{sorted:_,idx:X}=f(R,O,H),F=L1(R,H),N=R.map((E,I)=>{return{streamSinkId:F.has(I)?1:0,amount:E.value}});if(F.size===0)throw Error(`No terminal edges detected. Flow must have at least one edge delivering to receiver ${H}`);let P=Array.from(F),U=[{sourceCoordinate:X[O],flowEdgeIds:P,data:new Uint8Array(0)}],q=[];R.forEach((E)=>{q.push(X[E.tokenOwner.toLowerCase()]),q.push(X[E.from.toLowerCase()]),q.push(X[E.to.toLowerCase()])});let A=m(q),V=BigInt(B),b=N.filter((E)=>E.streamSinkId===1).reduce((E,I)=>E+BigInt(I.amount.toString()),BigInt(0));if(b!==V)throw Error(`Terminal sum ${b} does not equal expected ${V}`);return{flowVertices:_,flowEdges:N,streams:U,packedCoordinates:A,sourceCoordinate:X[O]}}function J1(z,j){let B=z.streams.map((R)=>({sourceCoordinate:R.sourceCoordinate,flowEdgeIds:R.flowEdgeIds,data:R.data instanceof Uint8Array?T(R.data):R.data}));if(j&&B.length>0)B[0].data=j instanceof Uint8Array?T(j):j;return B}var u=(z)=>BigInt(z),y=(z)=>parseInt(z,16),F1=(z)=>{if(z.startsWith("0x"))z=z.slice(2);if(z.length%2!==0)throw Error("Invalid hex string");let j=new Uint8Array(z.length/2);for(let B=0;B<z.length;B+=2)j[B/2]=parseInt(z.substr(B,2),16);return j};function D1(z,j){if(typeof j==="string"&&j.startsWith("0x")){let B=j.slice(2);if(B.length===40)return j;if(B.length===64){if(z.toLowerCase().includes("digest")||z.toLowerCase().includes("data")||z.toLowerCase().includes("bytes"))return F1(j);try{return u(j)}catch{return j}}try{let R=y(j);if(R<Number.MAX_SAFE_INTEGER)return R;return u(j)}catch{return j}}if(j==="true")return!0;if(j==="false")return!1;return j}function N1(z){let{event:j,values:B}=z,R={$event:j,blockNumber:B.blockNumber?y(B.blockNumber):0,timestamp:B.timestamp?y(B.timestamp):void 0,transactionIndex:B.transactionIndex?y(B.transactionIndex):0,logIndex:B.logIndex?y(B.logIndex):0,transactionHash:B.transactionHash};for(let[O,H]of Object.entries(B)){if(["blockNumber","timestamp","transactionIndex","logIndex","transactionHash"].includes(O))continue;R[O]=D1(O,H)}return R}function P1(z){return z.map(N1)}class Q{_subscribers=[];subscribe(z){return this._subscribers.push(z),()=>{let j=this._subscribers.indexOf(z);if(j>-1)this._subscribers.splice(j,1)}}constructor(){this._subscribers=[]}emit(z){this._subscribers.forEach((j)=>j(z))}static create(){let z=new Q;return{property:z,emit:(j)=>z.emit(j)}}}class $ extends Error{name;code;source;cause;context;constructor(z,j,B){super(j);if(this.name=z,this.code=B?.code,this.source=B?.source??"UNKNOWN",this.cause=B?.cause,this.context=B?.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 z=`[${this.source}] ${this.name}: ${this.message}`;if(this.code)z+=` (Code: ${this.code})`;if(this.context)z+=`
|
|
2
|
+
Context: ${JSON.stringify(this.context,null,2)}`;return z}}class C extends ${constructor(z,j){super("RpcError",z,{...j,source:j?.source??"RPC_REQUEST"})}static connectionFailed(z,j){return new C("Failed to connect to RPC endpoint",{code:"RPC_CONNECTION_FAILED",source:"RPC_CONNECTION",cause:j,context:{url:z}})}static timeout(z,j){return new C("RPC request timed out",{code:"RPC_TIMEOUT",source:"RPC_TIMEOUT",context:{method:z,timeout:j}})}static invalidResponse(z,j){return new C("Invalid RPC response",{code:"RPC_INVALID_RESPONSE",source:"RPC_RESPONSE",context:{method:z,response:j}})}static fromJsonRpcError(z){return new C(z.message,{code:z.code,source:"RPC_RESPONSE",context:{data:z.data}})}static websocketError(z,j){return new C(z,{code:"RPC_WEBSOCKET_ERROR",source:"RPC_WEBSOCKET",cause:j})}}class i{rpcUrl;requestId=0;websocket=null;websocketConnected=!1;pendingResponses={};subscriptionListeners={};reconnectAttempt=0;initialBackoff=2000;maxBackoff=120000;constructor(z){this.rpcUrl=z}async call(z,j){this.requestId++;let B={jsonrpc:"2.0",id:this.requestId,method:z,params:j};try{let R=await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!R.ok)throw C.connectionFailed(this.rpcUrl,Error(`HTTP ${R.status}: ${R.statusText}`));let O=await R.json();if(O.error)throw C.fromJsonRpcError(O.error);if(O.result===void 0)throw C.invalidResponse(z,O);return O.result}catch(R){if(R instanceof C)throw R;throw C.connectionFailed(this.rpcUrl,R)}}setRpcUrl(z){this.rpcUrl=z}getRpcUrl(){return this.rpcUrl}connect(){return new Promise((z,j)=>{let B=this.rpcUrl.replace("http","ws");if(B.endsWith("/"))B+="ws/subscribe";else B+="/ws/subscribe";this.websocket=new WebSocket(B),this.websocket.onopen=()=>{console.log("WebSocket connected"),this.websocketConnected=!0,this.reconnectAttempt=0,z()},this.websocket.onmessage=(R)=>{let O=JSON.parse(R.data),{id:H,method:_,params:X}=O;if(H!==void 0&&this.pendingResponses[H])this.pendingResponses[H].resolve(O),delete this.pendingResponses[H];if(_==="circles_subscription"&&X?.result)Object.values(this.subscriptionListeners).forEach((F)=>{F.forEach((N)=>N(X.result))})},this.websocket.onclose=()=>{console.warn("WebSocket closed");let R=this.websocketConnected;if(this.websocketConnected=!1,R)this.scheduleReconnect()},this.websocket.onerror=(R)=>{console.error("WebSocket error:",R),this.websocketConnected=!1,j(C.connectionFailed(this.rpcUrl,R instanceof Error?R:Error("WebSocket connection failed"))),this.scheduleReconnect()}})}scheduleReconnect(){let z=Math.min(this.initialBackoff*Math.pow(2,this.reconnectAttempt),this.maxBackoff),j=z*(Math.random()*0.5),B=z+j;console.log(`Reconnecting in ${Math.round(B)}ms (attempt #${this.reconnectAttempt+1})`),this.reconnectAttempt++,setTimeout(()=>{this.reconnect()},B)}async reconnect(){if(this.websocketConnected)return;try{await this.connect(),console.log("Reconnection successful")}catch(z){console.error("Reconnection attempt failed:",z),this.scheduleReconnect()}}sendMessage(z,j,B=5000){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return Promise.reject(C.connectionFailed(this.rpcUrl));let R=this.requestId++,O={jsonrpc:"2.0",method:z,params:j,id:R};return new Promise((H,_)=>{this.pendingResponses[R]={resolve:H,reject:_},this.websocket.send(JSON.stringify(O)),setTimeout(()=>{if(this.pendingResponses[R])this.pendingResponses[R].reject(C.timeout(z,B)),delete this.pendingResponses[R]},B)})}async subscribe(z){let j=z?.toLowerCase();if(!this.websocketConnected)await this.connect();let B=Q.create(),R=j?{address:j}:{},O=(await this.sendMessage("circles_subscribe",R)).result;if(!this.subscriptionListeners[O])this.subscriptionListeners[O]=[];return this.subscriptionListeners[O].push((H)=>{P1(H).forEach((_)=>B.emit(_))}),B.property}}var v=BigInt(4294967295),x=BigInt(32);function C1(z,j=!1){if(j)return{h:Number(z&v),l:Number(z>>x&v)};return{h:Number(z>>x&v)|0,l:Number(z&v)|0}}function E1(z,j=!1){let B=z.length,R=new Uint32Array(B),O=new Uint32Array(B);for(let H=0;H<B;H++){let{h:_,l:X}=C1(z[H],j);[R[H],O[H]]=[_,X]}return[R,O]}var U1=(z,j,B)=>z<<B|j>>>32-B,q1=(z,j,B)=>j<<B|z>>>32-B,A1=(z,j,B)=>j<<B-32|z>>>64-B,T1=(z,j,B)=>z<<B-32|j>>>64-B;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function K1(z){return z instanceof Uint8Array||ArrayBuffer.isView(z)&&z.constructor.name==="Uint8Array"}function W(z,j=""){if(!Number.isSafeInteger(z)||z<0){let B=j&&`"${j}" `;throw Error(`${B}expected integer >= 0, got ${z}`)}}function k(z,j,B=""){let R=K1(z),O=z?.length,H=j!==void 0;if(!R||H&&O!==j){let _=B&&`"${B}" `,X=H?` of length ${j}`:"",F=R?`length=${O}`:`type=${typeof z}`;throw Error(_+"expected Uint8Array"+X+", got "+F)}return z}function l(z,j=!0){if(z.destroyed)throw Error("Hash instance has been destroyed");if(j&&z.finished)throw Error("Hash#digest() has already been called")}function y1(z,j){k(z,void 0,"digestInto() output");let B=j.outputLen;if(z.length<B)throw Error('"digestInto() output" expected to be of length >='+B)}function M1(z){return new Uint32Array(z.buffer,z.byteOffset,Math.floor(z.byteLength/4))}function s(...z){for(let j=0;j<z.length;j++)z[j].fill(0)}var v1=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function S1(z){return z<<24&4278190080|z<<8&16711680|z>>>8&65280|z>>>24&255}function I1(z){for(let j=0;j<z.length;j++)z[j]=S1(z[j]);return z}var p=v1?(z)=>z:I1;function k1(z,j={}){let B=(O,H)=>z(H).update(O).digest(),R=z(void 0);return B.outputLen=R.outputLen,B.blockLen=R.blockLen,B.create=(O)=>z(O),Object.assign(B,j),Object.freeze(B)}var Q1=BigInt(0),K=BigInt(1),g1=BigInt(2),w1=BigInt(7),h1=BigInt(256),V1=BigInt(113),d=[],n=[],o=[];for(let z=0,j=K,B=1,R=0;z<24;z++){[B,R]=[R,(2*B+3*R)%5],d.push(2*(5*R+B)),n.push((z+1)*(z+2)/2%64);let O=Q1;for(let H=0;H<7;H++)if(j=(j<<K^(j>>w1)*V1)%h1,j&g1)O^=K<<(K<<BigInt(H))-K;o.push(O)}var a=E1(o,!0),b1=a[0],G1=a[1],Y=(z,j,B)=>B>32?A1(z,j,B):U1(z,j,B),c=(z,j,B)=>B>32?T1(z,j,B):q1(z,j,B);function m1(z,j=24){let B=new Uint32Array(10);for(let R=24-j;R<24;R++){for(let _=0;_<10;_++)B[_]=z[_]^z[_+10]^z[_+20]^z[_+30]^z[_+40];for(let _=0;_<10;_+=2){let X=(_+8)%10,F=(_+2)%10,N=B[F],P=B[F+1],U=Y(N,P,1)^B[X],q=c(N,P,1)^B[X+1];for(let A=0;A<50;A+=10)z[_+A]^=U,z[_+A+1]^=q}let O=z[2],H=z[3];for(let _=0;_<24;_++){let X=n[_],F=Y(O,H,X),N=c(O,H,X),P=d[_];O=z[P],H=z[P+1],z[P]=F,z[P+1]=N}for(let _=0;_<50;_+=10){for(let X=0;X<10;X++)B[X]=z[_+X];for(let X=0;X<10;X++)z[_+X]^=~B[(X+2)%10]&B[(X+4)%10]}z[0]^=b1[R],z[1]^=G1[R]}s(B)}class g{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(z,j,B,R=!1,O=24){if(this.blockLen=z,this.suffix=j,this.outputLen=B,this.enableXOF=R,this.rounds=O,W(B,"outputLen"),!(0<z&&z<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=M1(this.state)}clone(){return this._cloneInto()}keccak(){p(this.state32),m1(this.state32,this.rounds),p(this.state32),this.posOut=0,this.pos=0}update(z){l(this),k(z);let{blockLen:j,state:B}=this,R=z.length;for(let O=0;O<R;){let H=Math.min(j-this.pos,R-O);for(let _=0;_<H;_++)B[this.pos++]^=z[O++];if(this.pos===j)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:z,suffix:j,pos:B,blockLen:R}=this;if(z[B]^=j,(j&128)!==0&&B===R-1)this.keccak();z[R-1]^=128,this.keccak()}writeInto(z){l(this,!1),k(z),this.finish();let j=this.state,{blockLen:B}=this;for(let R=0,O=z.length;R<O;){if(this.posOut>=B)this.keccak();let H=Math.min(B-this.posOut,O-R);z.set(j.subarray(this.posOut,this.posOut+H),R),this.posOut+=H,R+=H}return z}xofInto(z){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(z)}xof(z){return W(z),this.xofInto(new Uint8Array(z))}digestInto(z){if(y1(z,this),this.finished)throw Error("digest() was already called");return this.writeInto(z),this.destroy(),z}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,s(this.state)}_cloneInto(z){let{blockLen:j,suffix:B,outputLen:R,rounds:O,enableXOF:H}=this;return z||=new g(j,B,R,H,O),z.state32.set(this.state32),z.pos=this.pos,z.posOut=this.posOut,z.finished=this.finished,z.rounds=O,z.suffix=B,z.outputLen=R,z.enableXOF=H,z.destroyed=this.destroyed,z}}var f1=(z,j,B,R={})=>k1(()=>new g(j,z,B),R),u1=f1(1,136,32),t=[];for(let z=0;z<256;z++)t[z]=z.toString(16).padStart(2,"0");function x1(z){let j="0x";for(let B=0;B<z.length;B++)j+=t[z[B]];return j}function W1(z){let j=z.toLowerCase().replace("0x",""),B=x1(u1(new TextEncoder().encode(j))).slice(2),R="0x";for(let O=0;O<j.length;O++)R+=parseInt(B[O],16)>=8?j[O].toUpperCase():j[O];return R}function L(z){return z.toLowerCase()}function l1(z){return W1(z)}function p1(z){if(typeof z!=="string")return!1;let j=z.replace("0x","");return j.length===40&&/^[0-9a-fA-F]{40}$/.test(j)}function D(z){if(z===null||z===void 0)return z;if(p1(z))return l1(z);if(Array.isArray(z))return z.map((j)=>D(j));if(typeof z==="object"&&z!==null){let j={};for(let B in z)if(Object.prototype.hasOwnProperty.call(z,B))j[B]=D(z[B]);return j}return z}function Y1(z){return{Source:L(z.from),Sink:L(z.to),TargetFlow:z.targetFlow.toString(),WithWrap:z.useWrappedBalances,FromTokens:z.fromTokens?.map(L),ToTokens:z.toTokens?.map(L),ExcludedFromTokens:z.excludeFromTokens?.map(L),ExcludedToTokens:z.excludeToTokens?.map(L),SimulatedBalances:z.simulatedBalances?.map((j)=>({Holder:L(j.holder),Token:L(j.token),Amount:j.amount.toString(),IsWrapped:j.isWrapped,IsStatic:j.isStatic})),SimulatedTrusts:z.simulatedTrusts?.map((j)=>({Truster:L(j.truster),Trustee:L(j.trustee)})),MaxTransfers:z.maxTransfers}}function M(z){let j={};for(let B in z){let R=z[B];if(R===null||R===void 0)j[B]=R;else if(typeof R==="string"&&/^\d+$/.test(R))j[B]=BigInt(R);else if(typeof R==="object"&&!Array.isArray(R))j[B]=M(R);else if(Array.isArray(R))j[B]=R.map((O)=>typeof O==="object"&&O!==null?M(O):O);else j[B]=R}return j}var j3=BigInt(96)*BigInt(1000000000000000000),c1=BigInt("9999999999999999999999999999999999999");class Z{client;constructor(z){this.client=z}async findPath(z){let j=Y1(z),B=await this.client.call("circlesV2_findPath",[j]),R=M(B);return D(R)}async findMaxFlow(z){let j=await this.findPath({...z,targetFlow:c1});return BigInt(j.maxFlow)}}class r{client;constructor(z){this.client=z}async query(z){let j=await this.client.call("circles_query",[z]),{columns:B,rows:R}=j,O=R.map((H)=>{let _={};return B.forEach((X,F)=>{_[X]=H[F]}),_});return D(O)}async tables(){return this.client.call("circles_tables",[])}async events(z=null,j=null,B=null,R=null,O=null,H=!1,_=100,X=null){let F=await this.client.call("circles_events_paginated",[z,j,B,R,O,H,_,X]);return{events:D(F.events),hasMore:F.hasMore,nextCursor:F.nextCursor}}}var $1=[{name:"blockNumber",sortOrder:"DESC"},{name:"transactionIndex",sortOrder:"DESC"},{name:"logIndex",sortOrder:"DESC"}];class S{params;client;rowTransformer;cursorColumns;orderColumns;get currentPage(){return this._currentPage}_currentPage;constructor(z,j,B){this.client=z,this.params=j,this.rowTransformer=B||j.rowTransformer,this.orderColumns=j.orderColumns,this.cursorColumns=j.cursorColumns||this.buildEventCursorColumns()}buildEventCursorColumns(){let z=$1.map((j)=>({...j,sortOrder:this.params.sortOrder}));if(this.params.table==="TransferBatch")z.push({name:"batchIndex",sortOrder:this.params.sortOrder});return z}buildOrderBy(){if(this.orderColumns&&this.orderColumns.length>0)return this.orderColumns;return this.cursorColumns.map((z)=>({Column:z.name,SortOrder:z.sortOrder}))}rowsToObjects(z){let{columns:j,rows:B}=z;return B.map((R)=>{let O={};return j.forEach((H,_)=>{O[H]=R[_]}),this.rowTransformer?this.rowTransformer(O):O})}async queryNextPage(){let z={Namespace:this.params.namespace,Table:this.params.table,Columns:this.params.columns,Filter:this.params.filter||[],Order:this.buildOrderBy(),Limit:this.params.limit},j=this._currentPage?.nextCursor?[z,this._currentPage.nextCursor]:[z],B=await this.client.call("circles_paginated_query",j),R=this.rowsToObjects(B);return this._currentPage={limit:this.params.limit,size:R.length,sortOrder:this.params.sortOrder,hasMore:B.hasMore,nextCursor:B.nextCursor??void 0,results:R},R.length>0}reset(){this._currentPage=void 0}}class e{client;constructor(z){this.client=z}transformQueryResponse(z){let{columns:j,rows:B}=z;return B.map((R)=>{let O={};return j.forEach((H,_)=>{O[H]=R[_]}),O})}async getCommonTrust(z,j){let B=await this.client.call("circles_getCommonTrust",[L(z),L(j)]);return D(B)}getTrustRelations(z,j=100,B="DESC"){let R=L(z),O=[{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:R},{Type:"FilterPredicate",FilterType:"Equals",Column:"truster",Value:R}]}]}];return new S(this.client,{namespace:"V_Crc",table:"TrustRelations",sortOrder:B,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","version","trustee","truster","expiryTime"],filter:O,limit:j},(H)=>D(H))}async getAggregatedTrustRelations(z){let j=L(z),B=await this.client.call("circles_getAggregatedTrustRelations",[j]);return D(B)}async getTrustedBy(z){let j=L(z),B=(await this.getAggregatedTrustRelations(j)).filter((R)=>R.relation==="trustedBy");return D(B)}async getTrusts(z){let j=L(z),B=(await this.getAggregatedTrustRelations(j)).filter((R)=>R.relation==="trusts");return D(B)}async getMutualTrusts(z){let j=L(z),B=(await this.getAggregatedTrustRelations(j)).filter((R)=>R.relation==="mutuallyTrusts");return D(B)}async getTrustNetworkSummary(z,j=2){return this.client.call("circles_getTrustNetworkSummary",[L(z),j])}async getAggregatedTrustRelationsEnriched(z){return this.client.call("circles_getAggregatedTrustRelationsEnriched",[L(z)])}async getValidInviters(z,j){let B=[L(z)];if(j)B.push(j);return this.client.call("circles_getValidInviters",B)}}class J{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(z,j){return z*j>>64n}static mulU(z,j){return z*j>>64n}static pow64(z,j){let B=z,R=j,O=this.ONE_64;while(R>0n){if((R&1n)===1n)O=this.mul64(O,B);B=this.mul64(B,B),R>>=1n}return O}static ONE_36=1000000000000000000000000000000000000000n;static GAMMA_36=999801332008598957430613406568191166n;static BETA_36=1000198707468214629156271489013303962n;static mul36(z,j){return z*j/this.ONE_36}static pow36(z,j){let B=this.ONE_36,R=z,O=j;while(O>0n){if((O&1n)===1n)B=this.mul36(B,R);R=this.mul36(R,R),O>>=1n}return B}static attoCirclesToCircles(z){if(z===0n)return 0;let j=z/this.ATTO_FACTOR,B=z%this.ATTO_FACTOR,R=BigInt(Number.MAX_SAFE_INTEGER);if(j>R||j<-R)throw RangeError("Atto value’s integer component exceeds JS double precision.");return Number(j)+Number(B)/Number(this.ATTO_FACTOR)}static circlesToAttoCircles(z){return BigInt(Math.trunc(z*Number(this.ATTO_FACTOR)))}static inflationaryToDemurrage(z,j){return this.mulU(this.pow64(this.GAMMA_64,j),z)}static demurrageToInflationary(z,j){return this.mulU(this.pow64(this.BETA_64,j),z)}static dayFromTimestamp(z){return(z-this.INFLATION_DAY_ZERO_UNIX)/this.SECONDS_PER_DAY}static attoCirclesToAttoStaticCircles(z,j=BigInt(Math.floor(Date.now()/1000))){return this.demurrageToInflationary(z,this.dayFromTimestamp(j))}static attoStaticCirclesToAttoCircles(z,j=BigInt(Math.floor(Date.now()/1000))){return this.inflationaryToDemurrage(z,this.dayFromTimestamp(j))}static inflationaryToDemurrageExact(z,j){let B=this.pow36(this.GAMMA_36,j);return z*B/this.ONE_36}static demurrageToInflationaryExact(z,j){let B=this.pow36(this.BETA_36,j);return z*B/this.ONE_36}static attoCirclesToAttoStaticCirclesExact(z,j=BigInt(Math.floor(Date.now()/1000))){let B=this.dayFromTimestamp(j);return this.demurrageToInflationaryExact(z,B)}static attoStaticCirclesToAttoCirclesExact(z,j=BigInt(Math.floor(Date.now()/1000))){let B=this.dayFromTimestamp(j);return this.inflationaryToDemurrageExact(z,B)}static truncateToInt64(z){let j=z/this.FACTOR_1E12,B=9223372036854775807n;return j>B?B:j}static blowUpToBigInt(z){return z*this.FACTOR_1E12}static truncateToSixDecimals(z){return this.blowUpToBigInt(this.truncateToInt64(z))}static v1InflateFactor(z){if(z===0n)return this.V1_ACCURACY;return this.V1_ACCURACY*this.V1_INFLATION_PCT_NUM**z/this.V1_INFLATION_PCT_DEN**z}static attoCrcToAttoCircles(z,j){let B=j-this.INFLATION_DAY_ZERO_UNIX,R=B/this.PERIOD_SEC,O=B%this.PERIOD_SEC,H=this.v1InflateFactor(R),_=this.v1InflateFactor(R+1n);return this.v1ToDemurrage(z,H,_,O,this.PERIOD_SEC)}static attoCirclesToAttoCrc(z,j){let B=j-this.INFLATION_DAY_ZERO_UNIX,R=B/this.PERIOD_SEC,O=B%this.PERIOD_SEC,H=this.v1InflateFactor(R),_=this.v1InflateFactor(R+1n),X=H*(this.PERIOD_SEC-O)+_*O;return z*3n*this.V1_ACCURACY*this.PERIOD_SEC/X}static v1ToDemurrage(z,j,B,R,O){let H=j*(O-R)+B*R;return z*3n*this.V1_ACCURACY*O/H}}class z1{client;constructor(z){this.client=z}async getTotalBalance(z,j=!0){let B=await this.client.call("circlesV2_getTotalBalance",[L(z),j]);return J.circlesToAttoCircles(B)}async getTokenBalances(z){let j=(await this.client.call("circles_getTokenBalances",[L(z)])).map((B)=>M(B));return D(j)}}class j1{client;constructor(z){this.client=z}async getAvatarInfo(z){let j=await this.getAvatarInfoBatch([z]);return j.length>0?j[0]:void 0}async getAvatarInfoBatch(z){if(z.length===0)return[];let j=z.map((R)=>L(R)),B=await this.client.call("circles_getAvatarInfoBatch",[j]);return D(B)}async getNetworkSnapshot(){let z=await this.client.call("circles_getNetworkSnapshot",[]);return D(z)}}class B1{client;constructor(z){this.client=z}async getProfileByCid(z){return this.client.call("circles_getProfileByCid",[z])}async getProfileByCidBatch(z){return this.client.call("circles_getProfileByCidBatch",[z])}async getProfileByAddress(z){return this.client.call("circles_getProfileByAddress",[L(z)])}async getProfileByAddressBatch(z){return this.client.call("circles_getProfileByAddressBatch",[z.map((j)=>j===null?null:L(j))])}async searchProfiles(z,j=10,B=0,R){return this.client.call("circles_searchProfiles",[z.toLowerCase(),j,B,R])}async searchByAddressOrName(z,j=10,B,R){return this.client.call("circles_searchProfileByAddressOrName",R?[z,j,B??null,R]:[z,j,B??null])}async getProfileView(z){return this.client.call("circles_getProfileView",[L(z)])}}class R1{client;constructor(z){this.client=z}async getTokenInfo(z){let j=await this.getTokenInfoBatch([z]);return j.length>0?j[0]:void 0}async getTokenInfoBatch(z){if(z.length===0)return[];let j=z.map((R)=>L(R)),B=(await this.client.call("circles_getTokenInfoBatch",[j])).map((R)=>M(R));return D(B)}async getTokenHolders(z,j=100,B){let R=await this.client.call("circles_getTokenHolders",[L(z),j,B??null]);return{hasMore:R.hasMore,nextCursor:R.nextCursor,results:D(R.results)}}}class O1{client;constructor(z){this.client=z}async getInvitationOrigin(z){let j=L(z),B=await this.client.call("circles_getInvitationOrigin",[j]);return B?D(B):null}async getInvitedBy(z){let j=await this.getInvitationOrigin(z);if(j?.inviter)return D(j.inviter);return}async getTrustInvitations(z,j){let B=L(z),R=await this.client.call("circles_getTrustInvitations",j?[B,j]:[B]);return D(R)}async getInvitations(z,j){let B=(await this.getValidInviters(z,j)).results.map((R)=>R.avatarInfo).filter((R)=>R!==void 0&&R!==null);return D(B)}async getValidInviters(z,j){let B=L(z),R=await this.client.call("circles_getValidInviters",j?[B,j]:[B]);return D(R)}async getInvitationsFrom(z,j=!1){let B=L(z),R=await this.client.call("circles_getInvitationsFrom",[B,j]);return D(R)}async getEscrowInvitations(z){let j=L(z),B=await this.client.call("circles_getEscrowInvitations",[j]);return D(B)}async getAtScaleInvitations(z){let j=L(z),B=await this.client.call("circles_getAtScaleInvitations",[j]);return D(B)}async getAllInvitations(z,j){let B=L(z),R=await this.client.call("circles_getAllInvitations",j?[B,j]:[B]);return D(R)}}class H1{client;constructor(z){this.client=z}async getTransactionHistory(z,j=50,B){let R=await this.client.call("circles_getTransactionHistory",[L(z),j,B??null]);return{hasMore:R.hasMore,nextCursor:R.nextCursor,results:D(R.results)}}async getTransactionHistoryEnriched(z,j=0,B=null,R=20,O){let H=await this.client.call("circles_getTransactionHistoryEnriched",[L(z),j,B,R,O??null]);return{hasMore:H.hasMore,nextCursor:H.nextCursor,results:D(H.results)}}}class _1{client;constructor(z){this.client=z}async findGroups(z=50,j,B){let R=j?{nameStartsWith:j.nameStartsWith,symbolStartsWith:j.symbolStartsWith,ownerIn:j.ownerIn?.map((_)=>L(_))}:void 0,O=await this.client.call("circles_findGroups",[z,R??null,B??null]),H=D(O.results).map((_)=>{let X=_;if(!X.owner&&X.mint)return{...X,owner:X.mint};return X});return{hasMore:O.hasMore,nextCursor:O.nextCursor,results:H}}async getGroupMemberships(z,j=50,B){let R=await this.client.call("circles_getGroupMemberships",[L(z),j,B??null]);return{hasMore:R.hasMore,nextCursor:R.nextCursor,results:D(R.results)}}async getGroupMembers(z,j=100,B){let R=await this.client.call("circles_getGroupMembers",[L(z),j,B??null]);return{hasMore:R.hasMore,nextCursor:R.nextCursor,results:D(R.results)}}getGroups(z=50,j,B="DESC"){let R=[];if(j){if(j.nameStartsWith)R.push({Type:"FilterPredicate",FilterType:"Like",Column:"name",Value:j.nameStartsWith+"%"});if(j.symbolStartsWith)R.push({Type:"FilterPredicate",FilterType:"Like",Column:"symbol",Value:j.symbolStartsWith+"%"});if(j.groupAddressIn&&j.groupAddressIn.length>0){let H=j.groupAddressIn.map((_)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:L(_)}));if(H.length===1)R.push(H[0]);else R.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:H})}if(j.groupTypeIn&&j.groupTypeIn.length>0){let H=j.groupTypeIn.map((_)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"type",Value:_}));if(H.length===1)R.push(H[0]);else R.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:H})}if(j.ownerIn&&j.ownerIn.length>0){let H=j.ownerIn.map((_)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"owner",Value:L(_)}));if(H.length===1)R.push(H[0]);else R.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:H})}if(j.mintHandlerEquals)R.push({Type:"FilterPredicate",FilterType:"Equals",Column:"mintHandler",Value:L(j.mintHandlerEquals)});if(j.treasuryEquals)R.push({Type:"FilterPredicate",FilterType:"Equals",Column:"treasury",Value:L(j.treasuryEquals)})}let O=R.length>1?[{Type:"Conjunction",ConjunctionType:"And",Predicates:R}]:R;return new S(this.client,{namespace:"V_CrcV2",table:"Groups",sortOrder:B,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","type","owner","mintPolicy","mintHandler","treasury","service","feeCollection","memberCount","name","symbol","cidV0Digest","erc20WrapperDemurraged","erc20WrapperStatic"],filter:O,limit:z},(H)=>D(H))}getGroupHolders(z,j=100){let B=L(z);return new S(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:B}],limit:j},(R)=>D(R))}}class X1{client;constructor(z){this.client=z}async getProfileView(z){let j=L(z);return this.client.call("circles_getProfileView",[j])}async getTrustNetworkSummary(z,j=2){let B=L(z);return this.client.call("circles_getTrustNetworkSummary",[B,j])}async getAggregatedTrustRelations(z){let j=L(z);return this.client.call("circles_getAggregatedTrustRelations",[j])}async getValidInviters(z,j){let B=L(z),R=await this.client.call("circles_getValidInviters",j?[B,j]:[B]);return D(R)}async getTransactionHistoryEnriched(z,j=0,B=null,R=50,O){let H=L(z),_=await this.client.call("circles_getTransactionHistoryEnriched",[H,j,B,R,O??null]);return{hasMore:_.hasMore,nextCursor:_.nextCursor,results:D(_.results)}}async searchProfileByAddressOrName(z,j=20,B,R){return this.client.call("circles_searchProfileByAddressOrName",R?[z,j,B??null,R]:[z,j,B??null])}}class w{client;_pathfinder;_query;_trust;_balance;_avatar;_profile;_token;_invitation;_transaction;_group;_sdk;constructor(z="https://rpc.aboutcircles.com/"){this.client=new i(z)}get pathfinder(){if(!this._pathfinder)this._pathfinder=new Z(this.client);return this._pathfinder}get query(){if(!this._query)this._query=new r(this.client);return this._query}get trust(){if(!this._trust)this._trust=new e(this.client);return this._trust}get balance(){if(!this._balance)this._balance=new z1(this.client);return this._balance}get avatar(){if(!this._avatar)this._avatar=new j1(this.client);return this._avatar}get profile(){if(!this._profile)this._profile=new B1(this.client);return this._profile}get token(){if(!this._token)this._token=new R1(this.client);return this._token}get invitation(){if(!this._invitation)this._invitation=new O1(this.client);return this._invitation}get transaction(){if(!this._transaction)this._transaction=new H1(this.client);return this._transaction}get group(){if(!this._group)this._group=new _1(this.client);return this._group}get sdk(){if(!this._sdk)this._sdk=new X1(this.client);return this._sdk}setRpcUrl(z){this.client.setRpcUrl(z)}getRpcUrl(){return this.client.getRpcUrl()}}class h{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(z,j){return z*j>>64n}static mulU(z,j){return z*j>>64n}static pow64(z,j){let B=z,R=j,O=this.ONE_64;while(R>0n){if((R&1n)===1n)O=this.mul64(O,B);B=this.mul64(B,B),R>>=1n}return O}static ONE_36=1000000000000000000000000000000000000000n;static GAMMA_36=999801332008598957430613406568191166n;static BETA_36=1000198707468214629156271489013303962n;static mul36(z,j){return z*j/this.ONE_36}static pow36(z,j){let B=this.ONE_36,R=z,O=j;while(O>0n){if((O&1n)===1n)B=this.mul36(B,R);R=this.mul36(R,R),O>>=1n}return B}static attoCirclesToCircles(z){if(z===0n)return 0;let j=z/this.ATTO_FACTOR,B=z%this.ATTO_FACTOR,R=BigInt(Number.MAX_SAFE_INTEGER);if(j>R||j<-R)throw RangeError("Atto value’s integer component exceeds JS double precision.");return Number(j)+Number(B)/Number(this.ATTO_FACTOR)}static circlesToAttoCircles(z){return BigInt(Math.trunc(z*Number(this.ATTO_FACTOR)))}static inflationaryToDemurrage(z,j){return this.mulU(this.pow64(this.GAMMA_64,j),z)}static demurrageToInflationary(z,j){return this.mulU(this.pow64(this.BETA_64,j),z)}static dayFromTimestamp(z){return(z-this.INFLATION_DAY_ZERO_UNIX)/this.SECONDS_PER_DAY}static attoCirclesToAttoStaticCircles(z,j=BigInt(Math.floor(Date.now()/1000))){return this.demurrageToInflationary(z,this.dayFromTimestamp(j))}static attoStaticCirclesToAttoCircles(z,j=BigInt(Math.floor(Date.now()/1000))){return this.inflationaryToDemurrage(z,this.dayFromTimestamp(j))}static inflationaryToDemurrageExact(z,j){let B=this.pow36(this.GAMMA_36,j);return z*B/this.ONE_36}static demurrageToInflationaryExact(z,j){let B=this.pow36(this.BETA_36,j);return z*B/this.ONE_36}static attoCirclesToAttoStaticCirclesExact(z,j=BigInt(Math.floor(Date.now()/1000))){let B=this.dayFromTimestamp(j);return this.demurrageToInflationaryExact(z,B)}static attoStaticCirclesToAttoCirclesExact(z,j=BigInt(Math.floor(Date.now()/1000))){let B=this.dayFromTimestamp(j);return this.inflationaryToDemurrageExact(z,B)}static truncateToInt64(z){let j=z/this.FACTOR_1E12,B=9223372036854775807n;return j>B?B:j}static blowUpToBigInt(z){return z*this.FACTOR_1E12}static truncateToSixDecimals(z){return this.blowUpToBigInt(this.truncateToInt64(z))}static v1InflateFactor(z){if(z===0n)return this.V1_ACCURACY;return this.V1_ACCURACY*this.V1_INFLATION_PCT_NUM**z/this.V1_INFLATION_PCT_DEN**z}static attoCrcToAttoCircles(z,j){let B=j-this.INFLATION_DAY_ZERO_UNIX,R=B/this.PERIOD_SEC,O=B%this.PERIOD_SEC,H=this.v1InflateFactor(R),_=this.v1InflateFactor(R+1n);return this.v1ToDemurrage(z,H,_,O,this.PERIOD_SEC)}static attoCirclesToAttoCrc(z,j){let B=j-this.INFLATION_DAY_ZERO_UNIX,R=B/this.PERIOD_SEC,O=B%this.PERIOD_SEC,H=this.v1InflateFactor(R),_=this.v1InflateFactor(R+1n),X=H*(this.PERIOD_SEC-O)+_*O;return z*3n*this.V1_ACCURACY*this.PERIOD_SEC/X}static v1ToDemurrage(z,j,B,R,O){let H=j*(O-R)+B*R;return z*3n*this.V1_ACCURACY*O/H}}async function _3(z,j,B){let R=new Map,O=new Set;return B.transfers.forEach((X)=>{if(z.toLowerCase()===X.from.toLowerCase())O.add(X.tokenOwner.toLowerCase())}),(await new w(j).token.getTokenInfoBatch(Array.from(O))).forEach((X)=>{if(X.isWrapped&&!X.isInflationary)X.tokenType="CrcV2_ERC20WrapperDeployed_Demurraged";R.set(X.tokenAddress.toLowerCase(),X)}),R}function X3(z,j){let B={};return z.transfers.forEach((R)=>{let O=j.get(R.tokenOwner.toLowerCase());if(O&&O.tokenType.startsWith("CrcV2_ERC20WrapperDeployed")){if(!B[R.tokenOwner])B[R.tokenOwner]=[BigInt(0),O.tokenType];B[R.tokenOwner][0]+=BigInt(R.value)}}),B}function L3(z,j){let B={};return Object.entries(z).forEach(([R,[O,H]])=>{let _=j.get(R.toLowerCase());if(!_)return;if(H==="CrcV2_ERC20WrapperDeployed_Demurraged")B[R]=[O,_.tokenOwner];if(H==="CrcV2_ERC20WrapperDeployed_Inflationary")B[R]=[h.attoStaticCirclesToAttoCircles(O),_.tokenOwner]}),B}function F3(z,j){let B=z.transfers.map((R)=>{let O=j.get(R.tokenOwner.toLowerCase());if(O&&O.tokenType.startsWith("CrcV2_ERC20WrapperDeployed"))return{...R,tokenOwner:O.tokenOwner};return R});return{...z,transfers:B}}function D3(z,j){let B={};Object.entries(j).forEach(([O,[,H]])=>{B[O.toLowerCase()]=H});let R=z.transfers.map((O)=>{let H=O.tokenOwner.toLowerCase(),_=B[H]||O.tokenOwner;return{...O,tokenOwner:_}});return{...z,transfers:R}}function N3(z,j,B=BigInt(999999999999)){let R=new Map,O=[],H=BigInt(1000000000000);return z.transfers.forEach((X)=>{let F=BigInt(X.value)*B/H;if(F===BigInt(0))return;O.push({...X,value:F}),R.set(X.to,(R.get(X.to)??BigInt(0))+F)}),{maxFlow:j?R.get(j.toLowerCase())??BigInt(0):BigInt(0),transfers:O}}function P3(z,j,B){let R=s1(z),{source:O,sink:H}=i1(z,j,B),_=O===H;R.forEach((X,F)=>{if(_){if(X!==BigInt(0))throw Error(`Vertex ${F} is unbalanced: ${X}`);return}let N=F===O,P=F===H;if(N&&X>=BigInt(0))throw Error(`Source ${F} should be net negative, got ${X}`);if(P&&X<=BigInt(0))throw Error(`Sink ${F} should be net positive, got ${X}`);if(!N&&!P&&X!==BigInt(0))throw Error(`Vertex ${F} is unbalanced: ${X}`)})}function i1(z,j,B){let R=new Set(z.transfers.map((X)=>X.from.toLowerCase())),O=new Set(z.transfers.map((X)=>X.to.toLowerCase())),H=[...R].find((X)=>!O.has(X)),_=[...O].find((X)=>!R.has(X));if(!(H??j)||!(_??B))throw Error("Could not determine unique source / sink");return{source:H??j,sink:_??B}}function s1(z){let j=new Map;return z.transfers.forEach(({from:B,to:R,value:O})=>{let H=BigInt(O);j.set(B.toLowerCase(),(j.get(B.toLowerCase())??BigInt(0))-H),j.set(R.toLowerCase(),(j.get(R.toLowerCase())??BigInt(0))+H)}),j}export{f as transformToFlowVertices,N3 as shrinkPathValues,F3 as replaceWrappedTokensWithAvatars,D3 as replaceWrappedTokens,J1 as prepareFlowMatrixStreams,m as packCoordinates,X3 as getWrappedTokensFromPath,_3 as getTokenInfoMapFromPath,L3 as getExpectedUnwrappedTokenTotals,e1 as createFlowMatrix,s1 as computeNettedFlow,P3 as assertNoNettedFlowMismatch};
|