@aboutcircles/sdk-invitations 0.1.9 → 0.1.11
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/README.md +159 -0
- package/dist/{InvitationBuilder.d.ts → Invitations.d.ts} +20 -10
- package/dist/Invitations.d.ts.map +1 -0
- package/dist/Invitations.js +455 -0
- package/dist/InviteFarm.d.ts +59 -0
- package/dist/InviteFarm.d.ts.map +1 -0
- package/dist/InviteFarm.js +123 -0
- package/dist/Referrals.d.ts +44 -0
- package/dist/Referrals.d.ts.map +1 -0
- package/dist/Referrals.js +129 -0
- package/dist/errors.js +69 -0
- package/dist/index.d.ts +4 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/types.d.ts +83 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +1 -0
- package/package.json +1 -1
- package/dist/InvitationBuilder.d.ts.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
Context: ${JSON.stringify(this.context,null,2)}`;return J}}class t extends a0{constructor(J,$){super("RpcError",J,{...$,source:$?.source??"RPC_REQUEST"})}static connectionFailed(J,$){return new t("Failed to connect to RPC endpoint",{code:"RPC_CONNECTION_FAILED",source:"RPC_CONNECTION",cause:$,context:{url:J}})}static timeout(J,$){return new t("RPC request timed out",{code:"RPC_TIMEOUT",source:"RPC_TIMEOUT",context:{method:J,timeout:$}})}static invalidResponse(J,$){return new t("Invalid RPC response",{code:"RPC_INVALID_RESPONSE",source:"RPC_RESPONSE",context:{method:J,response:$}})}static fromJsonRpcError(J){return new t(J.message,{code:J.code,source:"RPC_RESPONSE",context:{data:J.data}})}static websocketError(J,$){return new t(J,{code:"RPC_WEBSOCKET_ERROR",source:"RPC_WEBSOCKET",cause:$})}}class V0{rpcUrl;requestId=0;websocket=null;websocketConnected=!1;pendingResponses={};subscriptionListeners={};reconnectAttempt=0;initialBackoff=2000;maxBackoff=120000;constructor(J){this.rpcUrl=J}async call(J,$){this.requestId++;let Q={jsonrpc:"2.0",id:this.requestId,method:J,params:$};try{let G=await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)});if(!G.ok)throw t.connectionFailed(this.rpcUrl,Error(`HTTP ${G.status}: ${G.statusText}`));let Y=await G.json();if(Y.error)throw t.fromJsonRpcError(Y.error);if(Y.result===void 0)throw t.invalidResponse(J,Y);return Y.result}catch(G){if(G instanceof t)throw G;throw t.connectionFailed(this.rpcUrl,G)}}setRpcUrl(J){this.rpcUrl=J}getRpcUrl(){return this.rpcUrl}connect(){return new Promise((J)=>{let $=this.rpcUrl.replace("http","ws");if($.endsWith("/"))$+="ws";else $+="/ws";this.websocket=new WebSocket($),this.websocket.onopen=()=>{console.log("WebSocket connected"),this.websocketConnected=!0,this.reconnectAttempt=0,J()},this.websocket.onmessage=(Q)=>{let G=JSON.parse(Q.data),{id:Y,method:Z,params:K}=G;if(Y!==void 0&&this.pendingResponses[Y])this.pendingResponses[Y].resolve(G),delete this.pendingResponses[Y];if(Z==="eth_subscription"&&K){let{subscription:q,result:M}=K;if(this.subscriptionListeners[q])this.subscriptionListeners[q].forEach((X)=>X(M))}},this.websocket.onclose=()=>{console.warn("WebSocket closed"),this.websocketConnected=!1},this.websocket.onerror=(Q)=>{console.error("WebSocket error:",Q),this.websocketConnected=!1,this.scheduleReconnect()}})}scheduleReconnect(){let J=Math.min(this.initialBackoff*Math.pow(2,this.reconnectAttempt),this.maxBackoff),$=J*(Math.random()*0.5),Q=J+$;console.log(`Reconnecting in ${Math.round(Q)}ms (attempt #${this.reconnectAttempt+1})`),this.reconnectAttempt++,setTimeout(()=>{this.reconnect()},Q)}async reconnect(){if(this.websocketConnected)return;try{await this.connect(),console.log("Reconnection successful")}catch(J){console.error("Reconnection attempt failed:",J),this.scheduleReconnect()}}sendMessage(J,$,Q=5000){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return Promise.reject(t.connectionFailed(this.rpcUrl));let G=this.requestId++,Y={jsonrpc:"2.0",method:J,params:$,id:G};return new Promise((Z,K)=>{this.pendingResponses[G]={resolve:Z,reject:K},this.websocket.send(JSON.stringify(Y)),setTimeout(()=>{if(this.pendingResponses[G])this.pendingResponses[G].reject(t.timeout(J,Q)),delete this.pendingResponses[G]},Q)})}async subscribe(J){let $=J?.toLowerCase();if(!this.websocketConnected)await this.connect();let Q=f0.create(),G=JSON.stringify($?{address:$}:{}),Z=(await this.sendMessage("eth_subscribe",["circles",G])).result;if(!this.subscriptionListeners[Z])this.subscriptionListeners[Z]=[];return this.subscriptionListeners[Z].push((K)=>{NJ(K).forEach((q)=>Q.emit(q))}),Q.property}}var zJ=BigInt(4294967295),H$=BigInt(32);function _8(J,$=!1){if($)return{h:Number(J&zJ),l:Number(J>>H$&zJ)};return{h:Number(J>>H$&zJ)|0,l:Number(J&zJ)|0}}function S$(J,$=!1){let Q=J.length,G=new Uint32Array(Q),Y=new Uint32Array(Q);for(let Z=0;Z<Q;Z++){let{h:K,l:q}=_8(J[Z],$);[G[Z],Y[Z]]=[K,q]}return[G,Y]}var T$=(J,$,Q)=>J<<Q|$>>>32-Q,_$=(J,$,Q)=>$<<Q|J>>>32-Q,E$=(J,$,Q)=>$<<Q-32|J>>>64-Q,x$=(J,$,Q)=>J<<Q-32|$>>>64-Q;var B0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function E8(J){return J instanceof Uint8Array||ArrayBuffer.isView(J)&&J.constructor.name==="Uint8Array"}function I0(J){if(!Number.isSafeInteger(J)||J<0)throw Error("positive integer expected, got "+J)}function G0(J,...$){if(!E8(J))throw Error("Uint8Array expected");if($.length>0&&!$.includes(J.length))throw Error("Uint8Array expected of length "+$+", got length="+J.length)}function A$(J){if(typeof J!=="function"||typeof J.create!=="function")throw Error("Hash should be wrapped by utils.createHasher");I0(J.outputLen),I0(J.blockLen)}function M0(J,$=!0){if(J.destroyed)throw Error("Hash instance has been destroyed");if($&&J.finished)throw Error("Hash#digest() has already been called")}function DJ(J,$){G0(J);let Q=$.outputLen;if(J.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function k$(J){return new Uint32Array(J.buffer,J.byteOffset,Math.floor(J.byteLength/4))}function Y0(...J){for(let $=0;$<J.length;$++)J[$].fill(0)}function VJ(J){return new DataView(J.buffer,J.byteOffset,J.byteLength)}function Q0(J,$){return J<<32-$|J>>>$}var x8=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function A8(J){return J<<24&4278190080|J<<8&16711680|J>>>8&65280|J>>>24&255}function k8(J){for(let $=0;$<J.length;$++)J[$]=A8(J[$]);return J}var FJ=x8?(J)=>J:k8;function w8(J){if(typeof J!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(J))}function H0(J){if(typeof J==="string")J=w8(J);return G0(J),J}function w$(...J){let $=0;for(let G=0;G<J.length;G++){let Y=J[G];G0(Y),$+=Y.length}let Q=new Uint8Array($);for(let G=0,Y=0;G<J.length;G++){let Z=J[G];Q.set(Z,Y),Y+=Z.length}return Q}class S0{}function OJ(J){let $=(G)=>J().update(H0(G)).digest(),Q=J();return $.outputLen=Q.outputLen,$.blockLen=Q.blockLen,$.create=()=>J(),$}function y$(J=32){if(B0&&typeof B0.getRandomValues==="function")return B0.getRandomValues(new Uint8Array(J));if(B0&&typeof B0.randomBytes==="function")return Uint8Array.from(B0.randomBytes(J));throw Error("crypto.getRandomValues must be defined")}var y8=BigInt(0),s0=BigInt(1),F8=BigInt(2),b8=BigInt(7),g8=BigInt(256),f8=BigInt(113),g$=[],f$=[],v$=[];for(let J=0,$=s0,Q=1,G=0;J<24;J++){[Q,G]=[G,(2*Q+3*G)%5],g$.push(2*(5*G+Q)),f$.push((J+1)*(J+2)/2%64);let Y=y8;for(let Z=0;Z<7;Z++)if($=($<<s0^($>>b8)*f8)%g8,$&F8)Y^=s0<<(s0<<BigInt(Z))-s0;v$.push(Y)}var h$=S$(v$,!0),v8=h$[0],h8=h$[1],F$=(J,$,Q)=>Q>32?E$(J,$,Q):T$(J,$,Q),b$=(J,$,Q)=>Q>32?x$(J,$,Q):_$(J,$,Q);function m8(J,$=24){let Q=new Uint32Array(10);for(let G=24-$;G<24;G++){for(let K=0;K<10;K++)Q[K]=J[K]^J[K+10]^J[K+20]^J[K+30]^J[K+40];for(let K=0;K<10;K+=2){let q=(K+8)%10,M=(K+2)%10,X=Q[M],j=Q[M+1],N=F$(X,j,1)^Q[q],D=b$(X,j,1)^Q[q+1];for(let V=0;V<50;V+=10)J[K+V]^=N,J[K+V+1]^=D}let Y=J[2],Z=J[3];for(let K=0;K<24;K++){let q=f$[K],M=F$(Y,Z,q),X=b$(Y,Z,q),j=g$[K];Y=J[j],Z=J[j+1],J[j]=M,J[j+1]=X}for(let K=0;K<50;K+=10){for(let q=0;q<10;q++)Q[q]=J[K+q];for(let q=0;q<10;q++)J[K+q]^=~Q[(q+2)%10]&Q[(q+4)%10]}J[0]^=v8[G],J[1]^=h8[G]}Y0(Q)}class bJ extends S0{constructor(J,$,Q,G=!1,Y=24){super();if(this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=J,this.suffix=$,this.outputLen=Q,this.enableXOF=G,this.rounds=Y,I0(Q),!(0<J&&J<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=k$(this.state)}clone(){return this._cloneInto()}keccak(){FJ(this.state32),m8(this.state32,this.rounds),FJ(this.state32),this.posOut=0,this.pos=0}update(J){M0(this),J=H0(J),G0(J);let{blockLen:$,state:Q}=this,G=J.length;for(let Y=0;Y<G;){let Z=Math.min($-this.pos,G-Y);for(let K=0;K<Z;K++)Q[this.pos++]^=J[Y++];if(this.pos===$)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:J,suffix:$,pos:Q,blockLen:G}=this;if(J[Q]^=$,($&128)!==0&&Q===G-1)this.keccak();J[G-1]^=128,this.keccak()}writeInto(J){M0(this,!1),G0(J),this.finish();let $=this.state,{blockLen:Q}=this;for(let G=0,Y=J.length;G<Y;){if(this.posOut>=Q)this.keccak();let Z=Math.min(Q-this.posOut,Y-G);J.set($.subarray(this.posOut,this.posOut+Z),G),this.posOut+=Z,G+=Z}return J}xofInto(J){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(J)}xof(J){return I0(J),this.xofInto(new Uint8Array(J))}digestInto(J){if(DJ(J,this),this.finished)throw Error("digest() was already called");return this.writeInto(J),this.destroy(),J}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Y0(this.state)}_cloneInto(J){let{blockLen:$,suffix:Q,outputLen:G,rounds:Y,enableXOF:Z}=this;return J||(J=new bJ($,Q,G,Z,Y)),J.state32.set(this.state32),J.pos=this.pos,J.posOut=this.posOut,J.finished=this.finished,J.rounds=Y,J.suffix=Q,J.outputLen=G,J.enableXOF=Z,J.destroyed=this.destroyed,J}}var u8=(J,$,Q)=>OJ(()=>new bJ($,J,Q));var v0=(()=>u8(1,136,32))();var m$=[];for(let J=0;J<256;J++)m$[J]=J.toString(16).padStart(2,"0");function RJ(J){let $="0x";for(let Q=0;Q<J.length;Q++)$+=m$[J[Q]];return $}function LJ(J){let $=J.startsWith("0x")?J.slice(2):J,Q=new Uint8Array($.length/2);for(let G=0;G<$.length;G+=2)Q[G/2]=parseInt($.slice(G,G+2),16);return Q}var m=64,PJ=32,CJ=(J)=>J.startsWith("0x")?J.slice(2):J;var Z0=(J)=>J.toString(16).padStart(m,"0");function R0(J){let $=J.toLowerCase().replace("0x",""),Q=RJ(v0(new TextEncoder().encode($))).slice(2),G="0x";for(let Y=0;Y<$.length;Y++)G+=parseInt(Q[Y],16)>=8?$[Y].toUpperCase():$[Y];return G}function gJ(J,$){if(J==="tuple"&&$)return`(${$.map((Y)=>gJ(Y.type,Y.components)).join(",")})`;let Q=J.match(/^tuple(\[\d*\])$/);if(Q&&$)return`${gJ("tuple",$)}${Q[1]}`;return J}function c8(J){let Q=(J.inputs||[]).map((G)=>gJ(G.type,G.components));return`${J.name}(${Q.join(",")})`}function l8(J){let $=c8(J),Q=v0(new TextEncoder().encode($));return RJ(Q.slice(0,4))}function h0(J,$){if(J==="string"||J==="bytes")return!0;if(J.includes("[")){let Q=J.slice(0,J.indexOf("["));if(J.endsWith("[]"))return!0;if(Q==="tuple")return u$($);return h0(Q)}if(J==="tuple")return u$($);return!1}function u$(J){return J?.some(($)=>h0($.type,$.components))??!1}function O0(J,$,Q){if(J==="tuple"&&Q)return d8(Q,$);if(J.includes("["))return p8(J,$,Q);return i8(J,$)}function p8(J,$,Q){let G=J.slice(0,J.indexOf("[")),Y=J.endsWith("[]"),Z=h0(G,Q),K;if(Z){let q=$.map((j)=>O0(G,j,Q)),M=$.length*PJ;K=q.map((j)=>{let N=M;return M+=j.length/2,Z0(N)}).join("")+q.join("")}else K=$.map((q)=>O0(G,q,Q)).join("");return Y?Z0($.length)+K:K}function d8(J,$){let Q=Array.isArray($),G=[],Y=[],Z=[];for(let K=0;K<J.length;K++){let q=J[K],M=Q?$[K]:$[q.name||""],X=h0(q.type,q.components);if(Z.push(X),X)G.push(""),Y.push(O0(q.type,M,q.components));else G.push(O0(q.type,M,q.components))}if(Y.length>0){let K=G.reduce((X,j,N)=>X+(Z[N]?PJ:j.length/2),0),q="",M=0;for(let X=0;X<J.length;X++)if(Z[X])q+=Z0(K),K+=Y[M].length/2,M++;else q+=G[X];return q+Y.join("")}return G.join("")}function i8(J,$){if(J==="address")return CJ($).toLowerCase().padStart(m,"0");if(J==="bool")return Z0($?1:0);if(J.startsWith("uint")){let Q=typeof $==="bigint"?$:BigInt($);return Z0(Q)}if(J.startsWith("int")){let Q=typeof $==="bigint"?$:BigInt($);if(Q<0n){let G=J==="int"?256:parseInt(J.slice(3));Q=(1n<<BigInt(G))+Q}return Z0(Q)}if(J.startsWith("bytes")&&J!=="bytes")return CJ($).padEnd(m,"0");if(J==="bytes"){let Q=CJ($),G=Z0(Q.length/2),Y=Q.padEnd(Math.ceil(Q.length/m)*m,"0");return G+Y}if(J==="string"){let Q=Array.from(new TextEncoder().encode($)).map((Z)=>Z.toString(16).padStart(2,"0")).join(""),G=Z0(Q.length/2),Y=Q.padEnd(Math.ceil(Q.length/m)*m,"0");return G+Y}throw Error(`Unsupported type: ${J}`)}function r0(J,$,Q=0,G){if(J==="tuple"&&G)return o8(G,$,Q);if(J.includes("["))return n8(J,$,Q,G);return t8(J,$,Q)}function n8(J,$,Q,G){let Y=J.slice(0,J.indexOf("[")),Z=$.slice(Q,Q+m);if(J.endsWith("[]")){let q=parseInt(Z,16)*2,M=parseInt($.slice(q,q+m),16),X=[],j=q+m;for(let N=0;N<M;N++){let D=r0(Y,$,j,G);X.push(D.value),j+=D.consumed}return{value:X,consumed:m}}let K=J.match(/\[(\d+)\]$/);if(K){let q=parseInt(K[1]),M=[],X=0;for(let j=0;j<q;j++){let N=r0(Y,$,Q+X,G);M.push(N.value),X+=N.consumed}return{value:M,consumed:X}}throw Error(`Invalid array type: ${J}`)}function o8(J,$,Q){let G=[],Y=Q;for(let Z of J){let K=r0(Z.type,$,Y,Z.components);G.push(K.value),Y+=K.consumed}return{value:G,consumed:Y-Q}}function t8(J,$,Q){let G=$.slice(Q,Q+m);if(J==="address")return{value:R0("0x"+G.slice(24)),consumed:m};if(J==="bool")return{value:parseInt(G,16)!==0,consumed:m};if(J.startsWith("uint"))return{value:BigInt("0x"+G),consumed:m};if(J.startsWith("int")){let Y=BigInt("0x"+G),Z=J==="int"?256:parseInt(J.slice(3)),K=1n<<BigInt(Z-1);return{value:Y>=K?Y-(1n<<BigInt(Z)):Y,consumed:m}}if(J.startsWith("bytes")&&J!=="bytes"){let Y=parseInt(J.match(/^bytes(\d+)$/)[1]);return{value:"0x"+G.slice(0,Y*2),consumed:m}}if(J==="bytes"){let Y=parseInt(G,16)*2,Z=parseInt($.slice(Y,Y+m),16)*2;return{value:"0x"+$.slice(Y+m,Y+m+Z),consumed:m}}if(J==="string"){let Y=parseInt(G,16)*2,Z=parseInt($.slice(Y,Y+m),16)*2,K=$.slice(Y+m,Y+m+Z),q=new Uint8Array(K.match(/.{2}/g)?.map((M)=>parseInt(M,16))||[]);return{value:new TextDecoder().decode(q),consumed:m}}throw Error(`Unsupported type: ${J}`)}function BJ(J){let{abi:$,functionName:Q,args:G=[]}=J,Y=$.find((V)=>V.type==="function"&&V.name===Q);if(!Y)throw Error(`Function "${Q}" not found in ABI`);let Z=l8(Y),K=Y.inputs||[];if(K.length===0)return Z;if(G.length!==K.length)throw Error(`Expected ${K.length} arguments, got ${G.length}`);let q=[],M=[],X=[];for(let V=0;V<K.length;V++){let B=K[V],z=B.components,A=h0(B.type,z);if(X.push(A),A)q.push(""),M.push(O0(B.type,G[V],z));else q.push(O0(B.type,G[V],z))}if(M.length===0)return Z+q.join("");let j=q.reduce((V,B,z)=>V+(X[z]?PJ:B.length/2),0),N="",D=0;for(let V=0;V<K.length;V++)if(X[V])N+=Z0(j),j+=M[D].length/2,D++;else N+=q[V];return Z+N+M.join("")}function fJ(J){let{abi:$,functionName:Q,data:G}=J,Y=$.find((X)=>X.type==="function"&&X.name===Q);if(!Y)throw Error(`Function "${Q}" not found in ABI`);let Z=Y.outputs||[];if(Z.length===0)return;let K=CJ(G);if(Z.length===1)return r0(Z[0].type,K,0,Z[0].components).value;let q=[],M=0;for(let X of Z){let j=r0(X.type,K,M,X.components);q.push(j.value),M+=j.consumed}return q}function m0(J,$){if(J.length!==$.length)throw Error(`Type/value length mismatch: ${J.length} types, ${$.length} values`);let Q=[],G=[],Y=[];for(let M=0;M<J.length;M++){let X=J[M],j=h0(X);if(Y.push(j),j)Q.push(""),G.push(O0(X,$[M]));else Q.push(O0(X,$[M]))}if(G.length===0)return"0x"+Q.join("");let Z=Q.reduce((M,X,j)=>M+(Y[j]?PJ:X.length/2),0),K="",q=0;for(let M=0;M<J.length;M++)if(Y[M])K+=Z0(Z),Z+=G[q].length/2,q++;else K+=Q[M];return"0x"+K+G.join("")}function C(J){return J.toLowerCase()}function a8(J){return R0(J)}function s8(J){if(typeof J!=="string")return!1;let $=J.replace("0x","");return $.length===40&&/^[0-9a-fA-F]{40}$/.test($)}function g(J){if(J===null||J===void 0)return J;if(s8(J))return a8(J);if(Array.isArray(J))return J.map(($)=>g($));if(typeof J==="object"&&J!==null){let $={};for(let Q in J)if(Object.prototype.hasOwnProperty.call(J,Q))$[Q]=g(J[Q]);return $}return J}function c$(J){return{Source:C(J.from),Sink:C(J.to),TargetFlow:J.targetFlow.toString(),WithWrap:J.useWrappedBalances,FromTokens:J.fromTokens?.map(C),ToTokens:J.toTokens?.map(C),ExcludedFromTokens:J.excludeFromTokens?.map(C),ExcludedToTokens:J.excludeToTokens?.map(C),SimulatedBalances:J.simulatedBalances?.map(($)=>({Holder:C($.holder),Token:C($.token),Amount:$.amount.toString(),IsWrapped:$.isWrapped,IsStatic:$.isStatic})),SimulatedTrusts:J.simulatedTrusts?.map(($)=>({Truster:C($.truster),Trustee:C($.trustee)})),MaxTransfers:J.maxTransfers}}function q0(J){let $={};for(let Q in J){let G=J[Q];if(G===null||G===void 0)$[Q]=G;else if(typeof G==="string"&&/^\d+$/.test(G))$[Q]=BigInt(G);else if(typeof G==="object"&&!Array.isArray(G))$[Q]=q0(G);else if(Array.isArray(G))$[Q]=G.map((Y)=>typeof Y==="object"&&Y!==null?q0(Y):Y);else $[Q]=G}return $}var IJ="0x0000000000000000000000000000000000000000",T0=BigInt(96)*BigInt(1000000000000000000),e0=BigInt("9999999999999999999999999999999999999"),vJ="0x4e1DCf7AD4e460CfD30791CCC4F9c8a4f820ec67",hJ="0x440ea2f93c9703f7d456d48796f7bc25b8721582535a492ce0a09df32146242a",mJ="0xe298282cefe913ab5d282047161268a8222e4bd4ed106300c547894bbefd31ee";class X0{client;constructor(J){this.client=J}async findPath(J){let $=c$(J),Q=await this.client.call("circlesV2_findPath",[$]),G=q0(Q);return g(G)}async findMaxFlow(J){let $=await this.findPath({...J,targetFlow:e0});return BigInt($.maxFlow)}}class JJ{client;constructor(J){this.client=J}async query(J){let $=await this.client.call("circles_query",[J]);return g($)}async tables(){return this.client.call("circles_tables",[])}async events(J,$,Q=null,G=null,Y=!1){let Z=await this.client.call("circles_events",[J,$,Q,G,Y]);return g(Z)}}var r8=[{name:"blockNumber",sortOrder:"DESC"},{name:"transactionIndex",sortOrder:"DESC"},{name:"logIndex",sortOrder:"DESC"}];class J0{params;client;rowTransformer;cursorColumns;orderColumns;get currentPage(){return this._currentPage}_currentPage;constructor(J,$,Q){this.client=J,this.params=$,this.rowTransformer=Q||$.rowTransformer,this.orderColumns=$.orderColumns,this.cursorColumns=$.cursorColumns||this.buildEventCursorColumns()}buildEventCursorColumns(){let J=r8.map(($)=>({...$,sortOrder:this.params.sortOrder}));if(this.params.table==="TransferBatch")J.push({name:"batchIndex",sortOrder:this.params.sortOrder});return J}transformCursorValue(J,$){if($)return $(J);if(typeof J==="bigint")return J.toString();return J}createEqualityPredicate(J,$){return{Type:"FilterPredicate",FilterType:"Equals",Column:J.name,Value:this.transformCursorValue($,J.toValue)}}createComparisonPredicate(J,$){return{Type:"FilterPredicate",FilterType:J.sortOrder==="ASC"?"GreaterThan":"LessThan",Column:J.name,Value:this.transformCursorValue($,J.toValue)}}buildCursorFilter(J){if(!J)return[];let $=[];for(let Q=0;Q<this.cursorColumns.length;Q++){let G=this.cursorColumns[Q],Y=J[G.name];if(Y===void 0)continue;if(Q===0)$.push(this.createComparisonPredicate(G,Y));else{let Z=[];for(let K=0;K<Q;K++){let q=this.cursorColumns[K],M=J[q.name];if(M!==void 0)Z.push(this.createEqualityPredicate(q,M))}Z.push(this.createComparisonPredicate(G,Y)),$.push({Type:"Conjunction",ConjunctionType:"And",Predicates:Z})}}if($.length===0)return[];return[{Type:"Conjunction",ConjunctionType:"Or",Predicates:$}]}buildOrderBy(){if(this.orderColumns&&this.orderColumns.length>0)return this.orderColumns;return this.cursorColumns.map((J)=>({Column:J.name,SortOrder:J.sortOrder}))}combineFilters(J,$){if(!J?.length&&!$?.length)return[];if(!J?.length)return $||[];if(!$?.length)return J;return[{Type:"Conjunction",ConjunctionType:"And",Predicates:[...J,...$]}]}rowsToObjects(J){let{columns:$,rows:Q}=J;return Q.map((G)=>{let Y={};return $.forEach((Z,K)=>{Y[Z]=G[K]}),this.rowTransformer?this.rowTransformer(Y):Y})}rowToCursor(J){let $={};for(let Q of this.cursorColumns)$[Q.name]=J[Q.name];return $}getCursors(J){if(J.length===0)return{};return{first:this.rowToCursor(J[0]),last:this.rowToCursor(J[J.length-1])}}async queryNextPage(){let J=this.buildCursorFilter(this._currentPage?.lastCursor),$=this.combineFilters(this.params.filter,J),Q={Namespace:this.params.namespace,Table:this.params.table,Columns:this.params.columns,Filter:$,Order:this.buildOrderBy(),Limit:this.params.limit},G=await this.client.call("circles_query",[Q]),Y=this.rowsToObjects(G),Z=this.getCursors(Y);return this._currentPage={limit:this.params.limit,size:Y.length,firstCursor:Z.first,lastCursor:Z.last,sortOrder:this.params.sortOrder,hasMore:Y.length===this.params.limit,results:Y},Y.length>0}reset(){this._currentPage=void 0}}class _0{client;constructor(J){this.client=J}transformQueryResponse(J){let{columns:$,rows:Q}=J;return Q.map((G)=>{let Y={};return $.forEach((Z,K)=>{Y[Z]=G[K]}),Y})}async getCommonTrust(J,$){let Q=await this.client.call("circles_getCommonTrust",[C(J),C($)]);return g(Q)}getTrustRelations(J,$=100,Q="DESC"){let G=C(J),Y=[{Type:"Conjunction",ConjunctionType:"And",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"version",Value:2},{Type:"Conjunction",ConjunctionType:"Or",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"trustee",Value:G},{Type:"FilterPredicate",FilterType:"Equals",Column:"truster",Value:G}]}]}];return new J0(this.client,{namespace:"V_Crc",table:"TrustRelations",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","version","trustee","truster","expiryTime"],filter:Y,limit:$},(Z)=>g(Z))}async getAggregatedTrustRelations(J){let $=C(J),Q=this.getTrustRelations($,1000),G=[];while(await Q.queryNextPage())if(G.push(...Q.currentPage.results),!Q.currentPage.hasMore)break;let Y={};G.forEach((K)=>{let q=C(K.truster),M=C(K.trustee),X=q!==$?K.truster:K.trustee;if(!Y[X])Y[X]=[];Y[X].push(K)});let Z=Object.entries(Y).filter(([K])=>C(K)!==$).map(([K,q])=>{let M=Math.max(...q.map((j)=>j.timestamp)),X;if(q.length===2)X="mutuallyTrusts";else if(C(q[0]?.trustee)===$)X="trustedBy";else if(C(q[0]?.truster)===$)X="trusts";else throw Error("Unexpected trust list row. Couldn't determine trust relation.");return{subjectAvatar:$,relation:X,objectAvatar:K,timestamp:M}});return g(Z)}async getTrustedBy(J){let $=C(J),G=(await this.getAggregatedTrustRelations($)).filter((Y)=>Y.relation==="trustedBy");return g(G)}async getTrusts(J){let $=C(J),G=(await this.getAggregatedTrustRelations($)).filter((Y)=>Y.relation==="trusts");return g(G)}async getMutualTrusts(J){let $=C(J),G=(await this.getAggregatedTrustRelations($)).filter((Y)=>Y.relation==="mutuallyTrusts");return g(G)}}class p{static ONE_64=1n<<64n;static GAMMA_64=18443079296116538654n;static BETA_64=18450409579521241655n;static SECONDS_PER_DAY=86400n;static INFLATION_DAY_ZERO_UNIX=1602720000n;static ATTO_FACTOR=1000000000000000000n;static FACTOR_1E12=1000000000000n;static V1_ACCURACY=100000000n;static V1_INFLATION_PCT_NUM=107n;static V1_INFLATION_PCT_DEN=100n;static PERIOD_SEC=31556952n;static mul64(J,$){return J*$>>64n}static mulU(J,$){return J*$>>64n}static pow64(J,$){let Q=J,G=$,Y=this.ONE_64;while(G>0n){if((G&1n)===1n)Y=this.mul64(Y,Q);Q=this.mul64(Q,Q),G>>=1n}return Y}static ONE_36=1000000000000000000000000000000000000000n;static GAMMA_36=999801332008598957430613406568191166n;static BETA_36=1000198707468214629156271489013303962n;static mul36(J,$){return J*$/this.ONE_36}static pow36(J,$){let Q=this.ONE_36,G=J,Y=$;while(Y>0n){if((Y&1n)===1n)Q=this.mul36(Q,G);G=this.mul36(G,G),Y>>=1n}return Q}static attoCirclesToCircles(J){if(J===0n)return 0;let $=J/this.ATTO_FACTOR,Q=J%this.ATTO_FACTOR,G=BigInt(Number.MAX_SAFE_INTEGER);if($>G||$<-G)throw RangeError("Atto value’s integer component exceeds JS double precision.");return Number($)+Number(Q)/Number(this.ATTO_FACTOR)}static circlesToAttoCircles(J){return BigInt(Math.trunc(J*Number(this.ATTO_FACTOR)))}static inflationaryToDemurrage(J,$){return this.mulU(this.pow64(this.GAMMA_64,$),J)}static demurrageToInflationary(J,$){return this.mulU(this.pow64(this.BETA_64,$),J)}static dayFromTimestamp(J){return(J-this.INFLATION_DAY_ZERO_UNIX)/this.SECONDS_PER_DAY}static attoCirclesToAttoStaticCircles(J,$=BigInt(Math.floor(Date.now()/1000))){return this.demurrageToInflationary(J,this.dayFromTimestamp($))}static attoStaticCirclesToAttoCircles(J,$=BigInt(Math.floor(Date.now()/1000))){return this.inflationaryToDemurrage(J,this.dayFromTimestamp($))}static inflationaryToDemurrageExact(J,$){let Q=this.pow36(this.GAMMA_36,$);return J*Q/this.ONE_36}static demurrageToInflationaryExact(J,$){let Q=this.pow36(this.BETA_36,$);return J*Q/this.ONE_36}static attoCirclesToAttoStaticCirclesExact(J,$=BigInt(Math.floor(Date.now()/1000))){let Q=this.dayFromTimestamp($);return this.demurrageToInflationaryExact(J,Q)}static attoStaticCirclesToAttoCirclesExact(J,$=BigInt(Math.floor(Date.now()/1000))){let Q=this.dayFromTimestamp($);return this.inflationaryToDemurrageExact(J,Q)}static truncateToInt64(J){let $=J/this.FACTOR_1E12,Q=9223372036854775807n;return $>Q?Q:$}static blowUpToBigInt(J){return J*this.FACTOR_1E12}static truncateToSixDecimals(J){return this.blowUpToBigInt(this.truncateToInt64(J))}static v1InflateFactor(J){if(J===0n)return this.V1_ACCURACY;return this.V1_ACCURACY*this.V1_INFLATION_PCT_NUM**J/this.V1_INFLATION_PCT_DEN**J}static attoCrcToAttoCircles(J,$){let Q=$-this.INFLATION_DAY_ZERO_UNIX,G=Q/this.PERIOD_SEC,Y=Q%this.PERIOD_SEC,Z=this.v1InflateFactor(G),K=this.v1InflateFactor(G+1n);return this.v1ToDemurrage(J,Z,K,Y,this.PERIOD_SEC)}static attoCirclesToAttoCrc(J,$){let Q=$-this.INFLATION_DAY_ZERO_UNIX,G=Q/this.PERIOD_SEC,Y=Q%this.PERIOD_SEC,Z=this.v1InflateFactor(G),K=this.v1InflateFactor(G+1n),q=Z*(this.PERIOD_SEC-Y)+K*Y;return J*3n*this.V1_ACCURACY*this.PERIOD_SEC/q}static v1ToDemurrage(J,$,Q,G,Y){let Z=$*(Y-G)+Q*G;return J*3n*this.V1_ACCURACY*Y/Z}}class E0{client;constructor(J){this.client=J}async getTotalBalance(J,$=!0){let Q=await this.client.call("circlesV2_getTotalBalance",[C(J),$]);return p.circlesToAttoCircles(Q)}async getTokenBalances(J){let Q=(await this.client.call("circles_getTokenBalances",[C(J)])).map((G)=>q0(G));return g(Q)}}class $J{client;constructor(J){this.client=J}async getAvatarInfo(J){let $=await this.getAvatarInfoBatch([J]);return $.length>0?$[0]:void 0}async getAvatarInfoBatch(J){if(J.length===0)return[];let $=J.map((G)=>C(G)),Q=await this.client.call("circles_getAvatarInfoBatch",[$]);return g(Q)}async getNetworkSnapshot(){let J=await this.client.call("circles_getNetworkSnapshot",[]);return g(J)}}class QJ{client;constructor(J){this.client=J}async getProfileByCid(J){return this.client.call("circles_getProfileByCid",[J])}async getProfileByCidBatch(J){return this.client.call("circles_getProfileByCidBatch",[J])}async getProfileByAddress(J){return this.client.call("circles_getProfileByAddress",[C(J)])}async getProfileByAddressBatch(J){return this.client.call("circles_getProfileByAddressBatch",[J.map(($)=>$===null?null:C($))])}async searchProfiles(J,$=10,Q=0,G){return this.client.call("circles_searchProfiles",[J.toLowerCase(),$,Q,G])}async searchByAddressOrName(J,$=10,Q=0,G){let Y=[],Z=/^0x[a-fA-F0-9]{40}$/.test(J);if(Z)try{let K=await this.getProfileByAddress(J);if(K){let q={...K,address:J};if(!G||!q.avatarType||G.includes(q.avatarType))Y.push(q)}}catch(K){console.warn("Failed to get profile by address:",K)}try{let K=await this.searchProfiles(J,$,Q,G);if(Z&&Y.length>0){let q=J.toLowerCase(),M=K.filter((X)=>X.address?.toLowerCase()!==q);Y.push(...M)}else Y.push(...K)}catch(K){console.warn("Failed to search profiles by text:",K)}return Y.slice(0,$)}}class GJ{client;constructor(J){this.client=J}async getTokenInfo(J){let $=await this.getTokenInfoBatch([J]);return $.length>0?$[0]:void 0}async getTokenInfoBatch(J){if(J.length===0)return[];let $=J.map((Y)=>C(Y)),G=(await this.client.call("circles_getTokenInfoBatch",[$])).map((Y)=>q0(Y));return g(G)}getTokenHolders(J,$=100,Q="DESC"){let G=C(J);return new J0(this.client,{namespace:"V_CrcV2",table:"BalancesByAccountAndToken",columns:["account","tokenAddress","demurragedTotalBalance"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"tokenAddress",Value:G}],cursorColumns:[{name:"demurragedTotalBalance",sortOrder:Q},{name:"account",sortOrder:"ASC"}],orderColumns:[{Column:"demurragedTotalBalance",SortOrder:Q},{Column:"account",SortOrder:"ASC"}],limit:$,sortOrder:Q},(Y)=>({account:Y.account,tokenAddress:Y.tokenAddress,demurragedTotalBalance:Y.demurragedTotalBalance}))}}class YJ{client;constructor(J){this.client=J}transformQueryResponse(J){let{columns:$,rows:Q}=J;return Q.map((G)=>{let Y={};return $.forEach((Z,K)=>{Y[Z]=G[K]}),Y})}async getInvitedBy(J){let $=C(J),Q=await this.client.call("circles_query",[{Namespace:"CrcV2",Table:"RegisterHuman",Columns:["inviter"],Filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"avatar",Value:$}],Order:[{Column:"blockNumber",SortOrder:"DESC"}],Limit:1}]);if(Q.length>0)return g(Q[0].inviter);return}async getInvitations(J){let $=C(J),Q=96,G=await this.client.call("circles_getAvatarInfoBatch",[[$]]);if((G.length>0?G[0]:void 0)?.version===2)return[];let Z=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:$}]}],Order:[]}]),q=this.transformQueryResponse(Z).map((j)=>j.truster);if(q.length===0)return[];let M=await this.client.call("circles_getAvatarInfoBatch",[q]),X=[];for(let j of M){if(!j?.isHuman)continue;let D=(await this.client.call("circles_getTokenBalances",[j.avatar])).find((V)=>C(V.tokenAddress)===C(j.avatar));if(D&&D.circles>=96)X.push(j)}return g(X)}async getInvitationsFrom(J,$=!1){let Q=C(J);if($){let G=await this.client.call("circles_query",[{Namespace:"CrcV2",Table:"RegisterHuman",Columns:["avatar"],Filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"inviter",Value:Q}],Order:[{Column:"blockNumber",SortOrder:"DESC"}]}]),Z=this.transformQueryResponse(G).map((K)=>K.avatar);return g(Z)}else{let G=await this.client.call("circles_query",[{Namespace:"V_Crc",Table:"TrustRelations",Columns:["trustee","truster"],Filter:[{Type:"Conjunction",ConjunctionType:"And",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"version",Value:2},{Type:"FilterPredicate",FilterType:"Equals",Column:"truster",Value:Q}]}],Order:[]}]),Z=this.transformQueryResponse(G).map((X)=>X.trustee);if(Z.length===0)return[];let K=await this.client.call("circles_getAvatarInfoBatch",[Z]),q=new Set(K.filter((X)=>X!==null).map((X)=>C(X.avatar))),M=Z.filter((X)=>!q.has(C(X)));return g(M)}}}function e8(J,$){let Q=BigInt(J),G=p.attoCirclesToCircles(Q),Y=p.attoCirclesToAttoCrc(Q,BigInt($)),Z=p.attoCirclesToCircles(Y),K=p.attoCirclesToAttoStaticCircles(Q,BigInt($)),q=p.attoCirclesToCircles(K);return{attoCircles:Q,circles:G,staticAttoCircles:K,staticCircles:q,attoCrc:Y,crc:Z}}class ZJ{client;constructor(J){this.client=J}getTransactionHistory(J,$=50,Q="DESC"){let G=C(J),Y=[{Type:"Conjunction",ConjunctionType:"And",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"version",Value:2},{Type:"Conjunction",ConjunctionType:"Or",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"from",Value:G},{Type:"FilterPredicate",FilterType:"Equals",Column:"to",Value:G}]}]}];return new J0(this.client,{namespace:"V_Crc",table:"TransferSummary",sortOrder:Q,columns:[],filter:Y,limit:$},(Z)=>{let K=e8(Z.value,Z.timestamp),q={...Z,...K};return g(q)})}}class x0{client;constructor(J){this.client=J}async findGroups(J=50,$){let Q=this.getGroups(J,$,"DESC"),G=[];while(await Q.queryNextPage()){if(G.push(...Q.currentPage.results),G.length>=J)break;if(!Q.currentPage.hasMore)break}return G.slice(0,J)}getGroupMemberships(J,$=50,Q="DESC"){let G=C(J);return new J0(this.client,{namespace:"V_CrcV2",table:"GroupMemberships",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","member","expiryTime"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"member",Value:G}],limit:$},(Y)=>g(Y))}getGroupHolders(J,$=100){let Q=C(J);return new J0(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:Q}],limit:$,rowTransformer:(G)=>{let Y={...G,totalBalance:BigInt(G.totalBalance),demurragedTotalBalance:BigInt(G.demurragedTotalBalance)};return g(Y)}})}getGroupMembers(J,$=100,Q="DESC"){let G=C(J);return new J0(this.client,{namespace:"V_CrcV2",table:"GroupMemberships",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","member","expiryTime"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:G}],limit:$},(Y)=>g(Y))}getGroups(J=50,$,Q="DESC"){let G=[];if($){if($.nameStartsWith)G.push({Type:"FilterPredicate",FilterType:"Like",Column:"name",Value:$.nameStartsWith+"%"});if($.symbolStartsWith)G.push({Type:"FilterPredicate",FilterType:"Like",Column:"symbol",Value:$.symbolStartsWith+"%"});if($.groupAddressIn&&$.groupAddressIn.length>0){let Z=$.groupAddressIn.map((K)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:C(K)}));if(Z.length===1)G.push(Z[0]);else G.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:Z})}if($.groupTypeIn&&$.groupTypeIn.length>0){let Z=$.groupTypeIn.map((K)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"type",Value:K}));if(Z.length===1)G.push(Z[0]);else G.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:Z})}if($.ownerIn&&$.ownerIn.length>0){let Z=$.ownerIn.map((K)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"owner",Value:C(K)}));if(Z.length===1)G.push(Z[0]);else G.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:Z})}if($.mintHandlerEquals)G.push({Type:"FilterPredicate",FilterType:"Equals",Column:"mintHandler",Value:C($.mintHandlerEquals)});if($.treasuryEquals)G.push({Type:"FilterPredicate",FilterType:"Equals",Column:"treasury",Value:C($.treasuryEquals)})}let Y=G.length>1?[{Type:"Conjunction",ConjunctionType:"And",Predicates:G}]:G;return new J0(this.client,{namespace:"V_CrcV2",table:"Groups",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","type","owner","mintPolicy","mintHandler","treasury","service","feeCollection","memberCount","name","symbol","cidV0Digest","erc20WrapperDemurraged","erc20WrapperStatic"],filter:Y,limit:J},(Z)=>g(Z))}}class HJ{client;_pathfinder;_query;_trust;_balance;_avatar;_profile;_token;_invitation;_transaction;_group;constructor(J="https://rpc.circlesubi.network/"){this.client=new V0(J)}get pathfinder(){if(!this._pathfinder)this._pathfinder=new X0(this.client);return this._pathfinder}get query(){if(!this._query)this._query=new JJ(this.client);return this._query}get trust(){if(!this._trust)this._trust=new _0(this.client);return this._trust}get balance(){if(!this._balance)this._balance=new E0(this.client);return this._balance}get avatar(){if(!this._avatar)this._avatar=new $J(this.client);return this._avatar}get profile(){if(!this._profile)this._profile=new QJ(this.client);return this._profile}get token(){if(!this._token)this._token=new GJ(this.client);return this._token}get invitation(){if(!this._invitation)this._invitation=new YJ(this.client);return this._invitation}get transaction(){if(!this._transaction)this._transaction=new ZJ(this.client);return this._transaction}get group(){if(!this._group)this._group=new x0(this.client);return this._group}setRpcUrl(J){this.client.setRpcUrl(J)}getRpcUrl(){return this.client.getRpcUrl()}}class K0{address;abi;rpcUrl;constructor(J){this.address=J.address,this.abi=J.abi,this.rpcUrl=J.rpcUrl}async read(J,$,Q){let G=BJ({abi:this.abi,functionName:J,args:$}),Y={to:this.address,data:G,...Q?.from&&{from:Q.from}},K=await(await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[Y,"latest"]})})).json();if(K.error)throw Error(`RPC Error: ${K.error.message}`);if(!K.result)throw Error("No result returned from RPC call");return fJ({abi:this.abi,functionName:J,data:K.result})}encodeWrite(J,$){return BJ({abi:this.abi,functionName:J,args:$})}}var l$=[{type:"function",name:"operateFlowMatrix",inputs:[{name:"_flowVertices",type:"address[]"},{name:"_flow",type:"tuple[]",components:[{name:"streamSinkId",type:"uint16"},{name:"amount",type:"uint192"}]},{name:"_streams",type:"tuple[]",components:[{name:"sourceCoordinate",type:"uint16"},{name:"flowEdgeIds",type:"uint16[]"},{name:"data",type:"bytes"}]},{name:"_packedCoordinates",type:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"isApprovedForAll",inputs:[{name:"_account",type:"address"},{name:"_operator",type:"address"}],outputs:[{type:"bool"}],stateMutability:"view"},{type:"function",name:"setApprovalForAll",inputs:[{name:"_operator",type:"address"},{name:"_approved",type:"bool"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"wrap",inputs:[{name:"_avatar",type:"address"},{name:"_amount",type:"uint256"},{name:"_type",type:"uint8"}],outputs:[{type:"address"}],stateMutability:"nonpayable"},{type:"function",name:"trust",inputs:[{name:"_trustReceiver",type:"address"},{name:"_expiry",type:"uint96"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"isTrusted",inputs:[{name:"_truster",type:"address"},{name:"_trustee",type:"address"}],outputs:[{type:"bool"}],stateMutability:"view"},{type:"function",name:"toTokenId",inputs:[{name:"_avatar",type:"address"}],outputs:[{type:"uint256"}],stateMutability:"pure"},{type:"function",name:"safeTransferFrom",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_id",type:"uint256"},{name:"_value",type:"uint256"},{name:"_data",type:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"isHuman",inputs:[{name:"_human",type:"address"}],outputs:[{type:"bool"}],stateMutability:"view"}];class u0 extends K0{constructor(J){super({address:J.address,abi:l$,rpcUrl:J.rpcUrl})}async isTrusted(J,$){return this.read("isTrusted",[J,$])}async isApprovedForAll(J,$){return this.read("isApprovedForAll",[J,$])}async toTokenId(J){return this.read("toTokenId",[J])}trust(J,$){return{to:this.address,data:this.encodeWrite("trust",[J,$]),value:0n}}setApprovalForAll(J,$){return{to:this.address,data:this.encodeWrite("setApprovalForAll",[J,$]),value:0n}}wrap(J,$,Q){return{to:this.address,data:this.encodeWrite("wrap",[J,$,Q]),value:0n}}safeTransferFrom(J,$,Q,G,Y="0x"){return{to:this.address,data:this.encodeWrite("safeTransferFrom",[J,$,Q,G,Y]),value:0n}}operateFlowMatrix(J,$,Q,G){return{to:this.address,data:this.encodeWrite("operateFlowMatrix",[J,$,Q,G]),value:0n}}async isHuman(J){return this.read("isHuman",[J])}}var p$=[{type:"function",name:"erc20Circles",inputs:[{name:"_circlesType",type:"uint8"},{name:"_avatar",type:"address"}],outputs:[{type:"address"}],stateMutability:"view"}];class SJ extends K0{constructor(J){super({address:J.address,abi:p$,rpcUrl:J.rpcUrl})}async erc20Circles(J,$){return this.read("erc20Circles",[J,$])}}var uJ=[{type:"function",name:"unwrap",inputs:[{name:"_amount",type:"uint256"}],outputs:[],stateMutability:"nonpayable"}];class c0 extends K0{constructor(J){super({address:J.address,abi:uJ,rpcUrl:J.rpcUrl})}unwrap(J){return{to:this.address,data:this.encodeWrite("unwrap",[J]),value:0n}}}class l0 extends K0{constructor(J){super({address:J.address,abi:uJ,rpcUrl:J.rpcUrl})}unwrap(J){return{to:this.address,data:this.encodeWrite("unwrap",[J]),value:0n}}}var cJ=[{type:"function",name:"createAccount",inputs:[{name:"signer",type:"address"}],outputs:[{name:"account",type:"address"}],stateMutability:"nonpayable"},{type:"function",name:"createAccounts",inputs:[{name:"signers",type:"address[]"}],outputs:[{name:"_accounts",type:"address[]"}],stateMutability:"nonpayable"}];class TJ extends K0{constructor(J){super({address:J.address,abi:cJ,rpcUrl:J.rpcUrl})}createAccount(J){return{to:this.address,data:this.encodeWrite("createAccount",[J]),value:0n}}createAccounts(J){return{to:this.address,data:this.encodeWrite("createAccounts",[J]),value:0n}}}class _J extends Error{name;code;source;cause;context;constructor(J,$,Q){super($);if(this.name=J,this.code=Q?.code,this.source=Q?.source??"UNKNOWN",this.cause=Q?.cause,this.context=Q?.context,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,source:this.source,context:this.context,cause:this.cause instanceof Error?{name:this.cause.name,message:this.cause.message}:this.cause,stack:this.stack}}toString(){let J=`[${this.source}] ${this.name}: ${this.message}`;if(this.code)J+=` (Code: ${this.code})`;if(this.context)J+=`
|
|
3
|
-
Context: ${JSON.stringify(this.context,null,2)}`;return J}}function JQ(J,$,Q,G){if(typeof J.setBigUint64==="function")return J.setBigUint64($,Q,G);let Y=BigInt(32),Z=BigInt(4294967295),K=Number(Q>>Y&Z),q=Number(Q&Z),M=G?4:0,X=G?0:4;J.setUint32($+M,K,G),J.setUint32($+X,q,G)}function d$(J,$,Q){return J&$^~J&Q}function i$(J,$,Q){return J&$^J&Q^$&Q}class lJ extends S0{constructor(J,$,Q,G){super();this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=J,this.outputLen=$,this.padOffset=Q,this.isLE=G,this.buffer=new Uint8Array(J),this.view=VJ(this.buffer)}update(J){M0(this),J=H0(J),G0(J);let{view:$,buffer:Q,blockLen:G}=this,Y=J.length;for(let Z=0;Z<Y;){let K=Math.min(G-this.pos,Y-Z);if(K===G){let q=VJ(J);for(;G<=Y-Z;Z+=G)this.process(q,Z);continue}if(Q.set(J.subarray(Z,Z+K),this.pos),this.pos+=K,Z+=K,this.pos===G)this.process($,0),this.pos=0}return this.length+=J.length,this.roundClean(),this}digestInto(J){M0(this),DJ(J,this),this.finished=!0;let{buffer:$,view:Q,blockLen:G,isLE:Y}=this,{pos:Z}=this;if($[Z++]=128,Y0(this.buffer.subarray(Z)),this.padOffset>G-Z)this.process(Q,0),Z=0;for(let j=Z;j<G;j++)$[j]=0;JQ(Q,G-8,BigInt(this.length*8),Y),this.process(Q,0);let K=VJ(J),q=this.outputLen;if(q%4)throw Error("_sha2: outputLen should be aligned to 32bit");let M=q/4,X=this.get();if(M>X.length)throw Error("_sha2: outputLen bigger than state");for(let j=0;j<M;j++)K.setUint32(4*j,X[j],Y)}digest(){let{buffer:J,outputLen:$}=this;this.digestInto(J);let Q=J.slice(0,$);return this.destroy(),Q}_cloneInto(J){J||(J=new this.constructor),J.set(...this.get());let{blockLen:$,buffer:Q,length:G,finished:Y,destroyed:Z,pos:K}=this;if(J.destroyed=Z,J.finished=Y,J.length=G,J.pos=K,G%$)J.buffer.set(Q);return J}clone(){return this._cloneInto()}}var j0=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var $Q=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),L0=new Uint32Array(64);class n$ extends lJ{constructor(J=32){super(64,J,8,!1);this.A=j0[0]|0,this.B=j0[1]|0,this.C=j0[2]|0,this.D=j0[3]|0,this.E=j0[4]|0,this.F=j0[5]|0,this.G=j0[6]|0,this.H=j0[7]|0}get(){let{A:J,B:$,C:Q,D:G,E:Y,F:Z,G:K,H:q}=this;return[J,$,Q,G,Y,Z,K,q]}set(J,$,Q,G,Y,Z,K,q){this.A=J|0,this.B=$|0,this.C=Q|0,this.D=G|0,this.E=Y|0,this.F=Z|0,this.G=K|0,this.H=q|0}process(J,$){for(let j=0;j<16;j++,$+=4)L0[j]=J.getUint32($,!1);for(let j=16;j<64;j++){let N=L0[j-15],D=L0[j-2],V=Q0(N,7)^Q0(N,18)^N>>>3,B=Q0(D,17)^Q0(D,19)^D>>>10;L0[j]=B+L0[j-7]+V+L0[j-16]|0}let{A:Q,B:G,C:Y,D:Z,E:K,F:q,G:M,H:X}=this;for(let j=0;j<64;j++){let N=Q0(K,6)^Q0(K,11)^Q0(K,25),D=X+N+d$(K,q,M)+$Q[j]+L0[j]|0,B=(Q0(Q,2)^Q0(Q,13)^Q0(Q,22))+i$(Q,G,Y)|0;X=M,M=q,q=K,K=Z+D|0,Z=Y,Y=G,G=Q,Q=D+B|0}Q=Q+this.A|0,G=G+this.B|0,Y=Y+this.C|0,Z=Z+this.D|0,K=K+this.E|0,q=q+this.F|0,M=M+this.G|0,X=X+this.H|0,this.set(Q,G,Y,Z,K,q,M,X)}roundClean(){Y0(L0)}destroy(){this.set(0,0,0,0,0,0,0,0),Y0(this.buffer)}}var o$=OJ(()=>new n$);class pJ extends S0{constructor(J,$){super();this.finished=!1,this.destroyed=!1,A$(J);let Q=H0($);if(this.iHash=J.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let G=this.blockLen,Y=new Uint8Array(G);Y.set(Q.length>G?J.create().update(Q).digest():Q);for(let Z=0;Z<Y.length;Z++)Y[Z]^=54;this.iHash.update(Y),this.oHash=J.create();for(let Z=0;Z<Y.length;Z++)Y[Z]^=106;this.oHash.update(Y),Y0(Y)}update(J){return M0(this),this.iHash.update(J),this}digestInto(J){M0(this),G0(J,this.outputLen),this.finished=!0,this.iHash.digestInto(J),this.oHash.update(J),this.oHash.digestInto(J),this.destroy()}digest(){let J=new Uint8Array(this.oHash.outputLen);return this.digestInto(J),J}_cloneInto(J){J||(J=Object.create(Object.getPrototypeOf(this),{}));let{oHash:$,iHash:Q,finished:G,destroyed:Y,blockLen:Z,outputLen:K}=this;return J=J,J.finished=G,J.destroyed=Y,J.blockLen=Z,J.outputLen=K,J.oHash=$._cloneInto(J.oHash),J.iHash=Q._cloneInto(J.iHash),J}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var dJ=(J,$,Q)=>new pJ(J,$).update(Q).digest();dJ.create=(J,$)=>new pJ(J,$);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var tJ=BigInt(0),oJ=BigInt(1);function p0(J){return J instanceof Uint8Array||ArrayBuffer.isView(J)&&J.constructor.name==="Uint8Array"}function aJ(J){if(!p0(J))throw Error("Uint8Array expected")}function d0(J,$){if(typeof $!=="boolean")throw Error(J+" boolean expected, got "+$)}function KJ(J){let $=J.toString(16);return $.length&1?"0"+$:$}function s$(J){if(typeof J!=="string")throw Error("hex string expected, got "+typeof J);return J===""?tJ:BigInt("0x"+J)}var r$=typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function",QQ=Array.from({length:256},(J,$)=>$.toString(16).padStart(2,"0"));function i0(J){if(aJ(J),r$)return J.toHex();let $="";for(let Q=0;Q<J.length;Q++)$+=QQ[J[Q]];return $}var U0={_0:48,_9:57,A:65,F:70,a:97,f:102};function t$(J){if(J>=U0._0&&J<=U0._9)return J-U0._0;if(J>=U0.A&&J<=U0.F)return J-(U0.A-10);if(J>=U0.a&&J<=U0.f)return J-(U0.a-10);return}function MJ(J){if(typeof J!=="string")throw Error("hex string expected, got "+typeof J);if(r$)return Uint8Array.fromHex(J);let $=J.length,Q=$/2;if($%2)throw Error("hex string expected, got unpadded hex of length "+$);let G=new Uint8Array(Q);for(let Y=0,Z=0;Y<Q;Y++,Z+=2){let K=t$(J.charCodeAt(Z)),q=t$(J.charCodeAt(Z+1));if(K===void 0||q===void 0){let M=J[Z]+J[Z+1];throw Error('hex string expected, got non-hex character "'+M+'" at index '+Z)}G[Y]=K*16+q}return G}function W0(J){return s$(i0(J))}function sJ(J){return aJ(J),s$(i0(Uint8Array.from(J).reverse()))}function A0(J,$){return MJ(J.toString(16).padStart($*2,"0"))}function rJ(J,$){return A0(J,$).reverse()}function e(J,$,Q){let G;if(typeof $==="string")try{G=MJ($)}catch(Z){throw Error(J+" must be hex string or Uint8Array, cause: "+Z)}else if(p0($))G=Uint8Array.from($);else throw Error(J+" must be hex string or Uint8Array");let Y=G.length;if(typeof Q==="number"&&Y!==Q)throw Error(J+" of length "+Q+" expected, got "+Y);return G}function qJ(...J){let $=0;for(let G=0;G<J.length;G++){let Y=J[G];aJ(Y),$+=Y.length}let Q=new Uint8Array($);for(let G=0,Y=0;G<J.length;G++){let Z=J[G];Q.set(Z,Y),Y+=Z.length}return Q}var iJ=(J)=>typeof J==="bigint"&&tJ<=J;function EJ(J,$,Q){return iJ(J)&&iJ($)&&iJ(Q)&&$<=J&&J<Q}function k0(J,$,Q,G){if(!EJ($,Q,G))throw Error("expected valid "+J+": "+Q+" <= n < "+G+", got "+$)}function e$(J){let $;for($=0;J>tJ;J>>=oJ,$+=1);return $}var w0=(J)=>(oJ<<BigInt(J))-oJ,nJ=(J)=>new Uint8Array(J),a$=(J)=>Uint8Array.from(J);function J8(J,$,Q){if(typeof J!=="number"||J<2)throw Error("hashLen must be a number");if(typeof $!=="number"||$<2)throw Error("qByteLen must be a number");if(typeof Q!=="function")throw Error("hmacFn must be a function");let G=nJ(J),Y=nJ(J),Z=0,K=()=>{G.fill(1),Y.fill(0),Z=0},q=(...N)=>Q(Y,G,...N),M=(N=nJ(0))=>{if(Y=q(a$([0]),N),G=q(),N.length===0)return;Y=q(a$([1]),N),G=q()},X=()=>{if(Z++>=1000)throw Error("drbg: tried 1000 values");let N=0,D=[];while(N<$){G=q();let V=G.slice();D.push(V),N+=G.length}return qJ(...D)};return(N,D)=>{K(),M(N);let V=void 0;while(!(V=D(X())))M();return K(),V}}var GQ={bigint:(J)=>typeof J==="bigint",function:(J)=>typeof J==="function",boolean:(J)=>typeof J==="boolean",string:(J)=>typeof J==="string",stringOrUint8Array:(J)=>typeof J==="string"||p0(J),isSafeInteger:(J)=>Number.isSafeInteger(J),array:(J)=>Array.isArray(J),field:(J,$)=>$.Fp.isValid(J),hash:(J)=>typeof J==="function"&&Number.isSafeInteger(J.outputLen)};function y0(J,$,Q={}){let G=(Y,Z,K)=>{let q=GQ[Z];if(typeof q!=="function")throw Error("invalid validator function");let M=J[Y];if(K&&M===void 0)return;if(!q(M,J))throw Error("param "+String(Y)+" is invalid. Expected "+Z+", got "+M)};for(let[Y,Z]of Object.entries($))G(Y,Z,!1);for(let[Y,Z]of Object.entries(Q))G(Y,Z,!0);return J}function eJ(J){let $=new WeakMap;return(Q,...G)=>{let Y=$.get(Q);if(Y!==void 0)return Y;let Z=J(Q,...G);return $.set(Q,Z),Z}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var a=BigInt(0),n=BigInt(1),F0=BigInt(2),YQ=BigInt(3),Q8=BigInt(4),G8=BigInt(5),Y8=BigInt(8);function i(J,$){let Q=J%$;return Q>=a?Q:$+Q}function $0(J,$,Q){let G=J;while($-- >a)G*=G,G%=Q;return G}function xJ(J,$){if(J===a)throw Error("invert: expected non-zero number");if($<=a)throw Error("invert: expected positive modulus, got "+$);let Q=i(J,$),G=$,Y=a,Z=n,K=n,q=a;while(Q!==a){let X=G/Q,j=G%Q,N=Y-K*X,D=Z-q*X;G=Q,Q=j,Y=K,Z=q,K=N,q=D}if(G!==n)throw Error("invert: does not exist");return i(Y,$)}function Z8(J,$){let Q=(J.ORDER+n)/Q8,G=J.pow($,Q);if(!J.eql(J.sqr(G),$))throw Error("Cannot find square root");return G}function ZQ(J,$){let Q=(J.ORDER-G8)/Y8,G=J.mul($,F0),Y=J.pow(G,Q),Z=J.mul($,Y),K=J.mul(J.mul(Z,F0),Y),q=J.mul(Z,J.sub(K,J.ONE));if(!J.eql(J.sqr(q),$))throw Error("Cannot find square root");return q}function KQ(J){if(J<BigInt(3))throw Error("sqrt is not defined for small field");let $=J-n,Q=0;while($%F0===a)$/=F0,Q++;let G=F0,Y=XJ(J);while($8(Y,G)===1)if(G++>1000)throw Error("Cannot find square root: probably non-prime P");if(Q===1)return Z8;let Z=Y.pow(G,$),K=($+n)/F0;return function(M,X){if(M.is0(X))return X;if($8(M,X)!==1)throw Error("Cannot find square root");let j=Q,N=M.mul(M.ONE,Z),D=M.pow(X,$),V=M.pow(X,K);while(!M.eql(D,M.ONE)){if(M.is0(D))return M.ZERO;let B=1,z=M.sqr(D);while(!M.eql(z,M.ONE))if(B++,z=M.sqr(z),B===j)throw Error("Cannot find square root");let A=n<<BigInt(j-B-1),I=M.pow(N,A);j=B,N=M.sqr(I),D=M.mul(D,N),V=M.mul(V,I)}return V}}function MQ(J){if(J%Q8===YQ)return Z8;if(J%Y8===G8)return ZQ;return KQ(J)}var qQ=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function J$(J){let $={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},Q=qQ.reduce((G,Y)=>{return G[Y]="function",G},$);return y0(J,Q)}function XQ(J,$,Q){if(Q<a)throw Error("invalid exponent, negatives unsupported");if(Q===a)return J.ONE;if(Q===n)return $;let G=J.ONE,Y=$;while(Q>a){if(Q&n)G=J.mul(G,Y);Y=J.sqr(Y),Q>>=n}return G}function $$(J,$,Q=!1){let G=Array($.length).fill(Q?J.ZERO:void 0),Y=$.reduce((K,q,M)=>{if(J.is0(q))return K;return G[M]=K,J.mul(K,q)},J.ONE),Z=J.inv(Y);return $.reduceRight((K,q,M)=>{if(J.is0(q))return K;return G[M]=J.mul(K,G[M]),J.mul(K,q)},Z),G}function $8(J,$){let Q=(J.ORDER-n)/F0,G=J.pow($,Q),Y=J.eql(G,J.ONE),Z=J.eql(G,J.ZERO),K=J.eql(G,J.neg(J.ONE));if(!Y&&!Z&&!K)throw Error("invalid Legendre symbol result");return Y?1:Z?0:-1}function Q$(J,$){if($!==void 0)I0($);let Q=$!==void 0?$:J.toString(2).length,G=Math.ceil(Q/8);return{nBitLength:Q,nByteLength:G}}function XJ(J,$,Q=!1,G={}){if(J<=a)throw Error("invalid field: expected ORDER > 0, got "+J);let{nBitLength:Y,nByteLength:Z}=Q$(J,$);if(Z>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");let K,q=Object.freeze({ORDER:J,isLE:Q,BITS:Y,BYTES:Z,MASK:w0(Y),ZERO:a,ONE:n,create:(M)=>i(M,J),isValid:(M)=>{if(typeof M!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof M);return a<=M&&M<J},is0:(M)=>M===a,isOdd:(M)=>(M&n)===n,neg:(M)=>i(-M,J),eql:(M,X)=>M===X,sqr:(M)=>i(M*M,J),add:(M,X)=>i(M+X,J),sub:(M,X)=>i(M-X,J),mul:(M,X)=>i(M*X,J),pow:(M,X)=>XQ(q,M,X),div:(M,X)=>i(M*xJ(X,J),J),sqrN:(M)=>M*M,addN:(M,X)=>M+X,subN:(M,X)=>M-X,mulN:(M,X)=>M*X,inv:(M)=>xJ(M,J),sqrt:G.sqrt||((M)=>{if(!K)K=MQ(J);return K(q,M)}),toBytes:(M)=>Q?rJ(M,Z):A0(M,Z),fromBytes:(M)=>{if(M.length!==Z)throw Error("Field.fromBytes: expected "+Z+" bytes, got "+M.length);return Q?sJ(M):W0(M)},invertBatch:(M)=>$$(q,M),cmov:(M,X,j)=>j?X:M});return Object.freeze(q)}function K8(J){if(typeof J!=="bigint")throw Error("field order must be bigint");let $=J.toString(2).length;return Math.ceil($/8)}function G$(J){let $=K8(J);return $+Math.ceil($/2)}function M8(J,$,Q=!1){let G=J.length,Y=K8($),Z=G$($);if(G<16||G<Z||G>1024)throw Error("expected "+Z+"-1024 bytes of input, got "+G);let K=Q?sJ(J):W0(J),q=i(K,$-n)+n;return Q?rJ(q,Y):A0(q,Y)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var q8=BigInt(0),q$=BigInt(1);function Y$(J,$){let Q=$.negate();return J?Q:$}function j8(J,$){if(!Number.isSafeInteger(J)||J<=0||J>$)throw Error("invalid window size, expected [1.."+$+"], got W="+J)}function Z$(J,$){j8(J,$);let Q=Math.ceil($/J)+1,G=2**(J-1),Y=2**J,Z=w0(J),K=BigInt(J);return{windows:Q,windowSize:G,mask:Z,maxNumber:Y,shiftBy:K}}function X8(J,$,Q){let{windowSize:G,mask:Y,maxNumber:Z,shiftBy:K}=Q,q=Number(J&Y),M=J>>K;if(q>G)q-=Z,M+=q$;let X=$*G,j=X+Math.abs(q)-1,N=q===0,D=q<0,V=$%2!==0;return{nextN:M,offset:j,isZero:N,isNeg:D,isNegF:V,offsetF:X}}function jQ(J,$){if(!Array.isArray(J))throw Error("array expected");J.forEach((Q,G)=>{if(!(Q instanceof $))throw Error("invalid point at index "+G)})}function UQ(J,$){if(!Array.isArray(J))throw Error("array of scalars expected");J.forEach((Q,G)=>{if(!$.isValid(Q))throw Error("invalid scalar at index "+G)})}var K$=new WeakMap,U8=new WeakMap;function M$(J){return U8.get(J)||1}function W8(J,$){return{constTimeNegate:Y$,hasPrecomputes(Q){return M$(Q)!==1},unsafeLadder(Q,G,Y=J.ZERO){let Z=Q;while(G>q8){if(G&q$)Y=Y.add(Z);Z=Z.double(),G>>=q$}return Y},precomputeWindow(Q,G){let{windows:Y,windowSize:Z}=Z$(G,$),K=[],q=Q,M=q;for(let X=0;X<Y;X++){M=q,K.push(M);for(let j=1;j<Z;j++)M=M.add(q),K.push(M);q=M.double()}return K},wNAF(Q,G,Y){let{ZERO:Z,BASE:K}=J,q=Z$(Q,$);for(let M=0;M<q.windows;M++){let{nextN:X,offset:j,isZero:N,isNeg:D,isNegF:V,offsetF:B}=X8(Y,M,q);if(Y=X,N)K=K.add(Y$(V,G[B]));else Z=Z.add(Y$(D,G[j]))}return{p:Z,f:K}},wNAFUnsafe(Q,G,Y,Z=J.ZERO){let K=Z$(Q,$);for(let q=0;q<K.windows;q++){if(Y===q8)break;let{nextN:M,offset:X,isZero:j,isNeg:N}=X8(Y,q,K);if(Y=M,j)continue;else{let D=G[X];Z=Z.add(N?D.negate():D)}}return Z},getPrecomputes(Q,G,Y){let Z=K$.get(G);if(!Z){if(Z=this.precomputeWindow(G,Q),Q!==1)K$.set(G,Y(Z))}return Z},wNAFCached(Q,G,Y){let Z=M$(Q);return this.wNAF(Z,this.getPrecomputes(Z,Q,Y),G)},wNAFCachedUnsafe(Q,G,Y,Z){let K=M$(Q);if(K===1)return this.unsafeLadder(Q,G,Z);return this.wNAFUnsafe(K,this.getPrecomputes(K,Q,Y),G,Z)},setWindowSize(Q,G){j8(G,$),U8.set(Q,G),K$.delete(Q)}}}function N8(J,$,Q,G){jQ(Q,J),UQ(G,$);let Y=Q.length,Z=G.length;if(Y!==Z)throw Error("arrays of points and scalars must have equal length");let K=J.ZERO,q=e$(BigInt(Y)),M=1;if(q>12)M=q-3;else if(q>4)M=q-2;else if(q>0)M=2;let X=w0(M),j=Array(Number(X)+1).fill(K),N=Math.floor(($.BITS-1)/M)*M,D=K;for(let V=N;V>=0;V-=M){j.fill(K);for(let z=0;z<Z;z++){let A=G[z],I=Number(A>>BigInt(V)&X);j[I]=j[I].add(Q[z])}let B=K;for(let z=j.length-1,A=K;z>0;z--)A=A.add(j[z]),B=B.add(A);if(D=D.add(B),V!==0)for(let z=0;z<M;z++)D=D.double()}return D}function X$(J){return J$(J.Fp),y0(J,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Q$(J.n,J.nBitLength),...J,...{p:J.Fp.ORDER}})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function z8(J){if(J.lowS!==void 0)d0("lowS",J.lowS);if(J.prehash!==void 0)d0("prehash",J.prehash)}function WQ(J){let $=X$(J);y0($,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:Q,Fp:G,a:Y}=$;if(Q){if(!G.eql(Y,G.ZERO))throw Error("invalid endo: CURVE.a must be 0");if(typeof Q!=="object"||typeof Q.beta!=="bigint"||typeof Q.splitScalar!=="function")throw Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...$})}class D8 extends Error{constructor(J=""){super(J)}}var N0={Err:D8,_tlv:{encode:(J,$)=>{let{Err:Q}=N0;if(J<0||J>256)throw new Q("tlv.encode: wrong tag");if($.length&1)throw new Q("tlv.encode: unpadded data");let G=$.length/2,Y=KJ(G);if(Y.length/2&128)throw new Q("tlv.encode: long form length too big");let Z=G>127?KJ(Y.length/2|128):"";return KJ(J)+Z+Y+$},decode(J,$){let{Err:Q}=N0,G=0;if(J<0||J>256)throw new Q("tlv.encode: wrong tag");if($.length<2||$[G++]!==J)throw new Q("tlv.decode: wrong tlv");let Y=$[G++],Z=!!(Y&128),K=0;if(!Z)K=Y;else{let M=Y&127;if(!M)throw new Q("tlv.decode(long): indefinite length not supported");if(M>4)throw new Q("tlv.decode(long): byte length is too big");let X=$.subarray(G,G+M);if(X.length!==M)throw new Q("tlv.decode: length bytes not complete");if(X[0]===0)throw new Q("tlv.decode(long): zero leftmost byte");for(let j of X)K=K<<8|j;if(G+=M,K<128)throw new Q("tlv.decode(long): not minimal encoding")}let q=$.subarray(G,G+K);if(q.length!==K)throw new Q("tlv.decode: wrong value length");return{v:q,l:$.subarray(G+K)}}},_int:{encode(J){let{Err:$}=N0;if(J<z0)throw new $("integer: negative integers are not allowed");let Q=KJ(J);if(Number.parseInt(Q[0],16)&8)Q="00"+Q;if(Q.length&1)throw new $("unexpected DER parsing assertion: unpadded hex");return Q},decode(J){let{Err:$}=N0;if(J[0]&128)throw new $("invalid signature integer: negative");if(J[0]===0&&!(J[1]&128))throw new $("invalid signature integer: unnecessary leading zero");return W0(J)}},toSig(J){let{Err:$,_int:Q,_tlv:G}=N0,Y=e("signature",J),{v:Z,l:K}=G.decode(48,Y);if(K.length)throw new $("invalid signature: left bytes after parsing");let{v:q,l:M}=G.decode(2,Z),{v:X,l:j}=G.decode(2,M);if(j.length)throw new $("invalid signature: left bytes after parsing");return{r:Q.decode(q),s:Q.decode(X)}},hexFromSig(J){let{_tlv:$,_int:Q}=N0,G=$.encode(2,Q.encode(J.r)),Y=$.encode(2,Q.encode(J.s)),Z=G+Y;return $.encode(48,Z)}};function j$(J,$){return i0(A0(J,$))}var z0=BigInt(0),l=BigInt(1),a9=BigInt(2),U$=BigInt(3),NQ=BigInt(4);function zQ(J){let $=WQ(J),{Fp:Q}=$,G=XJ($.n,$.nBitLength),Y=$.toBytes||((U,R,P)=>{let H=R.toAffine();return qJ(Uint8Array.from([4]),Q.toBytes(H.x),Q.toBytes(H.y))}),Z=$.fromBytes||((U)=>{let R=U.subarray(1),P=Q.fromBytes(R.subarray(0,Q.BYTES)),H=Q.fromBytes(R.subarray(Q.BYTES,2*Q.BYTES));return{x:P,y:H}});function K(U){let{a:R,b:P}=$,H=Q.sqr(U),w=Q.mul(H,U);return Q.add(Q.add(w,Q.mul(U,R)),P)}function q(U,R){let P=Q.sqr(R),H=K(U);return Q.eql(P,H)}if(!q($.Gx,$.Gy))throw Error("bad curve params: generator point");let M=Q.mul(Q.pow($.a,U$),NQ),X=Q.mul(Q.sqr($.b),BigInt(27));if(Q.is0(Q.add(M,X)))throw Error("bad curve params: a or b");function j(U){return EJ(U,l,$.n)}function N(U){let{allowedPrivateKeyLengths:R,nByteLength:P,wrapPrivateKey:H,n:w}=$;if(R&&typeof U!=="bigint"){if(p0(U))U=i0(U);if(typeof U!=="string"||!R.includes(U.length))throw Error("invalid private key");U=U.padStart(P*2,"0")}let E;try{E=typeof U==="bigint"?U:W0(e("private key",U,P))}catch(y){throw Error("invalid private key, expected hex or "+P+" bytes, got "+typeof U)}if(H)E=i(E,w);return k0("private key",E,l,w),E}function D(U){if(!(U instanceof z))throw Error("ProjectivePoint expected")}let V=eJ((U,R)=>{let{px:P,py:H,pz:w}=U;if(Q.eql(w,Q.ONE))return{x:P,y:H};let E=U.is0();if(R==null)R=E?Q.ONE:Q.inv(w);let y=Q.mul(P,R),_=Q.mul(H,R),k=Q.mul(w,R);if(E)return{x:Q.ZERO,y:Q.ZERO};if(!Q.eql(k,Q.ONE))throw Error("invZ was invalid");return{x:y,y:_}}),B=eJ((U)=>{if(U.is0()){if($.allowInfinityPoint&&!Q.is0(U.py))return;throw Error("bad point: ZERO")}let{x:R,y:P}=U.toAffine();if(!Q.isValid(R)||!Q.isValid(P))throw Error("bad point: x or y not FE");if(!q(R,P))throw Error("bad point: equation left != right");if(!U.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});class z{constructor(U,R,P){if(U==null||!Q.isValid(U))throw Error("x required");if(R==null||!Q.isValid(R)||Q.is0(R))throw Error("y required");if(P==null||!Q.isValid(P))throw Error("z required");this.px=U,this.py=R,this.pz=P,Object.freeze(this)}static fromAffine(U){let{x:R,y:P}=U||{};if(!U||!Q.isValid(R)||!Q.isValid(P))throw Error("invalid affine point");if(U instanceof z)throw Error("projective point not allowed");let H=(w)=>Q.eql(w,Q.ZERO);if(H(R)&&H(P))return z.ZERO;return new z(R,P,Q.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(U){let R=$$(Q,U.map((P)=>P.pz));return U.map((P,H)=>P.toAffine(R[H])).map(z.fromAffine)}static fromHex(U){let R=z.fromAffine(Z(e("pointHex",U)));return R.assertValidity(),R}static fromPrivateKey(U){return z.BASE.multiply(N(U))}static msm(U,R){return N8(z,G,U,R)}_setWindowSize(U){v.setWindowSize(this,U)}assertValidity(){B(this)}hasEvenY(){let{y:U}=this.toAffine();if(Q.isOdd)return!Q.isOdd(U);throw Error("Field doesn't support isOdd")}equals(U){D(U);let{px:R,py:P,pz:H}=this,{px:w,py:E,pz:y}=U,_=Q.eql(Q.mul(R,y),Q.mul(w,H)),k=Q.eql(Q.mul(P,y),Q.mul(E,H));return _&&k}negate(){return new z(this.px,Q.neg(this.py),this.pz)}double(){let{a:U,b:R}=$,P=Q.mul(R,U$),{px:H,py:w,pz:E}=this,y=Q.ZERO,_=Q.ZERO,k=Q.ZERO,x=Q.mul(H,H),u=Q.mul(w,w),f=Q.mul(E,E),W=Q.mul(H,w);return W=Q.add(W,W),k=Q.mul(H,E),k=Q.add(k,k),y=Q.mul(U,k),_=Q.mul(P,f),_=Q.add(y,_),y=Q.sub(u,_),_=Q.add(u,_),_=Q.mul(y,_),y=Q.mul(W,y),k=Q.mul(P,k),f=Q.mul(U,f),W=Q.sub(x,f),W=Q.mul(U,W),W=Q.add(W,k),k=Q.add(x,x),x=Q.add(k,x),x=Q.add(x,f),x=Q.mul(x,W),_=Q.add(_,x),f=Q.mul(w,E),f=Q.add(f,f),x=Q.mul(f,W),y=Q.sub(y,x),k=Q.mul(f,u),k=Q.add(k,k),k=Q.add(k,k),new z(y,_,k)}add(U){D(U);let{px:R,py:P,pz:H}=this,{px:w,py:E,pz:y}=U,_=Q.ZERO,k=Q.ZERO,x=Q.ZERO,u=$.a,f=Q.mul($.b,U$),W=Q.mul(R,w),L=Q.mul(P,E),S=Q.mul(H,y),F=Q.add(R,P),T=Q.add(w,E);F=Q.mul(F,T),T=Q.add(W,L),F=Q.sub(F,T),T=Q.add(R,H);let O=Q.add(w,y);return T=Q.mul(T,O),O=Q.add(W,S),T=Q.sub(T,O),O=Q.add(P,H),_=Q.add(E,y),O=Q.mul(O,_),_=Q.add(L,S),O=Q.sub(O,_),x=Q.mul(u,T),_=Q.mul(f,S),x=Q.add(_,x),_=Q.sub(L,x),x=Q.add(L,x),k=Q.mul(_,x),L=Q.add(W,W),L=Q.add(L,W),S=Q.mul(u,S),T=Q.mul(f,T),L=Q.add(L,S),S=Q.sub(W,S),S=Q.mul(u,S),T=Q.add(T,S),W=Q.mul(L,T),k=Q.add(k,W),W=Q.mul(O,T),_=Q.mul(F,_),_=Q.sub(_,W),W=Q.mul(F,L),x=Q.mul(O,x),x=Q.add(x,W),new z(_,k,x)}subtract(U){return this.add(U.negate())}is0(){return this.equals(z.ZERO)}wNAF(U){return v.wNAFCached(this,U,z.normalizeZ)}multiplyUnsafe(U){let{endo:R,n:P}=$;k0("scalar",U,z0,P);let H=z.ZERO;if(U===z0)return H;if(this.is0()||U===l)return this;if(!R||v.hasPrecomputes(this))return v.wNAFCachedUnsafe(this,U,z.normalizeZ);let{k1neg:w,k1:E,k2neg:y,k2:_}=R.splitScalar(U),k=H,x=H,u=this;while(E>z0||_>z0){if(E&l)k=k.add(u);if(_&l)x=x.add(u);u=u.double(),E>>=l,_>>=l}if(w)k=k.negate();if(y)x=x.negate();return x=new z(Q.mul(x.px,R.beta),x.py,x.pz),k.add(x)}multiply(U){let{endo:R,n:P}=$;k0("scalar",U,l,P);let H,w;if(R){let{k1neg:E,k1:y,k2neg:_,k2:k}=R.splitScalar(U),{p:x,f:u}=this.wNAF(y),{p:f,f:W}=this.wNAF(k);x=v.constTimeNegate(E,x),f=v.constTimeNegate(_,f),f=new z(Q.mul(f.px,R.beta),f.py,f.pz),H=x.add(f),w=u.add(W)}else{let{p:E,f:y}=this.wNAF(U);H=E,w=y}return z.normalizeZ([H,w])[0]}multiplyAndAddUnsafe(U,R,P){let H=z.BASE,w=(y,_)=>_===z0||_===l||!y.equals(H)?y.multiplyUnsafe(_):y.multiply(_),E=w(this,R).add(w(U,P));return E.is0()?void 0:E}toAffine(U){return V(this,U)}isTorsionFree(){let{h:U,isTorsionFree:R}=$;if(U===l)return!0;if(R)return R(z,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:U,clearCofactor:R}=$;if(U===l)return this;if(R)return R(z,this);return this.multiplyUnsafe($.h)}toRawBytes(U=!0){return d0("isCompressed",U),this.assertValidity(),Y(z,this,U)}toHex(U=!0){return d0("isCompressed",U),i0(this.toRawBytes(U))}}z.BASE=new z($.Gx,$.Gy,Q.ONE),z.ZERO=new z(Q.ZERO,Q.ONE,Q.ZERO);let{endo:A,nBitLength:I}=$,v=W8(z,A?Math.ceil(I/2):I);return{CURVE:$,ProjectivePoint:z,normPrivateKeyToScalar:N,weierstrassEquation:K,isWithinCurveOrder:j}}function DQ(J){let $=X$(J);return y0($,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...$})}function V8(J){let $=DQ(J),{Fp:Q,n:G,nByteLength:Y,nBitLength:Z}=$,K=Q.BYTES+1,q=2*Q.BYTES+1;function M(W){return i(W,G)}function X(W){return xJ(W,G)}let{ProjectivePoint:j,normPrivateKeyToScalar:N,weierstrassEquation:D,isWithinCurveOrder:V}=zQ({...$,toBytes(W,L,S){let F=L.toAffine(),T=Q.toBytes(F.x),O=qJ;if(d0("isCompressed",S),S)return O(Uint8Array.from([L.hasEvenY()?2:3]),T);else return O(Uint8Array.from([4]),T,Q.toBytes(F.y))},fromBytes(W){let L=W.length,S=W[0],F=W.subarray(1);if(L===K&&(S===2||S===3)){let T=W0(F);if(!EJ(T,l,Q.ORDER))throw Error("Point is not on curve");let O=D(T),b;try{b=Q.sqrt(O)}catch(s){let r=s instanceof Error?": "+s.message:"";throw Error("Point is not on curve"+r)}let h=(b&l)===l;if((S&1)===1!==h)b=Q.neg(b);return{x:T,y:b}}else if(L===q&&S===4){let T=Q.fromBytes(F.subarray(0,Q.BYTES)),O=Q.fromBytes(F.subarray(Q.BYTES,2*Q.BYTES));return{x:T,y:O}}else{let T=K,O=q;throw Error("invalid Point, expected length of "+T+", or uncompressed "+O+", got "+L)}}});function B(W){let L=G>>l;return W>L}function z(W){return B(W)?M(-W):W}let A=(W,L,S)=>W0(W.slice(L,S));class I{constructor(W,L,S){if(k0("r",W,l,G),k0("s",L,l,G),this.r=W,this.s=L,S!=null)this.recovery=S;Object.freeze(this)}static fromCompact(W){let L=Y;return W=e("compactSignature",W,L*2),new I(A(W,0,L),A(W,L,2*L))}static fromDER(W){let{r:L,s:S}=N0.toSig(e("DER",W));return new I(L,S)}assertValidity(){}addRecoveryBit(W){return new I(this.r,this.s,W)}recoverPublicKey(W){let{r:L,s:S,recovery:F}=this,T=w(e("msgHash",W));if(F==null||![0,1,2,3].includes(F))throw Error("recovery id invalid");let O=F===2||F===3?L+$.n:L;if(O>=Q.ORDER)throw Error("recovery id 2 or 3 invalid");let b=(F&1)===0?"02":"03",h=j.fromHex(b+j$(O,Q.BYTES)),c=X(O),s=M(-T*c),r=M(S*c),D0=j.BASE.multiplyAndAddUnsafe(h,s,r);if(!D0)throw Error("point at infinify");return D0.assertValidity(),D0}hasHighS(){return B(this.s)}normalizeS(){return this.hasHighS()?new I(this.r,M(-this.s),this.recovery):this}toDERRawBytes(){return MJ(this.toDERHex())}toDERHex(){return N0.hexFromSig(this)}toCompactRawBytes(){return MJ(this.toCompactHex())}toCompactHex(){let W=Y;return j$(this.r,W)+j$(this.s,W)}}let v={isValidPrivateKey(W){try{return N(W),!0}catch(L){return!1}},normPrivateKeyToScalar:N,randomPrivateKey:()=>{let W=G$($.n);return M8($.randomBytes(W),$.n)},precompute(W=8,L=j.BASE){return L._setWindowSize(W),L.multiply(BigInt(3)),L}};function U(W,L=!0){return j.fromPrivateKey(W).toRawBytes(L)}function R(W){if(typeof W==="bigint")return!1;if(W instanceof j)return!0;let S=e("key",W).length,F=Q.BYTES,T=F+1,O=2*F+1;if($.allowedPrivateKeyLengths||Y===T)return;else return S===T||S===O}function P(W,L,S=!0){if(R(W)===!0)throw Error("first arg must be private key");if(R(L)===!1)throw Error("second arg must be public key");return j.fromHex(L).multiply(N(W)).toRawBytes(S)}let H=$.bits2int||function(W){if(W.length>8192)throw Error("input is too large");let L=W0(W),S=W.length*8-Z;return S>0?L>>BigInt(S):L},w=$.bits2int_modN||function(W){return M(H(W))},E=w0(Z);function y(W){return k0("num < 2^"+Z,W,z0,E),A0(W,Y)}function _(W,L,S=k){if(["recovered","canonical"].some((C0)=>(C0 in S)))throw Error("sign() legacy options not supported");let{hash:F,randomBytes:T}=$,{lowS:O,prehash:b,extraEntropy:h}=S;if(O==null)O=!0;if(W=e("msgHash",W),z8(S),b)W=e("prehashed msgHash",F(W));let c=w(W),s=N(L),r=[y(s),y(c)];if(h!=null&&h!==!1){let C0=h===!0?T(Q.BYTES):h;r.push(e("extraEntropy",C0))}let D0=qJ(...r),WJ=c;function kJ(C0){let b0=H(C0);if(!V(b0))return;let wJ=X(b0),n0=j.BASE.multiply(b0).toAffine(),P0=M(n0.x);if(P0===z0)return;let o0=M(wJ*M(WJ+P0*s));if(o0===z0)return;let g0=(n0.x===P0?0:2)|Number(n0.y&l),B$=o0;if(O&&B(o0))B$=z(o0),g0^=1;return new I(P0,B$,g0)}return{seed:D0,k2sig:kJ}}let k={lowS:$.lowS,prehash:!1},x={lowS:$.lowS,prehash:!1};function u(W,L,S=k){let{seed:F,k2sig:T}=_(W,L,S),O=$;return J8(O.hash.outputLen,O.nByteLength,O.hmac)(F,T)}j.BASE._setWindowSize(8);function f(W,L,S,F=x){let T=W;L=e("msgHash",L),S=e("publicKey",S);let{lowS:O,prehash:b,format:h}=F;if(z8(F),"strict"in F)throw Error("options.strict was renamed to lowS");if(h!==void 0&&h!=="compact"&&h!=="der")throw Error("format must be compact or der");let c=typeof T==="string"||p0(T),s=!c&&!h&&typeof T==="object"&&T!==null&&typeof T.r==="bigint"&&typeof T.s==="bigint";if(!c&&!s)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");let r=void 0,D0;try{if(s)r=new I(T.r,T.s);if(c){try{if(h!=="compact")r=I.fromDER(T)}catch(g0){if(!(g0 instanceof N0.Err))throw g0}if(!r&&h!=="der")r=I.fromCompact(T)}D0=j.fromHex(S)}catch(g0){return!1}if(!r)return!1;if(O&&r.hasHighS())return!1;if(b)L=$.hash(L);let{r:WJ,s:kJ}=r,C0=w(L),b0=X(kJ),wJ=M(C0*b0),n0=M(WJ*b0),P0=j.BASE.multiplyAndAddUnsafe(D0,wJ,n0)?.toAffine();if(!P0)return!1;return M(P0.x)===WJ}return{CURVE:$,getPublicKey:U,getSharedSecret:P,sign:u,verify:f,ProjectivePoint:j,Signature:I,utils:v}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function VQ(J){return{hash:J,hmac:($,...Q)=>dJ(J,$,w$(...Q)),randomBytes:y$}}function O8(J,$){let Q=(G)=>V8({...J,...VQ(G)});return{...Q($),create:Q}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var C8=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),R8=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),OQ=BigInt(0),RQ=BigInt(1),W$=BigInt(2),L8=(J,$)=>(J+$/W$)/$;function LQ(J){let $=C8,Q=BigInt(3),G=BigInt(6),Y=BigInt(11),Z=BigInt(22),K=BigInt(23),q=BigInt(44),M=BigInt(88),X=J*J*J%$,j=X*X*J%$,N=$0(j,Q,$)*j%$,D=$0(N,Q,$)*j%$,V=$0(D,W$,$)*X%$,B=$0(V,Y,$)*V%$,z=$0(B,Z,$)*B%$,A=$0(z,q,$)*z%$,I=$0(A,M,$)*A%$,v=$0(I,q,$)*z%$,U=$0(v,Q,$)*j%$,R=$0(U,K,$)*B%$,P=$0(R,G,$)*X%$,H=$0(P,W$,$);if(!N$.eql(N$.sqr(H),J))throw Error("Cannot find square root");return H}var N$=XJ(C8,void 0,void 0,{sqrt:LQ}),z$=O8({a:OQ,b:BigInt(7),Fp:N$,n:R8,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:(J)=>{let $=R8,Q=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),G=-RQ*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),Y=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),Z=Q,K=BigInt("0x100000000000000000000000000000000"),q=L8(Z*J,$),M=L8(-G*J,$),X=i(J-q*Q-M*Y,$),j=i(-q*G-M*Z,$),N=X>K,D=j>K;if(N)X=$-X;if(D)j=$-j;if(X>K||j>K)throw Error("splitScalar: Endomorphism failed, k="+J);return{k1neg:N,k1:X,k2neg:D,k2:j}}}},o$);function D$(){let J=z$.utils.randomPrivateKey();return"0x"+Buffer.from(J).toString("hex")}function V$(J){let $=J.startsWith("0x")?J.slice(2):J,Q=Buffer.from($,"hex"),G=z$.getPublicKey(Q,!1),Z=v0(G.slice(1)).slice(-20),K="0x"+Buffer.from(Z).toString("hex");return R0(K)}function AJ(J){let $;if(typeof J==="string"){let G=J.startsWith("0x")?J.slice(2):J;$=Buffer.from(G,"hex")}else $=J;let Q=v0($);return"0x"+Buffer.from(Q).toString("hex")}class d extends _J{constructor(J,$){super("InvitationError",J,{...$,source:$?.source||"INVITATIONS"})}static noPathFound(J,$,Q){return new d(`No valid invitation path found from ${J} to ${$}. ${Q||"The inviter may not have enough balance of the proxy inviter's token or there's no trust connection."}`,{code:"INVITATION_NO_PATH",source:"PATHFINDING",context:{from:J,to:$,reason:Q}})}static noProxyInviters(J){return new d(`No proxy inviters found for ${J}. The inviter must have mutual trust connections with users who are also trusted by the invitation module, and these users must have sufficient balance.`,{code:"INVITATION_NO_PROXY_INVITERS",source:"VALIDATION",context:{inviter:J}})}static insufficientBalance(J,$,Q,G,Y,Z){let K=Number(Q)/1000000000000000000,q=Number(G)/1000000000000000000;return new d(`Insufficient balance for ${J} invitation(s). Can only afford ${$} invitation(s). Requested: ${K.toFixed(6)} CRC, Available: ${q.toFixed(6)} CRC.`,{code:"INVITATION_INSUFFICIENT_BALANCE",source:"VALIDATION",context:{from:Y,to:Z,requestedInvites:J,availableInvites:$,requested:Q.toString(),available:G.toString(),requestedCrc:K,availableCrc:q}})}static inviteeAlreadyRegistered(J,$){return new d(`Invitee ${$} is already registered as a human in Circles Hub. Cannot invite an already registered user.`,{code:"INVITATION_INVITEE_ALREADY_REGISTERED",source:"VALIDATION",context:{inviter:J,invitee:$}})}static noAddressesProvided(){return new d("At least one address must be provided for invitation.",{code:"INVITATION_NO_ADDRESSES_PROVIDED",source:"VALIDATION"})}}var P8=[];for(let J=0;J<256;J++)P8[J]=J.toString(16).padStart(2,"0");function jJ(J){let $="0x";for(let Q=0;Q<J.length;Q++)$+=P8[J[Q]];return $}function B8(J){let $=new Uint8Array(J.length*2);return J.forEach((Q,G)=>{let Y=Q>>8,Z=Q&255,K=2*G;$[K]=Y,$[K+1]=Z}),jJ($)}function I8(J,$,Q){let G=new Set([$.toLowerCase(),Q.toLowerCase()]);J.forEach((K)=>{G.add(K.from.toLowerCase()),G.add(K.to.toLowerCase()),G.add(K.tokenOwner.toLowerCase())});let Y=[...G].sort((K,q)=>{let M=BigInt(K),X=BigInt(q),j=M<X,N=M>X;return j?-1:N?1:0}),Z={};return Y.forEach((K,q)=>{Z[K]=q}),{sorted:Y,idx:Z}}function CQ(J,$){let Q=new Set,G=[],Y=null;if(J.forEach((Z,K)=>{let q=Z.from.toLowerCase(),M=Z.to.toLowerCase();if(q===$&&M===$)Y=K;else if(M===$)G.push(K)}),Y!==null)Q.add(Y);else G.forEach((Z)=>Q.add(Z));return Q}function O$(J,$,Q,G){let Y=J.toLowerCase(),Z=$.toLowerCase(),{sorted:K,idx:q}=I8(G,Y,Z),M=CQ(G,Z),X=G.map((I,v)=>{return{streamSinkId:M.has(v)?1:0,amount:I.value}});if(M.size===0)throw Error(`No terminal edges detected. Flow must have at least one edge delivering to receiver ${Z}`);let j=Array.from(M),N=[{sourceCoordinate:q[Y],flowEdgeIds:j,data:new Uint8Array(0)}],D=[];G.forEach((I)=>{D.push(q[I.tokenOwner.toLowerCase()]),D.push(q[I.from.toLowerCase()]),D.push(q[I.to.toLowerCase()])});let V=B8(D),B=BigInt(Q),z=X.filter((I)=>I.streamSinkId===1).reduce((I,v)=>I+BigInt(v.amount.toString()),BigInt(0));if(z!==B)throw Error(`Terminal sum ${z} does not equal expected ${B}`);return{flowVertices:K,flowEdges:X,streams:N,packedCoordinates:V,sourceCoordinate:q[Y]}}function R$(J,$){let Q=J.streams.map((G)=>({sourceCoordinate:G.sourceCoordinate,flowEdgeIds:G.flowEdgeIds,data:G.data instanceof Uint8Array?jJ(G.data):G.data}));if($&&Q.length>0)Q[0].data=$ instanceof Uint8Array?jJ($):$;return Q}async function L$(J,$,Q){let G=new Map,Y=new Set;return Q.transfers.forEach((q)=>{if(J.toLowerCase()===q.from.toLowerCase())Y.add(q.tokenOwner.toLowerCase())}),(await new HJ($).token.getTokenInfoBatch(Array.from(Y))).forEach((q)=>{if(q.isWrapped&&!q.isInflationary)q.tokenType="CrcV2_ERC20WrapperDeployed_Demurraged";G.set(q.tokenAddress.toLowerCase(),q)}),G}function C$(J,$){let Q={};return J.transfers.forEach((G)=>{let Y=$.get(G.tokenOwner.toLowerCase());if(Y&&Y.tokenType.startsWith("CrcV2_ERC20WrapperDeployed")){if(!Q[G.tokenOwner])Q[G.tokenOwner]=[BigInt(0),Y.tokenType];Q[G.tokenOwner][0]+=BigInt(G.value)}}),Q}function P$(J,$){let Q=J.transfers.map((G)=>{let Y=$.get(G.tokenOwner.toLowerCase());if(Y&&Y.tokenType.startsWith("CrcV2_ERC20WrapperDeployed"))return{...G,tokenOwner:Y.tokenOwner};return G});return{...J,transfers:Q}}class o extends a0{constructor(J,$){super("TransferError",J,{...$,source:$?.source||"TRANSFERS"})}static noPathFound(J,$,Q){return new o(`No valid transfer path found from ${J} to ${$}. ${Q||"This could mean there's no trust connection, insufficient balance, or the tokens are not transferable."}`,{code:"TRANSFER_NO_PATH",source:"PATHFINDING",context:{from:J,to:$,reason:Q}})}static insufficientBalance(J,$,Q,G){let Y=Number(J)/1000000000000000000,Z=Number($)/1000000000000000000;return new o(`Insufficient balance for transfer. Requested: ${Y.toFixed(6)} CRC, Available: ${Z.toFixed(6)} CRC.`,{code:"TRANSFER_INSUFFICIENT_BALANCE",source:"VALIDATION",context:{from:Q,to:G,requested:J.toString(),available:$.toString(),requestedCrc:Y,availableCrc:Z}})}static wrappedTokensRequired(){return new o("Insufficient unwrapped token balance for transfer. Your balance contains wrapped tokens (ERC20 wrappers), but useWrappedBalances option is not enabled. Please enable it by passing { useWrappedBalances: true } in the transfer options.",{code:"TRANSFER_WRAPPED_TOKENS_REQUIRED",source:"VALIDATION"})}static unregisteredAvatars(J){return new o(`Flow matrix contains ${J.length} unregistered avatar(s): ${J.join(", ")}. All addresses in the flow must be registered Circles avatars (human or group).`,{code:"TRANSFER_UNREGISTERED_AVATARS",source:"FLOW_MATRIX",context:{unregisteredAddresses:J,count:J.length}})}static flowMatrixMismatch(J,$){return new o(`Flow matrix terminal sum (${J}) does not equal expected amount (${$})`,{code:"TRANSFER_FLOW_MATRIX_MISMATCH",source:"FLOW_MATRIX",context:{terminalSum:J.toString(),expected:$.toString()}})}static emptyPath(J,$){return new o(`Transfer path is empty for route from ${J} to ${$}`,{code:"TRANSFER_EMPTY_PATH",source:"PATHFINDING",context:{from:J,to:$}})}}class UJ{config;hubV2;liftERC20;rpcClient;pathfinder;balance;group;constructor(J){this.config=J,this.hubV2=new u0({address:J.v2HubAddress,rpcUrl:J.circlesRpcUrl}),this.liftERC20=new SJ({address:J.liftERC20Address,rpcUrl:J.circlesRpcUrl}),this.rpcClient=new V0(J.circlesRpcUrl),this.pathfinder=new X0(this.rpcClient),this.balance=new E0(this.rpcClient),this.group=new x0(this.rpcClient)}async buildFlowMatrixTx(J,$,Q,G,Y=!1){let Z=J.toLowerCase(),K=$.toLowerCase();if(!Q.transfers||Q.transfers.length===0)throw o.noPathFound(Z,K);let q={...Q};if(Y&&G?.toTokens?.length===1){let v=G.toTokens[0].toLowerCase();if(Q.maxFlow>0n)q.transfers.push({from:K,to:K,tokenOwner:v,value:Q.maxFlow})}let M=await L$(Z,this.config.circlesRpcUrl,q),X=C$(q,M),j=Object.keys(X).length>0;if(j&&!G?.useWrappedBalances)throw o.wrappedTokensRequired();let N=[],D=[];if(j){let v=await this._getTokenBalanceMap(Z),U=this._createDemurragedUnwrapCalls(X),{unwrapCalls:R,wrapCalls:P}=this._createInflationaryUnwrapAndWrapCalls(X,M,v);N=[...U,...R],D=P,q=P$(q,M)}let V=O$(Z,K,q.maxFlow,q.transfers),B=R$(V,G?.txData),z=this.hubV2.operateFlowMatrix(V.flowVertices,V.flowEdges,B,V.packedCoordinates),A=!1;try{A=await this.hubV2.isApprovedForAll(Z,Z)}catch(v){console.warn("Failed to check approval status, including approval transaction:",v)}return[...A?[]:[this.hubV2.setApprovalForAll(Z,!0)],...N,z,...D]}async constructAdvancedTransfer(J,$,Q,G,Y=!1){let Z=J.toLowerCase(),K=$.toLowerCase(),q=BigInt(Q);if(Z===K&&G?.fromTokens?.length===1&&G?.toTokens?.length===1){let V=G.fromTokens[0],B=G.toTokens[0],[z,A]=await Promise.all([this.liftERC20.erc20Circles(0,B),this.liftERC20.erc20Circles(1,B)]);if(V.toLowerCase()===z.toLowerCase()&&z!==IJ){let v=new c0({address:V,rpcUrl:this.config.circlesRpcUrl}).unwrap(q);return[{to:v.to,data:v.data,value:v.value??0n}]}if(V.toLowerCase()===A.toLowerCase()&&A!==IJ){let I=new l0({address:V,rpcUrl:this.config.circlesRpcUrl}),v=p.attoCirclesToAttoStaticCircles(q),U=I.unwrap(v);return[{to:U.to,data:U.data,value:U.value??0n}]}}let M=this._truncateToSixDecimals(q),X=await this._getDefaultTokenExcludeList(K,G?.excludeFromTokens),{...j}=G||{},N={...j,...X?{excludeFromTokens:X}:{}},D=await this.pathfinder.findPath({from:Z,to:K,targetFlow:M,...N});if(!D.transfers||D.transfers.length===0)throw o.noPathFound(Z,K);if(D.maxFlow<M)throw o.insufficientBalance(M,D.maxFlow,Z,K);return this.buildFlowMatrixTx(Z,K,D,G,Y)}async constructReplenish(J,$,Q,G){let Y=J.toLowerCase(),Z=$.toLowerCase(),K=(G||J).toLowerCase(),q=BigInt(Q),X=(await this.balance.getTokenBalances(Y)).filter((O)=>O.tokenOwner.toLowerCase()===Z),j=0n,N=0n,D=0n,V=null,B=null;for(let O of X)if(O.isWrapped)if(O.tokenType.includes("Demurrage"))N=BigInt(O.attoCircles),V=O.tokenAddress;else D=BigInt(O.staticAttoCircles),B=O.tokenAddress;else j=BigInt(O.attoCircles);let z=j+N+p.attoStaticCirclesToAttoCircles(D),A=[];if(j>=q){if(console.log(`✓ Already have ${Number(j)/1000000000000000000} CRC unwrapped (target: ${Number(q)/1000000000000000000} CRC). No replenish needed.`),K!==Y){let O=await this.hubV2.toTokenId(Z),b=this.hubV2.safeTransferFrom(Y,K,O,q);A.push({to:b.to,data:b.data,value:b.value??0n})}return A}let I=q-j;if(console.log(`Current unwrapped: ${Number(j)/1000000000000000000} CRC`),console.log(`Target amount: ${Number(q)/1000000000000000000} CRC`),console.log(`Need to acquire: ${Number(I)/1000000000000000000} CRC`),z>=q){let O=I;if(N>0n&&V&&O>0n){let b=O>N?N:O,c=new c0({address:V,rpcUrl:this.config.circlesRpcUrl}).unwrap(b);A.push({to:c.to,data:c.data,value:c.value??0n}),O-=b}if(D>0n&&B&&O>0n){let b=p.attoCirclesToAttoStaticCircles(O),h=b>D?D:b,s=new l0({address:B,rpcUrl:this.config.circlesRpcUrl}).unwrap(h);A.push({to:s.to,data:s.data,value:s.value??0n})}if(K!==Y){let b=await this.hubV2.toTokenId(Z),h=this.hubV2.safeTransferFrom(Y,K,b,q);A.push({to:h.to,data:h.data,value:h.value??0n})}return A}let U=!await this.hubV2.isTrusted(Y,Z),R=BigInt(Math.floor(Date.now()/1000)+31536000),P=p.truncateToInt64(I),H=I%p.FACTOR_1E12!==0n,w=p.blowUpToBigInt(H?P+1n:P),E;try{E=await this.pathfinder.findPath({from:Y,to:K,targetFlow:w,toTokens:[Z],useWrappedBalances:!0,simulatedTrusts:U?[{truster:Y,trustee:Z}]:void 0})}catch(O){let b=Number(z)/1000000000000000000,h=Number(q)/1000000000000000000,c=Number(I)/1000000000000000000;throw new o(`Insufficient tokens to replenish. Target: ${h.toFixed(6)} CRC, Current unwrapped: ${Number(j)/1000000000000000000} CRC, Need: ${c.toFixed(6)} CRC, Available (including all paths): ${b.toFixed(6)} CRC. Cannot acquire the remaining ${(Number(I-(z-j))/1000000000000000000).toFixed(6)} CRC.`,{code:"REPLENISH_INSUFFICIENT_TOKENS",source:"VALIDATION",context:{from:Y,tokenId:Z,target:q.toString(),unwrapped:j.toString(),deficit:I.toString(),available:z.toString(),targetCrc:h,unwrappedCrc:Number(j)/1000000000000000000,deficitCrc:c,availableCrc:b}})}if(!E.transfers||E.transfers.length===0)throw o.noPathFound(Y,K,`No path to acquire token ${Z}`);if(E.maxFlow<w){let O=Number(E.maxFlow)/1000000000000000000,b=Number(w)/1000000000000000000;throw new o(`Pathfinder can only provide ${O.toFixed(6)} CRC of the ${b.toFixed(6)} CRC deficit needed for token ${Z}.`,{code:"REPLENISH_INSUFFICIENT_PATH_FLOW",source:"PATHFINDING",context:{from:Y,tokenId:Z,deficit:w.toString(),pathFlow:E.maxFlow.toString(),deficitCrc:b,pathFlowCrc:O}})}if(U){let O=this.hubV2.trust(Z,R);A.push({to:O.to,data:O.data,value:O.value??0n})}let y=await L$(Y,this.config.circlesRpcUrl,E),_=C$(E,y),k=Object.keys(_).length>0,x=[],u=[];if(k){let O=await this._getTokenBalanceMap(Y),b=this._createDemurragedUnwrapCalls(_),{unwrapCalls:h,wrapCalls:c}=this._createInflationaryUnwrapAndWrapCalls(_,y,O);x=[...b,...h],u=c,E=P$(E,y)}let f=O$(Y,K,E.maxFlow,E.transfers),W=R$(f),L=this.hubV2.operateFlowMatrix(f.flowVertices,f.flowEdges,W,f.packedCoordinates),S={to:L.to,data:L.data,value:L.value??0n},F=!1;try{F=await this.hubV2.isApprovedForAll(Y,Y)}catch(O){console.warn("Failed to check approval status, including approval transaction:",O)}if(U){let O=this.hubV2.trust(Z,0n);u.push({to:O.to,data:O.data,value:O.value??0n})}let T=F?[]:[{to:this.hubV2.setApprovalForAll(Y,!0).to,data:this.hubV2.setApprovalForAll(Y,!0).data,value:0n}];return A.push(...T,...x,S,...u),A}async _getTokenBalanceMap(J){let $=await this.balance.getTokenBalances(J),Q=new Map;return $.forEach((G)=>{Q.set(G.tokenAddress.toLowerCase(),G.staticAttoCircles)}),Q}_createDemurragedUnwrapCalls(J){let $=[];for(let[Q,[G,Y]]of Object.entries(J)){if(Y!=="CrcV2_ERC20WrapperDeployed_Demurraged")continue;let K=new c0({address:Q,rpcUrl:this.config.circlesRpcUrl}).unwrap(G);$.push({to:K.to,data:K.data,value:K.value??0n})}return $}_createInflationaryUnwrapAndWrapCalls(J,$,Q){let G=[],Y=[];for(let[Z,[K,q]]of Object.entries(J)){if(q!=="CrcV2_ERC20WrapperDeployed_Inflationary")continue;let M=$.get(Z.toLowerCase()),X=Q.get(Z.toLowerCase())||0n;if(X===0n)continue;let N=new l0({address:Z,rpcUrl:this.config.circlesRpcUrl}).unwrap(X);G.push({to:N.to,data:N.data,value:N.value??0n});let D=M?.tokenOwner,V=p.attoStaticCirclesToAttoCircles(X)-K;if(V>0n){let B=this.hubV2.wrap(D,V,1);Y.push({to:B.to,data:B.data,value:B.value??0n})}}return{unwrapCalls:G,wrapCalls:Y}}_truncateToSixDecimals(J){let $=BigInt(1e6),Q=BigInt(10)**BigInt(18);return J/(Q/$)*(Q/$)}async _getDefaultTokenExcludeList(J,$){let Q=await this.group.findGroups(1,{mintHandlerEquals:J}),G=new Set;if(Q.length>0){let Y=Q[0];if(G.add(Y.group.toLowerCase()),Y.erc20WrapperDemurraged)G.add(Y.erc20WrapperDemurraged.toLowerCase());if(Y.erc20WrapperStatic)G.add(Y.erc20WrapperStatic.toLowerCase())}if($?.forEach((Y)=>G.add(Y.toLowerCase())),G.size===0)return;return Array.from(G)}}class BQ{config;rpcClient;pathfinder;trust;hubV2;referralsModule;constructor(J){if(!J.referralsServiceUrl)throw new d("referralsServiceUrl is required in config",{code:"INVITATION_MISSING_CONFIG",source:"INVITATIONS",context:{missingField:"referralsServiceUrl"}});this.config=J,this.rpcClient=new V0(J.circlesRpcUrl),this.pathfinder=new X0(this.rpcClient),this.trust=new _0(this.rpcClient),this.hubV2=new u0({address:J.v2HubAddress,rpcUrl:J.circlesRpcUrl}),this.referralsModule=new TJ({address:J.referralsModuleAddress,rpcUrl:J.circlesRpcUrl})}async saveReferralData(J,$){try{let Q=await fetch(`${this.config.referralsServiceUrl}/store`,{method:"POST",headers:{accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({privateKey:$,inviter:J})});if(!Q.ok)throw new d(`HTTP error! status: ${Q.status}`,{code:"INVITATION_HTTP_ERROR",source:"INVITATIONS",context:{status:Q.status,url:`${this.config.referralsServiceUrl}/store`}})}catch(Q){throw console.error("Failed to save referral data:",Q),new d(`Failed to save referral data: ${Q instanceof Error?Q.message:"Unknown error"}`,{code:"INVITATION_SAVE_REFERRAL_FAILED",source:"INVITATIONS",cause:Q})}}orderRealInviters(J,$){let Q=$.toLowerCase();return J.sort((G,Y)=>{let Z=G.address.toLowerCase()===Q,K=Y.address.toLowerCase()===Q;if(Z&&!K)return-1;if(!Z&&K)return 1;return 0})}async generateInvite(J,$){let Q=J.toLowerCase(),G=$.toLowerCase();if(await this.hubV2.isHuman(G))throw d.inviteeAlreadyRegistered(Q,G);let Z=await this.findInvitePath(Q),K=await this.generateInviteData([G],!1),q=new UJ(this.config),M=await this.getRealInviters(Q);if(M.length===0)throw d.noPathFound(Q,this.config.invitationModuleAddress);let X=M[0].address;return await q.buildFlowMatrixTx(Q,this.config.invitationModuleAddress,Z,{toTokens:[X],useWrappedBalances:!0,txData:LJ(K)},!0)}async findInvitePath(J,$){let Q=J.toLowerCase(),G;if($)G=$.toLowerCase();else{let Z=await this.getRealInviters(Q);if(Z.length===0)throw d.noPathFound(Q,this.config.invitationModuleAddress);G=Z[0].address}let Y=await this.pathfinder.findPath({from:Q,to:this.config.invitationModuleAddress,targetFlow:T0,toTokens:[G],useWrappedBalances:!0});if(!Y.transfers||Y.transfers.length===0)throw d.noPathFound(Q,this.config.invitationModuleAddress);if(Y.maxFlow<T0){let K=Number(Y.maxFlow/T0);throw d.insufficientBalance(1,K,T0,Y.maxFlow,Q,this.config.invitationModuleAddress)}return Y}async getRealInviters(J){let $=J.toLowerCase(),Q=await this.trust.getTrustedBy($),G=await this.trust.getMutualTrusts($),Y=new Set([...Q.map((z)=>z.objectAvatar.toLowerCase()),...G.map((z)=>z.objectAvatar.toLowerCase())]),Z=await this.trust.getTrusts(this.config.invitationModuleAddress),K=await this.trust.getMutualTrusts(this.config.invitationModuleAddress),q=new Set([...Z.map((z)=>z.objectAvatar.toLowerCase()),...K.map((z)=>z.objectAvatar.toLowerCase())]),M=[];for(let z of Y)if(q.has(z))M.push(z);let X=[...M,$];if(X.length===0)return[];let j=await this.pathfinder.findPath({from:$,to:this.config.invitationModuleAddress,useWrappedBalances:!0,targetFlow:e0,toTokens:X});if(!j.transfers||j.transfers.length===0)return[];let N=new Map,D=this.config.invitationModuleAddress.toLowerCase();for(let z of j.transfers)if(z.to.toLowerCase()===D){let A=z.tokenOwner.toLowerCase(),I=N.get(A)||BigInt(0);N.set(A,I+z.value)}let V=[];for(let[z,A]of N.entries()){let I=Number(A/T0);if(I>=1)V.push({address:z,possibleInvites:I})}return this.orderRealInviters(V,$)}async generateReferral(J){let $=J.toLowerCase(),Q=D$(),G=V$(Q),Y=await this.getRealInviters($);if(Y.length===0)throw d.noProxyInviters($);let K=Y[0].address,q=await this.findInvitePath($,K),M=new UJ(this.config),X=await this.generateInviteData([G],!0),j=await M.buildFlowMatrixTx($,this.config.invitationModuleAddress,q,{toTokens:[K],useWrappedBalances:!0,txData:LJ(X)},!0);await this.saveReferralData($,Q);let N=[];return N.push(...j),N}async generateInviteData(J,$=!0){if(J.length===0)throw d.noAddressesProvided();if(!$)if(J.length===1)return m0(["address"],[J[0]]);else return m0(["address[]"],[J]);if(J.length===1){let G=this.referralsModule.createAccount(J[0]).data;return m0(["address","bytes"],[this.config.referralsModuleAddress,G])}else{let G=this.referralsModule.createAccounts(J).data;return m0(["address","bytes"],[this.config.referralsModuleAddress,G])}}computeAddress(J){let Q=J.toLowerCase().replace("0x","").padStart(64,"0"),G=hJ.replace("0x","")+Q,Y=AJ("0x"+G),Z="ff",K=vJ.toLowerCase().replace("0x",""),q=Y.replace("0x",""),M=mJ.replace("0x",""),X="ff"+K+q+M,N="0x"+AJ("0x"+X).slice(-40);return R0(N)}}export{d as InvitationError,BQ as InvitationBuilder};
|
|
1
|
+
var TJ=($)=>BigInt($),a0=($)=>parseInt($,16),_8=($)=>{if($.startsWith("0x"))$=$.slice(2);if($.length%2!==0)throw Error("Invalid hex string");let J=new Uint8Array($.length/2);for(let Q=0;Q<$.length;Q+=2)J[Q/2]=parseInt($.substr(Q,2),16);return J};function E8($,J){if(typeof J==="string"&&J.startsWith("0x")){let Q=J.slice(2);if(Q.length===40)return J;if(Q.length===64){if($.toLowerCase().includes("digest")||$.toLowerCase().includes("data")||$.toLowerCase().includes("bytes"))return _8(J);try{return TJ(J)}catch{return J}}try{let G=a0(J);if(G<Number.MAX_SAFE_INTEGER)return G;return TJ(J)}catch{return J}}if(J==="true")return!0;if(J==="false")return!1;return J}function g$($){let{event:J,values:Q}=$,G={$event:J,blockNumber:Q.blockNumber?a0(Q.blockNumber):0,timestamp:Q.timestamp?a0(Q.timestamp):void 0,transactionIndex:Q.transactionIndex?a0(Q.transactionIndex):0,logIndex:Q.logIndex?a0(Q.logIndex):0,transactionHash:Q.transactionHash};for(let[Y,Z]of Object.entries(Q)){if(["blockNumber","timestamp","transactionIndex","logIndex","transactionHash"].includes(Y))continue;G[Y]=E8(Y,Z)}return G}function V$($){return $.map(g$)}class h0{_subscribers=[];subscribe($){return this._subscribers.push($),()=>{let J=this._subscribers.indexOf($);if(J>-1)this._subscribers.splice(J,1)}}constructor(){this._subscribers=[]}emit($){this._subscribers.forEach((J)=>J($))}static create(){let $=new h0;return{property:$,emit:(J)=>$.emit(J)}}}class s0 extends Error{name;code;source;cause;context;constructor($,J,Q){super(J);if(this.name=$,this.code=Q?.code,this.source=Q?.source??"UNKNOWN",this.cause=Q?.cause,this.context=Q?.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 $=`[${this.source}] ${this.name}: ${this.message}`;if(this.code)$+=` (Code: ${this.code})`;if(this.context)$+=`
|
|
2
|
+
Context: ${JSON.stringify(this.context,null,2)}`;return $}}class t extends s0{constructor($,J){super("RpcError",$,{...J,source:J?.source??"RPC_REQUEST"})}static connectionFailed($,J){return new t("Failed to connect to RPC endpoint",{code:"RPC_CONNECTION_FAILED",source:"RPC_CONNECTION",cause:J,context:{url:$}})}static timeout($,J){return new t("RPC request timed out",{code:"RPC_TIMEOUT",source:"RPC_TIMEOUT",context:{method:$,timeout:J}})}static invalidResponse($,J){return new t("Invalid RPC response",{code:"RPC_INVALID_RESPONSE",source:"RPC_RESPONSE",context:{method:$,response:J}})}static fromJsonRpcError($){return new t($.message,{code:$.code,source:"RPC_RESPONSE",context:{data:$.data}})}static websocketError($,J){return new t($,{code:"RPC_WEBSOCKET_ERROR",source:"RPC_WEBSOCKET",cause:J})}}class O0{rpcUrl;requestId=0;websocket=null;websocketConnected=!1;pendingResponses={};subscriptionListeners={};reconnectAttempt=0;initialBackoff=2000;maxBackoff=120000;constructor($){this.rpcUrl=$}async call($,J){this.requestId++;let Q={jsonrpc:"2.0",id:this.requestId,method:$,params:J};try{let G=await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)});if(!G.ok)throw t.connectionFailed(this.rpcUrl,Error(`HTTP ${G.status}: ${G.statusText}`));let Y=await G.json();if(Y.error)throw t.fromJsonRpcError(Y.error);if(Y.result===void 0)throw t.invalidResponse($,Y);return Y.result}catch(G){if(G instanceof t)throw G;throw t.connectionFailed(this.rpcUrl,G)}}setRpcUrl($){this.rpcUrl=$}getRpcUrl(){return this.rpcUrl}connect(){return new Promise(($)=>{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,$()},this.websocket.onmessage=(Q)=>{let G=JSON.parse(Q.data),{id:Y,method:Z,params:K}=G;if(Y!==void 0&&this.pendingResponses[Y])this.pendingResponses[Y].resolve(G),delete this.pendingResponses[Y];if(Z==="eth_subscription"&&K){let{subscription:q,result:X}=K;if(this.subscriptionListeners[q])this.subscriptionListeners[q].forEach((M)=>M(X))}},this.websocket.onclose=()=>{console.warn("WebSocket closed"),this.websocketConnected=!1},this.websocket.onerror=(Q)=>{console.error("WebSocket error:",Q),this.websocketConnected=!1,this.scheduleReconnect()}})}scheduleReconnect(){let $=Math.min(this.initialBackoff*Math.pow(2,this.reconnectAttempt),this.maxBackoff),J=$*(Math.random()*0.5),Q=$+J;console.log(`Reconnecting in ${Math.round(Q)}ms (attempt #${this.reconnectAttempt+1})`),this.reconnectAttempt++,setTimeout(()=>{this.reconnect()},Q)}async reconnect(){if(this.websocketConnected)return;try{await this.connect(),console.log("Reconnection successful")}catch($){console.error("Reconnection attempt failed:",$),this.scheduleReconnect()}}sendMessage($,J,Q=5000){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return Promise.reject(t.connectionFailed(this.rpcUrl));let G=this.requestId++,Y={jsonrpc:"2.0",method:$,params:J,id:G};return new Promise((Z,K)=>{this.pendingResponses[G]={resolve:Z,reject:K},this.websocket.send(JSON.stringify(Y)),setTimeout(()=>{if(this.pendingResponses[G])this.pendingResponses[G].reject(t.timeout($,Q)),delete this.pendingResponses[G]},Q)})}async subscribe($){let J=$?.toLowerCase();if(!this.websocketConnected)await this.connect();let Q=h0.create(),G=JSON.stringify(J?{address:J}:{}),Z=(await this.sendMessage("eth_subscribe",["circles",G])).result;if(!this.subscriptionListeners[Z])this.subscriptionListeners[Z]=[];return this.subscriptionListeners[Z].push((K)=>{V$(K).forEach((q)=>Q.emit(q))}),Q.property}}var O$=BigInt(4294967295),_J=BigInt(32);function A8($,J=!1){if(J)return{h:Number($&O$),l:Number($>>_J&O$)};return{h:Number($>>_J&O$)|0,l:Number($&O$)|0}}function EJ($,J=!1){let Q=$.length,G=new Uint32Array(Q),Y=new Uint32Array(Q);for(let Z=0;Z<Q;Z++){let{h:K,l:q}=A8($[Z],J);[G[Z],Y[Z]]=[K,q]}return[G,Y]}var xJ=($,J,Q)=>$<<Q|J>>>32-Q,AJ=($,J,Q)=>J<<Q|$>>>32-Q,kJ=($,J,Q)=>J<<Q-32|$>>>64-Q,wJ=($,J,Q)=>$<<Q-32|J>>>64-Q;var I0=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function k8($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function T0($){if(!Number.isSafeInteger($)||$<0)throw Error("positive integer expected, got "+$)}function Y0($,...J){if(!k8($))throw Error("Uint8Array expected");if(J.length>0&&!J.includes($.length))throw Error("Uint8Array expected of length "+J+", got length="+$.length)}function yJ($){if(typeof $!=="function"||typeof $.create!=="function")throw Error("Hash should be wrapped by utils.createHasher");T0($.outputLen),T0($.blockLen)}function X0($,J=!0){if($.destroyed)throw Error("Hash instance has been destroyed");if(J&&$.finished)throw Error("Hash#digest() has already been called")}function R$($,J){Y0($);let Q=J.outputLen;if($.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function FJ($){return new Uint32Array($.buffer,$.byteOffset,Math.floor($.byteLength/4))}function Z0(...$){for(let J=0;J<$.length;J++)$[J].fill(0)}function C$($){return new DataView($.buffer,$.byteOffset,$.byteLength)}function G0($,J){return $<<32-J|$>>>J}var w8=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function y8($){return $<<24&4278190080|$<<8&16711680|$>>>8&65280|$>>>24&255}function F8($){for(let J=0;J<$.length;J++)$[J]=y8($[J]);return $}var f$=w8?($)=>$:F8;function b8($){if(typeof $!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode($))}function _0($){if(typeof $==="string")$=b8($);return Y0($),$}function bJ(...$){let J=0;for(let G=0;G<$.length;G++){let Y=$[G];Y0(Y),J+=Y.length}let Q=new Uint8Array(J);for(let G=0,Y=0;G<$.length;G++){let Z=$[G];Q.set(Z,Y),Y+=Z.length}return Q}class E0{}function L$($){let J=(G)=>$().update(_0(G)).digest(),Q=$();return J.outputLen=Q.outputLen,J.blockLen=Q.blockLen,J.create=()=>$(),J}function gJ($=32){if(I0&&typeof I0.getRandomValues==="function")return I0.getRandomValues(new Uint8Array($));if(I0&&typeof I0.randomBytes==="function")return Uint8Array.from(I0.randomBytes($));throw Error("crypto.getRandomValues must be defined")}var g8=BigInt(0),r0=BigInt(1),f8=BigInt(2),v8=BigInt(7),h8=BigInt(256),m8=BigInt(113),hJ=[],mJ=[],uJ=[];for(let $=0,J=r0,Q=1,G=0;$<24;$++){[Q,G]=[G,(2*Q+3*G)%5],hJ.push(2*(5*G+Q)),mJ.push(($+1)*($+2)/2%64);let Y=g8;for(let Z=0;Z<7;Z++)if(J=(J<<r0^(J>>v8)*m8)%h8,J&f8)Y^=r0<<(r0<<BigInt(Z))-r0;uJ.push(Y)}var cJ=EJ(uJ,!0),u8=cJ[0],c8=cJ[1],fJ=($,J,Q)=>Q>32?kJ($,J,Q):xJ($,J,Q),vJ=($,J,Q)=>Q>32?wJ($,J,Q):AJ($,J,Q);function l8($,J=24){let Q=new Uint32Array(10);for(let G=24-J;G<24;G++){for(let K=0;K<10;K++)Q[K]=$[K]^$[K+10]^$[K+20]^$[K+30]^$[K+40];for(let K=0;K<10;K+=2){let q=(K+8)%10,X=(K+2)%10,M=Q[X],j=Q[X+1],N=fJ(M,j,1)^Q[q],D=vJ(M,j,1)^Q[q+1];for(let V=0;V<50;V+=10)$[K+V]^=N,$[K+V+1]^=D}let Y=$[2],Z=$[3];for(let K=0;K<24;K++){let q=mJ[K],X=fJ(Y,Z,q),M=vJ(Y,Z,q),j=hJ[K];Y=$[j],Z=$[j+1],$[j]=X,$[j+1]=M}for(let K=0;K<50;K+=10){for(let q=0;q<10;q++)Q[q]=$[K+q];for(let q=0;q<10;q++)$[K+q]^=~Q[(q+2)%10]&Q[(q+4)%10]}$[0]^=u8[G],$[1]^=c8[G]}Z0(Q)}class v$ extends E0{constructor($,J,Q,G=!1,Y=24){super();if(this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=$,this.suffix=J,this.outputLen=Q,this.enableXOF=G,this.rounds=Y,T0(Q),!(0<$&&$<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=FJ(this.state)}clone(){return this._cloneInto()}keccak(){f$(this.state32),l8(this.state32,this.rounds),f$(this.state32),this.posOut=0,this.pos=0}update($){X0(this),$=_0($),Y0($);let{blockLen:J,state:Q}=this,G=$.length;for(let Y=0;Y<G;){let Z=Math.min(J-this.pos,G-Y);for(let K=0;K<Z;K++)Q[this.pos++]^=$[Y++];if(this.pos===J)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:$,suffix:J,pos:Q,blockLen:G}=this;if($[Q]^=J,(J&128)!==0&&Q===G-1)this.keccak();$[G-1]^=128,this.keccak()}writeInto($){X0(this,!1),Y0($),this.finish();let J=this.state,{blockLen:Q}=this;for(let G=0,Y=$.length;G<Y;){if(this.posOut>=Q)this.keccak();let Z=Math.min(Q-this.posOut,Y-G);$.set(J.subarray(this.posOut,this.posOut+Z),G),this.posOut+=Z,G+=Z}return $}xofInto($){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto($)}xof($){return T0($),this.xofInto(new Uint8Array($))}digestInto($){if(R$($,this),this.finished)throw Error("digest() was already called");return this.writeInto($),this.destroy(),$}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Z0(this.state)}_cloneInto($){let{blockLen:J,suffix:Q,outputLen:G,rounds:Y,enableXOF:Z}=this;return $||($=new v$(J,Q,G,Z,Y)),$.state32.set(this.state32),$.pos=this.pos,$.posOut=this.posOut,$.finished=this.finished,$.rounds=Y,$.suffix=Q,$.outputLen=G,$.enableXOF=Z,$.destroyed=this.destroyed,$}}var p8=($,J,Q)=>L$(()=>new v$(J,$,Q));var m0=(()=>p8(1,136,32))();var lJ=[];for(let $=0;$<256;$++)lJ[$]=$.toString(16).padStart(2,"0");function P$($){let J="0x";for(let Q=0;Q<$.length;Q++)J+=lJ[$[Q]];return J}function B$($){let J=$.startsWith("0x")?$.slice(2):$,Q=new Uint8Array(J.length/2);for(let G=0;G<J.length;G+=2)Q[G/2]=parseInt(J.slice(G,G+2),16);return Q}var u=64,S$=32,H$=($)=>$.startsWith("0x")?$.slice(2):$;var K0=($)=>$.toString(16).padStart(u,"0");function C0($){let J=$.toLowerCase().replace("0x",""),Q=P$(m0(new TextEncoder().encode(J))).slice(2),G="0x";for(let Y=0;Y<J.length;Y++)G+=parseInt(Q[Y],16)>=8?J[Y].toUpperCase():J[Y];return G}function h$($,J){if($==="tuple"&&J)return`(${J.map((Y)=>h$(Y.type,Y.components)).join(",")})`;let Q=$.match(/^tuple(\[\d*\])$/);if(Q&&J)return`${h$("tuple",J)}${Q[1]}`;return $}function d8($){let Q=($.inputs||[]).map((G)=>h$(G.type,G.components));return`${$.name}(${Q.join(",")})`}function i8($){let J=d8($),Q=m0(new TextEncoder().encode(J));return P$(Q.slice(0,4))}function u0($,J){if($==="string"||$==="bytes")return!0;if($.includes("[")){let Q=$.slice(0,$.indexOf("["));if($.endsWith("[]"))return!0;if(Q==="tuple")return pJ(J);return u0(Q)}if($==="tuple")return pJ(J);return!1}function pJ($){return $?.some((J)=>u0(J.type,J.components))??!1}function R0($,J,Q){if($==="tuple"&&Q)return o8(Q,J);if($.includes("["))return n8($,J,Q);return t8($,J)}function n8($,J,Q){let G=$.slice(0,$.indexOf("[")),Y=$.endsWith("[]"),Z=u0(G,Q),K;if(Z){let q=J.map((j)=>R0(G,j,Q)),X=J.length*S$;K=q.map((j)=>{let N=X;return X+=j.length/2,K0(N)}).join("")+q.join("")}else K=J.map((q)=>R0(G,q,Q)).join("");return Y?K0(J.length)+K:K}function o8($,J){let Q=Array.isArray(J),G=[],Y=[],Z=[];for(let K=0;K<$.length;K++){let q=$[K],X=Q?J[K]:J[q.name||""],M=u0(q.type,q.components);if(Z.push(M),M)G.push(""),Y.push(R0(q.type,X,q.components));else G.push(R0(q.type,X,q.components))}if(Y.length>0){let K=G.reduce((M,j,N)=>M+(Z[N]?S$:j.length/2),0),q="",X=0;for(let M=0;M<$.length;M++)if(Z[M])q+=K0(K),K+=Y[X].length/2,X++;else q+=G[M];return q+Y.join("")}return G.join("")}function t8($,J){if($==="address")return H$(J).toLowerCase().padStart(u,"0");if($==="bool")return K0(J?1:0);if($.startsWith("uint")){let Q=typeof J==="bigint"?J:BigInt(J);return K0(Q)}if($.startsWith("int")){let Q=typeof J==="bigint"?J:BigInt(J);if(Q<0n){let G=$==="int"?256:parseInt($.slice(3));Q=(1n<<BigInt(G))+Q}return K0(Q)}if($.startsWith("bytes")&&$!=="bytes")return H$(J).padEnd(u,"0");if($==="bytes"){let Q=H$(J),G=K0(Q.length/2),Y=Q.padEnd(Math.ceil(Q.length/u)*u,"0");return G+Y}if($==="string"){let Q=Array.from(new TextEncoder().encode(J)).map((Z)=>Z.toString(16).padStart(2,"0")).join(""),G=K0(Q.length/2),Y=Q.padEnd(Math.ceil(Q.length/u)*u,"0");return G+Y}throw Error(`Unsupported type: ${$}`)}function e0($,J,Q=0,G){if($==="tuple"&&G)return s8(G,J,Q);if($.includes("["))return a8($,J,Q,G);return r8($,J,Q)}function a8($,J,Q,G){let Y=$.slice(0,$.indexOf("[")),Z=J.slice(Q,Q+u);if($.endsWith("[]")){let q=parseInt(Z,16)*2,X=parseInt(J.slice(q,q+u),16),M=[],j=q+u;for(let N=0;N<X;N++){let D=e0(Y,J,j,G);M.push(D.value),j+=D.consumed}return{value:M,consumed:u}}let K=$.match(/\[(\d+)\]$/);if(K){let q=parseInt(K[1]),X=[],M=0;for(let j=0;j<q;j++){let N=e0(Y,J,Q+M,G);X.push(N.value),M+=N.consumed}return{value:X,consumed:M}}throw Error(`Invalid array type: ${$}`)}function s8($,J,Q){let G=[],Y=Q;for(let Z of $){let K=e0(Z.type,J,Y,Z.components);G.push(K.value),Y+=K.consumed}return{value:G,consumed:Y-Q}}function r8($,J,Q){let G=J.slice(Q,Q+u);if($==="address")return{value:C0("0x"+G.slice(24)),consumed:u};if($==="bool")return{value:parseInt(G,16)!==0,consumed:u};if($.startsWith("uint"))return{value:BigInt("0x"+G),consumed:u};if($.startsWith("int")){let Y=BigInt("0x"+G),Z=$==="int"?256:parseInt($.slice(3)),K=1n<<BigInt(Z-1);return{value:Y>=K?Y-(1n<<BigInt(Z)):Y,consumed:u}}if($.startsWith("bytes")&&$!=="bytes"){let Y=parseInt($.match(/^bytes(\d+)$/)[1]);return{value:"0x"+G.slice(0,Y*2),consumed:u}}if($==="bytes"){let Y=parseInt(G,16)*2,Z=parseInt(J.slice(Y,Y+u),16)*2;return{value:"0x"+J.slice(Y+u,Y+u+Z),consumed:u}}if($==="string"){let Y=parseInt(G,16)*2,Z=parseInt(J.slice(Y,Y+u),16)*2,K=J.slice(Y+u,Y+u+Z),q=new Uint8Array(K.match(/.{2}/g)?.map((X)=>parseInt(X,16))||[]);return{value:new TextDecoder().decode(q),consumed:u}}throw Error(`Unsupported type: ${$}`)}function I$($){let{abi:J,functionName:Q,args:G=[]}=$,Y=J.find((V)=>V.type==="function"&&V.name===Q);if(!Y)throw Error(`Function "${Q}" not found in ABI`);let Z=i8(Y),K=Y.inputs||[];if(K.length===0)return Z;if(G.length!==K.length)throw Error(`Expected ${K.length} arguments, got ${G.length}`);let q=[],X=[],M=[];for(let V=0;V<K.length;V++){let L=K[V],z=L.components,A=u0(L.type,z);if(M.push(A),A)q.push(""),X.push(R0(L.type,G[V],z));else q.push(R0(L.type,G[V],z))}if(X.length===0)return Z+q.join("");let j=q.reduce((V,L,z)=>V+(M[z]?S$:L.length/2),0),N="",D=0;for(let V=0;V<K.length;V++)if(M[V])N+=K0(j),j+=X[D].length/2,D++;else N+=q[V];return Z+N+X.join("")}function m$($){let{abi:J,functionName:Q,data:G}=$,Y=J.find((M)=>M.type==="function"&&M.name===Q);if(!Y)throw Error(`Function "${Q}" not found in ABI`);let Z=Y.outputs||[];if(Z.length===0)return;let K=H$(G);if(Z.length===1)return e0(Z[0].type,K,0,Z[0].components).value;let q=[],X=0;for(let M of Z){let j=e0(M.type,K,X,M.components);q.push(j.value),X+=j.consumed}return q}function L0($,J){if($.length!==J.length)throw Error(`Type/value length mismatch: ${$.length} types, ${J.length} values`);let Q=[],G=[],Y=[];for(let X=0;X<$.length;X++){let M=$[X],j=u0(M);if(Y.push(j),j)Q.push(""),G.push(R0(M,J[X]));else Q.push(R0(M,J[X]))}if(G.length===0)return"0x"+Q.join("");let Z=Q.reduce((X,M,j)=>X+(Y[j]?S$:M.length/2),0),K="",q=0;for(let X=0;X<$.length;X++)if(Y[X])K+=K0(Z),Z+=G[q].length/2,q++;else K+=Q[X];return"0x"+K+G.join("")}function P($){return $.toLowerCase()}function e8($){return C0($)}function $Q($){if(typeof $!=="string")return!1;let J=$.replace("0x","");return J.length===40&&/^[0-9a-fA-F]{40}$/.test(J)}function g($){if($===null||$===void 0)return $;if($Q($))return e8($);if(Array.isArray($))return $.map((J)=>g(J));if(typeof $==="object"&&$!==null){let J={};for(let Q in $)if(Object.prototype.hasOwnProperty.call($,Q))J[Q]=g($[Q]);return J}return $}function dJ($){return{Source:P($.from),Sink:P($.to),TargetFlow:$.targetFlow.toString(),WithWrap:$.useWrappedBalances,FromTokens:$.fromTokens?.map(P),ToTokens:$.toTokens?.map(P),ExcludedFromTokens:$.excludeFromTokens?.map(P),ExcludedToTokens:$.excludeToTokens?.map(P),SimulatedBalances:$.simulatedBalances?.map((J)=>({Holder:P(J.holder),Token:P(J.token),Amount:J.amount.toString(),IsWrapped:J.isWrapped,IsStatic:J.isStatic})),SimulatedTrusts:$.simulatedTrusts?.map((J)=>({Truster:P(J.truster),Trustee:P(J.trustee)})),MaxTransfers:$.maxTransfers}}function q0($){let J={};for(let Q in $){let G=$[Q];if(G===null||G===void 0)J[Q]=G;else if(typeof G==="string"&&/^\d+$/.test(G))J[Q]=BigInt(G);else if(typeof G==="object"&&!Array.isArray(G))J[Q]=q0(G);else if(Array.isArray(G))J[Q]=G.map((Y)=>typeof Y==="object"&&Y!==null?q0(Y):Y);else J[Q]=G}return J}var T$="0x0000000000000000000000000000000000000000",M0=BigInt(96)*BigInt(1000000000000000000),$$=BigInt("9999999999999999999999999999999999999"),u$="0x4e1DCf7AD4e460CfD30791CCC4F9c8a4f820ec67",c$="0x440ea2f93c9703f7d456d48796f7bc25b8721582535a492ce0a09df32146242a",l$="0xe298282cefe913ab5d282047161268a8222e4bd4ed106300c547894bbefd31ee";class j0{client;constructor($){this.client=$}async findPath($){let J=dJ($),Q=await this.client.call("circlesV2_findPath",[J]),G=q0(Q);return g(G)}async findMaxFlow($){let J=await this.findPath({...$,targetFlow:$$});return BigInt(J.maxFlow)}}class J${client;constructor($){this.client=$}async query($){let J=await this.client.call("circles_query",[$]);return g(J)}async tables(){return this.client.call("circles_tables",[])}async events($,J,Q=null,G=null,Y=!1){let Z=await this.client.call("circles_events",[$,J,Q,G,Y]);return g(Z)}}var JQ=[{name:"blockNumber",sortOrder:"DESC"},{name:"transactionIndex",sortOrder:"DESC"},{name:"logIndex",sortOrder:"DESC"}];class $0{params;client;rowTransformer;cursorColumns;orderColumns;get currentPage(){return this._currentPage}_currentPage;constructor($,J,Q){this.client=$,this.params=J,this.rowTransformer=Q||J.rowTransformer,this.orderColumns=J.orderColumns,this.cursorColumns=J.cursorColumns||this.buildEventCursorColumns()}buildEventCursorColumns(){let $=JQ.map((J)=>({...J,sortOrder:this.params.sortOrder}));if(this.params.table==="TransferBatch")$.push({name:"batchIndex",sortOrder:this.params.sortOrder});return $}transformCursorValue($,J){if(J)return J($);if(typeof $==="bigint")return $.toString();return $}createEqualityPredicate($,J){return{Type:"FilterPredicate",FilterType:"Equals",Column:$.name,Value:this.transformCursorValue(J,$.toValue)}}createComparisonPredicate($,J){return{Type:"FilterPredicate",FilterType:$.sortOrder==="ASC"?"GreaterThan":"LessThan",Column:$.name,Value:this.transformCursorValue(J,$.toValue)}}buildCursorFilter($){if(!$)return[];let J=[];for(let Q=0;Q<this.cursorColumns.length;Q++){let G=this.cursorColumns[Q],Y=$[G.name];if(Y===void 0)continue;if(Q===0)J.push(this.createComparisonPredicate(G,Y));else{let Z=[];for(let K=0;K<Q;K++){let q=this.cursorColumns[K],X=$[q.name];if(X!==void 0)Z.push(this.createEqualityPredicate(q,X))}Z.push(this.createComparisonPredicate(G,Y)),J.push({Type:"Conjunction",ConjunctionType:"And",Predicates:Z})}}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(($)=>({Column:$.name,SortOrder:$.sortOrder}))}combineFilters($,J){if(!$?.length&&!J?.length)return[];if(!$?.length)return J||[];if(!J?.length)return $;return[{Type:"Conjunction",ConjunctionType:"And",Predicates:[...$,...J]}]}rowsToObjects($){let{columns:J,rows:Q}=$;return Q.map((G)=>{let Y={};return J.forEach((Z,K)=>{Y[Z]=G[K]}),this.rowTransformer?this.rowTransformer(Y):Y})}rowToCursor($){let J={};for(let Q of this.cursorColumns)J[Q.name]=$[Q.name];return J}getCursors($){if($.length===0)return{};return{first:this.rowToCursor($[0]),last:this.rowToCursor($[$.length-1])}}async queryNextPage(){let $=this.buildCursorFilter(this._currentPage?.lastCursor),J=this.combineFilters(this.params.filter,$),Q={Namespace:this.params.namespace,Table:this.params.table,Columns:this.params.columns,Filter:J,Order:this.buildOrderBy(),Limit:this.params.limit},G=await this.client.call("circles_query",[Q]),Y=this.rowsToObjects(G),Z=this.getCursors(Y);return this._currentPage={limit:this.params.limit,size:Y.length,firstCursor:Z.first,lastCursor:Z.last,sortOrder:this.params.sortOrder,hasMore:Y.length===this.params.limit,results:Y},Y.length>0}reset(){this._currentPage=void 0}}class x0{client;constructor($){this.client=$}transformQueryResponse($){let{columns:J,rows:Q}=$;return Q.map((G)=>{let Y={};return J.forEach((Z,K)=>{Y[Z]=G[K]}),Y})}async getCommonTrust($,J){let Q=await this.client.call("circles_getCommonTrust",[P($),P(J)]);return g(Q)}getTrustRelations($,J=100,Q="DESC"){let G=P($),Y=[{Type:"Conjunction",ConjunctionType:"And",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"version",Value:2},{Type:"Conjunction",ConjunctionType:"Or",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"trustee",Value:G},{Type:"FilterPredicate",FilterType:"Equals",Column:"truster",Value:G}]}]}];return new $0(this.client,{namespace:"V_Crc",table:"TrustRelations",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","version","trustee","truster","expiryTime"],filter:Y,limit:J},(Z)=>g(Z))}async getAggregatedTrustRelations($){let J=P($),Q=this.getTrustRelations(J,1000),G=[];while(await Q.queryNextPage())if(G.push(...Q.currentPage.results),!Q.currentPage.hasMore)break;let Y={};G.forEach((K)=>{let q=P(K.truster),X=P(K.trustee),M=q!==J?K.truster:K.trustee;if(!Y[M])Y[M]=[];Y[M].push(K)});let Z=Object.entries(Y).filter(([K])=>P(K)!==J).map(([K,q])=>{let X=Math.max(...q.map((j)=>j.timestamp)),M;if(q.length===2)M="mutuallyTrusts";else if(P(q[0]?.trustee)===J)M="trustedBy";else if(P(q[0]?.truster)===J)M="trusts";else throw Error("Unexpected trust list row. Couldn't determine trust relation.");return{subjectAvatar:J,relation:M,objectAvatar:K,timestamp:X}});return g(Z)}async getTrustedBy($){let J=P($),G=(await this.getAggregatedTrustRelations(J)).filter((Y)=>Y.relation==="trustedBy");return g(G)}async getTrusts($){let J=P($),G=(await this.getAggregatedTrustRelations(J)).filter((Y)=>Y.relation==="trusts");return g(G)}async getMutualTrusts($){let J=P($),G=(await this.getAggregatedTrustRelations(J)).filter((Y)=>Y.relation==="mutuallyTrusts");return g(G)}}class d{static ONE_64=1n<<64n;static GAMMA_64=18443079296116538654n;static BETA_64=18450409579521241655n;static SECONDS_PER_DAY=86400n;static INFLATION_DAY_ZERO_UNIX=1602720000n;static ATTO_FACTOR=1000000000000000000n;static FACTOR_1E12=1000000000000n;static V1_ACCURACY=100000000n;static V1_INFLATION_PCT_NUM=107n;static V1_INFLATION_PCT_DEN=100n;static PERIOD_SEC=31556952n;static mul64($,J){return $*J>>64n}static mulU($,J){return $*J>>64n}static pow64($,J){let Q=$,G=J,Y=this.ONE_64;while(G>0n){if((G&1n)===1n)Y=this.mul64(Y,Q);Q=this.mul64(Q,Q),G>>=1n}return Y}static ONE_36=1000000000000000000000000000000000000000n;static GAMMA_36=999801332008598957430613406568191166n;static BETA_36=1000198707468214629156271489013303962n;static mul36($,J){return $*J/this.ONE_36}static pow36($,J){let Q=this.ONE_36,G=$,Y=J;while(Y>0n){if((Y&1n)===1n)Q=this.mul36(Q,G);G=this.mul36(G,G),Y>>=1n}return Q}static attoCirclesToCircles($){if($===0n)return 0;let J=$/this.ATTO_FACTOR,Q=$%this.ATTO_FACTOR,G=BigInt(Number.MAX_SAFE_INTEGER);if(J>G||J<-G)throw RangeError("Atto value’s integer component exceeds JS double precision.");return Number(J)+Number(Q)/Number(this.ATTO_FACTOR)}static circlesToAttoCircles($){return BigInt(Math.trunc($*Number(this.ATTO_FACTOR)))}static inflationaryToDemurrage($,J){return this.mulU(this.pow64(this.GAMMA_64,J),$)}static demurrageToInflationary($,J){return this.mulU(this.pow64(this.BETA_64,J),$)}static dayFromTimestamp($){return($-this.INFLATION_DAY_ZERO_UNIX)/this.SECONDS_PER_DAY}static attoCirclesToAttoStaticCircles($,J=BigInt(Math.floor(Date.now()/1000))){return this.demurrageToInflationary($,this.dayFromTimestamp(J))}static attoStaticCirclesToAttoCircles($,J=BigInt(Math.floor(Date.now()/1000))){return this.inflationaryToDemurrage($,this.dayFromTimestamp(J))}static inflationaryToDemurrageExact($,J){let Q=this.pow36(this.GAMMA_36,J);return $*Q/this.ONE_36}static demurrageToInflationaryExact($,J){let Q=this.pow36(this.BETA_36,J);return $*Q/this.ONE_36}static attoCirclesToAttoStaticCirclesExact($,J=BigInt(Math.floor(Date.now()/1000))){let Q=this.dayFromTimestamp(J);return this.demurrageToInflationaryExact($,Q)}static attoStaticCirclesToAttoCirclesExact($,J=BigInt(Math.floor(Date.now()/1000))){let Q=this.dayFromTimestamp(J);return this.inflationaryToDemurrageExact($,Q)}static truncateToInt64($){let J=$/this.FACTOR_1E12,Q=9223372036854775807n;return J>Q?Q:J}static blowUpToBigInt($){return $*this.FACTOR_1E12}static truncateToSixDecimals($){return this.blowUpToBigInt(this.truncateToInt64($))}static v1InflateFactor($){if($===0n)return this.V1_ACCURACY;return this.V1_ACCURACY*this.V1_INFLATION_PCT_NUM**$/this.V1_INFLATION_PCT_DEN**$}static attoCrcToAttoCircles($,J){let Q=J-this.INFLATION_DAY_ZERO_UNIX,G=Q/this.PERIOD_SEC,Y=Q%this.PERIOD_SEC,Z=this.v1InflateFactor(G),K=this.v1InflateFactor(G+1n);return this.v1ToDemurrage($,Z,K,Y,this.PERIOD_SEC)}static attoCirclesToAttoCrc($,J){let Q=J-this.INFLATION_DAY_ZERO_UNIX,G=Q/this.PERIOD_SEC,Y=Q%this.PERIOD_SEC,Z=this.v1InflateFactor(G),K=this.v1InflateFactor(G+1n),q=Z*(this.PERIOD_SEC-Y)+K*Y;return $*3n*this.V1_ACCURACY*this.PERIOD_SEC/q}static v1ToDemurrage($,J,Q,G,Y){let Z=J*(Y-G)+Q*G;return $*3n*this.V1_ACCURACY*Y/Z}}class A0{client;constructor($){this.client=$}async getTotalBalance($,J=!0){let Q=await this.client.call("circlesV2_getTotalBalance",[P($),J]);return d.circlesToAttoCircles(Q)}async getTokenBalances($){let Q=(await this.client.call("circles_getTokenBalances",[P($)])).map((G)=>q0(G));return g(Q)}}class Q${client;constructor($){this.client=$}async getAvatarInfo($){let J=await this.getAvatarInfoBatch([$]);return J.length>0?J[0]:void 0}async getAvatarInfoBatch($){if($.length===0)return[];let J=$.map((G)=>P(G)),Q=await this.client.call("circles_getAvatarInfoBatch",[J]);return g(Q)}async getNetworkSnapshot(){let $=await this.client.call("circles_getNetworkSnapshot",[]);return g($)}}class G${client;constructor($){this.client=$}async getProfileByCid($){return this.client.call("circles_getProfileByCid",[$])}async getProfileByCidBatch($){return this.client.call("circles_getProfileByCidBatch",[$])}async getProfileByAddress($){return this.client.call("circles_getProfileByAddress",[P($)])}async getProfileByAddressBatch($){return this.client.call("circles_getProfileByAddressBatch",[$.map((J)=>J===null?null:P(J))])}async searchProfiles($,J=10,Q=0,G){return this.client.call("circles_searchProfiles",[$.toLowerCase(),J,Q,G])}async searchByAddressOrName($,J=10,Q=0,G){let Y=[],Z=/^0x[a-fA-F0-9]{40}$/.test($);if(Z)try{let K=await this.getProfileByAddress($);if(K){let q={...K,address:$};if(!G||!q.avatarType||G.includes(q.avatarType))Y.push(q)}}catch(K){console.warn("Failed to get profile by address:",K)}try{let K=await this.searchProfiles($,J,Q,G);if(Z&&Y.length>0){let q=$.toLowerCase(),X=K.filter((M)=>M.address?.toLowerCase()!==q);Y.push(...X)}else Y.push(...K)}catch(K){console.warn("Failed to search profiles by text:",K)}return Y.slice(0,J)}}class Y${client;constructor($){this.client=$}async getTokenInfo($){let J=await this.getTokenInfoBatch([$]);return J.length>0?J[0]:void 0}async getTokenInfoBatch($){if($.length===0)return[];let J=$.map((Y)=>P(Y)),G=(await this.client.call("circles_getTokenInfoBatch",[J])).map((Y)=>q0(Y));return g(G)}getTokenHolders($,J=100,Q="DESC"){let G=P($);return new $0(this.client,{namespace:"V_CrcV2",table:"BalancesByAccountAndToken",columns:["account","tokenAddress","demurragedTotalBalance"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"tokenAddress",Value:G}],cursorColumns:[{name:"demurragedTotalBalance",sortOrder:Q},{name:"account",sortOrder:"ASC"}],orderColumns:[{Column:"demurragedTotalBalance",SortOrder:Q},{Column:"account",SortOrder:"ASC"}],limit:J,sortOrder:Q},(Y)=>({account:Y.account,tokenAddress:Y.tokenAddress,demurragedTotalBalance:Y.demurragedTotalBalance}))}}class Z${client;constructor($){this.client=$}transformQueryResponse($){let{columns:J,rows:Q}=$;return Q.map((G)=>{let Y={};return J.forEach((Z,K)=>{Y[Z]=G[K]}),Y})}async getInvitedBy($){let J=P($),Q=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(Q.length>0)return g(Q[0].inviter);return}async getInvitations($){let J=P($),Q=96,G=await this.client.call("circles_getAvatarInfoBatch",[[J]]);if((G.length>0?G[0]:void 0)?.version===2)return[];let Z=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:[]}]),q=this.transformQueryResponse(Z).map((j)=>j.truster);if(q.length===0)return[];let X=await this.client.call("circles_getAvatarInfoBatch",[q]),M=[];for(let j of X){if(!j?.isHuman)continue;let D=(await this.client.call("circles_getTokenBalances",[j.avatar])).find((V)=>P(V.tokenAddress)===P(j.avatar));if(D&&D.circles>=96)M.push(j)}return g(M)}async getInvitationsFrom($,J=!1){let Q=P($);if(J){let G=await this.client.call("circles_query",[{Namespace:"CrcV2",Table:"RegisterHuman",Columns:["avatar"],Filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"inviter",Value:Q}],Order:[{Column:"blockNumber",SortOrder:"DESC"}]}]),Z=this.transformQueryResponse(G).map((K)=>K.avatar);return g(Z)}else{let G=await this.client.call("circles_query",[{Namespace:"V_Crc",Table:"TrustRelations",Columns:["trustee","truster"],Filter:[{Type:"Conjunction",ConjunctionType:"And",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"version",Value:2},{Type:"FilterPredicate",FilterType:"Equals",Column:"truster",Value:Q}]}],Order:[]}]),Z=this.transformQueryResponse(G).map((M)=>M.trustee);if(Z.length===0)return[];let K=await this.client.call("circles_getAvatarInfoBatch",[Z]),q=new Set(K.filter((M)=>M!==null).map((M)=>P(M.avatar))),X=Z.filter((M)=>!q.has(P(M)));return g(X)}}}function QQ($,J){let Q=BigInt($),G=d.attoCirclesToCircles(Q),Y=d.attoCirclesToAttoCrc(Q,BigInt(J)),Z=d.attoCirclesToCircles(Y),K=d.attoCirclesToAttoStaticCircles(Q,BigInt(J)),q=d.attoCirclesToCircles(K);return{attoCircles:Q,circles:G,staticAttoCircles:K,staticCircles:q,attoCrc:Y,crc:Z}}class K${client;constructor($){this.client=$}getTransactionHistory($,J=50,Q="DESC"){let G=P($),Y=[{Type:"Conjunction",ConjunctionType:"And",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"version",Value:2},{Type:"Conjunction",ConjunctionType:"Or",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"from",Value:G},{Type:"FilterPredicate",FilterType:"Equals",Column:"to",Value:G}]}]}];return new $0(this.client,{namespace:"V_Crc",table:"TransferSummary",sortOrder:Q,columns:[],filter:Y,limit:J},(Z)=>{let K=QQ(Z.value,Z.timestamp),q={...Z,...K};return g(q)})}}class k0{client;constructor($){this.client=$}async findGroups($=50,J){let Q=this.getGroups($,J,"DESC"),G=[];while(await Q.queryNextPage()){if(G.push(...Q.currentPage.results),G.length>=$)break;if(!Q.currentPage.hasMore)break}return G.slice(0,$)}getGroupMemberships($,J=50,Q="DESC"){let G=P($);return new $0(this.client,{namespace:"V_CrcV2",table:"GroupMemberships",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","member","expiryTime"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"member",Value:G}],limit:J},(Y)=>g(Y))}getGroupHolders($,J=100){let Q=P($);return new $0(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:Q}],limit:J,rowTransformer:(G)=>{let Y={...G,totalBalance:BigInt(G.totalBalance),demurragedTotalBalance:BigInt(G.demurragedTotalBalance)};return g(Y)}})}getGroupMembers($,J=100,Q="DESC"){let G=P($);return new $0(this.client,{namespace:"V_CrcV2",table:"GroupMemberships",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","member","expiryTime"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:G}],limit:J},(Y)=>g(Y))}getGroups($=50,J,Q="DESC"){let G=[];if(J){if(J.nameStartsWith)G.push({Type:"FilterPredicate",FilterType:"Like",Column:"name",Value:J.nameStartsWith+"%"});if(J.symbolStartsWith)G.push({Type:"FilterPredicate",FilterType:"Like",Column:"symbol",Value:J.symbolStartsWith+"%"});if(J.groupAddressIn&&J.groupAddressIn.length>0){let Z=J.groupAddressIn.map((K)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:P(K)}));if(Z.length===1)G.push(Z[0]);else G.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:Z})}if(J.groupTypeIn&&J.groupTypeIn.length>0){let Z=J.groupTypeIn.map((K)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"type",Value:K}));if(Z.length===1)G.push(Z[0]);else G.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:Z})}if(J.ownerIn&&J.ownerIn.length>0){let Z=J.ownerIn.map((K)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"owner",Value:P(K)}));if(Z.length===1)G.push(Z[0]);else G.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:Z})}if(J.mintHandlerEquals)G.push({Type:"FilterPredicate",FilterType:"Equals",Column:"mintHandler",Value:P(J.mintHandlerEquals)});if(J.treasuryEquals)G.push({Type:"FilterPredicate",FilterType:"Equals",Column:"treasury",Value:P(J.treasuryEquals)})}let Y=G.length>1?[{Type:"Conjunction",ConjunctionType:"And",Predicates:G}]:G;return new $0(this.client,{namespace:"V_CrcV2",table:"Groups",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","group","type","owner","mintPolicy","mintHandler","treasury","service","feeCollection","memberCount","name","symbol","cidV0Digest","erc20WrapperDemurraged","erc20WrapperStatic"],filter:Y,limit:$},(Z)=>g(Z))}}class _${client;_pathfinder;_query;_trust;_balance;_avatar;_profile;_token;_invitation;_transaction;_group;constructor($="https://rpc.circlesubi.network/"){this.client=new O0($)}get pathfinder(){if(!this._pathfinder)this._pathfinder=new j0(this.client);return this._pathfinder}get query(){if(!this._query)this._query=new J$(this.client);return this._query}get trust(){if(!this._trust)this._trust=new x0(this.client);return this._trust}get balance(){if(!this._balance)this._balance=new A0(this.client);return this._balance}get avatar(){if(!this._avatar)this._avatar=new Q$(this.client);return this._avatar}get profile(){if(!this._profile)this._profile=new G$(this.client);return this._profile}get token(){if(!this._token)this._token=new Y$(this.client);return this._token}get invitation(){if(!this._invitation)this._invitation=new Z$(this.client);return this._invitation}get transaction(){if(!this._transaction)this._transaction=new K$(this.client);return this._transaction}get group(){if(!this._group)this._group=new k0(this.client);return this._group}setRpcUrl($){this.client.setRpcUrl($)}getRpcUrl(){return this.client.getRpcUrl()}}class Q0{address;abi;rpcUrl;constructor($){this.address=$.address,this.abi=$.abi,this.rpcUrl=$.rpcUrl}async read($,J,Q){let G=I$({abi:this.abi,functionName:$,args:J}),Y={to:this.address,data:G,...Q?.from&&{from:Q.from}},K=await(await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[Y,"latest"]})})).json();if(K.error)throw Error(`RPC Error: ${K.error.message}`);if(!K.result)throw Error("No result returned from RPC call");return m$({abi:this.abi,functionName:$,data:K.result})}encodeWrite($,J){return I$({abi:this.abi,functionName:$,args:J})}}var iJ=[{type:"function",name:"operateFlowMatrix",inputs:[{name:"_flowVertices",type:"address[]"},{name:"_flow",type:"tuple[]",components:[{name:"streamSinkId",type:"uint16"},{name:"amount",type:"uint192"}]},{name:"_streams",type:"tuple[]",components:[{name:"sourceCoordinate",type:"uint16"},{name:"flowEdgeIds",type:"uint16[]"},{name:"data",type:"bytes"}]},{name:"_packedCoordinates",type:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"isApprovedForAll",inputs:[{name:"_account",type:"address"},{name:"_operator",type:"address"}],outputs:[{type:"bool"}],stateMutability:"view"},{type:"function",name:"setApprovalForAll",inputs:[{name:"_operator",type:"address"},{name:"_approved",type:"bool"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"wrap",inputs:[{name:"_avatar",type:"address"},{name:"_amount",type:"uint256"},{name:"_type",type:"uint8"}],outputs:[{type:"address"}],stateMutability:"nonpayable"},{type:"function",name:"trust",inputs:[{name:"_trustReceiver",type:"address"},{name:"_expiry",type:"uint96"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"isTrusted",inputs:[{name:"_truster",type:"address"},{name:"_trustee",type:"address"}],outputs:[{type:"bool"}],stateMutability:"view"},{type:"function",name:"toTokenId",inputs:[{name:"_avatar",type:"address"}],outputs:[{type:"uint256"}],stateMutability:"pure"},{type:"function",name:"safeTransferFrom",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_id",type:"uint256"},{name:"_value",type:"uint256"},{name:"_data",type:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"isHuman",inputs:[{name:"_human",type:"address"}],outputs:[{type:"bool"}],stateMutability:"view"},{type:"function",name:"safeBatchTransferFrom",inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_ids",type:"uint256[]"},{name:"_values",type:"uint256[]"},{name:"_data",type:"bytes"}],outputs:[],stateMutability:"nonpayable"}];class P0 extends Q0{constructor($){super({address:$.address,abi:iJ,rpcUrl:$.rpcUrl})}async isTrusted($,J){return this.read("isTrusted",[$,J])}async isApprovedForAll($,J){return this.read("isApprovedForAll",[$,J])}async toTokenId($){return this.read("toTokenId",[$])}trust($,J){return{to:this.address,data:this.encodeWrite("trust",[$,J]),value:0n}}setApprovalForAll($,J){return{to:this.address,data:this.encodeWrite("setApprovalForAll",[$,J]),value:0n}}wrap($,J,Q){return{to:this.address,data:this.encodeWrite("wrap",[$,J,Q]),value:0n}}safeTransferFrom($,J,Q,G,Y="0x"){return{to:this.address,data:this.encodeWrite("safeTransferFrom",[$,J,Q,G,Y]),value:0n}}operateFlowMatrix($,J,Q,G){return{to:this.address,data:this.encodeWrite("operateFlowMatrix",[$,J,Q,G]),value:0n}}async isHuman($){return this.read("isHuman",[$])}safeBatchTransferFrom($,J,Q,G,Y="0x"){return{to:this.address,data:this.encodeWrite("safeBatchTransferFrom",[$,J,Q,G,Y]),value:0n}}}var nJ=[{type:"function",name:"erc20Circles",inputs:[{name:"_circlesType",type:"uint8"},{name:"_avatar",type:"address"}],outputs:[{type:"address"}],stateMutability:"view"}];class E$ extends Q0{constructor($){super({address:$.address,abi:nJ,rpcUrl:$.rpcUrl})}async erc20Circles($,J){return this.read("erc20Circles",[$,J])}}var p$=[{type:"function",name:"unwrap",inputs:[{name:"_amount",type:"uint256"}],outputs:[],stateMutability:"nonpayable"}];class c0 extends Q0{constructor($){super({address:$.address,abi:p$,rpcUrl:$.rpcUrl})}unwrap($){return{to:this.address,data:this.encodeWrite("unwrap",[$]),value:0n}}}class l0 extends Q0{constructor($){super({address:$.address,abi:p$,rpcUrl:$.rpcUrl})}unwrap($){return{to:this.address,data:this.encodeWrite("unwrap",[$]),value:0n}}}var d$=[{type:"function",name:"createAccount",inputs:[{name:"signer",type:"address"}],outputs:[{name:"account",type:"address"}],stateMutability:"nonpayable"},{type:"function",name:"createAccounts",inputs:[{name:"signers",type:"address[]"}],outputs:[{name:"_accounts",type:"address[]"}],stateMutability:"nonpayable"}];var i$=[{type:"function",name:"claimInvites",inputs:[{name:"numberOfInvites",type:"uint256"}],outputs:[{name:"ids",type:"uint256[]"}],stateMutability:"nonpayable"},{type:"function",name:"inviterQuota",inputs:[{name:"",type:"address"}],outputs:[{type:"uint256"}],stateMutability:"view"},{type:"function",name:"INVITATION_FEE",inputs:[],outputs:[{type:"uint256"}],stateMutability:"view"},{type:"function",name:"invitationModule",inputs:[],outputs:[{type:"address"}],stateMutability:"view"}];class p0 extends Q0{constructor($){super({address:$.address,abi:d$,rpcUrl:$.rpcUrl})}createAccount($){return{to:this.address,data:this.encodeWrite("createAccount",[$]),value:0n}}createAccounts($){return{to:this.address,data:this.encodeWrite("createAccounts",[$]),value:0n}}}class x$ extends Q0{constructor($){super({address:$.address,abi:i$,rpcUrl:$.rpcUrl})}claimInvites($){return{to:this.address,data:this.encodeWrite("claimInvites",[$]),value:0n}}async inviterQuota($){return this.read("inviterQuota",[$])}async invitationFee(){return this.read("INVITATION_FEE")}async invitationModule(){return this.read("invitationModule")}}class A$ extends Error{name;code;source;cause;context;constructor($,J,Q){super(J);if(this.name=$,this.code=Q?.code,this.source=Q?.source??"UNKNOWN",this.cause=Q?.cause,this.context=Q?.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 $=`[${this.source}] ${this.name}: ${this.message}`;if(this.code)$+=` (Code: ${this.code})`;if(this.context)$+=`
|
|
3
|
+
Context: ${JSON.stringify(this.context,null,2)}`;return $}}function GQ($,J,Q,G){if(typeof $.setBigUint64==="function")return $.setBigUint64(J,Q,G);let Y=BigInt(32),Z=BigInt(4294967295),K=Number(Q>>Y&Z),q=Number(Q&Z),X=G?4:0,M=G?0:4;$.setUint32(J+X,K,G),$.setUint32(J+M,q,G)}function oJ($,J,Q){return $&J^~$&Q}function tJ($,J,Q){return $&J^$&Q^J&Q}class n$ extends E0{constructor($,J,Q,G){super();this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=$,this.outputLen=J,this.padOffset=Q,this.isLE=G,this.buffer=new Uint8Array($),this.view=C$(this.buffer)}update($){X0(this),$=_0($),Y0($);let{view:J,buffer:Q,blockLen:G}=this,Y=$.length;for(let Z=0;Z<Y;){let K=Math.min(G-this.pos,Y-Z);if(K===G){let q=C$($);for(;G<=Y-Z;Z+=G)this.process(q,Z);continue}if(Q.set($.subarray(Z,Z+K),this.pos),this.pos+=K,Z+=K,this.pos===G)this.process(J,0),this.pos=0}return this.length+=$.length,this.roundClean(),this}digestInto($){X0(this),R$($,this),this.finished=!0;let{buffer:J,view:Q,blockLen:G,isLE:Y}=this,{pos:Z}=this;if(J[Z++]=128,Z0(this.buffer.subarray(Z)),this.padOffset>G-Z)this.process(Q,0),Z=0;for(let j=Z;j<G;j++)J[j]=0;GQ(Q,G-8,BigInt(this.length*8),Y),this.process(Q,0);let K=C$($),q=this.outputLen;if(q%4)throw Error("_sha2: outputLen should be aligned to 32bit");let X=q/4,M=this.get();if(X>M.length)throw Error("_sha2: outputLen bigger than state");for(let j=0;j<X;j++)K.setUint32(4*j,M[j],Y)}digest(){let{buffer:$,outputLen:J}=this;this.digestInto($);let Q=$.slice(0,J);return this.destroy(),Q}_cloneInto($){$||($=new this.constructor),$.set(...this.get());let{blockLen:J,buffer:Q,length:G,finished:Y,destroyed:Z,pos:K}=this;if($.destroyed=Z,$.finished=Y,$.length=G,$.pos=K,G%J)$.buffer.set(Q);return $}clone(){return this._cloneInto()}}var U0=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var YQ=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),B0=new Uint32Array(64);class aJ extends n${constructor($=32){super(64,$,8,!1);this.A=U0[0]|0,this.B=U0[1]|0,this.C=U0[2]|0,this.D=U0[3]|0,this.E=U0[4]|0,this.F=U0[5]|0,this.G=U0[6]|0,this.H=U0[7]|0}get(){let{A:$,B:J,C:Q,D:G,E:Y,F:Z,G:K,H:q}=this;return[$,J,Q,G,Y,Z,K,q]}set($,J,Q,G,Y,Z,K,q){this.A=$|0,this.B=J|0,this.C=Q|0,this.D=G|0,this.E=Y|0,this.F=Z|0,this.G=K|0,this.H=q|0}process($,J){for(let j=0;j<16;j++,J+=4)B0[j]=$.getUint32(J,!1);for(let j=16;j<64;j++){let N=B0[j-15],D=B0[j-2],V=G0(N,7)^G0(N,18)^N>>>3,L=G0(D,17)^G0(D,19)^D>>>10;B0[j]=L+B0[j-7]+V+B0[j-16]|0}let{A:Q,B:G,C:Y,D:Z,E:K,F:q,G:X,H:M}=this;for(let j=0;j<64;j++){let N=G0(K,6)^G0(K,11)^G0(K,25),D=M+N+oJ(K,q,X)+YQ[j]+B0[j]|0,L=(G0(Q,2)^G0(Q,13)^G0(Q,22))+tJ(Q,G,Y)|0;M=X,X=q,q=K,K=Z+D|0,Z=Y,Y=G,G=Q,Q=D+L|0}Q=Q+this.A|0,G=G+this.B|0,Y=Y+this.C|0,Z=Z+this.D|0,K=K+this.E|0,q=q+this.F|0,X=X+this.G|0,M=M+this.H|0,this.set(Q,G,Y,Z,K,q,X,M)}roundClean(){Z0(B0)}destroy(){this.set(0,0,0,0,0,0,0,0),Z0(this.buffer)}}var sJ=L$(()=>new aJ);class o$ extends E0{constructor($,J){super();this.finished=!1,this.destroyed=!1,yJ($);let Q=_0(J);if(this.iHash=$.create(),typeof this.iHash.update!=="function")throw Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let G=this.blockLen,Y=new Uint8Array(G);Y.set(Q.length>G?$.create().update(Q).digest():Q);for(let Z=0;Z<Y.length;Z++)Y[Z]^=54;this.iHash.update(Y),this.oHash=$.create();for(let Z=0;Z<Y.length;Z++)Y[Z]^=106;this.oHash.update(Y),Z0(Y)}update($){return X0(this),this.iHash.update($),this}digestInto($){X0(this),Y0($,this.outputLen),this.finished=!0,this.iHash.digestInto($),this.oHash.update($),this.oHash.digestInto($),this.destroy()}digest(){let $=new Uint8Array(this.oHash.outputLen);return this.digestInto($),$}_cloneInto($){$||($=Object.create(Object.getPrototypeOf(this),{}));let{oHash:J,iHash:Q,finished:G,destroyed:Y,blockLen:Z,outputLen:K}=this;return $=$,$.finished=G,$.destroyed=Y,$.blockLen=Z,$.outputLen=K,$.oHash=J._cloneInto($.oHash),$.iHash=Q._cloneInto($.iHash),$}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var t$=($,J,Q)=>new o$($,J).update(Q).digest();t$.create=($,J)=>new o$($,J);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var e$=BigInt(0),r$=BigInt(1);function d0($){return $ instanceof Uint8Array||ArrayBuffer.isView($)&&$.constructor.name==="Uint8Array"}function $J($){if(!d0($))throw Error("Uint8Array expected")}function i0($,J){if(typeof J!=="boolean")throw Error($+" boolean expected, got "+J)}function X$($){let J=$.toString(16);return J.length&1?"0"+J:J}function $8($){if(typeof $!=="string")throw Error("hex string expected, got "+typeof $);return $===""?e$:BigInt("0x"+$)}var J8=typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function",ZQ=Array.from({length:256},($,J)=>J.toString(16).padStart(2,"0"));function n0($){if($J($),J8)return $.toHex();let J="";for(let Q=0;Q<$.length;Q++)J+=ZQ[$[Q]];return J}var W0={_0:48,_9:57,A:65,F:70,a:97,f:102};function rJ($){if($>=W0._0&&$<=W0._9)return $-W0._0;if($>=W0.A&&$<=W0.F)return $-(W0.A-10);if($>=W0.a&&$<=W0.f)return $-(W0.a-10);return}function q$($){if(typeof $!=="string")throw Error("hex string expected, got "+typeof $);if(J8)return Uint8Array.fromHex($);let J=$.length,Q=J/2;if(J%2)throw Error("hex string expected, got unpadded hex of length "+J);let G=new Uint8Array(Q);for(let Y=0,Z=0;Y<Q;Y++,Z+=2){let K=rJ($.charCodeAt(Z)),q=rJ($.charCodeAt(Z+1));if(K===void 0||q===void 0){let X=$[Z]+$[Z+1];throw Error('hex string expected, got non-hex character "'+X+'" at index '+Z)}G[Y]=K*16+q}return G}function N0($){return $8(n0($))}function JJ($){return $J($),$8(n0(Uint8Array.from($).reverse()))}function w0($,J){return q$($.toString(16).padStart(J*2,"0"))}function QJ($,J){return w0($,J).reverse()}function e($,J,Q){let G;if(typeof J==="string")try{G=q$(J)}catch(Z){throw Error($+" must be hex string or Uint8Array, cause: "+Z)}else if(d0(J))G=Uint8Array.from(J);else throw Error($+" must be hex string or Uint8Array");let Y=G.length;if(typeof Q==="number"&&Y!==Q)throw Error($+" of length "+Q+" expected, got "+Y);return G}function M$(...$){let J=0;for(let G=0;G<$.length;G++){let Y=$[G];$J(Y),J+=Y.length}let Q=new Uint8Array(J);for(let G=0,Y=0;G<$.length;G++){let Z=$[G];Q.set(Z,Y),Y+=Z.length}return Q}var a$=($)=>typeof $==="bigint"&&e$<=$;function k$($,J,Q){return a$($)&&a$(J)&&a$(Q)&&J<=$&&$<Q}function y0($,J,Q,G){if(!k$(J,Q,G))throw Error("expected valid "+$+": "+Q+" <= n < "+G+", got "+J)}function Q8($){let J;for(J=0;$>e$;$>>=r$,J+=1);return J}var F0=($)=>(r$<<BigInt($))-r$,s$=($)=>new Uint8Array($),eJ=($)=>Uint8Array.from($);function G8($,J,Q){if(typeof $!=="number"||$<2)throw Error("hashLen must be a number");if(typeof J!=="number"||J<2)throw Error("qByteLen must be a number");if(typeof Q!=="function")throw Error("hmacFn must be a function");let G=s$($),Y=s$($),Z=0,K=()=>{G.fill(1),Y.fill(0),Z=0},q=(...N)=>Q(Y,G,...N),X=(N=s$(0))=>{if(Y=q(eJ([0]),N),G=q(),N.length===0)return;Y=q(eJ([1]),N),G=q()},M=()=>{if(Z++>=1000)throw Error("drbg: tried 1000 values");let N=0,D=[];while(N<J){G=q();let V=G.slice();D.push(V),N+=G.length}return M$(...D)};return(N,D)=>{K(),X(N);let V=void 0;while(!(V=D(M())))X();return K(),V}}var KQ={bigint:($)=>typeof $==="bigint",function:($)=>typeof $==="function",boolean:($)=>typeof $==="boolean",string:($)=>typeof $==="string",stringOrUint8Array:($)=>typeof $==="string"||d0($),isSafeInteger:($)=>Number.isSafeInteger($),array:($)=>Array.isArray($),field:($,J)=>J.Fp.isValid($),hash:($)=>typeof $==="function"&&Number.isSafeInteger($.outputLen)};function b0($,J,Q={}){let G=(Y,Z,K)=>{let q=KQ[Z];if(typeof q!=="function")throw Error("invalid validator function");let X=$[Y];if(K&&X===void 0)return;if(!q(X,$))throw Error("param "+String(Y)+" is invalid. Expected "+Z+", got "+X)};for(let[Y,Z]of Object.entries(J))G(Y,Z,!1);for(let[Y,Z]of Object.entries(Q))G(Y,Z,!0);return $}function GJ($){let J=new WeakMap;return(Q,...G)=>{let Y=J.get(Q);if(Y!==void 0)return Y;let Z=$(Q,...G);return J.set(Q,Z),Z}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var a=BigInt(0),n=BigInt(1),g0=BigInt(2),XQ=BigInt(3),Z8=BigInt(4),K8=BigInt(5),X8=BigInt(8);function i($,J){let Q=$%J;return Q>=a?Q:J+Q}function J0($,J,Q){let G=$;while(J-- >a)G*=G,G%=Q;return G}function w$($,J){if($===a)throw Error("invert: expected non-zero number");if(J<=a)throw Error("invert: expected positive modulus, got "+J);let Q=i($,J),G=J,Y=a,Z=n,K=n,q=a;while(Q!==a){let M=G/Q,j=G%Q,N=Y-K*M,D=Z-q*M;G=Q,Q=j,Y=K,Z=q,K=N,q=D}if(G!==n)throw Error("invert: does not exist");return i(Y,J)}function q8($,J){let Q=($.ORDER+n)/Z8,G=$.pow(J,Q);if(!$.eql($.sqr(G),J))throw Error("Cannot find square root");return G}function qQ($,J){let Q=($.ORDER-K8)/X8,G=$.mul(J,g0),Y=$.pow(G,Q),Z=$.mul(J,Y),K=$.mul($.mul(Z,g0),Y),q=$.mul(Z,$.sub(K,$.ONE));if(!$.eql($.sqr(q),J))throw Error("Cannot find square root");return q}function MQ($){if($<BigInt(3))throw Error("sqrt is not defined for small field");let J=$-n,Q=0;while(J%g0===a)J/=g0,Q++;let G=g0,Y=j$($);while(Y8(Y,G)===1)if(G++>1000)throw Error("Cannot find square root: probably non-prime P");if(Q===1)return q8;let Z=Y.pow(G,J),K=(J+n)/g0;return function(X,M){if(X.is0(M))return M;if(Y8(X,M)!==1)throw Error("Cannot find square root");let j=Q,N=X.mul(X.ONE,Z),D=X.pow(M,J),V=X.pow(M,K);while(!X.eql(D,X.ONE)){if(X.is0(D))return X.ZERO;let L=1,z=X.sqr(D);while(!X.eql(z,X.ONE))if(L++,z=X.sqr(z),L===j)throw Error("Cannot find square root");let A=n<<BigInt(j-L-1),H=X.pow(N,A);j=L,N=X.sqr(H),D=X.mul(D,N),V=X.mul(V,H)}return V}}function jQ($){if($%Z8===XQ)return q8;if($%X8===K8)return qQ;return MQ($)}var UQ=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function YJ($){let J={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},Q=UQ.reduce((G,Y)=>{return G[Y]="function",G},J);return b0($,Q)}function WQ($,J,Q){if(Q<a)throw Error("invalid exponent, negatives unsupported");if(Q===a)return $.ONE;if(Q===n)return J;let G=$.ONE,Y=J;while(Q>a){if(Q&n)G=$.mul(G,Y);Y=$.sqr(Y),Q>>=n}return G}function ZJ($,J,Q=!1){let G=Array(J.length).fill(Q?$.ZERO:void 0),Y=J.reduce((K,q,X)=>{if($.is0(q))return K;return G[X]=K,$.mul(K,q)},$.ONE),Z=$.inv(Y);return J.reduceRight((K,q,X)=>{if($.is0(q))return K;return G[X]=$.mul(K,G[X]),$.mul(K,q)},Z),G}function Y8($,J){let Q=($.ORDER-n)/g0,G=$.pow(J,Q),Y=$.eql(G,$.ONE),Z=$.eql(G,$.ZERO),K=$.eql(G,$.neg($.ONE));if(!Y&&!Z&&!K)throw Error("invalid Legendre symbol result");return Y?1:Z?0:-1}function KJ($,J){if(J!==void 0)T0(J);let Q=J!==void 0?J:$.toString(2).length,G=Math.ceil(Q/8);return{nBitLength:Q,nByteLength:G}}function j$($,J,Q=!1,G={}){if($<=a)throw Error("invalid field: expected ORDER > 0, got "+$);let{nBitLength:Y,nByteLength:Z}=KJ($,J);if(Z>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");let K,q=Object.freeze({ORDER:$,isLE:Q,BITS:Y,BYTES:Z,MASK:F0(Y),ZERO:a,ONE:n,create:(X)=>i(X,$),isValid:(X)=>{if(typeof X!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof X);return a<=X&&X<$},is0:(X)=>X===a,isOdd:(X)=>(X&n)===n,neg:(X)=>i(-X,$),eql:(X,M)=>X===M,sqr:(X)=>i(X*X,$),add:(X,M)=>i(X+M,$),sub:(X,M)=>i(X-M,$),mul:(X,M)=>i(X*M,$),pow:(X,M)=>WQ(q,X,M),div:(X,M)=>i(X*w$(M,$),$),sqrN:(X)=>X*X,addN:(X,M)=>X+M,subN:(X,M)=>X-M,mulN:(X,M)=>X*M,inv:(X)=>w$(X,$),sqrt:G.sqrt||((X)=>{if(!K)K=jQ($);return K(q,X)}),toBytes:(X)=>Q?QJ(X,Z):w0(X,Z),fromBytes:(X)=>{if(X.length!==Z)throw Error("Field.fromBytes: expected "+Z+" bytes, got "+X.length);return Q?JJ(X):N0(X)},invertBatch:(X)=>ZJ(q,X),cmov:(X,M,j)=>j?M:X});return Object.freeze(q)}function M8($){if(typeof $!=="bigint")throw Error("field order must be bigint");let J=$.toString(2).length;return Math.ceil(J/8)}function XJ($){let J=M8($);return J+Math.ceil(J/2)}function j8($,J,Q=!1){let G=$.length,Y=M8(J),Z=XJ(J);if(G<16||G<Z||G>1024)throw Error("expected "+Z+"-1024 bytes of input, got "+G);let K=Q?JJ($):N0($),q=i(K,J-n)+n;return Q?QJ(q,Y):w0(q,Y)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var U8=BigInt(0),WJ=BigInt(1);function qJ($,J){let Q=J.negate();return $?Q:J}function N8($,J){if(!Number.isSafeInteger($)||$<=0||$>J)throw Error("invalid window size, expected [1.."+J+"], got W="+$)}function MJ($,J){N8($,J);let Q=Math.ceil(J/$)+1,G=2**($-1),Y=2**$,Z=F0($),K=BigInt($);return{windows:Q,windowSize:G,mask:Z,maxNumber:Y,shiftBy:K}}function W8($,J,Q){let{windowSize:G,mask:Y,maxNumber:Z,shiftBy:K}=Q,q=Number($&Y),X=$>>K;if(q>G)q-=Z,X+=WJ;let M=J*G,j=M+Math.abs(q)-1,N=q===0,D=q<0,V=J%2!==0;return{nextN:X,offset:j,isZero:N,isNeg:D,isNegF:V,offsetF:M}}function NQ($,J){if(!Array.isArray($))throw Error("array expected");$.forEach((Q,G)=>{if(!(Q instanceof J))throw Error("invalid point at index "+G)})}function zQ($,J){if(!Array.isArray($))throw Error("array of scalars expected");$.forEach((Q,G)=>{if(!J.isValid(Q))throw Error("invalid scalar at index "+G)})}var jJ=new WeakMap,z8=new WeakMap;function UJ($){return z8.get($)||1}function D8($,J){return{constTimeNegate:qJ,hasPrecomputes(Q){return UJ(Q)!==1},unsafeLadder(Q,G,Y=$.ZERO){let Z=Q;while(G>U8){if(G&WJ)Y=Y.add(Z);Z=Z.double(),G>>=WJ}return Y},precomputeWindow(Q,G){let{windows:Y,windowSize:Z}=MJ(G,J),K=[],q=Q,X=q;for(let M=0;M<Y;M++){X=q,K.push(X);for(let j=1;j<Z;j++)X=X.add(q),K.push(X);q=X.double()}return K},wNAF(Q,G,Y){let{ZERO:Z,BASE:K}=$,q=MJ(Q,J);for(let X=0;X<q.windows;X++){let{nextN:M,offset:j,isZero:N,isNeg:D,isNegF:V,offsetF:L}=W8(Y,X,q);if(Y=M,N)K=K.add(qJ(V,G[L]));else Z=Z.add(qJ(D,G[j]))}return{p:Z,f:K}},wNAFUnsafe(Q,G,Y,Z=$.ZERO){let K=MJ(Q,J);for(let q=0;q<K.windows;q++){if(Y===U8)break;let{nextN:X,offset:M,isZero:j,isNeg:N}=W8(Y,q,K);if(Y=X,j)continue;else{let D=G[M];Z=Z.add(N?D.negate():D)}}return Z},getPrecomputes(Q,G,Y){let Z=jJ.get(G);if(!Z){if(Z=this.precomputeWindow(G,Q),Q!==1)jJ.set(G,Y(Z))}return Z},wNAFCached(Q,G,Y){let Z=UJ(Q);return this.wNAF(Z,this.getPrecomputes(Z,Q,Y),G)},wNAFCachedUnsafe(Q,G,Y,Z){let K=UJ(Q);if(K===1)return this.unsafeLadder(Q,G,Z);return this.wNAFUnsafe(K,this.getPrecomputes(K,Q,Y),G,Z)},setWindowSize(Q,G){N8(G,J),z8.set(Q,G),jJ.delete(Q)}}}function V8($,J,Q,G){NQ(Q,$),zQ(G,J);let Y=Q.length,Z=G.length;if(Y!==Z)throw Error("arrays of points and scalars must have equal length");let K=$.ZERO,q=Q8(BigInt(Y)),X=1;if(q>12)X=q-3;else if(q>4)X=q-2;else if(q>0)X=2;let M=F0(X),j=Array(Number(M)+1).fill(K),N=Math.floor((J.BITS-1)/X)*X,D=K;for(let V=N;V>=0;V-=X){j.fill(K);for(let z=0;z<Z;z++){let A=G[z],H=Number(A>>BigInt(V)&M);j[H]=j[H].add(Q[z])}let L=K;for(let z=j.length-1,A=K;z>0;z--)A=A.add(j[z]),L=L.add(A);if(D=D.add(L),V!==0)for(let z=0;z<X;z++)D=D.double()}return D}function NJ($){return YJ($.Fp),b0($,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...KJ($.n,$.nBitLength),...$,...{p:$.Fp.ORDER}})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function O8($){if($.lowS!==void 0)i0("lowS",$.lowS);if($.prehash!==void 0)i0("prehash",$.prehash)}function DQ($){let J=NJ($);b0(J,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:Q,Fp:G,a:Y}=J;if(Q){if(!G.eql(Y,G.ZERO))throw Error("invalid endo: CURVE.a must be 0");if(typeof Q!=="object"||typeof Q.beta!=="bigint"||typeof Q.splitScalar!=="function")throw Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...J})}class R8 extends Error{constructor($=""){super($)}}var z0={Err:R8,_tlv:{encode:($,J)=>{let{Err:Q}=z0;if($<0||$>256)throw new Q("tlv.encode: wrong tag");if(J.length&1)throw new Q("tlv.encode: unpadded data");let G=J.length/2,Y=X$(G);if(Y.length/2&128)throw new Q("tlv.encode: long form length too big");let Z=G>127?X$(Y.length/2|128):"";return X$($)+Z+Y+J},decode($,J){let{Err:Q}=z0,G=0;if($<0||$>256)throw new Q("tlv.encode: wrong tag");if(J.length<2||J[G++]!==$)throw new Q("tlv.decode: wrong tlv");let Y=J[G++],Z=!!(Y&128),K=0;if(!Z)K=Y;else{let X=Y&127;if(!X)throw new Q("tlv.decode(long): indefinite length not supported");if(X>4)throw new Q("tlv.decode(long): byte length is too big");let M=J.subarray(G,G+X);if(M.length!==X)throw new Q("tlv.decode: length bytes not complete");if(M[0]===0)throw new Q("tlv.decode(long): zero leftmost byte");for(let j of M)K=K<<8|j;if(G+=X,K<128)throw new Q("tlv.decode(long): not minimal encoding")}let q=J.subarray(G,G+K);if(q.length!==K)throw new Q("tlv.decode: wrong value length");return{v:q,l:J.subarray(G+K)}}},_int:{encode($){let{Err:J}=z0;if($<D0)throw new J("integer: negative integers are not allowed");let Q=X$($);if(Number.parseInt(Q[0],16)&8)Q="00"+Q;if(Q.length&1)throw new J("unexpected DER parsing assertion: unpadded hex");return Q},decode($){let{Err:J}=z0;if($[0]&128)throw new J("invalid signature integer: negative");if($[0]===0&&!($[1]&128))throw new J("invalid signature integer: unnecessary leading zero");return N0($)}},toSig($){let{Err:J,_int:Q,_tlv:G}=z0,Y=e("signature",$),{v:Z,l:K}=G.decode(48,Y);if(K.length)throw new J("invalid signature: left bytes after parsing");let{v:q,l:X}=G.decode(2,Z),{v:M,l:j}=G.decode(2,X);if(j.length)throw new J("invalid signature: left bytes after parsing");return{r:Q.decode(q),s:Q.decode(M)}},hexFromSig($){let{_tlv:J,_int:Q}=z0,G=J.encode(2,Q.encode($.r)),Y=J.encode(2,Q.encode($.s)),Z=G+Y;return J.encode(48,Z)}};function zJ($,J){return n0(w0($,J))}var D0=BigInt(0),p=BigInt(1),KY=BigInt(2),DJ=BigInt(3),VQ=BigInt(4);function OQ($){let J=DQ($),{Fp:Q}=J,G=j$(J.n,J.nBitLength),Y=J.toBytes||((U,R,B)=>{let S=R.toAffine();return M$(Uint8Array.from([4]),Q.toBytes(S.x),Q.toBytes(S.y))}),Z=J.fromBytes||((U)=>{let R=U.subarray(1),B=Q.fromBytes(R.subarray(0,Q.BYTES)),S=Q.fromBytes(R.subarray(Q.BYTES,2*Q.BYTES));return{x:B,y:S}});function K(U){let{a:R,b:B}=J,S=Q.sqr(U),w=Q.mul(S,U);return Q.add(Q.add(w,Q.mul(U,R)),B)}function q(U,R){let B=Q.sqr(R),S=K(U);return Q.eql(B,S)}if(!q(J.Gx,J.Gy))throw Error("bad curve params: generator point");let X=Q.mul(Q.pow(J.a,DJ),VQ),M=Q.mul(Q.sqr(J.b),BigInt(27));if(Q.is0(Q.add(X,M)))throw Error("bad curve params: a or b");function j(U){return k$(U,p,J.n)}function N(U){let{allowedPrivateKeyLengths:R,nByteLength:B,wrapPrivateKey:S,n:w}=J;if(R&&typeof U!=="bigint"){if(d0(U))U=n0(U);if(typeof U!=="string"||!R.includes(U.length))throw Error("invalid private key");U=U.padStart(B*2,"0")}let E;try{E=typeof U==="bigint"?U:N0(e("private key",U,B))}catch(y){throw Error("invalid private key, expected hex or "+B+" bytes, got "+typeof U)}if(S)E=i(E,w);return y0("private key",E,p,w),E}function D(U){if(!(U instanceof z))throw Error("ProjectivePoint expected")}let V=GJ((U,R)=>{let{px:B,py:S,pz:w}=U;if(Q.eql(w,Q.ONE))return{x:B,y:S};let E=U.is0();if(R==null)R=E?Q.ONE:Q.inv(w);let y=Q.mul(B,R),_=Q.mul(S,R),k=Q.mul(w,R);if(E)return{x:Q.ZERO,y:Q.ZERO};if(!Q.eql(k,Q.ONE))throw Error("invZ was invalid");return{x:y,y:_}}),L=GJ((U)=>{if(U.is0()){if(J.allowInfinityPoint&&!Q.is0(U.py))return;throw Error("bad point: ZERO")}let{x:R,y:B}=U.toAffine();if(!Q.isValid(R)||!Q.isValid(B))throw Error("bad point: x or y not FE");if(!q(R,B))throw Error("bad point: equation left != right");if(!U.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});class z{constructor(U,R,B){if(U==null||!Q.isValid(U))throw Error("x required");if(R==null||!Q.isValid(R)||Q.is0(R))throw Error("y required");if(B==null||!Q.isValid(B))throw Error("z required");this.px=U,this.py=R,this.pz=B,Object.freeze(this)}static fromAffine(U){let{x:R,y:B}=U||{};if(!U||!Q.isValid(R)||!Q.isValid(B))throw Error("invalid affine point");if(U instanceof z)throw Error("projective point not allowed");let S=(w)=>Q.eql(w,Q.ZERO);if(S(R)&&S(B))return z.ZERO;return new z(R,B,Q.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(U){let R=ZJ(Q,U.map((B)=>B.pz));return U.map((B,S)=>B.toAffine(R[S])).map(z.fromAffine)}static fromHex(U){let R=z.fromAffine(Z(e("pointHex",U)));return R.assertValidity(),R}static fromPrivateKey(U){return z.BASE.multiply(N(U))}static msm(U,R){return V8(z,G,U,R)}_setWindowSize(U){h.setWindowSize(this,U)}assertValidity(){L(this)}hasEvenY(){let{y:U}=this.toAffine();if(Q.isOdd)return!Q.isOdd(U);throw Error("Field doesn't support isOdd")}equals(U){D(U);let{px:R,py:B,pz:S}=this,{px:w,py:E,pz:y}=U,_=Q.eql(Q.mul(R,y),Q.mul(w,S)),k=Q.eql(Q.mul(B,y),Q.mul(E,S));return _&&k}negate(){return new z(this.px,Q.neg(this.py),this.pz)}double(){let{a:U,b:R}=J,B=Q.mul(R,DJ),{px:S,py:w,pz:E}=this,y=Q.ZERO,_=Q.ZERO,k=Q.ZERO,x=Q.mul(S,S),c=Q.mul(w,w),v=Q.mul(E,E),W=Q.mul(S,w);return W=Q.add(W,W),k=Q.mul(S,E),k=Q.add(k,k),y=Q.mul(U,k),_=Q.mul(B,v),_=Q.add(y,_),y=Q.sub(c,_),_=Q.add(c,_),_=Q.mul(y,_),y=Q.mul(W,y),k=Q.mul(B,k),v=Q.mul(U,v),W=Q.sub(x,v),W=Q.mul(U,W),W=Q.add(W,k),k=Q.add(x,x),x=Q.add(k,x),x=Q.add(x,v),x=Q.mul(x,W),_=Q.add(_,x),v=Q.mul(w,E),v=Q.add(v,v),x=Q.mul(v,W),y=Q.sub(y,x),k=Q.mul(v,c),k=Q.add(k,k),k=Q.add(k,k),new z(y,_,k)}add(U){D(U);let{px:R,py:B,pz:S}=this,{px:w,py:E,pz:y}=U,_=Q.ZERO,k=Q.ZERO,x=Q.ZERO,c=J.a,v=Q.mul(J.b,DJ),W=Q.mul(R,w),C=Q.mul(B,E),I=Q.mul(S,y),F=Q.add(R,B),T=Q.add(w,E);F=Q.mul(F,T),T=Q.add(W,C),F=Q.sub(F,T),T=Q.add(R,S);let O=Q.add(w,y);return T=Q.mul(T,O),O=Q.add(W,I),T=Q.sub(T,O),O=Q.add(B,S),_=Q.add(E,y),O=Q.mul(O,_),_=Q.add(C,I),O=Q.sub(O,_),x=Q.mul(c,T),_=Q.mul(v,I),x=Q.add(_,x),_=Q.sub(C,x),x=Q.add(C,x),k=Q.mul(_,x),C=Q.add(W,W),C=Q.add(C,W),I=Q.mul(c,I),T=Q.mul(v,T),C=Q.add(C,I),I=Q.sub(W,I),I=Q.mul(c,I),T=Q.add(T,I),W=Q.mul(C,T),k=Q.add(k,W),W=Q.mul(O,T),_=Q.mul(F,_),_=Q.sub(_,W),W=Q.mul(F,C),x=Q.mul(O,x),x=Q.add(x,W),new z(_,k,x)}subtract(U){return this.add(U.negate())}is0(){return this.equals(z.ZERO)}wNAF(U){return h.wNAFCached(this,U,z.normalizeZ)}multiplyUnsafe(U){let{endo:R,n:B}=J;y0("scalar",U,D0,B);let S=z.ZERO;if(U===D0)return S;if(this.is0()||U===p)return this;if(!R||h.hasPrecomputes(this))return h.wNAFCachedUnsafe(this,U,z.normalizeZ);let{k1neg:w,k1:E,k2neg:y,k2:_}=R.splitScalar(U),k=S,x=S,c=this;while(E>D0||_>D0){if(E&p)k=k.add(c);if(_&p)x=x.add(c);c=c.double(),E>>=p,_>>=p}if(w)k=k.negate();if(y)x=x.negate();return x=new z(Q.mul(x.px,R.beta),x.py,x.pz),k.add(x)}multiply(U){let{endo:R,n:B}=J;y0("scalar",U,p,B);let S,w;if(R){let{k1neg:E,k1:y,k2neg:_,k2:k}=R.splitScalar(U),{p:x,f:c}=this.wNAF(y),{p:v,f:W}=this.wNAF(k);x=h.constTimeNegate(E,x),v=h.constTimeNegate(_,v),v=new z(Q.mul(v.px,R.beta),v.py,v.pz),S=x.add(v),w=c.add(W)}else{let{p:E,f:y}=this.wNAF(U);S=E,w=y}return z.normalizeZ([S,w])[0]}multiplyAndAddUnsafe(U,R,B){let S=z.BASE,w=(y,_)=>_===D0||_===p||!y.equals(S)?y.multiplyUnsafe(_):y.multiply(_),E=w(this,R).add(w(U,B));return E.is0()?void 0:E}toAffine(U){return V(this,U)}isTorsionFree(){let{h:U,isTorsionFree:R}=J;if(U===p)return!0;if(R)return R(z,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:U,clearCofactor:R}=J;if(U===p)return this;if(R)return R(z,this);return this.multiplyUnsafe(J.h)}toRawBytes(U=!0){return i0("isCompressed",U),this.assertValidity(),Y(z,this,U)}toHex(U=!0){return i0("isCompressed",U),n0(this.toRawBytes(U))}}z.BASE=new z(J.Gx,J.Gy,Q.ONE),z.ZERO=new z(Q.ZERO,Q.ONE,Q.ZERO);let{endo:A,nBitLength:H}=J,h=D8(z,A?Math.ceil(H/2):H);return{CURVE:J,ProjectivePoint:z,normPrivateKeyToScalar:N,weierstrassEquation:K,isWithinCurveOrder:j}}function RQ($){let J=NJ($);return b0(J,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...J})}function C8($){let J=RQ($),{Fp:Q,n:G,nByteLength:Y,nBitLength:Z}=J,K=Q.BYTES+1,q=2*Q.BYTES+1;function X(W){return i(W,G)}function M(W){return w$(W,G)}let{ProjectivePoint:j,normPrivateKeyToScalar:N,weierstrassEquation:D,isWithinCurveOrder:V}=OQ({...J,toBytes(W,C,I){let F=C.toAffine(),T=Q.toBytes(F.x),O=M$;if(i0("isCompressed",I),I)return O(Uint8Array.from([C.hasEvenY()?2:3]),T);else return O(Uint8Array.from([4]),T,Q.toBytes(F.y))},fromBytes(W){let C=W.length,I=W[0],F=W.subarray(1);if(C===K&&(I===2||I===3)){let T=N0(F);if(!k$(T,p,Q.ORDER))throw Error("Point is not on curve");let O=D(T),b;try{b=Q.sqrt(O)}catch(s){let r=s instanceof Error?": "+s.message:"";throw Error("Point is not on curve"+r)}let m=(b&p)===p;if((I&1)===1!==m)b=Q.neg(b);return{x:T,y:b}}else if(C===q&&I===4){let T=Q.fromBytes(F.subarray(0,Q.BYTES)),O=Q.fromBytes(F.subarray(Q.BYTES,2*Q.BYTES));return{x:T,y:O}}else{let T=K,O=q;throw Error("invalid Point, expected length of "+T+", or uncompressed "+O+", got "+C)}}});function L(W){let C=G>>p;return W>C}function z(W){return L(W)?X(-W):W}let A=(W,C,I)=>N0(W.slice(C,I));class H{constructor(W,C,I){if(y0("r",W,p,G),y0("s",C,p,G),this.r=W,this.s=C,I!=null)this.recovery=I;Object.freeze(this)}static fromCompact(W){let C=Y;return W=e("compactSignature",W,C*2),new H(A(W,0,C),A(W,C,2*C))}static fromDER(W){let{r:C,s:I}=z0.toSig(e("DER",W));return new H(C,I)}assertValidity(){}addRecoveryBit(W){return new H(this.r,this.s,W)}recoverPublicKey(W){let{r:C,s:I,recovery:F}=this,T=w(e("msgHash",W));if(F==null||![0,1,2,3].includes(F))throw Error("recovery id invalid");let O=F===2||F===3?C+J.n:C;if(O>=Q.ORDER)throw Error("recovery id 2 or 3 invalid");let b=(F&1)===0?"02":"03",m=j.fromHex(b+zJ(O,Q.BYTES)),l=M(O),s=X(-T*l),r=X(I*l),V0=j.BASE.multiplyAndAddUnsafe(m,s,r);if(!V0)throw Error("point at infinify");return V0.assertValidity(),V0}hasHighS(){return L(this.s)}normalizeS(){return this.hasHighS()?new H(this.r,X(-this.s),this.recovery):this}toDERRawBytes(){return q$(this.toDERHex())}toDERHex(){return z0.hexFromSig(this)}toCompactRawBytes(){return q$(this.toCompactHex())}toCompactHex(){let W=Y;return zJ(this.r,W)+zJ(this.s,W)}}let h={isValidPrivateKey(W){try{return N(W),!0}catch(C){return!1}},normPrivateKeyToScalar:N,randomPrivateKey:()=>{let W=XJ(J.n);return j8(J.randomBytes(W),J.n)},precompute(W=8,C=j.BASE){return C._setWindowSize(W),C.multiply(BigInt(3)),C}};function U(W,C=!0){return j.fromPrivateKey(W).toRawBytes(C)}function R(W){if(typeof W==="bigint")return!1;if(W instanceof j)return!0;let I=e("key",W).length,F=Q.BYTES,T=F+1,O=2*F+1;if(J.allowedPrivateKeyLengths||Y===T)return;else return I===T||I===O}function B(W,C,I=!0){if(R(W)===!0)throw Error("first arg must be private key");if(R(C)===!1)throw Error("second arg must be public key");return j.fromHex(C).multiply(N(W)).toRawBytes(I)}let S=J.bits2int||function(W){if(W.length>8192)throw Error("input is too large");let C=N0(W),I=W.length*8-Z;return I>0?C>>BigInt(I):C},w=J.bits2int_modN||function(W){return X(S(W))},E=F0(Z);function y(W){return y0("num < 2^"+Z,W,D0,E),w0(W,Y)}function _(W,C,I=k){if(["recovered","canonical"].some((H0)=>(H0 in I)))throw Error("sign() legacy options not supported");let{hash:F,randomBytes:T}=J,{lowS:O,prehash:b,extraEntropy:m}=I;if(O==null)O=!0;if(W=e("msgHash",W),O8(I),b)W=e("prehashed msgHash",F(W));let l=w(W),s=N(C),r=[y(s),y(l)];if(m!=null&&m!==!1){let H0=m===!0?T(Q.BYTES):m;r.push(e("extraEntropy",H0))}let V0=M$(...r),D$=l;function F$(H0){let f0=S(H0);if(!V(f0))return;let b$=M(f0),o0=j.BASE.multiply(f0).toAffine(),S0=X(o0.x);if(S0===D0)return;let t0=X(b$*X(D$+S0*s));if(t0===D0)return;let v0=(o0.x===S0?0:2)|Number(o0.y&p),IJ=t0;if(O&&L(t0))IJ=z(t0),v0^=1;return new H(S0,IJ,v0)}return{seed:V0,k2sig:F$}}let k={lowS:J.lowS,prehash:!1},x={lowS:J.lowS,prehash:!1};function c(W,C,I=k){let{seed:F,k2sig:T}=_(W,C,I),O=J;return G8(O.hash.outputLen,O.nByteLength,O.hmac)(F,T)}j.BASE._setWindowSize(8);function v(W,C,I,F=x){let T=W;C=e("msgHash",C),I=e("publicKey",I);let{lowS:O,prehash:b,format:m}=F;if(O8(F),"strict"in F)throw Error("options.strict was renamed to lowS");if(m!==void 0&&m!=="compact"&&m!=="der")throw Error("format must be compact or der");let l=typeof T==="string"||d0(T),s=!l&&!m&&typeof T==="object"&&T!==null&&typeof T.r==="bigint"&&typeof T.s==="bigint";if(!l&&!s)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");let r=void 0,V0;try{if(s)r=new H(T.r,T.s);if(l){try{if(m!=="compact")r=H.fromDER(T)}catch(v0){if(!(v0 instanceof z0.Err))throw v0}if(!r&&m!=="der")r=H.fromCompact(T)}V0=j.fromHex(I)}catch(v0){return!1}if(!r)return!1;if(O&&r.hasHighS())return!1;if(b)C=J.hash(C);let{r:D$,s:F$}=r,H0=w(C),f0=M(F$),b$=X(H0*f0),o0=X(D$*f0),S0=j.BASE.multiplyAndAddUnsafe(V0,b$,o0)?.toAffine();if(!S0)return!1;return X(S0.x)===D$}return{CURVE:J,getPublicKey:U,getSharedSecret:B,sign:c,verify:v,ProjectivePoint:j,Signature:H,utils:h}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function CQ($){return{hash:$,hmac:(J,...Q)=>t$($,J,bJ(...Q)),randomBytes:gJ}}function L8($,J){let Q=(G)=>C8({...$,...CQ(G)});return{...Q(J),create:Q}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var H8=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),P8=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),LQ=BigInt(0),PQ=BigInt(1),VJ=BigInt(2),B8=($,J)=>($+J/VJ)/J;function BQ($){let J=H8,Q=BigInt(3),G=BigInt(6),Y=BigInt(11),Z=BigInt(22),K=BigInt(23),q=BigInt(44),X=BigInt(88),M=$*$*$%J,j=M*M*$%J,N=J0(j,Q,J)*j%J,D=J0(N,Q,J)*j%J,V=J0(D,VJ,J)*M%J,L=J0(V,Y,J)*V%J,z=J0(L,Z,J)*L%J,A=J0(z,q,J)*z%J,H=J0(A,X,J)*A%J,h=J0(H,q,J)*z%J,U=J0(h,Q,J)*j%J,R=J0(U,K,J)*L%J,B=J0(R,G,J)*M%J,S=J0(B,VJ,J);if(!OJ.eql(OJ.sqr(S),$))throw Error("Cannot find square root");return S}var OJ=j$(H8,void 0,void 0,{sqrt:BQ}),RJ=L8({a:LQ,b:BigInt(7),Fp:OJ,n:P8,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:($)=>{let J=P8,Q=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),G=-PQ*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),Y=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),Z=Q,K=BigInt("0x100000000000000000000000000000000"),q=B8(Z*$,J),X=B8(-G*$,J),M=i($-q*Q-X*Y,J),j=i(-q*G-X*Z,J),N=M>K,D=j>K;if(N)M=J-M;if(D)j=J-j;if(M>K||j>K)throw Error("splitScalar: Endomorphism failed, k="+$);return{k1neg:N,k1:M,k2neg:D,k2:j}}}},sJ);function U$(){let $=RJ.utils.randomPrivateKey();return"0x"+Buffer.from($).toString("hex")}function W$($){let J=$.startsWith("0x")?$.slice(2):$,Q=Buffer.from(J,"hex"),G=RJ.getPublicKey(Q,!1),Z=m0(G.slice(1)).slice(-20),K="0x"+Buffer.from(Z).toString("hex");return C0(K)}function y$($){let J;if(typeof $==="string"){let G=$.startsWith("0x")?$.slice(2):$;J=Buffer.from(G,"hex")}else J=$;let Q=m0(J);return"0x"+Buffer.from(Q).toString("hex")}class f extends A${constructor($,J){super("InvitationError",$,{...J,source:J?.source||"INVITATIONS"})}static noPathFound($,J,Q){return new f(`No valid invitation path found from ${$} to ${J}. ${Q||"The inviter may not have enough balance of the proxy inviter's token or there's no trust connection."}`,{code:"INVITATION_NO_PATH",source:"PATHFINDING",context:{from:$,to:J,reason:Q}})}static noProxyInviters($){return new f(`No proxy inviters found for ${$}. The inviter must have mutual trust connections with users who are also trusted by the invitation module, and these users must have sufficient balance.`,{code:"INVITATION_NO_PROXY_INVITERS",source:"VALIDATION",context:{inviter:$}})}static insufficientBalance($,J,Q,G,Y,Z){let K=Number(Q)/1000000000000000000,q=Number(G)/1000000000000000000;return new f(`Insufficient balance for ${$} invitation(s). Can only afford ${J} invitation(s). Requested: ${K.toFixed(6)} CRC, Available: ${q.toFixed(6)} CRC.`,{code:"INVITATION_INSUFFICIENT_BALANCE",source:"VALIDATION",context:{from:Y,to:Z,requestedInvites:$,availableInvites:J,requested:Q.toString(),available:G.toString(),requestedCrc:K,availableCrc:q}})}static inviteeAlreadyRegistered($,J){return new f(`Invitee ${J} is already registered as a human in Circles Hub. Cannot invite an already registered user.`,{code:"INVITATION_INVITEE_ALREADY_REGISTERED",source:"VALIDATION",context:{inviter:$,invitee:J}})}static noAddressesProvided(){return new f("At least one address must be provided for invitation.",{code:"INVITATION_NO_ADDRESSES_PROVIDED",source:"VALIDATION"})}}var S8=[];for(let $=0;$<256;$++)S8[$]=$.toString(16).padStart(2,"0");function N$($){let J="0x";for(let Q=0;Q<$.length;Q++)J+=S8[$[Q]];return J}function I8($){let J=new Uint8Array($.length*2);return $.forEach((Q,G)=>{let Y=Q>>8,Z=Q&255,K=2*G;J[K]=Y,J[K+1]=Z}),N$(J)}function T8($,J,Q){let G=new Set([J.toLowerCase(),Q.toLowerCase()]);$.forEach((K)=>{G.add(K.from.toLowerCase()),G.add(K.to.toLowerCase()),G.add(K.tokenOwner.toLowerCase())});let Y=[...G].sort((K,q)=>{let X=BigInt(K),M=BigInt(q),j=X<M,N=X>M;return j?-1:N?1:0}),Z={};return Y.forEach((K,q)=>{Z[K]=q}),{sorted:Y,idx:Z}}function HQ($,J){let Q=new Set,G=[],Y=null;if($.forEach((Z,K)=>{let q=Z.from.toLowerCase(),X=Z.to.toLowerCase();if(q===J&&X===J)Y=K;else if(X===J)G.push(K)}),Y!==null)Q.add(Y);else G.forEach((Z)=>Q.add(Z));return Q}function CJ($,J,Q,G){let Y=$.toLowerCase(),Z=J.toLowerCase(),{sorted:K,idx:q}=T8(G,Y,Z),X=HQ(G,Z),M=G.map((H,h)=>{return{streamSinkId:X.has(h)?1:0,amount:H.value}});if(X.size===0)throw Error(`No terminal edges detected. Flow must have at least one edge delivering to receiver ${Z}`);let j=Array.from(X),N=[{sourceCoordinate:q[Y],flowEdgeIds:j,data:new Uint8Array(0)}],D=[];G.forEach((H)=>{D.push(q[H.tokenOwner.toLowerCase()]),D.push(q[H.from.toLowerCase()]),D.push(q[H.to.toLowerCase()])});let V=I8(D),L=BigInt(Q),z=M.filter((H)=>H.streamSinkId===1).reduce((H,h)=>H+BigInt(h.amount.toString()),BigInt(0));if(z!==L)throw Error(`Terminal sum ${z} does not equal expected ${L}`);return{flowVertices:K,flowEdges:M,streams:N,packedCoordinates:V,sourceCoordinate:q[Y]}}function LJ($,J){let Q=$.streams.map((G)=>({sourceCoordinate:G.sourceCoordinate,flowEdgeIds:G.flowEdgeIds,data:G.data instanceof Uint8Array?N$(G.data):G.data}));if(J&&Q.length>0)Q[0].data=J instanceof Uint8Array?N$(J):J;return Q}async function PJ($,J,Q){let G=new Map,Y=new Set;return Q.transfers.forEach((q)=>{if($.toLowerCase()===q.from.toLowerCase())Y.add(q.tokenOwner.toLowerCase())}),(await new _$(J).token.getTokenInfoBatch(Array.from(Y))).forEach((q)=>{if(q.isWrapped&&!q.isInflationary)q.tokenType="CrcV2_ERC20WrapperDeployed_Demurraged";G.set(q.tokenAddress.toLowerCase(),q)}),G}function BJ($,J){let Q={};return $.transfers.forEach((G)=>{let Y=J.get(G.tokenOwner.toLowerCase());if(Y&&Y.tokenType.startsWith("CrcV2_ERC20WrapperDeployed")){if(!Q[G.tokenOwner])Q[G.tokenOwner]=[BigInt(0),Y.tokenType];Q[G.tokenOwner][0]+=BigInt(G.value)}}),Q}function HJ($,J){let Q=$.transfers.map((G)=>{let Y=J.get(G.tokenOwner.toLowerCase());if(Y&&Y.tokenType.startsWith("CrcV2_ERC20WrapperDeployed"))return{...G,tokenOwner:Y.tokenOwner};return G});return{...$,transfers:Q}}class o extends s0{constructor($,J){super("TransferError",$,{...J,source:J?.source||"TRANSFERS"})}static noPathFound($,J,Q){return new o(`No valid transfer path found from ${$} to ${J}. ${Q||"This could mean there's no trust connection, insufficient balance, or the tokens are not transferable."}`,{code:"TRANSFER_NO_PATH",source:"PATHFINDING",context:{from:$,to:J,reason:Q}})}static insufficientBalance($,J,Q,G){let Y=Number($)/1000000000000000000,Z=Number(J)/1000000000000000000;return new o(`Insufficient balance for transfer. Requested: ${Y.toFixed(6)} CRC, Available: ${Z.toFixed(6)} CRC.`,{code:"TRANSFER_INSUFFICIENT_BALANCE",source:"VALIDATION",context:{from:Q,to:G,requested:$.toString(),available:J.toString(),requestedCrc:Y,availableCrc:Z}})}static wrappedTokensRequired(){return new o("Insufficient unwrapped token balance for transfer. Your balance contains wrapped tokens (ERC20 wrappers), but useWrappedBalances option is not enabled. Please enable it by passing { useWrappedBalances: true } in the transfer options.",{code:"TRANSFER_WRAPPED_TOKENS_REQUIRED",source:"VALIDATION"})}static unregisteredAvatars($){return new o(`Flow matrix contains ${$.length} unregistered avatar(s): ${$.join(", ")}. All addresses in the flow must be registered Circles avatars (human or group).`,{code:"TRANSFER_UNREGISTERED_AVATARS",source:"FLOW_MATRIX",context:{unregisteredAddresses:$,count:$.length}})}static flowMatrixMismatch($,J){return new o(`Flow matrix terminal sum (${$}) does not equal expected amount (${J})`,{code:"TRANSFER_FLOW_MATRIX_MISMATCH",source:"FLOW_MATRIX",context:{terminalSum:$.toString(),expected:J.toString()}})}static emptyPath($,J){return new o(`Transfer path is empty for route from ${$} to ${J}`,{code:"TRANSFER_EMPTY_PATH",source:"PATHFINDING",context:{from:$,to:J}})}}class z${config;hubV2;liftERC20;rpcClient;pathfinder;balance;group;constructor($){this.config=$,this.hubV2=new P0({address:$.v2HubAddress,rpcUrl:$.circlesRpcUrl}),this.liftERC20=new E$({address:$.liftERC20Address,rpcUrl:$.circlesRpcUrl}),this.rpcClient=new O0($.circlesRpcUrl),this.pathfinder=new j0(this.rpcClient),this.balance=new A0(this.rpcClient),this.group=new k0(this.rpcClient)}async buildFlowMatrixTx($,J,Q,G,Y=!1){let Z=$.toLowerCase(),K=J.toLowerCase();if(!Q.transfers||Q.transfers.length===0)throw o.noPathFound(Z,K);let q={...Q};if(Y&&G?.toTokens?.length===1){let h=G.toTokens[0].toLowerCase();if(Q.maxFlow>0n)q.transfers.push({from:K,to:K,tokenOwner:h,value:Q.maxFlow})}let X=await PJ(Z,this.config.circlesRpcUrl,q),M=BJ(q,X),j=Object.keys(M).length>0;if(j&&!G?.useWrappedBalances)throw o.wrappedTokensRequired();let N=[],D=[];if(j){let h=await this._getTokenBalanceMap(Z),U=this._createDemurragedUnwrapCalls(M),{unwrapCalls:R,wrapCalls:B}=this._createInflationaryUnwrapAndWrapCalls(M,X,h);N=[...U,...R],D=B,q=HJ(q,X)}let V=CJ(Z,K,q.maxFlow,q.transfers),L=LJ(V,G?.txData),z=this.hubV2.operateFlowMatrix(V.flowVertices,V.flowEdges,L,V.packedCoordinates),A=!1;try{A=await this.hubV2.isApprovedForAll(Z,Z)}catch(h){console.warn("Failed to check approval status, including approval transaction:",h)}return[...A?[]:[this.hubV2.setApprovalForAll(Z,!0)],...N,z,...D]}async constructAdvancedTransfer($,J,Q,G,Y=!1){let Z=$.toLowerCase(),K=J.toLowerCase(),q=BigInt(Q);if(Z===K&&G?.fromTokens?.length===1&&G?.toTokens?.length===1){let V=G.fromTokens[0],L=G.toTokens[0],[z,A]=await Promise.all([this.liftERC20.erc20Circles(0,L),this.liftERC20.erc20Circles(1,L)]);if(V.toLowerCase()===z.toLowerCase()&&z!==T$){let h=new c0({address:V,rpcUrl:this.config.circlesRpcUrl}).unwrap(q);return[{to:h.to,data:h.data,value:h.value??0n}]}if(V.toLowerCase()===A.toLowerCase()&&A!==T$){let H=new l0({address:V,rpcUrl:this.config.circlesRpcUrl}),h=d.attoCirclesToAttoStaticCircles(q),U=H.unwrap(h);return[{to:U.to,data:U.data,value:U.value??0n}]}}let X=this._truncateToSixDecimals(q),M=await this._getDefaultTokenExcludeList(K,G?.excludeFromTokens),{...j}=G||{},N={...j,...M?{excludeFromTokens:M}:{}},D=await this.pathfinder.findPath({from:Z,to:K,targetFlow:X,...N});if(!D.transfers||D.transfers.length===0)throw o.noPathFound(Z,K);if(D.maxFlow<X)throw o.insufficientBalance(X,D.maxFlow,Z,K);return this.buildFlowMatrixTx(Z,K,D,G,Y)}async constructReplenish($,J,Q,G){let Y=$.toLowerCase(),Z=J.toLowerCase(),K=(G||$).toLowerCase(),q=BigInt(Q),M=(await this.balance.getTokenBalances(Y)).filter((O)=>O.tokenOwner.toLowerCase()===Z),j=0n,N=0n,D=0n,V=null,L=null;for(let O of M)if(O.isWrapped)if(O.tokenType.includes("Demurrage"))N=BigInt(O.attoCircles),V=O.tokenAddress;else D=BigInt(O.staticAttoCircles),L=O.tokenAddress;else j=BigInt(O.attoCircles);let z=j+N+d.attoStaticCirclesToAttoCircles(D),A=[];if(j>=q){if(console.log(`✓ Already have ${Number(j)/1000000000000000000} CRC unwrapped (target: ${Number(q)/1000000000000000000} CRC). No replenish needed.`),K!==Y){let O=await this.hubV2.toTokenId(Z),b=this.hubV2.safeTransferFrom(Y,K,O,q);A.push({to:b.to,data:b.data,value:b.value??0n})}return A}let H=q-j;if(console.log(`Current unwrapped: ${Number(j)/1000000000000000000} CRC`),console.log(`Target amount: ${Number(q)/1000000000000000000} CRC`),console.log(`Need to acquire: ${Number(H)/1000000000000000000} CRC`),z>=q){let O=H;if(N>0n&&V&&O>0n){let b=O>N?N:O,l=new c0({address:V,rpcUrl:this.config.circlesRpcUrl}).unwrap(b);A.push({to:l.to,data:l.data,value:l.value??0n}),O-=b}if(D>0n&&L&&O>0n){let b=d.attoCirclesToAttoStaticCircles(O),m=b>D?D:b,s=new l0({address:L,rpcUrl:this.config.circlesRpcUrl}).unwrap(m);A.push({to:s.to,data:s.data,value:s.value??0n})}if(K!==Y){let b=await this.hubV2.toTokenId(Z),m=this.hubV2.safeTransferFrom(Y,K,b,q);A.push({to:m.to,data:m.data,value:m.value??0n})}return A}let U=!await this.hubV2.isTrusted(Y,Z),R=BigInt(Math.floor(Date.now()/1000)+31536000),B=d.truncateToInt64(H),S=H%d.FACTOR_1E12!==0n,w=d.blowUpToBigInt(S?B+1n:B),E;try{E=await this.pathfinder.findPath({from:Y,to:K,targetFlow:w,toTokens:[Z],useWrappedBalances:!0,simulatedTrusts:U?[{truster:Y,trustee:Z}]:void 0})}catch(O){let b=Number(z)/1000000000000000000,m=Number(q)/1000000000000000000,l=Number(H)/1000000000000000000;throw new o(`Insufficient tokens to replenish. Target: ${m.toFixed(6)} CRC, Current unwrapped: ${Number(j)/1000000000000000000} CRC, Need: ${l.toFixed(6)} CRC, Available (including all paths): ${b.toFixed(6)} CRC. Cannot acquire the remaining ${(Number(H-(z-j))/1000000000000000000).toFixed(6)} CRC.`,{code:"REPLENISH_INSUFFICIENT_TOKENS",source:"VALIDATION",context:{from:Y,tokenId:Z,target:q.toString(),unwrapped:j.toString(),deficit:H.toString(),available:z.toString(),targetCrc:m,unwrappedCrc:Number(j)/1000000000000000000,deficitCrc:l,availableCrc:b}})}if(!E.transfers||E.transfers.length===0)throw o.noPathFound(Y,K,`No path to acquire token ${Z}`);if(E.maxFlow<w){let O=Number(E.maxFlow)/1000000000000000000,b=Number(w)/1000000000000000000;throw new o(`Pathfinder can only provide ${O.toFixed(6)} CRC of the ${b.toFixed(6)} CRC deficit needed for token ${Z}.`,{code:"REPLENISH_INSUFFICIENT_PATH_FLOW",source:"PATHFINDING",context:{from:Y,tokenId:Z,deficit:w.toString(),pathFlow:E.maxFlow.toString(),deficitCrc:b,pathFlowCrc:O}})}if(U){let O=this.hubV2.trust(Z,R);A.push({to:O.to,data:O.data,value:O.value??0n})}let y=await PJ(Y,this.config.circlesRpcUrl,E),_=BJ(E,y),k=Object.keys(_).length>0,x=[],c=[];if(k){let O=await this._getTokenBalanceMap(Y),b=this._createDemurragedUnwrapCalls(_),{unwrapCalls:m,wrapCalls:l}=this._createInflationaryUnwrapAndWrapCalls(_,y,O);x=[...b,...m],c=l,E=HJ(E,y)}let v=CJ(Y,K,E.maxFlow,E.transfers),W=LJ(v),C=this.hubV2.operateFlowMatrix(v.flowVertices,v.flowEdges,W,v.packedCoordinates),I={to:C.to,data:C.data,value:C.value??0n},F=!1;try{F=await this.hubV2.isApprovedForAll(Y,Y)}catch(O){console.warn("Failed to check approval status, including approval transaction:",O)}if(U){let O=this.hubV2.trust(Z,0n);c.push({to:O.to,data:O.data,value:O.value??0n})}let T=F?[]:[{to:this.hubV2.setApprovalForAll(Y,!0).to,data:this.hubV2.setApprovalForAll(Y,!0).data,value:0n}];return A.push(...T,...x,I,...c),A}async _getTokenBalanceMap($){let J=await this.balance.getTokenBalances($),Q=new Map;return J.forEach((G)=>{Q.set(G.tokenAddress.toLowerCase(),G.staticAttoCircles)}),Q}_createDemurragedUnwrapCalls($){let J=[];for(let[Q,[G,Y]]of Object.entries($)){if(Y!=="CrcV2_ERC20WrapperDeployed_Demurraged")continue;let K=new c0({address:Q,rpcUrl:this.config.circlesRpcUrl}).unwrap(G);J.push({to:K.to,data:K.data,value:K.value??0n})}return J}_createInflationaryUnwrapAndWrapCalls($,J,Q){let G=[],Y=[];for(let[Z,[K,q]]of Object.entries($)){if(q!=="CrcV2_ERC20WrapperDeployed_Inflationary")continue;let X=J.get(Z.toLowerCase()),M=Q.get(Z.toLowerCase())||0n;if(M===0n)continue;let N=new l0({address:Z,rpcUrl:this.config.circlesRpcUrl}).unwrap(M);G.push({to:N.to,data:N.data,value:N.value??0n});let D=X?.tokenOwner,V=d.attoStaticCirclesToAttoCircles(M)-K;if(V>0n){let L=this.hubV2.wrap(D,V,1);Y.push({to:L.to,data:L.data,value:L.value??0n})}}return{unwrapCalls:G,wrapCalls:Y}}_truncateToSixDecimals($){let J=BigInt(1e6),Q=BigInt(10)**BigInt(18);return $/(Q/J)*(Q/J)}async _getDefaultTokenExcludeList($,J){let Q=await this.group.findGroups(1,{mintHandlerEquals:$}),G=new Set;if(Q.length>0){let Y=Q[0];if(G.add(Y.group.toLowerCase()),Y.erc20WrapperDemurraged)G.add(Y.erc20WrapperDemurraged.toLowerCase());if(Y.erc20WrapperStatic)G.add(Y.erc20WrapperStatic.toLowerCase())}if(J?.forEach((Y)=>G.add(Y.toLowerCase())),G.size===0)return;return Array.from(G)}}class SJ{config;rpcClient;pathfinder;trust;hubV2;referralsModule;constructor($){if(!$.referralsServiceUrl)throw new f("referralsServiceUrl is required in config",{code:"INVITATION_MISSING_CONFIG",source:"INVITATIONS",context:{missingField:"referralsServiceUrl"}});this.config=$,this.rpcClient=new O0($.circlesRpcUrl),this.pathfinder=new j0(this.rpcClient),this.trust=new x0(this.rpcClient),this.hubV2=new P0({address:$.v2HubAddress,rpcUrl:$.circlesRpcUrl}),this.referralsModule=new p0({address:$.referralsModuleAddress,rpcUrl:$.circlesRpcUrl})}async saveReferralData($,J){try{let Q=await fetch(`${this.config.referralsServiceUrl}/store`,{method:"POST",headers:{accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({privateKey:J,inviter:$})});if(!Q.ok)throw new f(`HTTP error! status: ${Q.status}`,{code:"INVITATION_HTTP_ERROR",source:"INVITATIONS",context:{status:Q.status,url:`${this.config.referralsServiceUrl}/store`}})}catch(Q){throw console.error("Failed to save referral data:",Q),new f(`Failed to save referral data: ${Q instanceof Error?Q.message:"Unknown error"}`,{code:"INVITATION_SAVE_REFERRAL_FAILED",source:"INVITATIONS",cause:Q})}}async listReferrals($,J=10,Q=0){try{let G=new URL(`${this.config.referralsServiceUrl}/referrals/list/${$}`);G.searchParams.set("limit",String(J)),G.searchParams.set("offset",String(Q));let Y=await fetch(G.toString(),{method:"GET",headers:{accept:"application/json"}});if(!Y.ok)throw new f(`HTTP error! status: ${Y.status}`,{code:"INVITATION_HTTP_ERROR",source:"INVITATIONS",context:{status:Y.status,url:G.toString()}});return await Y.json()}catch(G){if(G instanceof f)throw G;throw new f(`Failed to list referrals: ${G instanceof Error?G.message:"Unknown error"}`,{code:"INVITATION_LIST_REFERRALS_FAILED",source:"INVITATIONS",cause:G})}}orderRealInviters($,J){let Q=J.toLowerCase();return $.sort((G,Y)=>{let Z=G.address.toLowerCase()===Q,K=Y.address.toLowerCase()===Q;if(Z&&!K)return-1;if(!Z&&K)return 1;return 0})}async generateInvite($,J){let Q=$.toLowerCase(),G=J.toLowerCase();if(await this.hubV2.isHuman(G))throw f.inviteeAlreadyRegistered(Q,G);let Z=await this.findInvitePath(Q),K=await this.generateInviteData([G],!1),q=new z$(this.config),X=await this.getRealInviters(Q);if(X.length===0)throw f.noPathFound(Q,this.config.invitationModuleAddress);let M=X[0].address;return await q.buildFlowMatrixTx(Q,this.config.invitationModuleAddress,Z,{toTokens:[M],useWrappedBalances:!0,txData:B$(K)},!0)}async findInvitePath($,J){let Q=$.toLowerCase(),G;if(J)G=J.toLowerCase();else{let Z=await this.getRealInviters(Q);if(Z.length===0)throw f.noPathFound(Q,this.config.invitationModuleAddress);G=Z[0].address}let Y=await this.pathfinder.findPath({from:Q,to:this.config.invitationModuleAddress,targetFlow:M0,toTokens:[G],useWrappedBalances:!0});if(!Y.transfers||Y.transfers.length===0)throw f.noPathFound(Q,this.config.invitationModuleAddress);if(Y.maxFlow<M0){let K=Number(Y.maxFlow/M0);throw f.insufficientBalance(1,K,M0,Y.maxFlow,Q,this.config.invitationModuleAddress)}return Y}async getRealInviters($){let J=$.toLowerCase(),Q=await this.trust.getTrustedBy(J),G=await this.trust.getMutualTrusts(J),Y=new Set([...Q.map((z)=>z.objectAvatar.toLowerCase()),...G.map((z)=>z.objectAvatar.toLowerCase())]),Z=await this.trust.getTrusts(this.config.invitationModuleAddress),K=await this.trust.getMutualTrusts(this.config.invitationModuleAddress),q=new Set([...Z.map((z)=>z.objectAvatar.toLowerCase()),...K.map((z)=>z.objectAvatar.toLowerCase())]),X=[];for(let z of Y)if(q.has(z))X.push(z);let M=[...X,J];if(M.length===0)return[];let j=await this.pathfinder.findPath({from:J,to:this.config.invitationModuleAddress,useWrappedBalances:!0,targetFlow:$$,toTokens:M});if(!j.transfers||j.transfers.length===0)return[];let N=new Map,D=this.config.invitationModuleAddress.toLowerCase();for(let z of j.transfers)if(z.to.toLowerCase()===D){let A=z.tokenOwner.toLowerCase(),H=N.get(A)||BigInt(0);N.set(A,H+z.value)}let V=[];for(let[z,A]of N.entries()){let H=Number(A/M0);if(H>=1)V.push({address:z,possibleInvites:H})}return this.orderRealInviters(V,J)}async generateReferral($){let J=$.toLowerCase(),Q=U$(),G=W$(Q),Y=await this.getRealInviters(J);if(Y.length===0)throw f.noProxyInviters(J);let K=Y[0].address,q=await this.findInvitePath(J,K),X=new z$(this.config),M=await this.generateInviteData([G],!0),j=await X.buildFlowMatrixTx(J,this.config.invitationModuleAddress,q,{toTokens:[K],useWrappedBalances:!0,txData:B$(M)},!0);await this.saveReferralData(J,Q);let N=[];return N.push(...j),{transactions:N,privateKey:Q}}async generateInviteData($,J=!0){if($.length===0)throw f.noAddressesProvided();if(!J)if($.length===1)return L0(["address"],[$[0]]);else return L0(["address[]"],[$]);if($.length===1){let G=this.referralsModule.createAccount($[0]).data;return L0(["address","bytes"],[this.config.referralsModuleAddress,G])}else{let G=this.referralsModule.createAccounts($).data;return L0(["address","bytes"],[this.config.referralsModuleAddress,G])}}computeAddress($){let Q=$.toLowerCase().replace("0x","").padStart(64,"0"),G=c$.replace("0x","")+Q,Y=y$("0x"+G),Z="ff",K=u$.toLowerCase().replace("0x",""),q=Y.replace("0x",""),X=l$.replace("0x",""),M="ff"+K+q+X,N="0x"+y$("0x"+M).slice(-40);return C0(N)}}class IQ{config;invitations;invitationFarm;referralsModule;hubV2;constructor($){this.config=$,this.invitations=new SJ($),this.invitationFarm=new x$({address:$.invitationFarmAddress,rpcUrl:$.circlesRpcUrl}),this.referralsModule=new p0({address:$.referralsModuleAddress,rpcUrl:$.circlesRpcUrl}),this.hubV2=new P0({address:$.v2HubAddress,rpcUrl:$.circlesRpcUrl})}async getQuota($){return this.invitationFarm.inviterQuota($)}async getInvitationFee(){return this.invitationFarm.invitationFee()}async getInvitationModule(){return this.invitationFarm.invitationModule()}async generateInvites($,J){if(J<=0)throw new f("Count must be greater than 0",{code:"INVITATION_INVALID_COUNT",source:"VALIDATION",context:{count:J}});let Q=$.toLowerCase(),G=BigInt(J),Y=await this.invitationFarm.read("claimInvites",[G],{from:Q});if(!Y||Y.length===0)throw new f("No invitation IDs returned from claimInvites",{code:"INVITATION_NO_IDS",source:"INVITATIONS",context:{inviter:Q,count:J}});let Z=[],K=[];for(let L=0;L<J;L++){let z=U$(),A=W$(z).toLowerCase();Z.push({secret:z,signer:A}),K.push(A)}let q=await this.invitationFarm.invitationModule(),X=this.invitationFarm.claimInvites(G),j=this.referralsModule.createAccounts(K).data,N=L0(["address","bytes"],[this.config.referralsModuleAddress,j]),D=Y.map(()=>M0),V=this.hubV2.safeBatchTransferFrom(Q,q,Y,D,N);return await Promise.all(Z.map((L)=>this.invitations.saveReferralData(Q,L.secret))),{invites:Z,transactions:[X,V]}}async listReferrals($,J=10,Q=0){return this.invitations.listReferrals($,J,Q)}}class TQ{baseUrl;getToken;constructor($,J){this.baseUrl=$;this.getToken=J}getBaseUrl(){return this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}async getAuthHeaders(){if(!this.getToken)return{"Content-Type":"application/json"};return{"Content-Type":"application/json",Authorization:`Bearer ${await this.getToken()}`}}async retrieve($){try{let J=`${this.getBaseUrl()}/referral/retrieve?key=${encodeURIComponent($)}`,Q=await fetch(J);if(!Q.ok){let G=`HTTP error! status: ${Q.status}`;try{G=(await Q.json()).error||G}catch{G=Q.statusText||G}throw new f(G,{code:"INVITATION_RETRIEVE_FAILED",source:"INVITATIONS",context:{status:Q.status,url:J,privateKey:$}})}return Q.json()}catch(J){if(J instanceof f)throw J;throw new f(`Failed to retrieve referral: ${J instanceof Error?J.message:"Unknown error"}`,{code:"INVITATION_RETRIEVE_ERROR",source:"INVITATIONS",cause:J,context:{privateKey:$}})}}async listMine(){if(!this.getToken)throw new f("Authentication required to list referrals",{code:"INVITATION_AUTH_REQUIRED",source:"INVITATIONS"});try{let $=`${this.getBaseUrl()}/referral/my-referrals`,J=await this.getAuthHeaders(),Q=await fetch($,{headers:J});if(!Q.ok){let G=`HTTP error! status: ${Q.status}`;try{G=(await Q.json()).error||G}catch{G=Q.statusText||G}throw new f(G,{code:"INVITATION_LIST_FAILED",source:"INVITATIONS",context:{status:Q.status,url:$}})}return Q.json()}catch($){if($ instanceof f)throw $;throw new f(`Failed to list referrals: ${$ instanceof Error?$.message:"Unknown error"}`,{code:"INVITATION_LIST_ERROR",source:"INVITATIONS",cause:$})}}}export{TQ as Referrals,IQ as InviteFarm,SJ as Invitations,f as InvitationError};
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Referral status lifecycle
|
|
3
|
+
*/
|
|
4
|
+
export type ReferralStatus = "pending" | "confirmed" | "claimed" | "expired";
|
|
5
|
+
/**
|
|
6
|
+
* Referral info returned from retrieve endpoint
|
|
7
|
+
*/
|
|
8
|
+
export interface ReferralInfo {
|
|
9
|
+
/** The inviter's Ethereum address */
|
|
10
|
+
inviter: string;
|
|
11
|
+
/** Current status of the referral */
|
|
12
|
+
status: ReferralStatus;
|
|
13
|
+
/** The Safe account address (if available) */
|
|
14
|
+
accountAddress?: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Full referral record returned from my-referrals endpoint
|
|
18
|
+
*/
|
|
19
|
+
export interface Referral {
|
|
20
|
+
/** Unique identifier */
|
|
21
|
+
id: string;
|
|
22
|
+
/** The referral private key */
|
|
23
|
+
privateKey: string;
|
|
24
|
+
/** Current status */
|
|
25
|
+
status: ReferralStatus;
|
|
26
|
+
/** The Safe account address */
|
|
27
|
+
accountAddress?: string;
|
|
28
|
+
/** When the referral was created */
|
|
29
|
+
createdAt: string;
|
|
30
|
+
/** When the account was confirmed on-chain */
|
|
31
|
+
confirmedAt: string | null;
|
|
32
|
+
/** When the account was claimed */
|
|
33
|
+
claimedAt: string | null;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Response from my-referrals endpoint
|
|
37
|
+
*/
|
|
38
|
+
export interface ReferralList {
|
|
39
|
+
/** List of referrals */
|
|
40
|
+
referrals: Referral[];
|
|
41
|
+
/** Total count */
|
|
42
|
+
count: number;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Referral preview returned from the list endpoint (key is masked)
|
|
46
|
+
*/
|
|
47
|
+
export interface ReferralPreview {
|
|
48
|
+
/** Unique identifier */
|
|
49
|
+
id: string;
|
|
50
|
+
/** Masked private key preview (e.g. "0x123456...cdef") */
|
|
51
|
+
keyPreview: string;
|
|
52
|
+
/** Current status */
|
|
53
|
+
status: ReferralStatus;
|
|
54
|
+
/** The Safe account address */
|
|
55
|
+
accountAddress: string | null;
|
|
56
|
+
/** When the referral was created */
|
|
57
|
+
createdAt: string;
|
|
58
|
+
/** When the referral entered pending state */
|
|
59
|
+
pendingAt: string | null;
|
|
60
|
+
/** When the referral became stale */
|
|
61
|
+
staleAt: string | null;
|
|
62
|
+
/** When the account was confirmed on-chain */
|
|
63
|
+
confirmedAt: string | null;
|
|
64
|
+
/** When the account was claimed */
|
|
65
|
+
claimedAt: string | null;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Paginated response from referrals/list endpoint
|
|
69
|
+
*/
|
|
70
|
+
export interface ReferralPreviewList {
|
|
71
|
+
referrals: ReferralPreview[];
|
|
72
|
+
count: number;
|
|
73
|
+
total: number;
|
|
74
|
+
limit: number;
|
|
75
|
+
offset: number;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Error response from API
|
|
79
|
+
*/
|
|
80
|
+
export interface ApiError {
|
|
81
|
+
error: string;
|
|
82
|
+
}
|
|
83
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG,SAAS,GAAG,WAAW,GAAG,SAAS,GAAG,SAAS,CAAC;AAE7E;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,qCAAqC;IACrC,OAAO,EAAE,MAAM,CAAC;IAChB,qCAAqC;IACrC,MAAM,EAAE,cAAc,CAAC;IACvB,8CAA8C;IAC9C,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,wBAAwB;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,+BAA+B;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,qBAAqB;IACrB,MAAM,EAAE,cAAc,CAAC;IACvB,+BAA+B;IAC/B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,oCAAoC;IACpC,SAAS,EAAE,MAAM,CAAC;IAClB,8CAA8C;IAC9C,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,mCAAmC;IACnC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AAED;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,wBAAwB;IACxB,SAAS,EAAE,QAAQ,EAAE,CAAC;IACtB,kBAAkB;IAClB,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,wBAAwB;IACxB,EAAE,EAAE,MAAM,CAAC;IACX,0DAA0D;IAC1D,UAAU,EAAE,MAAM,CAAC;IACnB,qBAAqB;IACrB,MAAM,EAAE,cAAc,CAAC;IACvB,+BAA+B;IAC/B,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,oCAAoC;IACpC,SAAS,EAAE,MAAM,CAAC;IAClB,8CAA8C;IAC9C,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,qCAAqC;IACrC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,8CAA8C;IAC9C,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,mCAAmC;IACnC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,SAAS,EAAE,eAAe,EAAE,CAAC;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,KAAK,EAAE,MAAM,CAAC;CACf"}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"InvitationBuilder.d.ts","sourceRoot":"","sources":["../src/InvitationBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAmB1F,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,OAAO,CAAC;IACjB,eAAe,EAAE,MAAM,CAAC;CACzB;AAED;;;GAGG;AACH,qBAAa,iBAAiB;IAC5B,OAAO,CAAC,MAAM,CAAgB;IAC9B,OAAO,CAAC,SAAS,CAAY;IAC7B,OAAO,CAAC,UAAU,CAAoB;IACtC,OAAO,CAAC,KAAK,CAAe;IAC5B,OAAO,CAAC,KAAK,CAAuB;IACpC,OAAO,CAAC,eAAe,CAAiC;gBAE5C,MAAM,EAAE,aAAa;IAsBjC;;;;;;;;OAQG;YACW,gBAAgB;IAmC9B;;;;;;;;;;OAUG;IACH,OAAO,CAAC,iBAAiB;IAezB;;;;;;;;;;;;;;;;;OAiBG;IACG,cAAc,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,kBAAkB,EAAE,CAAC;IA+CvF;;;;;;;;;;;OAWG;IACG,cAAc,CAAC,OAAO,EAAE,OAAO,EAAE,mBAAmB,CAAC,EAAE,OAAO;IA+CpE;;;;;;;;;;;;;;;;;OAiBG;IACG,eAAe,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;IAwFhE;;;;;;;;;;;;;;;;;OAiBG;IACG,gBAAgB,CACpB,OAAO,EAAE,OAAO,GACf,OAAO,CAAC,kBAAkB,EAAE,CAAC;IAiDhC;;;;;;;;;;;;;OAaG;IACG,kBAAkB,CAAC,SAAS,EAAE,OAAO,EAAE,EAAE,eAAe,GAAE,OAAc,GAAG,OAAO,CAAC,KAAK,MAAM,EAAE,CAAC;IA8CvG;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,cAAc,CAAC,MAAM,EAAE,OAAO,GAAG,OAAO;CA8BzC"}
|