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