@aboutcircles/sdk-invitations 0.1.32 → 0.1.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +3 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var f8=(J)=>BigInt(J),Q$=(J)=>parseInt(J,16),t0=(J)=>{if(J.startsWith("0x"))J=J.slice(2);if(J.length%2!==0)throw Error("Invalid hex string");let $=new Uint8Array(J.length/2);for(let Q=0;Q<J.length;Q+=2)$[Q/2]=parseInt(J.substr(Q,2),16);return $};function o0(J,$){if(typeof $==="string"&&$.startsWith("0x")){let Q=$.slice(2);if(Q.length===40)return $;if(Q.length===64){if(J.toLowerCase().includes("digest")||J.toLowerCase().includes("data")||J.toLowerCase().includes("bytes"))return t0($);try{return f8($)}catch{return $}}try{let Y=Q$($);if(Y<Number.MAX_SAFE_INTEGER)return Y;return f8($)}catch{return $}}if($==="true")return!0;if($==="false")return!1;return $}function p$(J){let{event:$,values:Q}=J,Y={$event:$,blockNumber:Q.blockNumber?Q$(Q.blockNumber):0,timestamp:Q.timestamp?Q$(Q.timestamp):void 0,transactionIndex:Q.transactionIndex?Q$(Q.transactionIndex):0,logIndex:Q.logIndex?Q$(Q.logIndex):0,transactionHash:Q.transactionHash};for(let[M
|
|
2
|
-
Context: ${JSON.stringify(this.context,null,2)}`;return J}}class c extends Y${constructor(J,$){super("RpcError",J,{...$,source:$?.source??"RPC_REQUEST"})}static connectionFailed(J,$){return new c("Failed to connect to RPC endpoint",{code:"RPC_CONNECTION_FAILED",source:"RPC_CONNECTION",cause:$,context:{url:J}})}static timeout(J,$){return new c("RPC request timed out",{code:"RPC_TIMEOUT",source:"RPC_TIMEOUT",context:{method:J,timeout:$}})}static invalidResponse(J,$){return new c("Invalid RPC response",{code:"RPC_INVALID_RESPONSE",source:"RPC_RESPONSE",context:{method:J,response:$}})}static fromJsonRpcError(J){return new c(J.message,{code:J.code,source:"RPC_RESPONSE",context:{data:J.data}})}static websocketError(J,$){return new c(J,{code:"RPC_WEBSOCKET_ERROR",source:"RPC_WEBSOCKET",cause:$})}}class VJ{rpcUrl;requestId=0;websocket=null;websocketConnected=!1;pendingResponses={};subscriptionListeners={};activeSubscriptions=[];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 Y=await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)});if(!Y.ok)throw c.connectionFailed(this.rpcUrl,Error(`HTTP ${Y.status}: ${Y.statusText}`));let M=await Y.json();if(M.error)throw c.fromJsonRpcError(M.error);if(M.result===void 0)throw c.invalidResponse(J,M);return M.result}catch(Y){if(Y instanceof c)throw Y;throw c.connectionFailed(this.rpcUrl,Y)}}setRpcUrl(J){this.rpcUrl=J}getRpcUrl(){return this.rpcUrl}connect(){return new Promise((J,$)=>{let Q=this.rpcUrl.replace("http","ws");if(Q.endsWith("/"))Q+="ws/subscribe";else Q+="/ws/subscribe";this.websocket=new WebSocket(Q),this.websocket.onopen=()=>{console.log("WebSocket connected"),this.websocketConnected=!0,this.reconnectAttempt=0,J()},this.websocket.onmessage=(Y)=>{let M=JSON.parse(Y.data),{id:G,method:Z,params:K}=M;if(G!==void 0&&this.pendingResponses[G])this.pendingResponses[G].resolve(M),delete this.pendingResponses[G];if(Z==="circles_subscription"&&K?.result)Object.values(this.subscriptionListeners).forEach((X)=>{X.forEach((q)=>q(K.result))})},this.websocket.onclose=()=>{console.warn("WebSocket closed");let Y=this.websocketConnected;if(this.websocketConnected=!1,Y)this.scheduleReconnect()},this.websocket.onerror=(Y)=>{console.error("WebSocket error:",Y),this.websocketConnected=!1,$(c.connectionFailed(this.rpcUrl,Y instanceof Error?Y:Error("WebSocket connection failed"))),this.scheduleReconnect()}})}scheduleReconnect(){let J=Math.min(this.initialBackoff*Math.pow(2,this.reconnectAttempt),this.maxBackoff),$=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"),await this.resubscribeActive()}catch(J){console.error("Reconnection attempt failed:",J),this.scheduleReconnect()}}async resubscribeActive(){if(this.activeSubscriptions.length===0)return;let J=[...this.activeSubscriptions];this.activeSubscriptions=[];for(let $ of J)try{let Q=$.address?{address:$.address}:{},M=(await this.sendMessage("circles_subscribe",Q)).result,G=this.subscriptionListeners[$.id];if(G)this.subscriptionListeners[M]=G,delete this.subscriptionListeners[$.id];this.activeSubscriptions.push({id:M,address:$.address})}catch(Q){console.error("Failed to re-issue circles_subscribe after reconnect:",Q),this.activeSubscriptions.push($)}}sendMessage(J,$,Q=5000){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return Promise.reject(c.connectionFailed(this.rpcUrl));let Y=this.requestId++,M={jsonrpc:"2.0",method:J,params:$,id:Y};return new Promise((G,Z)=>{this.pendingResponses[Y]={resolve:G,reject:Z},this.websocket.send(JSON.stringify(M)),setTimeout(()=>{if(this.pendingResponses[Y])this.pendingResponses[Y].reject(c.timeout(J,Q)),delete this.pendingResponses[Y]},Q)})}async subscribe(J){let $=J?.toLowerCase();if(!this.websocketConnected)await this.connect();let Q=lJ.create(),Y=$?{address:$}:{},G=(await this.sendMessage("circles_subscribe",Y)).result;if(!this.subscriptionListeners[G])this.subscriptionListeners[G]=[];return this.subscriptionListeners[G].push((Z)=>{I$(Z).forEach((K)=>Q.emit(K))}),this.activeSubscriptions.push({id:G,address:$}),Q.property}}var H$=BigInt(4294967295),g8=BigInt(32);function s0(J,$=!1){if($)return{h:Number(J&H$),l:Number(J>>g8&H$)};return{h:Number(J>>g8&H$)|0,l:Number(J&H$)|0}}function v8(J,$=!1){let Q=J.length,Y=new Uint32Array(Q),M=new Uint32Array(Q);for(let G=0;G<Q;G++){let{h:Z,l:K}=s0(J[G],$);[Y[G],M[G]]=[Z,K]}return[Y,M]}var u8=(J,$,Q)=>J<<Q|$>>>32-Q,m8=(J,$,Q)=>$<<Q|J>>>32-Q,h8=(J,$,Q)=>$<<Q-32|J>>>64-Q,l8=(J,$,Q)=>J<<Q-32|$>>>64-Q;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function r0(J){return J instanceof Uint8Array||ArrayBuffer.isView(J)&&J.constructor.name==="Uint8Array"}function d$(J,$=""){if(!Number.isSafeInteger(J)||J<0){let Q=$&&`"${$}" `;throw Error(`${Q}expected integer >= 0, got ${J}`)}}function S$(J,$,Q=""){let Y=r0(J),M=J?.length,G=$!==void 0;if(!Y||G&&M!==$){let Z=Q&&`"${Q}" `,K=G?` of length ${$}`:"",X=Y?`length=${M}`:`type=${typeof J}`;throw Error(Z+"expected Uint8Array"+K+", got "+X)}return J}function n$(J,$=!0){if(J.destroyed)throw Error("Hash instance has been destroyed");if($&&J.finished)throw Error("Hash#digest() has already been called")}function c8(J,$){S$(J,void 0,"digestInto() output");let Q=$.outputLen;if(J.length<Q)throw Error('"digestInto() output" expected to be of length >='+Q)}function p8(J){return new Uint32Array(J.buffer,J.byteOffset,Math.floor(J.byteLength/4))}function i$(...J){for(let $=0;$<J.length;$++)J[$].fill(0)}var e0=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function JQ(J){return J<<24&4278190080|J<<8&16711680|J>>>8&65280|J>>>24&255}function $Q(J){for(let $=0;$<J.length;$++)J[$]=JQ(J[$]);return J}var t$=e0?(J)=>J:$Q;function d8(J,$={}){let Q=(M,G)=>J(G).update(M).digest(),Y=J(void 0);return Q.outputLen=Y.outputLen,Q.blockLen=Y.blockLen,Q.create=(M)=>J(M),Object.assign(Q,$),Object.freeze(Q)}var QQ=BigInt(0),M$=BigInt(1),YQ=BigInt(2),MQ=BigInt(7),GQ=BigInt(256),ZQ=BigInt(113),t8=[],o8=[],a8=[];for(let J=0,$=M$,Q=1,Y=0;J<24;J++){[Q,Y]=[Y,(2*Q+3*Y)%5],t8.push(2*(5*Y+Q)),o8.push((J+1)*(J+2)/2%64);let M=QQ;for(let G=0;G<7;G++)if($=($<<M$^($>>MQ)*ZQ)%GQ,$&YQ)M^=M$<<(M$<<BigInt(G))-M$;a8.push(M)}var s8=v8(a8,!0),XQ=s8[0],KQ=s8[1],n8=(J,$,Q)=>Q>32?h8(J,$,Q):u8(J,$,Q),i8=(J,$,Q)=>Q>32?l8(J,$,Q):m8(J,$,Q);function qQ(J,$=24){let Q=new Uint32Array(10);for(let Y=24-$;Y<24;Y++){for(let Z=0;Z<10;Z++)Q[Z]=J[Z]^J[Z+10]^J[Z+20]^J[Z+30]^J[Z+40];for(let Z=0;Z<10;Z+=2){let K=(Z+8)%10,X=(Z+2)%10,q=Q[X],U=Q[X+1],D=n8(q,U,1)^Q[K],V=i8(q,U,1)^Q[K+1];for(let O=0;O<50;O+=10)J[Z+O]^=D,J[Z+O+1]^=V}let M=J[2],G=J[3];for(let Z=0;Z<24;Z++){let K=o8[Z],X=n8(M,G,K),q=i8(M,G,K),U=t8[Z];M=J[U],G=J[U+1],J[U]=X,J[U+1]=q}for(let Z=0;Z<50;Z+=10){for(let K=0;K<10;K++)Q[K]=J[Z+K];for(let K=0;K<10;K++)J[Z+K]^=~Q[(K+2)%10]&Q[(K+4)%10]}J[0]^=XQ[Y],J[1]^=KQ[Y]}i$(Q)}class o${state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(J,$,Q,Y=!1,M=24){if(this.blockLen=J,this.suffix=$,this.outputLen=Q,this.enableXOF=Y,this.rounds=M,d$(Q,"outputLen"),!(0<J&&J<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=p8(this.state)}clone(){return this._cloneInto()}keccak(){t$(this.state32),qQ(this.state32,this.rounds),t$(this.state32),this.posOut=0,this.pos=0}update(J){n$(this),S$(J);let{blockLen:$,state:Q}=this,Y=J.length;for(let M=0;M<Y;){let G=Math.min($-this.pos,Y-M);for(let Z=0;Z<G;Z++)Q[this.pos++]^=J[M++];if(this.pos===$)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:J,suffix:$,pos:Q,blockLen:Y}=this;if(J[Q]^=$,($&128)!==0&&Q===Y-1)this.keccak();J[Y-1]^=128,this.keccak()}writeInto(J){n$(this,!1),S$(J),this.finish();let $=this.state,{blockLen:Q}=this;for(let Y=0,M=J.length;Y<M;){if(this.posOut>=Q)this.keccak();let G=Math.min(Q-this.posOut,M-Y);J.set($.subarray(this.posOut,this.posOut+G),Y),this.posOut+=G,Y+=G}return J}xofInto(J){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(J)}xof(J){return d$(J),this.xofInto(new Uint8Array(J))}digestInto(J){if(c8(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,i$(this.state)}_cloneInto(J){let{blockLen:$,suffix:Q,outputLen:Y,rounds:M,enableXOF:G}=this;return J||=new o$($,Q,Y,G,M),J.state32.set(this.state32),J.pos=this.pos,J.posOut=this.posOut,J.finished=this.finished,J.rounds=M,J.suffix=Q,J.outputLen=Y,J.enableXOF=G,J.destroyed=this.destroyed,J}}var UQ=(J,$,Q,Y={})=>d8(()=>new o$($,J,Q),Y);var cJ=UQ(1,136,32);var r8=[];for(let J=0;J<256;J++)r8[J]=J.toString(16).padStart(2,"0");function _$(J){let $="0x";for(let Q=0;Q<J.length;Q++)$+=r8[J[Q]];return $}function y$(J){let $=J.startsWith("0x")?J.slice(2):J,Q=new Uint8Array($.length/2);for(let Y=0;Y<$.length;Y+=2)Q[Y/2]=parseInt($.slice(Y,Y+2),16);return Q}var g=64,w$=32,A$=(J)=>J.startsWith("0x")?J.slice(2):J;var GJ=(J)=>J.toString(16).padStart(g,"0");function OJ(J){let $=J.toLowerCase().replace("0x",""),Q=_$(cJ(new TextEncoder().encode($))).slice(2),Y="0x";for(let M=0;M<$.length;M++)Y+=parseInt(Q[M],16)>=8?$[M].toUpperCase():$[M];return Y}function a$(J,$){if(J==="tuple"&&$)return`(${$.map((M)=>a$(M.type,M.components)).join(",")})`;let Q=J.match(/^tuple(\[\d*\])$/);if(Q&&$)return`${a$("tuple",$)}${Q[1]}`;return J}function WQ(J){let Q=(J.inputs||[]).map((Y)=>a$(Y.type,Y.components));return`${J.name}(${Q.join(",")})`}function jQ(J){let $=WQ(J),Q=cJ(new TextEncoder().encode($));return _$(Q.slice(0,4))}function pJ(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 e8($);return pJ(Q)}if(J==="tuple")return e8($);return!1}function e8(J){return J?.some(($)=>pJ($.type,$.components))??!1}function NJ(J,$,Q){if(J==="tuple"&&Q)return DQ(Q,$);if(J.includes("["))return zQ(J,$,Q);return VQ(J,$)}function zQ(J,$,Q){let Y=J.slice(0,J.indexOf("[")),M=J.endsWith("[]"),G=pJ(Y,Q),Z;if(G){let K=$.map((U)=>NJ(Y,U,Q)),X=$.length*w$;Z=K.map((U)=>{let D=X;return X+=U.length/2,GJ(D)}).join("")+K.join("")}else Z=$.map((K)=>NJ(Y,K,Q)).join("");return M?GJ($.length)+Z:Z}function DQ(J,$){let Q=Array.isArray($),Y=[],M=[],G=[];for(let Z=0;Z<J.length;Z++){let K=J[Z],X=Q?$[Z]:$[K.name||""],q=pJ(K.type,K.components);if(G.push(q),q)Y.push(""),M.push(NJ(K.type,X,K.components));else Y.push(NJ(K.type,X,K.components))}if(M.length>0){let Z=Y.reduce((q,U,D)=>q+(G[D]?w$:U.length/2),0),K="",X=0;for(let q=0;q<J.length;q++)if(G[q])K+=GJ(Z),Z+=M[X].length/2,X++;else K+=Y[q];return K+M.join("")}return Y.join("")}function VQ(J,$){if(J==="address")return A$($).toLowerCase().padStart(g,"0");if(J==="bool")return GJ($?1:0);if(J.startsWith("uint")){let Q=typeof $==="bigint"?$:BigInt($);return GJ(Q)}if(J.startsWith("int")){let Q=typeof $==="bigint"?$:BigInt($);if(Q<0n){let Y=J==="int"?256:parseInt(J.slice(3));Q=(1n<<BigInt(Y))+Q}return GJ(Q)}if(J.startsWith("bytes")&&J!=="bytes")return A$($).padEnd(g,"0");if(J==="bytes"){let Q=A$($),Y=GJ(Q.length/2),M=Q.padEnd(Math.ceil(Q.length/g)*g,"0");return Y+M}if(J==="string"){let Q=Array.from(new TextEncoder().encode($)).map((G)=>G.toString(16).padStart(2,"0")).join(""),Y=GJ(Q.length/2),M=Q.padEnd(Math.ceil(Q.length/g)*g,"0");return Y+M}throw Error(`Unsupported type: ${J}`)}function G$(J,$,Q=0,Y){if(J==="tuple"&&Y)return OQ(Y,$,Q);if(J.includes("["))return NQ(J,$,Q,Y);return CQ(J,$,Q)}function NQ(J,$,Q,Y){let M=J.slice(0,J.indexOf("[")),G=$.slice(Q,Q+g);if(J.endsWith("[]")){let K=parseInt(G,16)*2,X=parseInt($.slice(K,K+g),16),q=[],U=K+g;for(let D=0;D<X;D++){let V=G$(M,$,U,Y);q.push(V.value),U+=V.consumed}return{value:q,consumed:g}}let Z=J.match(/\[(\d+)\]$/);if(Z){let K=parseInt(Z[1]),X=[],q=0;for(let U=0;U<K;U++){let D=G$(M,$,Q+q,Y);X.push(D.value),q+=D.consumed}return{value:X,consumed:q}}throw Error(`Invalid array type: ${J}`)}function OQ(J,$,Q){let Y=[],M=Q;for(let G of J){let Z=G$(G.type,$,M,G.components);Y.push(Z.value),M+=Z.consumed}return{value:Y,consumed:M-Q}}function CQ(J,$,Q){let Y=$.slice(Q,Q+g);if(J==="address")return{value:OJ("0x"+Y.slice(24)),consumed:g};if(J==="bool")return{value:parseInt(Y,16)!==0,consumed:g};if(J.startsWith("uint"))return{value:BigInt("0x"+Y),consumed:g};if(J.startsWith("int")){let M=BigInt("0x"+Y),G=J==="int"?256:parseInt(J.slice(3)),Z=1n<<BigInt(G-1);return{value:M>=Z?M-(1n<<BigInt(G)):M,consumed:g}}if(J.startsWith("bytes")&&J!=="bytes"){let M=parseInt(J.match(/^bytes(\d+)$/)[1]);return{value:"0x"+Y.slice(0,M*2),consumed:g}}if(J==="bytes"){let M=parseInt(Y,16)*2,G=parseInt($.slice(M,M+g),16)*2;return{value:"0x"+$.slice(M+g,M+g+G),consumed:g}}if(J==="string"){let M=parseInt(Y,16)*2,G=parseInt($.slice(M,M+g),16)*2,Z=$.slice(M+g,M+g+G),K=new Uint8Array(Z.match(/.{2}/g)?.map((X)=>parseInt(X,16))||[]);return{value:new TextDecoder().decode(K),consumed:g}}throw Error(`Unsupported type: ${J}`)}function TJ(J){let{abi:$,functionName:Q,args:Y=[]}=J,M=$.find((O)=>O.type==="function"&&O.name===Q);if(!M)throw Error(`Function "${Q}" not found in ABI`);let G=jQ(M),Z=M.inputs||[];if(Z.length===0)return G;if(Y.length!==Z.length)throw Error(`Expected ${Z.length} arguments, got ${Y.length}`);let K=[],X=[],q=[];for(let O=0;O<Z.length;O++){let L=Z[O],N=L.components,b=pJ(L.type,N);if(q.push(b),b)K.push(""),X.push(NJ(L.type,Y[O],N));else K.push(NJ(L.type,Y[O],N))}if(X.length===0)return G+K.join("");let U=K.reduce((O,L,N)=>O+(q[N]?w$:L.length/2),0),D="",V=0;for(let O=0;O<Z.length;O++)if(q[O])D+=GJ(U),U+=X[V].length/2,V++;else D+=K[O];return G+D+X.join("")}function Z$(J){let{abi:$,functionName:Q,data:Y}=J,M=$.find((q)=>q.type==="function"&&q.name===Q);if(!M)throw Error(`Function "${Q}" not found in ABI`);let G=M.outputs||[];if(G.length===0)return;let Z=A$(Y);if(G.length===1)return G$(G[0].type,Z,0,G[0].components).value;let K=[],X=0;for(let q of G){let U=G$(q.type,Z,X,q.components);K.push(U.value),X+=U.consumed}return K}function r(J,$){if(J.length!==$.length)throw Error(`Type/value length mismatch: ${J.length} types, ${$.length} values`);let Q=[],Y=[],M=[];for(let X=0;X<J.length;X++){let q=J[X],U=pJ(q);if(M.push(U),U)Q.push(""),Y.push(NJ(q,$[X]));else Q.push(NJ(q,$[X]))}if(Y.length===0)return"0x"+Q.join("");let G=Q.reduce((X,q,U)=>X+(M[U]?w$:q.length/2),0),Z="",K=0;for(let X=0;X<J.length;X++)if(M[X])Z+=GJ(G),G+=Y[K].length/2,K++;else Z+=Q[X];return"0x"+Z+Y.join("")}function C(J){return J.toLowerCase()}function RQ(J){return OJ(J)}function BQ(J){if(typeof J!=="string")return!1;let $=J.replace("0x","");return $.length===40&&/^[0-9a-fA-F]{40}$/.test($)}function H(J){if(J===null||J===void 0)return J;if(BQ(J))return RQ(J);if(Array.isArray(J))return J.map(($)=>H($));if(typeof J==="object"&&J!==null){let $={};for(let Q in J)if(Object.prototype.hasOwnProperty.call(J,Q))$[Q]=H(J[Q]);return $}return J}function J0(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 XJ(J){let $={};for(let Q in J){let Y=J[Q];if(Y===null||Y===void 0)$[Q]=Y;else if(typeof Y==="string"&&/^\d+$/.test(Y))$[Q]=BigInt(Y);else if(typeof Y==="object"&&!Array.isArray(Y))$[Q]=XJ(Y);else if(Array.isArray(Y))$[Q]=Y.map((M)=>typeof M==="object"&&M!==null?XJ(M):M);else $[Q]=Y}return $}var IJ="0x0000000000000000000000000000000000000000",m=BigInt(96)*BigInt(1000000000000000000),X$=BigInt("9999999999999999999999999999999999999"),s$="0x4e1DCf7AD4e460CfD30791CCC4F9c8a4f820ec67",r$="0x89867a67674bd4bf33165a653cde826b696ab7d050166b71066dfa0b9b6f90f4",e$="0xe298282cefe913ab5d282047161268a8222e4bd4ed106300c547894bbefd31ee",dJ="0xc19bc204eb1c1d5b3fe500e5e5dfabab625f286c",HJ="0x9Eb51E6A39B3F17bB1883B80748b56170039ff1d";class KJ{client;constructor(J){this.client=J}async findPath(J){let $=J0(J),Q=await this.client.call("circlesV2_findPath",[$]),Y=XJ(Q);return H(Y)}async findMaxFlow(J){let $=await this.findPath({...J,targetFlow:X$});return BigInt($.maxFlow)}}class K${client;constructor(J){this.client=J}async query(J){let $=await this.client.call("circles_query",[J]),{columns:Q,rows:Y}=$,M=Y.map((G)=>{let Z={};return Q.forEach((K,X)=>{Z[K]=G[X]}),Z});return H(M)}async tables(){return this.client.call("circles_tables",[])}async events(J=null,$=null,Q=null,Y=null,M=null,G=!1,Z=100,K=null){let X=await this.client.call("circles_events_paginated",[J,$,Q,Y,M,G,Z,K]);return{events:H(X.events),hasMore:X.hasMore,nextCursor:X.nextCursor}}}var PQ=[{name:"blockNumber",sortOrder:"DESC"},{name:"transactionIndex",sortOrder:"DESC"},{name:"logIndex",sortOrder:"DESC"}];class SJ{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=PQ.map(($)=>({...$,sortOrder:this.params.sortOrder}));if(this.params.table==="TransferBatch")J.push({name:"batchIndex",sortOrder:this.params.sortOrder});return J}buildOrderBy(){if(this.orderColumns&&this.orderColumns.length>0)return this.orderColumns;return this.cursorColumns.map((J)=>({Column:J.name,SortOrder:J.sortOrder}))}rowsToObjects(J){let{columns:$,rows:Q}=J;return Q.map((Y)=>{let M={};return $.forEach((G,Z)=>{M[G]=Y[Z]}),this.rowTransformer?this.rowTransformer(M):M})}async queryNextPage(){let J={Namespace:this.params.namespace,Table:this.params.table,Columns:this.params.columns,Filter:this.params.filter||[],Order:this.buildOrderBy(),Limit:this.params.limit},$=this._currentPage?.nextCursor?[J,this._currentPage.nextCursor]:[J],Q=await this.client.call("circles_paginated_query",$),Y=this.rowsToObjects(Q);return this._currentPage={limit:this.params.limit,size:Y.length,sortOrder:this.params.sortOrder,hasMore:Q.hasMore,nextCursor:Q.nextCursor??void 0,results:Y},Y.length>0}reset(){this._currentPage=void 0}}class _J{client;constructor(J){this.client=J}transformQueryResponse(J){let{columns:$,rows:Q}=J;return Q.map((Y)=>{let M={};return $.forEach((G,Z)=>{M[G]=Y[Z]}),M})}async getCommonTrust(J,$){let Q=await this.client.call("circles_getCommonTrust",[C(J),C($)]);return H(Q)}getTrustRelations(J,$=100,Q="DESC"){let Y=C(J),M=[{Type:"Conjunction",ConjunctionType:"And",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"version",Value:2},{Type:"Conjunction",ConjunctionType:"Or",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"trustee",Value:Y},{Type:"FilterPredicate",FilterType:"Equals",Column:"truster",Value:Y}]}]}];return new SJ(this.client,{namespace:"V_Crc",table:"TrustRelations",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","version","trustee","truster","expiryTime"],filter:M,limit:$},(G)=>H(G))}async getAggregatedTrustRelations(J){let $=C(J),Q=await this.client.call("circles_getAggregatedTrustRelations",[$]);return H(Q)}async getTrustedBy(J){let $=C(J),Y=(await this.getAggregatedTrustRelations($)).filter((M)=>M.relation==="trustedBy");return H(Y)}async getTrusts(J){let $=C(J),Y=(await this.getAggregatedTrustRelations($)).filter((M)=>M.relation==="trusts");return H(Y)}async getMutualTrusts(J){let $=C(J),Y=(await this.getAggregatedTrustRelations($)).filter((M)=>M.relation==="mutuallyTrusts");return H(Y)}async getTrustNetworkSummary(J,$=2){return this.client.call("circles_getTrustNetworkSummary",[C(J),$])}async getAggregatedTrustRelationsEnriched(J){return this.client.call("circles_getAggregatedTrustRelationsEnriched",[C(J)])}async getValidInviters(J,$){let Q=[C(J)];if($)Q.push($);return this.client.call("circles_getValidInviters",Q)}}class nJ{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,Y=$,M=this.ONE_64;while(Y>0n){if((Y&1n)===1n)M=this.mul64(M,Q);Q=this.mul64(Q,Q),Y>>=1n}return M}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,Y=J,M=$;while(M>0n){if((M&1n)===1n)Q=this.mul36(Q,Y);Y=this.mul36(Y,Y),M>>=1n}return Q}static attoCirclesToCircles(J){if(J===0n)return 0;let $=J/this.ATTO_FACTOR,Q=J%this.ATTO_FACTOR,Y=BigInt(Number.MAX_SAFE_INTEGER);if($>Y||$<-Y)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,Y=Q/this.PERIOD_SEC,M=Q%this.PERIOD_SEC,G=this.v1InflateFactor(Y),Z=this.v1InflateFactor(Y+1n);return this.v1ToDemurrage(J,G,Z,M,this.PERIOD_SEC)}static attoCirclesToAttoCrc(J,$){let Q=$-this.INFLATION_DAY_ZERO_UNIX,Y=Q/this.PERIOD_SEC,M=Q%this.PERIOD_SEC,G=this.v1InflateFactor(Y),Z=this.v1InflateFactor(Y+1n),K=G*(this.PERIOD_SEC-M)+Z*M;return J*3n*this.V1_ACCURACY*this.PERIOD_SEC/K}static v1ToDemurrage(J,$,Q,Y,M){let G=$*(M-Y)+Q*Y;return J*3n*this.V1_ACCURACY*M/G}}class yJ{client;constructor(J){this.client=J}async getTotalBalance(J,$=!0){let Q=await this.client.call("circlesV2_getTotalBalance",[C(J),$]);return nJ.circlesToAttoCircles(Q)}async getTokenBalances(J){let Q=(await this.client.call("circles_getTokenBalances",[C(J)])).map((Y)=>XJ(Y));return H(Q)}}class q${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((Y)=>C(Y)),Q=await this.client.call("circles_getAvatarInfoBatch",[$]);return H(Q)}async getNetworkSnapshot(){let J=await this.client.call("circles_getNetworkSnapshot",[]);return H(J)}}class U${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,Y){return this.client.call("circles_searchProfiles",[J.toLowerCase(),$,Q,Y])}async searchByAddressOrName(J,$=10,Q,Y){return this.client.call("circles_searchProfileByAddressOrName",Y?[J,$,Q??null,Y]:[J,$,Q??null])}async getProfileView(J){return this.client.call("circles_getProfileView",[C(J)])}}class AJ{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((M)=>C(M)),Y=(await this.client.call("circles_getTokenInfoBatch",[$])).map((M)=>XJ(M));return H(Y)}async getTokenHolders(J,$=100,Q){let Y=await this.client.call("circles_getTokenHolders",[C(J),$,Q??null]);return{hasMore:Y.hasMore,nextCursor:Y.nextCursor,results:H(Y.results)}}}class W${client;constructor(J){this.client=J}async getInvitationOrigin(J){let $=C(J),Q=await this.client.call("circles_getInvitationOrigin",[$]);return Q?H(Q):null}async getInvitedBy(J){let $=await this.getInvitationOrigin(J);if($?.inviter)return H($.inviter);return}async getTrustInvitations(J,$){let Q=C(J),Y=await this.client.call("circles_getTrustInvitations",$?[Q,$]:[Q]);return H(Y)}async getInvitations(J,$){let Y=(await this.getValidInviters(J,$)).results.map((M)=>M.avatarInfo).filter((M)=>M!==void 0&&M!==null);return H(Y)}async getValidInviters(J,$){let Q=C(J),Y=await this.client.call("circles_getValidInviters",$?[Q,$]:[Q]);return H(Y)}async getInvitationsFrom(J,$=!1){let Q=C(J),Y=await this.client.call("circles_getInvitationsFrom",[Q,$]);return H(Y)}async getEscrowInvitations(J){let $=C(J),Q=await this.client.call("circles_getEscrowInvitations",[$]);return H(Q)}async getAtScaleInvitations(J){let $=C(J),Q=await this.client.call("circles_getAtScaleInvitations",[$]);return H(Q)}async getAllInvitations(J,$){let Q=C(J),Y=await this.client.call("circles_getAllInvitations",$?[Q,$]:[Q]);return H(Y)}}class j${client;constructor(J){this.client=J}async getTransactionHistory(J,$=50,Q){let Y=await this.client.call("circles_getTransactionHistory",[C(J),$,Q??null]);return{hasMore:Y.hasMore,nextCursor:Y.nextCursor,results:H(Y.results)}}async getTransactionHistoryEnriched(J,$=0,Q=null,Y=20,M){let G=await this.client.call("circles_getTransactionHistoryEnriched",[C(J),$,Q,Y,M??null]);return{hasMore:G.hasMore,nextCursor:G.nextCursor,results:H(G.results)}}}class wJ{client;constructor(J){this.client=J}async findGroups(J=50,$,Q){let Y=$?{nameStartsWith:$.nameStartsWith,symbolStartsWith:$.symbolStartsWith,ownerIn:$.ownerIn?.map((Z)=>C(Z))}:void 0,M=await this.client.call("circles_findGroups",[J,Y??null,Q??null]),G=H(M.results).map((Z)=>{let K=Z;if(!K.owner&&K.mint)return{...K,owner:K.mint};return K});return{hasMore:M.hasMore,nextCursor:M.nextCursor,results:G}}async getGroupMemberships(J,$=50,Q){let Y=await this.client.call("circles_getGroupMemberships",[C(J),$,Q??null]);return{hasMore:Y.hasMore,nextCursor:Y.nextCursor,results:H(Y.results)}}async getGroupMembers(J,$=100,Q){let Y=await this.client.call("circles_getGroupMembers",[C(J),$,Q??null]);return{hasMore:Y.hasMore,nextCursor:Y.nextCursor,results:H(Y.results)}}getGroups(J=50,$,Q="DESC"){let Y=[];if($){if($.nameStartsWith)Y.push({Type:"FilterPredicate",FilterType:"Like",Column:"name",Value:$.nameStartsWith+"%"});if($.symbolStartsWith)Y.push({Type:"FilterPredicate",FilterType:"Like",Column:"symbol",Value:$.symbolStartsWith+"%"});if($.groupAddressIn&&$.groupAddressIn.length>0){let G=$.groupAddressIn.map((Z)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:C(Z)}));if(G.length===1)Y.push(G[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:G})}if($.groupTypeIn&&$.groupTypeIn.length>0){let G=$.groupTypeIn.map((Z)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"type",Value:Z}));if(G.length===1)Y.push(G[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:G})}if($.ownerIn&&$.ownerIn.length>0){let G=$.ownerIn.map((Z)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"owner",Value:C(Z)}));if(G.length===1)Y.push(G[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:G})}if($.mintHandlerEquals)Y.push({Type:"FilterPredicate",FilterType:"Equals",Column:"mintHandler",Value:C($.mintHandlerEquals)});if($.treasuryEquals)Y.push({Type:"FilterPredicate",FilterType:"Equals",Column:"treasury",Value:C($.treasuryEquals)})}let M=Y.length>1?[{Type:"Conjunction",ConjunctionType:"And",Predicates:Y}]:Y;return new SJ(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:M,limit:J},(G)=>H(G))}getGroupHolders(J,$=100){let Q=C(J);return new SJ(this.client,{namespace:"V_Crc",table:"TokenBalances",sortOrder:"DESC",columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","token","account","balance","lastChangedAt"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"token",Value:Q}],limit:$},(Y)=>H(Y))}}class E${client;constructor(J){this.client=J}async getProfileView(J){let $=C(J);return this.client.call("circles_getProfileView",[$])}async getTrustNetworkSummary(J,$=2){let Q=C(J);return this.client.call("circles_getTrustNetworkSummary",[Q,$])}async getAggregatedTrustRelations(J){let $=C(J);return this.client.call("circles_getAggregatedTrustRelations",[$])}async getValidInviters(J,$){let Q=C(J),Y=await this.client.call("circles_getValidInviters",$?[Q,$]:[Q]);return H(Y)}async getTransactionHistoryEnriched(J,$=0,Q=null,Y=50,M){let G=C(J),Z=await this.client.call("circles_getTransactionHistoryEnriched",[G,$,Q,Y,M??null]);return{hasMore:Z.hasMore,nextCursor:Z.nextCursor,results:H(Z.results)}}async searchProfileByAddressOrName(J,$=20,Q,Y){return this.client.call("circles_searchProfileByAddressOrName",Y?[J,$,Q??null,Y]:[J,$,Q??null])}}class x${client;_pathfinder;_query;_trust;_balance;_avatar;_profile;_token;_invitation;_transaction;_group;_sdk;constructor(J="https://rpc.aboutcircles.com/"){this.client=new VJ(J)}get pathfinder(){if(!this._pathfinder)this._pathfinder=new KJ(this.client);return this._pathfinder}get query(){if(!this._query)this._query=new K$(this.client);return this._query}get trust(){if(!this._trust)this._trust=new _J(this.client);return this._trust}get balance(){if(!this._balance)this._balance=new yJ(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 U$(this.client);return this._profile}get token(){if(!this._token)this._token=new AJ(this.client);return this._token}get invitation(){if(!this._invitation)this._invitation=new W$(this.client);return this._invitation}get transaction(){if(!this._transaction)this._transaction=new j$(this.client);return this._transaction}get group(){if(!this._group)this._group=new wJ(this.client);return this._group}get sdk(){if(!this._sdk)this._sdk=new E$(this.client);return this._sdk}setRpcUrl(J){this.client.setRpcUrl(J)}getRpcUrl(){return this.client.getRpcUrl()}}class p{address;abi;rpcUrl;constructor(J){this.address=J.address,this.abi=J.abi,this.rpcUrl=J.rpcUrl}async read(J,$,Q){let Y=TJ({abi:this.abi,functionName:J,args:$}),M={to:this.address,data:Y,...Q?.from&&{from:Q.from}},Z=await(await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[M,"latest"]})})).json();if(Z.error)throw Error(`RPC Error: ${Z.error.message}`);if(!Z.result)throw Error("No result returned from RPC call");return Z$({abi:this.abi,functionName:J,data:Z.result})}encodeWrite(J,$){return TJ({abi:this.abi,functionName:J,args:$})}}var $0=[{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 CJ extends p{constructor(J){super({address:J.address,abi:$0,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,Y,M="0x"){return{to:this.address,data:this.encodeWrite("safeTransferFrom",[J,$,Q,Y,M]),value:0n}}operateFlowMatrix(J,$,Q,Y){return{to:this.address,data:this.encodeWrite("operateFlowMatrix",[J,$,Q,Y]),value:0n}}async isHuman(J){return this.read("isHuman",[J])}safeBatchTransferFrom(J,$,Q,Y,M="0x"){return{to:this.address,data:this.encodeWrite("safeBatchTransferFrom",[J,$,Q,Y,M]),value:0n}}}var Q0=[{type:"function",name:"erc20Circles",inputs:[{name:"_circlesType",type:"uint8"},{name:"_avatar",type:"address"}],outputs:[{type:"address"}],stateMutability:"view"}];class k$ extends p{constructor(J){super({address:J.address,abi:Q0,rpcUrl:J.rpcUrl})}async erc20Circles(J,$){return this.read("erc20Circles",[J,$])}}var J8=[{type:"function",name:"unwrap",inputs:[{name:"_amount",type:"uint256"}],outputs:[],stateMutability:"nonpayable"}];class z$ extends p{constructor(J){super({address:J.address,abi:J8,rpcUrl:J.rpcUrl})}unwrap(J){return{to:this.address,data:this.encodeWrite("unwrap",[J]),value:0n}}}class D$ extends p{constructor(J){super({address:J.address,abi:J8,rpcUrl:J.rpcUrl})}unwrap(J){return{to:this.address,data:this.encodeWrite("unwrap",[J]),value:0n}}}var $8=[{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 Q8=[{type:"function",name:"claimInvite",inputs:[],outputs:[{name:"id",type:"uint256"}],stateMutability:"nonpayable"},{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"}];var Y8=[{type:"function",name:"isModuleEnabled",inputs:[{name:"module",type:"address"}],outputs:[{name:"",type:"bool"}],stateMutability:"view"},{type:"function",name:"enableModule",inputs:[{name:"module",type:"address"}],outputs:[],stateMutability:"nonpayable"}];var M8=[{type:"function",name:"trustInviter",inputs:[{name:"inviter",type:"address"}],outputs:[],stateMutability:"nonpayable"}];class iJ extends p{constructor(J){super({address:J.address,abi:$8,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 tJ extends p{constructor(J){super({address:J.address,abi:Q8,rpcUrl:J.rpcUrl})}claimInvite(){return{to:this.address,data:this.encodeWrite("claimInvite",[]),value:0n}}claimInvites(J){return{to:this.address,data:this.encodeWrite("claimInvites",[J]),value:0n}}async inviterQuota(J){return this.read("inviterQuota",[J])}async invitationFee(){return this.read("INVITATION_FEE")}async invitationModule(){return this.read("invitationModule")}}class b$ extends p{constructor(J){super({address:J.address,abi:Y8,rpcUrl:J.rpcUrl})}async isModuleEnabled(J){return this.read("isModuleEnabled",[J])}enableModule(J){return{to:this.address,data:this.encodeWrite("enableModule",[J]),value:0n}}}class F$ extends p{constructor(J){super({address:J.address,abi:M8,rpcUrl:J.rpcUrl})}trustInviter(J){return{to:this.address,data:this.encodeWrite("trustInviter",[J]),value:0n}}}class V$ 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}}var EJ=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function LQ(J){return J instanceof Uint8Array||ArrayBuffer.isView(J)&&J.constructor.name==="Uint8Array"}function f$(J){if(!Number.isSafeInteger(J)||J<0)throw Error("positive integer expected, got "+J)}function xJ(J,...$){if(!LQ(J))throw Error("Uint8Array expected");if($.length>0&&!$.includes(J.length))throw Error("Uint8Array expected of length "+$+", got length="+J.length)}function Y0(J){if(typeof J!=="function"||typeof J.create!=="function")throw Error("Hash should be wrapped by utils.createHasher");f$(J.outputLen),f$(J.blockLen)}function oJ(J,$=!0){if(J.destroyed)throw Error("Hash instance has been destroyed");if($&&J.finished)throw Error("Hash#digest() has already been called")}function M0(J,$){xJ(J);let Q=$.outputLen;if(J.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function kJ(...J){for(let $=0;$<J.length;$++)J[$].fill(0)}function g$(J){return new DataView(J.buffer,J.byteOffset,J.byteLength)}function QJ(J,$){return J<<32-$|J>>>$}function TQ(J){if(typeof J!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(J))}function N$(J){if(typeof J==="string")J=TQ(J);return xJ(J),J}function G0(...J){let $=0;for(let Y=0;Y<J.length;Y++){let M=J[Y];xJ(M),$+=M.length}let Q=new Uint8Array($);for(let Y=0,M=0;Y<J.length;Y++){let G=J[Y];Q.set(G,M),M+=G.length}return Q}class O${}function Z0(J){let $=(Y)=>J().update(N$(Y)).digest(),Q=J();return $.outputLen=Q.outputLen,$.blockLen=Q.blockLen,$.create=()=>J(),$}function X0(J=32){if(EJ&&typeof EJ.getRandomValues==="function")return EJ.getRandomValues(new Uint8Array(J));if(EJ&&typeof EJ.randomBytes==="function")return Uint8Array.from(EJ.randomBytes(J));throw Error("crypto.getRandomValues must be defined")}function IQ(J,$,Q,Y){if(typeof J.setBigUint64==="function")return J.setBigUint64($,Q,Y);let M=BigInt(32),G=BigInt(4294967295),Z=Number(Q>>M&G),K=Number(Q&G),X=Y?4:0,q=Y?0:4;J.setUint32($+X,Z,Y),J.setUint32($+q,K,Y)}function K0(J,$,Q){return J&$^~J&Q}function q0(J,$,Q){return J&$^J&Q^$&Q}class G8 extends O${constructor(J,$,Q,Y){super();this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=J,this.outputLen=$,this.padOffset=Q,this.isLE=Y,this.buffer=new Uint8Array(J),this.view=g$(this.buffer)}update(J){oJ(this),J=N$(J),xJ(J);let{view:$,buffer:Q,blockLen:Y}=this,M=J.length;for(let G=0;G<M;){let Z=Math.min(Y-this.pos,M-G);if(Z===Y){let K=g$(J);for(;Y<=M-G;G+=Y)this.process(K,G);continue}if(Q.set(J.subarray(G,G+Z),this.pos),this.pos+=Z,G+=Z,this.pos===Y)this.process($,0),this.pos=0}return this.length+=J.length,this.roundClean(),this}digestInto(J){oJ(this),M0(J,this),this.finished=!0;let{buffer:$,view:Q,blockLen:Y,isLE:M}=this,{pos:G}=this;if($[G++]=128,kJ(this.buffer.subarray(G)),this.padOffset>Y-G)this.process(Q,0),G=0;for(let U=G;U<Y;U++)$[U]=0;IQ(Q,Y-8,BigInt(this.length*8),M),this.process(Q,0);let Z=g$(J),K=this.outputLen;if(K%4)throw Error("_sha2: outputLen should be aligned to 32bit");let X=K/4,q=this.get();if(X>q.length)throw Error("_sha2: outputLen bigger than state");for(let U=0;U<X;U++)Z.setUint32(4*U,q[U],M)}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:Y,finished:M,destroyed:G,pos:Z}=this;if(J.destroyed=G,J.finished=M,J.length=Y,J.pos=Z,Y%$)J.buffer.set(Q);return J}clone(){return this._cloneInto()}}var qJ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var HQ=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]),RJ=new Uint32Array(64);class U0 extends G8{constructor(J=32){super(64,J,8,!1);this.A=qJ[0]|0,this.B=qJ[1]|0,this.C=qJ[2]|0,this.D=qJ[3]|0,this.E=qJ[4]|0,this.F=qJ[5]|0,this.G=qJ[6]|0,this.H=qJ[7]|0}get(){let{A:J,B:$,C:Q,D:Y,E:M,F:G,G:Z,H:K}=this;return[J,$,Q,Y,M,G,Z,K]}set(J,$,Q,Y,M,G,Z,K){this.A=J|0,this.B=$|0,this.C=Q|0,this.D=Y|0,this.E=M|0,this.F=G|0,this.G=Z|0,this.H=K|0}process(J,$){for(let U=0;U<16;U++,$+=4)RJ[U]=J.getUint32($,!1);for(let U=16;U<64;U++){let D=RJ[U-15],V=RJ[U-2],O=QJ(D,7)^QJ(D,18)^D>>>3,L=QJ(V,17)^QJ(V,19)^V>>>10;RJ[U]=L+RJ[U-7]+O+RJ[U-16]|0}let{A:Q,B:Y,C:M,D:G,E:Z,F:K,G:X,H:q}=this;for(let U=0;U<64;U++){let D=QJ(Z,6)^QJ(Z,11)^QJ(Z,25),V=q+D+K0(Z,K,X)+HQ[U]+RJ[U]|0,L=(QJ(Q,2)^QJ(Q,13)^QJ(Q,22))+q0(Q,Y,M)|0;q=X,X=K,K=Z,Z=G+V|0,G=M,M=Y,Y=Q,Q=V+L|0}Q=Q+this.A|0,Y=Y+this.B|0,M=M+this.C|0,G=G+this.D|0,Z=Z+this.E|0,K=K+this.F|0,X=X+this.G|0,q=q+this.H|0,this.set(Q,Y,M,G,Z,K,X,q)}roundClean(){kJ(RJ)}destroy(){this.set(0,0,0,0,0,0,0,0),kJ(this.buffer)}}var W0=Z0(()=>new U0);class Z8 extends O${constructor(J,$){super();this.finished=!1,this.destroyed=!1,Y0(J);let Q=N$($);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 Y=this.blockLen,M=new Uint8Array(Y);M.set(Q.length>Y?J.create().update(Q).digest():Q);for(let G=0;G<M.length;G++)M[G]^=54;this.iHash.update(M),this.oHash=J.create();for(let G=0;G<M.length;G++)M[G]^=106;this.oHash.update(M),kJ(M)}update(J){return oJ(this),this.iHash.update(J),this}digestInto(J){oJ(this),xJ(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:Y,destroyed:M,blockLen:G,outputLen:Z}=this;return J=J,J.finished=Y,J.destroyed=M,J.blockLen=G,J.outputLen=Z,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 X8=(J,$,Q)=>new Z8(J,$).update(Q).digest();X8.create=(J,$)=>new Z8(J,$);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var W8=BigInt(0),U8=BigInt(1);function aJ(J){return J instanceof Uint8Array||ArrayBuffer.isView(J)&&J.constructor.name==="Uint8Array"}function j8(J){if(!aJ(J))throw Error("Uint8Array expected")}function sJ(J,$){if(typeof $!=="boolean")throw Error(J+" boolean expected, got "+$)}function C$(J){let $=J.toString(16);return $.length&1?"0"+$:$}function D0(J){if(typeof J!=="string")throw Error("hex string expected, got "+typeof J);return J===""?W8:BigInt("0x"+J)}var V0=typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function",SQ=Array.from({length:256},(J,$)=>$.toString(16).padStart(2,"0"));function rJ(J){if(j8(J),V0)return J.toHex();let $="";for(let Q=0;Q<J.length;Q++)$+=SQ[J[Q]];return $}var UJ={_0:48,_9:57,A:65,F:70,a:97,f:102};function j0(J){if(J>=UJ._0&&J<=UJ._9)return J-UJ._0;if(J>=UJ.A&&J<=UJ.F)return J-(UJ.A-10);if(J>=UJ.a&&J<=UJ.f)return J-(UJ.a-10);return}function R$(J){if(typeof J!=="string")throw Error("hex string expected, got "+typeof J);if(V0)return Uint8Array.fromHex(J);let $=J.length,Q=$/2;if($%2)throw Error("hex string expected, got unpadded hex of length "+$);let Y=new Uint8Array(Q);for(let M=0,G=0;M<Q;M++,G+=2){let Z=j0(J.charCodeAt(G)),K=j0(J.charCodeAt(G+1));if(Z===void 0||K===void 0){let X=J[G]+J[G+1];throw Error('hex string expected, got non-hex character "'+X+'" at index '+G)}Y[M]=Z*16+K}return Y}function WJ(J){return D0(rJ(J))}function z8(J){return j8(J),D0(rJ(Uint8Array.from(J).reverse()))}function bJ(J,$){return R$(J.toString(16).padStart($*2,"0"))}function D8(J,$){return bJ(J,$).reverse()}function s(J,$,Q){let Y;if(typeof $==="string")try{Y=R$($)}catch(G){throw Error(J+" must be hex string or Uint8Array, cause: "+G)}else if(aJ($))Y=Uint8Array.from($);else throw Error(J+" must be hex string or Uint8Array");let M=Y.length;if(typeof Q==="number"&&M!==Q)throw Error(J+" of length "+Q+" expected, got "+M);return Y}function B$(...J){let $=0;for(let Y=0;Y<J.length;Y++){let M=J[Y];j8(M),$+=M.length}let Q=new Uint8Array($);for(let Y=0,M=0;Y<J.length;Y++){let G=J[Y];Q.set(G,M),M+=G.length}return Q}var K8=(J)=>typeof J==="bigint"&&W8<=J;function v$(J,$,Q){return K8(J)&&K8($)&&K8(Q)&&$<=J&&J<Q}function FJ(J,$,Q,Y){if(!v$($,Q,Y))throw Error("expected valid "+J+": "+Q+" <= n < "+Y+", got "+$)}function N0(J){let $;for($=0;J>W8;J>>=U8,$+=1);return $}var fJ=(J)=>(U8<<BigInt(J))-U8,q8=(J)=>new Uint8Array(J),z0=(J)=>Uint8Array.from(J);function O0(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 Y=q8(J),M=q8(J),G=0,Z=()=>{Y.fill(1),M.fill(0),G=0},K=(...D)=>Q(M,Y,...D),X=(D=q8(0))=>{if(M=K(z0([0]),D),Y=K(),D.length===0)return;M=K(z0([1]),D),Y=K()},q=()=>{if(G++>=1000)throw Error("drbg: tried 1000 values");let D=0,V=[];while(D<$){Y=K();let O=Y.slice();V.push(O),D+=Y.length}return B$(...V)};return(D,V)=>{Z(),X(D);let O=void 0;while(!(O=V(q())))X();return Z(),O}}var _Q={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"||aJ(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 gJ(J,$,Q={}){let Y=(M,G,Z)=>{let K=_Q[G];if(typeof K!=="function")throw Error("invalid validator function");let X=J[M];if(Z&&X===void 0)return;if(!K(X,J))throw Error("param "+String(M)+" is invalid. Expected "+G+", got "+X)};for(let[M,G]of Object.entries($))Y(M,G,!1);for(let[M,G]of Object.entries(Q))Y(M,G,!0);return J}function V8(J){let $=new WeakMap;return(Q,...Y)=>{let M=$.get(Q);if(M!==void 0)return M;let G=J(Q,...Y);return $.set(Q,G),G}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var t=BigInt(0),n=BigInt(1),vJ=BigInt(2),yQ=BigInt(3),R0=BigInt(4),B0=BigInt(5),P0=BigInt(8);function d(J,$){let Q=J%$;return Q>=t?Q:$+Q}function e(J,$,Q){let Y=J;while($-- >t)Y*=Y,Y%=Q;return Y}function u$(J,$){if(J===t)throw Error("invert: expected non-zero number");if($<=t)throw Error("invert: expected positive modulus, got "+$);let Q=d(J,$),Y=$,M=t,G=n,Z=n,K=t;while(Q!==t){let q=Y/Q,U=Y%Q,D=M-Z*q,V=G-K*q;Y=Q,Q=U,M=Z,G=K,Z=D,K=V}if(Y!==n)throw Error("invert: does not exist");return d(M,$)}function L0(J,$){let Q=(J.ORDER+n)/R0,Y=J.pow($,Q);if(!J.eql(J.sqr(Y),$))throw Error("Cannot find square root");return Y}function AQ(J,$){let Q=(J.ORDER-B0)/P0,Y=J.mul($,vJ),M=J.pow(Y,Q),G=J.mul($,M),Z=J.mul(J.mul(G,vJ),M),K=J.mul(G,J.sub(Z,J.ONE));if(!J.eql(J.sqr(K),$))throw Error("Cannot find square root");return K}function wQ(J){if(J<BigInt(3))throw Error("sqrt is not defined for small field");let $=J-n,Q=0;while($%vJ===t)$/=vJ,Q++;let Y=vJ,M=P$(J);while(C0(M,Y)===1)if(Y++>1000)throw Error("Cannot find square root: probably non-prime P");if(Q===1)return L0;let G=M.pow(Y,$),Z=($+n)/vJ;return function(X,q){if(X.is0(q))return q;if(C0(X,q)!==1)throw Error("Cannot find square root");let U=Q,D=X.mul(X.ONE,G),V=X.pow(q,$),O=X.pow(q,Z);while(!X.eql(V,X.ONE)){if(X.is0(V))return X.ZERO;let L=1,N=X.sqr(V);while(!X.eql(N,X.ONE))if(L++,N=X.sqr(N),L===U)throw Error("Cannot find square root");let b=n<<BigInt(U-L-1),y=X.pow(D,b);U=L,D=X.sqr(y),V=X.mul(V,D),O=X.mul(O,y)}return O}}function EQ(J){if(J%R0===yQ)return L0;if(J%P0===B0)return AQ;return wQ(J)}var xQ=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function N8(J){let $={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},Q=xQ.reduce((Y,M)=>{return Y[M]="function",Y},$);return gJ(J,Q)}function kQ(J,$,Q){if(Q<t)throw Error("invalid exponent, negatives unsupported");if(Q===t)return J.ONE;if(Q===n)return $;let Y=J.ONE,M=$;while(Q>t){if(Q&n)Y=J.mul(Y,M);M=J.sqr(M),Q>>=n}return Y}function O8(J,$,Q=!1){let Y=Array($.length).fill(Q?J.ZERO:void 0),M=$.reduce((Z,K,X)=>{if(J.is0(K))return Z;return Y[X]=Z,J.mul(Z,K)},J.ONE),G=J.inv(M);return $.reduceRight((Z,K,X)=>{if(J.is0(K))return Z;return Y[X]=J.mul(Z,Y[X]),J.mul(Z,K)},G),Y}function C0(J,$){let Q=(J.ORDER-n)/vJ,Y=J.pow($,Q),M=J.eql(Y,J.ONE),G=J.eql(Y,J.ZERO),Z=J.eql(Y,J.neg(J.ONE));if(!M&&!G&&!Z)throw Error("invalid Legendre symbol result");return M?1:G?0:-1}function C8(J,$){if($!==void 0)f$($);let Q=$!==void 0?$:J.toString(2).length,Y=Math.ceil(Q/8);return{nBitLength:Q,nByteLength:Y}}function P$(J,$,Q=!1,Y={}){if(J<=t)throw Error("invalid field: expected ORDER > 0, got "+J);let{nBitLength:M,nByteLength:G}=C8(J,$);if(G>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");let Z,K=Object.freeze({ORDER:J,isLE:Q,BITS:M,BYTES:G,MASK:fJ(M),ZERO:t,ONE:n,create:(X)=>d(X,J),isValid:(X)=>{if(typeof X!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof X);return t<=X&&X<J},is0:(X)=>X===t,isOdd:(X)=>(X&n)===n,neg:(X)=>d(-X,J),eql:(X,q)=>X===q,sqr:(X)=>d(X*X,J),add:(X,q)=>d(X+q,J),sub:(X,q)=>d(X-q,J),mul:(X,q)=>d(X*q,J),pow:(X,q)=>kQ(K,X,q),div:(X,q)=>d(X*u$(q,J),J),sqrN:(X)=>X*X,addN:(X,q)=>X+q,subN:(X,q)=>X-q,mulN:(X,q)=>X*q,inv:(X)=>u$(X,J),sqrt:Y.sqrt||((X)=>{if(!Z)Z=EQ(J);return Z(K,X)}),toBytes:(X)=>Q?D8(X,G):bJ(X,G),fromBytes:(X)=>{if(X.length!==G)throw Error("Field.fromBytes: expected "+G+" bytes, got "+X.length);return Q?z8(X):WJ(X)},invertBatch:(X)=>O8(K,X),cmov:(X,q,U)=>U?q:X});return Object.freeze(K)}function T0(J){if(typeof J!=="bigint")throw Error("field order must be bigint");let $=J.toString(2).length;return Math.ceil($/8)}function R8(J){let $=T0(J);return $+Math.ceil($/2)}function I0(J,$,Q=!1){let Y=J.length,M=T0($),G=R8($);if(Y<16||Y<G||Y>1024)throw Error("expected "+G+"-1024 bytes of input, got "+Y);let Z=Q?z8(J):WJ(J),K=d(Z,$-n)+n;return Q?D8(K,M):bJ(K,M)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var H0=BigInt(0),I8=BigInt(1);function B8(J,$){let Q=$.negate();return J?Q:$}function _0(J,$){if(!Number.isSafeInteger(J)||J<=0||J>$)throw Error("invalid window size, expected [1.."+$+"], got W="+J)}function P8(J,$){_0(J,$);let Q=Math.ceil($/J)+1,Y=2**(J-1),M=2**J,G=fJ(J),Z=BigInt(J);return{windows:Q,windowSize:Y,mask:G,maxNumber:M,shiftBy:Z}}function S0(J,$,Q){let{windowSize:Y,mask:M,maxNumber:G,shiftBy:Z}=Q,K=Number(J&M),X=J>>Z;if(K>Y)K-=G,X+=I8;let q=$*Y,U=q+Math.abs(K)-1,D=K===0,V=K<0,O=$%2!==0;return{nextN:X,offset:U,isZero:D,isNeg:V,isNegF:O,offsetF:q}}function bQ(J,$){if(!Array.isArray(J))throw Error("array expected");J.forEach((Q,Y)=>{if(!(Q instanceof $))throw Error("invalid point at index "+Y)})}function FQ(J,$){if(!Array.isArray(J))throw Error("array of scalars expected");J.forEach((Q,Y)=>{if(!$.isValid(Q))throw Error("invalid scalar at index "+Y)})}var L8=new WeakMap,y0=new WeakMap;function T8(J){return y0.get(J)||1}function A0(J,$){return{constTimeNegate:B8,hasPrecomputes(Q){return T8(Q)!==1},unsafeLadder(Q,Y,M=J.ZERO){let G=Q;while(Y>H0){if(Y&I8)M=M.add(G);G=G.double(),Y>>=I8}return M},precomputeWindow(Q,Y){let{windows:M,windowSize:G}=P8(Y,$),Z=[],K=Q,X=K;for(let q=0;q<M;q++){X=K,Z.push(X);for(let U=1;U<G;U++)X=X.add(K),Z.push(X);K=X.double()}return Z},wNAF(Q,Y,M){let{ZERO:G,BASE:Z}=J,K=P8(Q,$);for(let X=0;X<K.windows;X++){let{nextN:q,offset:U,isZero:D,isNeg:V,isNegF:O,offsetF:L}=S0(M,X,K);if(M=q,D)Z=Z.add(B8(O,Y[L]));else G=G.add(B8(V,Y[U]))}return{p:G,f:Z}},wNAFUnsafe(Q,Y,M,G=J.ZERO){let Z=P8(Q,$);for(let K=0;K<Z.windows;K++){if(M===H0)break;let{nextN:X,offset:q,isZero:U,isNeg:D}=S0(M,K,Z);if(M=X,U)continue;else{let V=Y[q];G=G.add(D?V.negate():V)}}return G},getPrecomputes(Q,Y,M){let G=L8.get(Y);if(!G){if(G=this.precomputeWindow(Y,Q),Q!==1)L8.set(Y,M(G))}return G},wNAFCached(Q,Y,M){let G=T8(Q);return this.wNAF(G,this.getPrecomputes(G,Q,M),Y)},wNAFCachedUnsafe(Q,Y,M,G){let Z=T8(Q);if(Z===1)return this.unsafeLadder(Q,Y,G);return this.wNAFUnsafe(Z,this.getPrecomputes(Z,Q,M),Y,G)},setWindowSize(Q,Y){_0(Y,$),y0.set(Q,Y),L8.delete(Q)}}}function w0(J,$,Q,Y){bQ(Q,J),FQ(Y,$);let M=Q.length,G=Y.length;if(M!==G)throw Error("arrays of points and scalars must have equal length");let Z=J.ZERO,K=N0(BigInt(M)),X=1;if(K>12)X=K-3;else if(K>4)X=K-2;else if(K>0)X=2;let q=fJ(X),U=Array(Number(q)+1).fill(Z),D=Math.floor(($.BITS-1)/X)*X,V=Z;for(let O=D;O>=0;O-=X){U.fill(Z);for(let N=0;N<G;N++){let b=Y[N],y=Number(b>>BigInt(O)&q);U[y]=U[y].add(Q[N])}let L=Z;for(let N=U.length-1,b=Z;N>0;N--)b=b.add(U[N]),L=L.add(b);if(V=V.add(L),O!==0)for(let N=0;N<X;N++)V=V.double()}return V}function H8(J){return N8(J.Fp),gJ(J,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...C8(J.n,J.nBitLength),...J,...{p:J.Fp.ORDER}})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function E0(J){if(J.lowS!==void 0)sJ("lowS",J.lowS);if(J.prehash!==void 0)sJ("prehash",J.prehash)}function fQ(J){let $=H8(J);gJ($,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:Q,Fp:Y,a:M}=$;if(Q){if(!Y.eql(M,Y.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 x0 extends Error{constructor(J=""){super(J)}}var jJ={Err:x0,_tlv:{encode:(J,$)=>{let{Err:Q}=jJ;if(J<0||J>256)throw new Q("tlv.encode: wrong tag");if($.length&1)throw new Q("tlv.encode: unpadded data");let Y=$.length/2,M=C$(Y);if(M.length/2&128)throw new Q("tlv.encode: long form length too big");let G=Y>127?C$(M.length/2|128):"";return C$(J)+G+M+$},decode(J,$){let{Err:Q}=jJ,Y=0;if(J<0||J>256)throw new Q("tlv.encode: wrong tag");if($.length<2||$[Y++]!==J)throw new Q("tlv.decode: wrong tlv");let M=$[Y++],G=!!(M&128),Z=0;if(!G)Z=M;else{let X=M&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 q=$.subarray(Y,Y+X);if(q.length!==X)throw new Q("tlv.decode: length bytes not complete");if(q[0]===0)throw new Q("tlv.decode(long): zero leftmost byte");for(let U of q)Z=Z<<8|U;if(Y+=X,Z<128)throw new Q("tlv.decode(long): not minimal encoding")}let K=$.subarray(Y,Y+Z);if(K.length!==Z)throw new Q("tlv.decode: wrong value length");return{v:K,l:$.subarray(Y+Z)}}},_int:{encode(J){let{Err:$}=jJ;if(J<zJ)throw new $("integer: negative integers are not allowed");let Q=C$(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:$}=jJ;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 WJ(J)}},toSig(J){let{Err:$,_int:Q,_tlv:Y}=jJ,M=s("signature",J),{v:G,l:Z}=Y.decode(48,M);if(Z.length)throw new $("invalid signature: left bytes after parsing");let{v:K,l:X}=Y.decode(2,G),{v:q,l:U}=Y.decode(2,X);if(U.length)throw new $("invalid signature: left bytes after parsing");return{r:Q.decode(K),s:Q.decode(q)}},hexFromSig(J){let{_tlv:$,_int:Q}=jJ,Y=$.encode(2,Q.encode(J.r)),M=$.encode(2,Q.encode(J.s)),G=Y+M;return $.encode(48,G)}};function S8(J,$){return rJ(bJ(J,$))}var zJ=BigInt(0),h=BigInt(1),hG=BigInt(2),_8=BigInt(3),gQ=BigInt(4);function vQ(J){let $=fQ(J),{Fp:Q}=$,Y=P$($.n,$.nBitLength),M=$.toBytes||((W,j,B)=>{let P=j.toAffine();return B$(Uint8Array.from([4]),Q.toBytes(P.x),Q.toBytes(P.y))}),G=$.fromBytes||((W)=>{let j=W.subarray(1),B=Q.fromBytes(j.subarray(0,Q.BYTES)),P=Q.fromBytes(j.subarray(Q.BYTES,2*Q.BYTES));return{x:B,y:P}});function Z(W){let{a:j,b:B}=$,P=Q.sqr(W),E=Q.mul(P,W);return Q.add(Q.add(E,Q.mul(W,j)),B)}function K(W,j){let B=Q.sqr(j),P=Z(W);return Q.eql(B,P)}if(!K($.Gx,$.Gy))throw Error("bad curve params: generator point");let X=Q.mul(Q.pow($.a,_8),gQ),q=Q.mul(Q.sqr($.b),BigInt(27));if(Q.is0(Q.add(X,q)))throw Error("bad curve params: a or b");function U(W){return v$(W,h,$.n)}function D(W){let{allowedPrivateKeyLengths:j,nByteLength:B,wrapPrivateKey:P,n:E}=$;if(j&&typeof W!=="bigint"){if(aJ(W))W=rJ(W);if(typeof W!=="string"||!j.includes(W.length))throw Error("invalid private key");W=W.padStart(B*2,"0")}let x;try{x=typeof W==="bigint"?W:WJ(s("private key",W,B))}catch(k){throw Error("invalid private key, expected hex or "+B+" bytes, got "+typeof W)}if(P)x=d(x,E);return FJ("private key",x,h,E),x}function V(W){if(!(W instanceof N))throw Error("ProjectivePoint expected")}let O=V8((W,j)=>{let{px:B,py:P,pz:E}=W;if(Q.eql(E,Q.ONE))return{x:B,y:P};let x=W.is0();if(j==null)j=x?Q.ONE:Q.inv(E);let k=Q.mul(B,j),S=Q.mul(P,j),A=Q.mul(E,j);if(x)return{x:Q.ZERO,y:Q.ZERO};if(!Q.eql(A,Q.ONE))throw Error("invZ was invalid");return{x:k,y:S}}),L=V8((W)=>{if(W.is0()){if($.allowInfinityPoint&&!Q.is0(W.py))return;throw Error("bad point: ZERO")}let{x:j,y:B}=W.toAffine();if(!Q.isValid(j)||!Q.isValid(B))throw Error("bad point: x or y not FE");if(!K(j,B))throw Error("bad point: equation left != right");if(!W.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});class N{constructor(W,j,B){if(W==null||!Q.isValid(W))throw Error("x required");if(j==null||!Q.isValid(j)||Q.is0(j))throw Error("y required");if(B==null||!Q.isValid(B))throw Error("z required");this.px=W,this.py=j,this.pz=B,Object.freeze(this)}static fromAffine(W){let{x:j,y:B}=W||{};if(!W||!Q.isValid(j)||!Q.isValid(B))throw Error("invalid affine point");if(W instanceof N)throw Error("projective point not allowed");let P=(E)=>Q.eql(E,Q.ZERO);if(P(j)&&P(B))return N.ZERO;return new N(j,B,Q.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(W){let j=O8(Q,W.map((B)=>B.pz));return W.map((B,P)=>B.toAffine(j[P])).map(N.fromAffine)}static fromHex(W){let j=N.fromAffine(G(s("pointHex",W)));return j.assertValidity(),j}static fromPrivateKey(W){return N.BASE.multiply(D(W))}static msm(W,j){return w0(N,Y,W,j)}_setWindowSize(W){f.setWindowSize(this,W)}assertValidity(){L(this)}hasEvenY(){let{y:W}=this.toAffine();if(Q.isOdd)return!Q.isOdd(W);throw Error("Field doesn't support isOdd")}equals(W){V(W);let{px:j,py:B,pz:P}=this,{px:E,py:x,pz:k}=W,S=Q.eql(Q.mul(j,k),Q.mul(E,P)),A=Q.eql(Q.mul(B,k),Q.mul(x,P));return S&&A}negate(){return new N(this.px,Q.neg(this.py),this.pz)}double(){let{a:W,b:j}=$,B=Q.mul(j,_8),{px:P,py:E,pz:x}=this,k=Q.ZERO,S=Q.ZERO,A=Q.ZERO,_=Q.mul(P,P),l=Q.mul(E,E),u=Q.mul(x,x),z=Q.mul(P,E);return z=Q.add(z,z),A=Q.mul(P,x),A=Q.add(A,A),k=Q.mul(W,A),S=Q.mul(B,u),S=Q.add(k,S),k=Q.sub(l,S),S=Q.add(l,S),S=Q.mul(k,S),k=Q.mul(z,k),A=Q.mul(B,A),u=Q.mul(W,u),z=Q.sub(_,u),z=Q.mul(W,z),z=Q.add(z,A),A=Q.add(_,_),_=Q.add(A,_),_=Q.add(_,u),_=Q.mul(_,z),S=Q.add(S,_),u=Q.mul(E,x),u=Q.add(u,u),_=Q.mul(u,z),k=Q.sub(k,_),A=Q.mul(u,l),A=Q.add(A,A),A=Q.add(A,A),new N(k,S,A)}add(W){V(W);let{px:j,py:B,pz:P}=this,{px:E,py:x,pz:k}=W,S=Q.ZERO,A=Q.ZERO,_=Q.ZERO,l=$.a,u=Q.mul($.b,_8),z=Q.mul(j,E),R=Q.mul(B,x),T=Q.mul(P,k),F=Q.add(j,B),I=Q.add(E,x);F=Q.mul(F,I),I=Q.add(z,R),F=Q.sub(F,I),I=Q.add(j,P);let w=Q.add(E,k);return I=Q.mul(I,w),w=Q.add(z,T),I=Q.sub(I,w),w=Q.add(B,P),S=Q.add(x,k),w=Q.mul(w,S),S=Q.add(R,T),w=Q.sub(w,S),_=Q.mul(l,I),S=Q.mul(u,T),_=Q.add(S,_),S=Q.sub(R,_),_=Q.add(R,_),A=Q.mul(S,_),R=Q.add(z,z),R=Q.add(R,z),T=Q.mul(l,T),I=Q.mul(u,I),R=Q.add(R,T),T=Q.sub(z,T),T=Q.mul(l,T),I=Q.add(I,T),z=Q.mul(R,I),A=Q.add(A,z),z=Q.mul(w,I),S=Q.mul(F,S),S=Q.sub(S,z),z=Q.mul(F,R),_=Q.mul(w,_),_=Q.add(_,z),new N(S,A,_)}subtract(W){return this.add(W.negate())}is0(){return this.equals(N.ZERO)}wNAF(W){return f.wNAFCached(this,W,N.normalizeZ)}multiplyUnsafe(W){let{endo:j,n:B}=$;FJ("scalar",W,zJ,B);let P=N.ZERO;if(W===zJ)return P;if(this.is0()||W===h)return this;if(!j||f.hasPrecomputes(this))return f.wNAFCachedUnsafe(this,W,N.normalizeZ);let{k1neg:E,k1:x,k2neg:k,k2:S}=j.splitScalar(W),A=P,_=P,l=this;while(x>zJ||S>zJ){if(x&h)A=A.add(l);if(S&h)_=_.add(l);l=l.double(),x>>=h,S>>=h}if(E)A=A.negate();if(k)_=_.negate();return _=new N(Q.mul(_.px,j.beta),_.py,_.pz),A.add(_)}multiply(W){let{endo:j,n:B}=$;FJ("scalar",W,h,B);let P,E;if(j){let{k1neg:x,k1:k,k2neg:S,k2:A}=j.splitScalar(W),{p:_,f:l}=this.wNAF(k),{p:u,f:z}=this.wNAF(A);_=f.constTimeNegate(x,_),u=f.constTimeNegate(S,u),u=new N(Q.mul(u.px,j.beta),u.py,u.pz),P=_.add(u),E=l.add(z)}else{let{p:x,f:k}=this.wNAF(W);P=x,E=k}return N.normalizeZ([P,E])[0]}multiplyAndAddUnsafe(W,j,B){let P=N.BASE,E=(k,S)=>S===zJ||S===h||!k.equals(P)?k.multiplyUnsafe(S):k.multiply(S),x=E(this,j).add(E(W,B));return x.is0()?void 0:x}toAffine(W){return O(this,W)}isTorsionFree(){let{h:W,isTorsionFree:j}=$;if(W===h)return!0;if(j)return j(N,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:W,clearCofactor:j}=$;if(W===h)return this;if(j)return j(N,this);return this.multiplyUnsafe($.h)}toRawBytes(W=!0){return sJ("isCompressed",W),this.assertValidity(),M(N,this,W)}toHex(W=!0){return sJ("isCompressed",W),rJ(this.toRawBytes(W))}}N.BASE=new N($.Gx,$.Gy,Q.ONE),N.ZERO=new N(Q.ZERO,Q.ONE,Q.ZERO);let{endo:b,nBitLength:y}=$,f=A0(N,b?Math.ceil(y/2):y);return{CURVE:$,ProjectivePoint:N,normPrivateKeyToScalar:D,weierstrassEquation:Z,isWithinCurveOrder:U}}function uQ(J){let $=H8(J);return gJ($,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...$})}function k0(J){let $=uQ(J),{Fp:Q,n:Y,nByteLength:M,nBitLength:G}=$,Z=Q.BYTES+1,K=2*Q.BYTES+1;function X(z){return d(z,Y)}function q(z){return u$(z,Y)}let{ProjectivePoint:U,normPrivateKeyToScalar:D,weierstrassEquation:V,isWithinCurveOrder:O}=vQ({...$,toBytes(z,R,T){let F=R.toAffine(),I=Q.toBytes(F.x),w=B$;if(sJ("isCompressed",T),T)return w(Uint8Array.from([R.hasEvenY()?2:3]),I);else return w(Uint8Array.from([4]),I,Q.toBytes(F.y))},fromBytes(z){let R=z.length,T=z[0],F=z.subarray(1);if(R===Z&&(T===2||T===3)){let I=WJ(F);if(!v$(I,h,Q.ORDER))throw Error("Point is not on curve");let w=V(I),$J;try{$J=Q.sqrt(w)}catch(MJ){let a=MJ instanceof Error?": "+MJ.message:"";throw Error("Point is not on curve"+a)}let i=($J&h)===h;if((T&1)===1!==i)$J=Q.neg($J);return{x:I,y:$J}}else if(R===K&&T===4){let I=Q.fromBytes(F.subarray(0,Q.BYTES)),w=Q.fromBytes(F.subarray(Q.BYTES,2*Q.BYTES));return{x:I,y:w}}else{let I=Z,w=K;throw Error("invalid Point, expected length of "+I+", or uncompressed "+w+", got "+R)}}});function L(z){let R=Y>>h;return z>R}function N(z){return L(z)?X(-z):z}let b=(z,R,T)=>WJ(z.slice(R,T));class y{constructor(z,R,T){if(FJ("r",z,h,Y),FJ("s",R,h,Y),this.r=z,this.s=R,T!=null)this.recovery=T;Object.freeze(this)}static fromCompact(z){let R=M;return z=s("compactSignature",z,R*2),new y(b(z,0,R),b(z,R,2*R))}static fromDER(z){let{r:R,s:T}=jJ.toSig(s("DER",z));return new y(R,T)}assertValidity(){}addRecoveryBit(z){return new y(this.r,this.s,z)}recoverPublicKey(z){let{r:R,s:T,recovery:F}=this,I=E(s("msgHash",z));if(F==null||![0,1,2,3].includes(F))throw Error("recovery id invalid");let w=F===2||F===3?R+$.n:R;if(w>=Q.ORDER)throw Error("recovery id 2 or 3 invalid");let $J=(F&1)===0?"02":"03",i=U.fromHex($J+S8(w,Q.BYTES)),YJ=q(w),MJ=X(-I*YJ),a=X(T*YJ),DJ=U.BASE.multiplyAndAddUnsafe(i,MJ,a);if(!DJ)throw Error("point at infinify");return DJ.assertValidity(),DJ}hasHighS(){return L(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,X(-this.s),this.recovery):this}toDERRawBytes(){return R$(this.toDERHex())}toDERHex(){return jJ.hexFromSig(this)}toCompactRawBytes(){return R$(this.toCompactHex())}toCompactHex(){let z=M;return S8(this.r,z)+S8(this.s,z)}}let f={isValidPrivateKey(z){try{return D(z),!0}catch(R){return!1}},normPrivateKeyToScalar:D,randomPrivateKey:()=>{let z=R8($.n);return I0($.randomBytes(z),$.n)},precompute(z=8,R=U.BASE){return R._setWindowSize(z),R.multiply(BigInt(3)),R}};function W(z,R=!0){return U.fromPrivateKey(z).toRawBytes(R)}function j(z){if(typeof z==="bigint")return!1;if(z instanceof U)return!0;let T=s("key",z).length,F=Q.BYTES,I=F+1,w=2*F+1;if($.allowedPrivateKeyLengths||M===I)return;else return T===I||T===w}function B(z,R,T=!0){if(j(z)===!0)throw Error("first arg must be private key");if(j(R)===!1)throw Error("second arg must be public key");return U.fromHex(R).multiply(D(z)).toRawBytes(T)}let P=$.bits2int||function(z){if(z.length>8192)throw Error("input is too large");let R=WJ(z),T=z.length*8-G;return T>0?R>>BigInt(T):R},E=$.bits2int_modN||function(z){return X(P(z))},x=fJ(G);function k(z){return FJ("num < 2^"+G,z,zJ,x),bJ(z,M)}function S(z,R,T=A){if(["recovered","canonical"].some((PJ)=>(PJ in T)))throw Error("sign() legacy options not supported");let{hash:F,randomBytes:I}=$,{lowS:w,prehash:$J,extraEntropy:i}=T;if(w==null)w=!0;if(z=s("msgHash",z),E0(T),$J)z=s("prehashed msgHash",F(z));let YJ=E(z),MJ=D(R),a=[k(MJ),k(YJ)];if(i!=null&&i!==!1){let PJ=i===!0?I(Q.BYTES):i;a.push(s("extraEntropy",PJ))}let DJ=B$(...a),T$=YJ;function l$(PJ){let mJ=P(PJ);if(!O(mJ))return;let c$=q(mJ),J$=U.BASE.multiply(mJ).toAffine(),LJ=X(J$.x);if(LJ===zJ)return;let $$=X(c$*X(T$+LJ*MJ));if($$===zJ)return;let hJ=(J$.x===LJ?0:2)|Number(J$.y&h),F8=$$;if(w&&L($$))F8=N($$),hJ^=1;return new y(LJ,F8,hJ)}return{seed:DJ,k2sig:l$}}let A={lowS:$.lowS,prehash:!1},_={lowS:$.lowS,prehash:!1};function l(z,R,T=A){let{seed:F,k2sig:I}=S(z,R,T),w=$;return O0(w.hash.outputLen,w.nByteLength,w.hmac)(F,I)}U.BASE._setWindowSize(8);function u(z,R,T,F=_){let I=z;R=s("msgHash",R),T=s("publicKey",T);let{lowS:w,prehash:$J,format:i}=F;if(E0(F),"strict"in F)throw Error("options.strict was renamed to lowS");if(i!==void 0&&i!=="compact"&&i!=="der")throw Error("format must be compact or der");let YJ=typeof I==="string"||aJ(I),MJ=!YJ&&!i&&typeof I==="object"&&I!==null&&typeof I.r==="bigint"&&typeof I.s==="bigint";if(!YJ&&!MJ)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");let a=void 0,DJ;try{if(MJ)a=new y(I.r,I.s);if(YJ){try{if(i!=="compact")a=y.fromDER(I)}catch(hJ){if(!(hJ instanceof jJ.Err))throw hJ}if(!a&&i!=="der")a=y.fromCompact(I)}DJ=U.fromHex(T)}catch(hJ){return!1}if(!a)return!1;if(w&&a.hasHighS())return!1;if($J)R=$.hash(R);let{r:T$,s:l$}=a,PJ=E(R),mJ=q(l$),c$=X(PJ*mJ),J$=X(T$*mJ),LJ=U.BASE.multiplyAndAddUnsafe(DJ,c$,J$)?.toAffine();if(!LJ)return!1;return X(LJ.x)===T$}return{CURVE:$,getPublicKey:W,getSharedSecret:B,sign:l,verify:u,ProjectivePoint:U,Signature:y,utils:f}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function mQ(J){return{hash:J,hmac:($,...Q)=>X8(J,$,G0(...Q)),randomBytes:X0}}function b0(J,$){let Q=(Y)=>k0({...J,...mQ(Y)});return{...Q($),create:Q}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var g0=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),F0=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),hQ=BigInt(0),lQ=BigInt(1),y8=BigInt(2),f0=(J,$)=>(J+$/y8)/$;function cQ(J){let $=g0,Q=BigInt(3),Y=BigInt(6),M=BigInt(11),G=BigInt(22),Z=BigInt(23),K=BigInt(44),X=BigInt(88),q=J*J*J%$,U=q*q*J%$,D=e(U,Q,$)*U%$,V=e(D,Q,$)*U%$,O=e(V,y8,$)*q%$,L=e(O,M,$)*O%$,N=e(L,G,$)*L%$,b=e(N,K,$)*N%$,y=e(b,X,$)*b%$,f=e(y,K,$)*N%$,W=e(f,Q,$)*U%$,j=e(W,Z,$)*L%$,B=e(j,Y,$)*q%$,P=e(B,y8,$);if(!A8.eql(A8.sqr(P),J))throw Error("Cannot find square root");return P}var A8=P$(g0,void 0,void 0,{sqrt:cQ}),w8=b0({a:hQ,b:BigInt(7),Fp:A8,n:F0,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:(J)=>{let $=F0,Q=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),Y=-lQ*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),M=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),G=Q,Z=BigInt("0x100000000000000000000000000000000"),K=f0(G*J,$),X=f0(-Y*J,$),q=d(J-K*Q-X*M,$),U=d(-K*Y-X*G,$),D=q>Z,V=U>Z;if(D)q=$-q;if(V)U=$-U;if(q>Z||U>Z)throw Error("splitScalar: Endomorphism failed, k="+J);return{k1neg:D,k1:q,k2neg:V,k2:U}}}},W0);function m$(){let J=w8.utils.randomPrivateKey();return"0x"+Buffer.from(J).toString("hex")}function eJ(J){let $=J.startsWith("0x")?J.slice(2):J,Q=Buffer.from($,"hex"),Y=w8.getPublicKey(Q,!1),G=cJ(Y.slice(1)).slice(-20),Z="0x"+Buffer.from(G).toString("hex");return OJ(Z)}function h$(J){let $;if(typeof J==="string"){let Y=J.startsWith("0x")?J.slice(2):J;$=Buffer.from(Y,"hex")}else $=J;let Q=cJ($);return"0x"+Buffer.from(Q).toString("hex")}class o extends V${httpStatus;constructor(J,$){super("ReferralError",J,{...$,source:$?.source||"REFERRALS"});this.httpStatus=$?.httpStatus}static notFoundOnChain(J){return new o(`Referral not found on-chain for signer ${J}`,{code:"REFERRAL_NOT_FOUND_ONCHAIN",source:"ONCHAIN",httpStatus:404,context:{signer:J}})}static alreadyClaimed(J){return new o(`Referral for signer ${J} has already been claimed`,{code:"REFERRAL_ALREADY_CLAIMED",source:"ONCHAIN",httpStatus:410,context:{signer:J}})}static storeFailed(J){return new o(`Failed to store referral: ${J}`,{code:"REFERRAL_STORE_FAILED"})}static storeBatchFailed(J){return new o(`Failed to store referral batch: ${J}`,{code:"REFERRAL_STORE_BATCH_FAILED"})}static retrieveFailed(J,$){return new o(`Failed to retrieve referral: ${J}`,{code:"REFERRAL_RETRIEVE_FAILED",httpStatus:$})}static listFailed(J){return new o(`Failed to list referrals: ${J}`,{code:"REFERRAL_LIST_FAILED"})}static authRequired(){return new o("Authentication required to list referrals",{code:"REFERRAL_AUTH_REQUIRED",source:"VALIDATION"})}}class v extends V${constructor(J,$){super("InvitationError",J,{...$,source:$?.source||"INVITATIONS"})}static noPathFound(J,$,Q){return new v(`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 v(`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,Y,M,G){let Z=Number(Q)/1000000000000000000,K=Number(Y)/1000000000000000000;return new v(`Insufficient balance for ${J} invitation(s). Can only afford ${$} invitation(s). Requested: ${Z.toFixed(6)} CRC, Available: ${K.toFixed(6)} CRC.`,{code:"INVITATION_INSUFFICIENT_BALANCE",source:"VALIDATION",context:{from:M,to:G,requestedInvites:J,availableInvites:$,requested:Q.toString(),available:Y.toString(),requestedCrc:Z,availableCrc:K}})}static inviteeAlreadyRegistered(J,$){return new v(`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 v("At least one address must be provided for invitation.",{code:"INVITATION_NO_ADDRESSES_PROVIDED",source:"VALIDATION"})}}var v0=[];for(let J=0;J<256;J++)v0[J]=J.toString(16).padStart(2,"0");function L$(J){let $="0x";for(let Q=0;Q<J.length;Q++)$+=v0[J[Q]];return $}function u0(J){let $=new Uint8Array(J.length*2);return J.forEach((Q,Y)=>{let M=Q>>8,G=Q&255,Z=2*Y;$[Z]=M,$[Z+1]=G}),L$($)}function m0(J,$,Q){let Y=new Set([$.toLowerCase(),Q.toLowerCase()]);J.forEach((Z)=>{Y.add(Z.from.toLowerCase()),Y.add(Z.to.toLowerCase()),Y.add(Z.tokenOwner.toLowerCase())});let M=[...Y].sort((Z,K)=>{let X=BigInt(Z),q=BigInt(K),U=X<q,D=X>q;return U?-1:D?1:0}),G={};return M.forEach((Z,K)=>{G[Z]=K}),{sorted:M,idx:G}}function pQ(J,$){let Q=new Set,Y=[],M=null;if(J.forEach((G,Z)=>{let K=G.from.toLowerCase(),X=G.to.toLowerCase();if(K===$&&X===$)M=Z;else if(X===$)Y.push(Z)}),M!==null)Q.add(M);else Y.forEach((G)=>Q.add(G));return Q}function h0(J,$,Q,Y){let M=J.toLowerCase(),G=$.toLowerCase(),{sorted:Z,idx:K}=m0(Y,M,G),X=pQ(Y,G),q=Y.map((y,f)=>{return{streamSinkId:X.has(f)?1:0,amount:y.value}});if(X.size===0)throw Error(`No terminal edges detected. Flow must have at least one edge delivering to receiver ${G}`);let U=Array.from(X),D=[{sourceCoordinate:K[M],flowEdgeIds:U,data:new Uint8Array(0)}],V=[];Y.forEach((y)=>{V.push(K[y.tokenOwner.toLowerCase()]),V.push(K[y.from.toLowerCase()]),V.push(K[y.to.toLowerCase()])});let O=u0(V),L=BigInt(Q),N=q.filter((y)=>y.streamSinkId===1).reduce((y,f)=>y+BigInt(f.amount.toString()),BigInt(0));if(N!==L)throw Error(`Terminal sum ${N} does not equal expected ${L}`);return{flowVertices:Z,flowEdges:q,streams:D,packedCoordinates:O,sourceCoordinate:K[M]}}function l0(J,$){let Q=J.streams.map((Y)=>({sourceCoordinate:Y.sourceCoordinate,flowEdgeIds:Y.flowEdgeIds,data:Y.data instanceof Uint8Array?L$(Y.data):Y.data}));if($&&Q.length>0)Q[0].data=$ instanceof Uint8Array?L$($):$;return Q}async function c0(J,$,Q){let Y=new Map,M=new Set;return Q.transfers.forEach((K)=>{if(J.toLowerCase()===K.from.toLowerCase())M.add(K.tokenOwner.toLowerCase())}),(await new x$($).token.getTokenInfoBatch(Array.from(M))).forEach((K)=>{if(K.isWrapped&&!K.isInflationary)K.tokenType="CrcV2_ERC20WrapperDeployed_Demurraged";Y.set(K.tokenAddress.toLowerCase(),K)}),Y}function p0(J,$){let Q={};return J.transfers.forEach((Y)=>{let M=$.get(Y.tokenOwner.toLowerCase());if(M&&M.tokenType.startsWith("CrcV2_ERC20WrapperDeployed")){if(!Q[Y.tokenOwner])Q[Y.tokenOwner]=[BigInt(0),M.tokenType];Q[Y.tokenOwner][0]+=BigInt(Y.value)}}),Q}function d0(J,$){let Q=J.transfers.map((Y)=>{let M=$.get(Y.tokenOwner.toLowerCase());if(M&&M.tokenType.startsWith("CrcV2_ERC20WrapperDeployed"))return{...Y,tokenOwner:M.tokenOwner};return Y});return{...J,transfers:Q}}class JJ extends Y${constructor(J,$){super("TransferError",J,{...$,source:$?.source||"TRANSFERS"})}static noPathFound(J,$,Q){return new JJ(`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,Y){let M=Number(J)/1000000000000000000,G=Number($)/1000000000000000000;return new JJ(`Insufficient balance for transfer. Requested: ${M.toFixed(6)} CRC, Available: ${G.toFixed(6)} CRC.`,{code:"TRANSFER_INSUFFICIENT_BALANCE",source:"VALIDATION",context:{from:Q,to:Y,requested:J.toString(),available:$.toString(),requestedCrc:M,availableCrc:G}})}static wrappedTokensRequired(){return new JJ("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 JJ(`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 JJ(`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 JJ(`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 CJ({address:J.v2HubAddress,rpcUrl:J.circlesRpcUrl}),this.liftERC20=new k$({address:J.liftERC20Address,rpcUrl:J.circlesRpcUrl}),this.rpcClient=new VJ(J.circlesRpcUrl),this.pathfinder=new KJ(this.rpcClient),this.balance=new yJ(this.rpcClient),this.group=new wJ(this.rpcClient)}async buildFlowMatrixTx(J,$,Q,Y,M=!1){let G=J.toLowerCase(),Z=$.toLowerCase();if(!Q.transfers||Q.transfers.length===0)throw JJ.noPathFound(G,Z);let K={...Q};if(M&&Y?.toTokens?.length===1){let f=Y.toTokens[0].toLowerCase();if(Q.maxFlow>0n)K.transfers.push({from:Z,to:Z,tokenOwner:f,value:Q.maxFlow})}let X=await c0(G,this.config.circlesRpcUrl,K),q=p0(K,X),U=Object.keys(q).length>0;if(U&&!Y?.useWrappedBalances)throw JJ.wrappedTokensRequired();let D=[],V=[];if(U){let f=await this._getTokenBalanceMap(G),W=this._createDemurragedUnwrapCalls(q),{unwrapCalls:j,wrapCalls:B}=this._createInflationaryUnwrapAndWrapCalls(q,X,f);D=[...W,...j],V=B,K=d0(K,X)}let O=h0(G,Z,K.maxFlow,K.transfers),L=l0(O,Y?.txData),N=this.hubV2.operateFlowMatrix(O.flowVertices,O.flowEdges,L,O.packedCoordinates),b=!1;try{b=await this.hubV2.isApprovedForAll(G,G)}catch(f){console.warn("Failed to check approval status, including approval transaction:",f)}return[...b?[]:[this.hubV2.setApprovalForAll(G,!0)],...D,N,...V]}async constructAdvancedTransfer(J,$,Q,Y,M=!1){let G=J.toLowerCase(),Z=$.toLowerCase(),K=BigInt(Q);if(G===Z&&Y?.fromTokens?.length===1&&Y?.toTokens?.length===1){let O=Y.fromTokens[0],L=Y.toTokens[0],[N,b]=await Promise.all([this.liftERC20.erc20Circles(0,L),this.liftERC20.erc20Circles(1,L)]);if(O.toLowerCase()===N.toLowerCase()&&N!==IJ){let f=new z$({address:O,rpcUrl:this.config.circlesRpcUrl}).unwrap(K);return[{to:f.to,data:f.data,value:f.value??0n}]}if(O.toLowerCase()===b.toLowerCase()&&b!==IJ){let y=new D$({address:O,rpcUrl:this.config.circlesRpcUrl}),f=nJ.attoCirclesToAttoStaticCircles(K),W=y.unwrap(f);return[{to:W.to,data:W.data,value:W.value??0n}]}}let X=this._truncateToSixDecimals(K),q=await this._getDefaultTokenExcludeList(Z,Y?.excludeFromTokens),{...U}=Y||{},D={...U,...q?{excludeFromTokens:q}:{}},V=await this.pathfinder.findPath({from:G,to:Z,targetFlow:X,...D});if(!V.transfers||V.transfers.length===0)throw JJ.noPathFound(G,Z);if(V.maxFlow<X)throw JJ.insufficientBalance(X,V.maxFlow,G,Z);return this.buildFlowMatrixTx(G,Z,V,Y,M)}async _getTokenBalanceMap(J){let $=await this.balance.getTokenBalances(J),Q=new Map;return $.forEach((Y)=>{Q.set(Y.tokenAddress.toLowerCase(),Y.staticAttoCircles)}),Q}_createDemurragedUnwrapCalls(J){let $=[];for(let[Q,[Y,M]]of Object.entries(J)){if(M!=="CrcV2_ERC20WrapperDeployed_Demurraged")continue;let Z=new z$({address:Q,rpcUrl:this.config.circlesRpcUrl}).unwrap(Y);$.push({to:Z.to,data:Z.data,value:Z.value??0n})}return $}_createInflationaryUnwrapAndWrapCalls(J,$,Q){let Y=[],M=[];for(let[G,[Z,K]]of Object.entries(J)){if(K!=="CrcV2_ERC20WrapperDeployed_Inflationary")continue;let X=$.get(G.toLowerCase()),q=Q.get(G.toLowerCase())||0n;if(q===0n)continue;let D=new D$({address:G,rpcUrl:this.config.circlesRpcUrl}).unwrap(q);Y.push({to:D.to,data:D.data,value:D.value??0n});let V=X?.tokenOwner,O=nJ.attoStaticCirclesToAttoCircles(q)-Z;if(O>0n){let L=this.hubV2.wrap(V,O,1);M.push({to:L.to,data:L.data,value:L.value??0n})}}return{unwrapCalls:Y,wrapCalls:M}}_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}),Y=new Set;if(Q.results.length>0){let M=Q.results[0];if(Y.add(M.group.toLowerCase()),M.erc20WrapperDemurraged)Y.add(M.erc20WrapperDemurraged.toLowerCase());if(M.erc20WrapperStatic)Y.add(M.erc20WrapperStatic.toLowerCase())}if($?.forEach((M)=>Y.add(M.toLowerCase())),Y.size===0)return;return Array.from(Y)}}var n0=dJ;class E8{config;rpcClient;pathfinder;trust;token;hubV2;referralsModule;invitationFarm;invitationModuleContract;constructor(J){if(!J.referralsServiceUrl)throw new v("referralsServiceUrl is required in config",{code:"INVITATION_MISSING_CONFIG",source:"INVITATIONS",context:{missingField:"referralsServiceUrl"}});this.config=J,this.rpcClient=new VJ(J.circlesRpcUrl),this.pathfinder=new KJ(this.rpcClient),this.trust=new _J(this.rpcClient),this.token=new AJ(this.rpcClient),this.hubV2=new CJ({address:J.v2HubAddress,rpcUrl:J.circlesRpcUrl}),this.referralsModule=new iJ({address:J.referralsModuleAddress,rpcUrl:J.circlesRpcUrl}),this.invitationFarm=new tJ({address:J.invitationFarmAddress,rpcUrl:J.circlesRpcUrl}),this.invitationModuleContract=new F$({address:J.invitationModuleAddress,rpcUrl:J.circlesRpcUrl})}async ensureInviterSetup(J){let $=J.toLowerCase(),Q=this.config.invitationModuleAddress,Y=[],M=new b$({address:$,rpcUrl:this.config.circlesRpcUrl});if(!await M.isModuleEnabled(Q))Y.push(M.enableModule(Q)),Y.push(this.invitationModuleContract.trustInviter($));else if(!await this.hubV2.isTrusted(Q,$))Y.push(this.invitationModuleContract.trustInviter($));return Y}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 v(`HTTP error! status: ${Q.status}`,{code:"INVITATION_HTTP_ERROR",source:"INVITATIONS",context:{status:Q.status,url:`${this.config.referralsServiceUrl}/store`}})}catch(Q){throw new v(`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 Y=new URL(`${this.config.referralsServiceUrl}/list/${J}`);Y.searchParams.set("limit",String($)),Y.searchParams.set("offset",String(Q));let M=await fetch(Y.toString(),{method:"GET",headers:{accept:"application/json"}});if(!M.ok)throw new v(`HTTP error! status: ${M.status}`,{code:"INVITATION_HTTP_ERROR",source:"INVITATIONS",context:{status:M.status,url:Y.toString()}});return await M.json()}catch(Y){if(Y instanceof v)throw Y;throw new v(`Failed to list referrals: ${Y instanceof Error?Y.message:"Unknown error"}`,{code:"INVITATION_LIST_REFERRALS_FAILED",source:"INVITATIONS",cause:Y})}}orderRealInviters(J,$){let Q=$.toLowerCase();return J.sort((Y,M)=>{let G=Y.address.toLowerCase()===Q,Z=M.address.toLowerCase()===Q;if(G&&!Z)return-1;if(!G&&Z)return 1;return 0})}async generateInvite(J,$){let Q=J.toLowerCase(),Y=$.toLowerCase();if(await this.hubV2.isHuman(Y))throw v.inviteeAlreadyRegistered(Q,Y);let G=await this.ensureInviterSetup(Q),Z=await this.getRealInviters(Q),K=[...G];if(Z.length>0){console.log("[generateInvite] Using STANDARD PATH (proxy inviters available)");let X=Z[0].address,q=await this.findInvitePath(Q,X),U=await this.generateInviteData([Y],!1),V=await new uJ(this.config).buildFlowMatrixTx(Q,this.config.invitationModuleAddress,q,{toTokens:[X],useWrappedBalances:!0,txData:y$(U)},!0);K.push(...V)}else{console.log("[generateInvite] Using FARM FALLBACK PATH (no proxy inviters available)");let X=new uJ(this.config),q=await this.findFarmInvitePath(Q),U=await X.buildFlowMatrixTx(Q,HJ,q,{toTokens:[dJ],useWrappedBalances:!0},!0);K.push(...U);let D="0x20EcD8bDeb2F48d8a7c94E542aA4feC5790D9676",V=await this.invitationFarm.read("claimInvite",[],{from:D}),O=this.invitationFarm.claimInvite();K.push(O);let L=await this.invitationFarm.invitationModule(),N=r(["address"],[Y]),b=this.hubV2.safeTransferFrom(Q,L,V,m,N);K.push(b)}return K}async findInvitePath(J,$){let Q=J.toLowerCase(),Y;if($)Y=$.toLowerCase();else{let G=await this.getRealInviters(Q);if(G.length===0)throw v.noPathFound(Q,this.config.invitationModuleAddress);Y=G[0].address}let M=await this.pathfinder.findPath({from:Q,to:this.config.invitationModuleAddress,targetFlow:m,toTokens:[Y],useWrappedBalances:!0,simulatedTrusts:[{truster:this.config.invitationModuleAddress,trustee:Q}]});if(!M.transfers||M.transfers.length===0)throw v.noPathFound(Q,this.config.invitationModuleAddress);if(M.maxFlow<m){let Z=Number(M.maxFlow/m);throw v.insufficientBalance(1,Z,m,M.maxFlow,Q,this.config.invitationModuleAddress)}return M}async findFarmInvitePath(J){let $=J.toLowerCase(),Q=await this.pathfinder.findPath({from:$,to:HJ,targetFlow:m,toTokens:[n0],useWrappedBalances:!0});if(!Q.transfers||Q.transfers.length===0)throw v.noPathFound($,HJ);if(Q.maxFlow<m){let M=Number(Q.maxFlow/m);throw v.insufficientBalance(1,M,m,Q.maxFlow,$,HJ)}return Q}async getRealInviters(J){let $=J.toLowerCase(),[Q,Y,M,G,Z]=await Promise.all([dJ!=="0x0000000000000000000000000000000000000000"?this.trust.getTrusts(dJ):Promise.resolve([]),this.trust.getTrustedBy($),this.trust.getMutualTrusts($),this.trust.getTrusts(this.config.invitationModuleAddress),this.trust.getMutualTrusts(this.config.invitationModuleAddress)]),K=new Set(Q.map((j)=>j.objectAvatar.toLowerCase())),X=new Set([...Y.map((j)=>j.objectAvatar.toLowerCase()),...M.map((j)=>j.objectAvatar.toLowerCase())]),q=new Set([...G.map((j)=>j.objectAvatar.toLowerCase()),...Z.map((j)=>j.objectAvatar.toLowerCase())]),D=[...[...X].filter((j)=>q.has(j)&&!K.has(j)),$];if(D.length===0)return[];let V=await this.pathfinder.findPath({from:$,to:this.config.invitationModuleAddress,useWrappedBalances:!0,targetFlow:X$,toTokens:D,simulatedTrusts:[{truster:this.config.invitationModuleAddress,trustee:$}]});if(!V.transfers||V.transfers.length===0)return[];let O=this.config.invitationModuleAddress.toLowerCase(),L=V.transfers.filter((j)=>j.to.toLowerCase()===O),N=[...new Set(L.map((j)=>j.tokenOwner.toLowerCase()))],b=await this.token.getTokenInfoBatch(N),y=new Map;for(let j of b){let B=j.tokenAddress??j.token;if(B&&j?.tokenOwner)y.set(B.toLowerCase(),j.tokenOwner.toLowerCase())}let f=new Map;for(let j of L){let B=j.tokenOwner.toLowerCase(),P=y.get(B)??B;f.set(P,(f.get(P)??0n)+j.value)}let W=[];for(let[j,B]of f.entries()){let P=Number(B/m);if(P>=1)W.push({address:j,possibleInvites:P})}return this.orderRealInviters(W,$)}async generateReferral(J){let $=J.toLowerCase(),Q=m$(),Y=eJ(Q),M=await this.ensureInviterSetup($),G=await this.getRealInviters($),Z=[...M];if(G.length>0){console.log("[generateReferral] Using STANDARD PATH (proxy inviters available)");let K=new uJ(this.config),X=await this.generateInviteData([Y],!0),q=G[0].address,U=await this.findInvitePath($,q),D=await K.buildFlowMatrixTx($,this.config.invitationModuleAddress,U,{toTokens:[q],useWrappedBalances:!0,txData:y$(X)},!0);Z.push(...D)}else{console.log("[generateReferral] Using FARM FALLBACK PATH (no proxy inviters available)");let K=new uJ(this.config),X=await this.findFarmInvitePath($),q=await K.buildFlowMatrixTx($,HJ,X,{toTokens:[n0],useWrappedBalances:!0},!0);Z.push(...q);let U="0x20EcD8bDeb2F48d8a7c94E542aA4feC5790D9676",D=await this.invitationFarm.read("claimInvite",[],{from:U}),V=this.invitationFarm.claimInvite();Z.push(V);let O=await this.invitationFarm.invitationModule(),L=this.referralsModule.createAccount(Y).data,N=r(["address","bytes"],[this.config.referralsModuleAddress,L]),b=this.hubV2.safeTransferFrom($,O,D,m,N);Z.push(b)}return{transactions:Z,privateKey:Q}}async generateInviteData(J,$=!0){if(J.length===0)throw v.noAddressesProvided();if(!$)if(J.length===1)return r(["address"],[J[0]]);else return r(["address[]"],[J]);if(J.length===1){let Y=this.referralsModule.createAccount(J[0]).data;return r(["address","bytes"],[this.config.referralsModuleAddress,Y])}else{let Y=this.referralsModule.createAccounts(J).data;return r(["address","bytes"],[this.config.referralsModuleAddress,Y])}}computeAddress(J){let Q=J.toLowerCase().replace("0x","").padStart(64,"0"),Y=r$.replace("0x","")+Q,M=h$("0x"+Y),G="ff",Z=s$.toLowerCase().replace("0x",""),K=M.replace("0x",""),X=e$.replace("0x",""),q="ff"+Z+K+X,D="0x"+h$("0x"+q).slice(-40);return OJ(D)}generateSecrets(J){return Array.from({length:J},()=>{let $=m$(),Q=eJ($).toLowerCase();return{secret:$,signer:Q}})}}class nQ{referralsModuleAddress;invitations;invitationFarm;referralsModule;hubV2;constructor(J){this.referralsModuleAddress=J.referralsModuleAddress,this.invitations=new E8(J),this.invitationFarm=new tJ({address:J.invitationFarmAddress,rpcUrl:J.circlesRpcUrl}),this.referralsModule=new iJ({address:J.referralsModuleAddress,rpcUrl:J.circlesRpcUrl}),this.hubV2=new CJ({address:J.v2HubAddress,rpcUrl:J.circlesRpcUrl})}async getQuota(J){return this.invitationFarm.inviterQuota(J)}async getInvitationFee(){return this.invitationFarm.invitationFee()}async getInvitationModule(){return this.invitationFarm.invitationModule()}async generateReferrals(J,$){if($<=0)throw new v("Count must be greater than 0",{code:"INVITATION_INVALID_COUNT",source:"VALIDATION",context:{count:$}});let Q=J.toLowerCase(),Y=$===1,M=await this.simulateClaim(Q,$);if(!M.length)throw new v("No invitation IDs returned from claim",{code:"INVITATION_NO_IDS",source:"INVITATIONS",context:{inviter:Q,count:$}});let G=this.invitations.generateSecrets($),Z=G.map((U)=>U.signer),K=await this.invitationFarm.invitationModule(),X=Y?this.invitationFarm.claimInvite():this.invitationFarm.claimInvites(BigInt($)),q=Y?this.buildReferralTransfer(Q,K,M[0],Z[0]):this.buildBatchReferralTransfer(Q,K,M,Z);return{referrals:G,transactions:[X,q]}}async generateInvites(J,$){if($.length===0)throw new v("At least one invitee address must be provided",{code:"INVITATION_INVALID_COUNT",source:"VALIDATION",context:{count:0}});let Q=J.toLowerCase(),Y=$.map((U)=>U.toLowerCase()),M=Y.length,G=M===1,Z=await this.simulateClaim(Q,M);if(!Z.length)throw new v("No invitation IDs returned from claim",{code:"INVITATION_NO_IDS",source:"INVITATIONS",context:{inviter:Q,count:M}});let K=await this.invitationFarm.invitationModule(),X=G?this.invitationFarm.claimInvite():this.invitationFarm.claimInvites(BigInt(M)),q=G?this.buildInviteTransfer(Q,K,Z[0],Y[0]):this.buildBatchInviteTransfer(Q,K,Z,Y);return{invitees:Y,transactions:[X,q]}}async listReferrals(J,$=10,Q=0){return this.invitations.listReferrals(J,$,Q)}async simulateClaim(J,$){if($===1)return[await this.invitationFarm.read("claimInvite",[],{from:J})];return this.invitationFarm.read("claimInvites",[BigInt($)],{from:J})}buildReferralTransfer(J,$,Q,Y){let M=this.referralsModule.createAccount(Y).data,G=r(["address","bytes"],[this.referralsModuleAddress,M]);return this.hubV2.safeTransferFrom(J,$,Q,m,G)}buildBatchReferralTransfer(J,$,Q,Y){let M=this.referralsModule.createAccounts(Y).data,G=r(["address","bytes"],[this.referralsModuleAddress,M]),Z=Q.map(()=>m);return this.hubV2.safeBatchTransferFrom(J,$,Q,Z,G)}buildInviteTransfer(J,$,Q,Y){let M=r(["address"],[Y]);return this.hubV2.safeTransferFrom(J,$,Q,m,M)}buildBatchInviteTransfer(J,$,Q,Y){let M=r(["address[]"],[Y]),G=Q.map(()=>m);return this.hubV2.safeBatchTransferFrom(J,$,Q,G,M)}}class x8{address;abi;rpcUrl;constructor(J){this.address=J.address,this.abi=J.abi,this.rpcUrl=J.rpcUrl}async read(J,$,Q){let Y=TJ({abi:this.abi,functionName:J,args:$}),M={to:this.address,data:Y,...Q?.from&&{from:Q.from}},Z=await(await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[M,"latest"]})})).json();if(Z.error)throw Error(`RPC Error: ${Z.error.message}`);if(!Z.result)throw Error("No result returned from RPC call");return Z$({abi:this.abi,functionName:J,data:Z.result})}encodeWrite(J,$){return TJ({abi:this.abi,functionName:J,args:$})}}var i0=[{type:"constructor",inputs:[{name:"invitationModule",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"AFFILIATE_GROUP_REGISTRY",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"DOMAIN_SEPARATOR",inputs:[],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"GENERIC_CALL_PROXY",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"HUB",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"INVITATION_MODULE",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"NAME_REGISTRY",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"SAFE_4337_MODULE",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"SAFE_MODULE_SETUP",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"SAFE_PROXY_FACTORY",inputs:[],outputs:[{name:"",type:"address",internalType:"contract ISafeProxyFactory"}],stateMutability:"view"},{type:"function",name:"SAFE_SINGLETON",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"SAFE_WEB_AUTHN_SHARED_SIGNER",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"WELCOME_BONUS",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"accounts",inputs:[{name:"signer",type:"address",internalType:"address"}],outputs:[{name:"account",type:"address",internalType:"address"},{name:"claimed",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"claimAccount",inputs:[{name:"x",type:"uint256",internalType:"uint256"},{name:"y",type:"uint256",internalType:"uint256"},{name:"verifier",type:"address",internalType:"address"},{name:"signature",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"claimAccount",inputs:[{name:"x",type:"uint256",internalType:"uint256"},{name:"y",type:"uint256",internalType:"uint256"},{name:"verifier",type:"address",internalType:"address"},{name:"signature",type:"bytes",internalType:"bytes"},{name:"metadataDigest",type:"bytes32",internalType:"bytes32"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"claimAccount",inputs:[{name:"x",type:"uint256",internalType:"uint256"},{name:"y",type:"uint256",internalType:"uint256"},{name:"verifier",type:"address",internalType:"address"},{name:"signature",type:"bytes",internalType:"bytes"},{name:"affiliateGroup",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"claimAccount",inputs:[{name:"x",type:"uint256",internalType:"uint256"},{name:"y",type:"uint256",internalType:"uint256"},{name:"verifier",type:"address",internalType:"address"},{name:"signature",type:"bytes",internalType:"bytes"},{name:"metadataDigest",type:"bytes32",internalType:"bytes32"},{name:"affiliateGroup",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"computeAddress",inputs:[{name:"signer",type:"address",internalType:"address"}],outputs:[{name:"predictedAddress",type:"address",internalType:"address"}],stateMutability:"pure"},{type:"function",name:"createAccount",inputs:[{name:"signer",type:"address",internalType:"address"}],outputs:[{name:"account",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"createAccounts",inputs:[{name:"signers",type:"address[]",internalType:"address[]"}],outputs:[{name:"_accounts",type:"address[]",internalType:"address[]"}],stateMutability:"nonpayable"},{type:"function",name:"encodePasskeyData",inputs:[{name:"x",type:"uint256",internalType:"uint256"},{name:"y",type:"uint256",internalType:"uint256"},{name:"verifier",type:"address",internalType:"address"}],outputs:[{name:"",type:"bytes",internalType:"bytes"}],stateMutability:"view"},{type:"function",name:"getPasskeyHash",inputs:[{name:"x",type:"uint256",internalType:"uint256"},{name:"y",type:"uint256",internalType:"uint256"},{name:"verifier",type:"address",internalType:"address"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"event",name:"AccountClaimed",inputs:[{name:"account",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"AccountCreated",inputs:[{name:"account",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"error",name:"AccountAlreadyClaimed",inputs:[]},{type:"error",name:"InvalidSignature",inputs:[]},{type:"error",name:"OnlyGenericCallProxy",inputs:[]},{type:"error",name:"SignerAlreadyUsed",inputs:[]}];class k8 extends x8{constructor(J){super({address:J.address,abi:i0,rpcUrl:J.rpcUrl})}createAccount(J){return{to:this.address,data:this.encodeWrite("createAccount",[J]),value:BigInt(0)}}createAccounts(J){return{to:this.address,data:this.encodeWrite("createAccounts",[J]),value:BigInt(0)}}async computeAddress(J){return this.read("computeAddress",[J])}claimAccount(J,$,Q,Y){return{to:this.address,data:this.encodeWrite("claimAccount",[J,$,Q,Y]),value:BigInt(0)}}claimAccountWithMetadata(J,$,Q,Y,M){return{to:this.address,data:this.encodeWrite("claimAccount",[J,$,Q,Y,M]),value:BigInt(0)}}claimAccountWithAffiliateGroup(J,$,Q,Y,M){return{to:this.address,data:this.encodeWrite("claimAccount",[J,$,Q,Y,M]),value:BigInt(0)}}claimAccountWithMetadataAndAffiliateGroup(J,$,Q,Y,M,G){return{to:this.address,data:this.encodeWrite("claimAccount",[J,$,Q,Y,M,G]),value:BigInt(0)}}async accounts(J){let[$,Q]=await this.read("accounts",[J]);return{account:$,claimed:Q}}async domainSeparator(){return this.read("DOMAIN_SEPARATOR")}async welcomeBonus(){return this.read("WELCOME_BONUS")}async hub(){return this.read("HUB")}async invitationModule(){return this.read("INVITATION_MODULE")}async genericCallProxy(){return this.read("GENERIC_CALL_PROXY")}async nameRegistry(){return this.read("NAME_REGISTRY")}async affiliateGroupRegistry(){return this.read("AFFILIATE_GROUP_REGISTRY")}async safeProxyFactory(){return this.read("SAFE_PROXY_FACTORY")}async safeSingleton(){return this.read("SAFE_SINGLETON")}async safe4337Module(){return this.read("SAFE_4337_MODULE")}async safeModuleSetup(){return this.read("SAFE_MODULE_SETUP")}async safeWebAuthnSharedSigner(){return this.read("SAFE_WEB_AUTHN_SHARED_SIGNER")}}class iQ{baseUrl;getToken;referralsModule;constructor(J,$,Q,Y){this.baseUrl=J;this.getToken=Y;this.referralsModule=new k8({address:$,rpcUrl:Q})}getBaseUrl(){return this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}async getAuthHeaders(){let J={"Content-Type":"application/json"};if(!this.getToken)return J;let $=await this.getToken();return{...J,Authorization:`Bearer ${$}`}}async store(J,$){let Q=await fetch(`${this.getBaseUrl()}/store`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({privateKey:J,inviter:$})});if(!Q.ok){let Y=await Q.json();throw o.storeFailed(Y.error||Q.statusText)}}async storeBatch(J){let $=await fetch(`${this.getBaseUrl()}/store-batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({invitations:J})});if(!$.ok){let Q=await $.json();throw o.storeBatchFailed(Q.error||$.statusText)}return $.json()}async retrieve(J){let $=eJ(J),{account:Q,claimed:Y}=await this.referralsModule.accounts($),M=await fetch(`${this.getBaseUrl()}/retrieve?key=${encodeURIComponent(J)}`);if(M.ok||M.status===410||Y){let Z=await M.json();if(Q===IJ)return{...Z,error:`Referral not found on-chain for signer ${$}`};return Z}if(Q===IJ)return{error:`Referral not found on-chain for signer ${$}`};let G=await M.json().catch(()=>null);throw o.retrieveFailed(G?.error||M.statusText,M.status)}async listMine(J){if(!this.getToken)throw o.authRequired();let $=new URLSearchParams;if(J?.limit!==void 0)$.set("limit",String(J.limit));if(J?.offset!==void 0)$.set("offset",String(J.offset));if(J?.inSession!==void 0)$.set("inSession",String(J.inSession));if(J?.status!==void 0)$.set("status",J.status);let Q=$.toString()?`?${$}`:"",Y=await this.getAuthHeaders(),M=await fetch(`${this.getBaseUrl()}/my-referrals${Q}`,{headers:Y});if(!M.ok){let G=await M.json();throw o.listFailed(G.error||M.statusText)}return M.json()}async listPublic(J,$){let Q=new URLSearchParams;if($?.limit!==void 0)Q.set("limit",String($.limit));if($?.offset!==void 0)Q.set("offset",String($.offset));if($?.inSession!==void 0)Q.set("inSession",String($.inSession));let Y=Q.toString()?`?${Q}`:"",M=await fetch(`${this.getBaseUrl()}/list/${encodeURIComponent(J)}${Y}`);if(!M.ok){let G=await M.json();throw o.listFailed(G.error||M.statusText)}return M.json()}}class b8 extends Error{code;httpStatus;constructor(J,$,Q){super(J);this.code=$;this.httpStatus=Q;this.name="DispenseError"}}class ZJ extends Error{code;httpStatus;constructor(J,$,Q){super(J);this.code=$;this.httpStatus=Q;this.name="SessionError"}}function BJ(J){if(J===400)return"VALIDATION_ERROR";if(J===404)return"NOT_FOUND";if(J===409)return"CONFLICT";return"SERVER_ERROR"}class tQ{baseUrl;getToken;constructor(J,$){this.baseUrl=J;this.getToken=$}getBaseUrl(){return this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}async getAuthHeaders(){let J={"Content-Type":"application/json"};if(!this.getToken)return J;let $=await this.getToken();return{...J,Authorization:`Bearer ${$}`}}async createSession(J){let $=await fetch(`${this.getBaseUrl()}/distributions/sessions`,{method:"POST",headers:await this.getAuthHeaders(),body:JSON.stringify(J)});if(!$.ok){let Q=await $.json();throw new ZJ(Q.error||`Failed to create session: ${$.statusText}`,BJ($.status),$.status)}return $.json()}async listSessions(J,$){let Q=new URLSearchParams({inviter:J});if($?.limit!==void 0)Q.set("limit",String($.limit));if($?.offset!==void 0)Q.set("offset",String($.offset));let Y=await fetch(`${this.getBaseUrl()}/distributions/sessions?${Q}`,{headers:await this.getAuthHeaders()});if(!Y.ok){let M=await Y.json();throw new ZJ(M.error||`Failed to list sessions: ${Y.statusText}`,BJ(Y.status),Y.status)}return Y.json()}async getSession(J){let $=await fetch(`${this.getBaseUrl()}/distributions/sessions/${encodeURIComponent(J)}`,{headers:await this.getAuthHeaders()});if(!$.ok){let Q=await $.json();throw new ZJ(Q.error||`Failed to get session: ${$.statusText}`,BJ($.status),$.status)}return $.json()}async updateSession(J,$){let Q=await fetch(`${this.getBaseUrl()}/distributions/sessions/${encodeURIComponent(J)}`,{method:"PATCH",headers:await this.getAuthHeaders(),body:JSON.stringify($)});if(!Q.ok){let Y=await Q.json();throw new ZJ(Y.error||`Failed to update session: ${Q.statusText}`,BJ(Q.status),Q.status)}return Q.json()}async deleteSession(J){let $=await fetch(`${this.getBaseUrl()}/distributions/sessions/${encodeURIComponent(J)}`,{method:"DELETE",headers:await this.getAuthHeaders()});if(!$.ok){let Q=await $.json();throw new ZJ(Q.error||`Failed to delete session: ${$.statusText}`,BJ($.status),$.status)}}async addKeys(J,$){let Q=await fetch(`${this.getBaseUrl()}/distributions/sessions/${encodeURIComponent(J)}/keys`,{method:"POST",headers:await this.getAuthHeaders(),body:JSON.stringify({keys:$})});if(!Q.ok){let Y=await Q.json();throw new ZJ(Y.error||`Failed to add keys: ${Q.statusText}`,BJ(Q.status),Q.status)}return Q.json()}async listKeys(J,$){let Q=new URLSearchParams;if($?.limit!==void 0)Q.set("limit",String($.limit));if($?.offset!==void 0)Q.set("offset",String($.offset));let Y=Q.toString()?`?${Q}`:"",M=await fetch(`${this.getBaseUrl()}/distributions/sessions/${encodeURIComponent(J)}/keys${Y}`,{headers:await this.getAuthHeaders()});if(!M.ok){let G=await M.json();throw new ZJ(G.error||`Failed to list keys: ${M.statusText}`,BJ(M.status),M.status)}return M.json()}async removeKey(J,$){let Q=await fetch(`${this.getBaseUrl()}/distributions/sessions/${encodeURIComponent(J)}/keys/${encodeURIComponent($)}`,{method:"DELETE",headers:await this.getAuthHeaders()});if(!Q.ok){let Y=await Q.json();throw new ZJ(Y.error||`Failed to remove key: ${Q.statusText}`,BJ(Q.status),Q.status)}}async dispense(J){let $=await fetch(`${this.getBaseUrl()}/d/${encodeURIComponent(J)}`,{headers:{Accept:"application/json"}});if(!$.ok){let Q,Y;try{Q=(await $.json()).error}catch{Q=$.statusText}switch($.status){case 404:Y=Q.includes("keys available")?"POOL_EMPTY":"SESSION_NOT_FOUND";break;case 410:Y=Q.includes("quota")?"QUOTA_EXHAUSTED":"SESSION_EXPIRED";break;case 423:Y="SESSION_PAUSED";break;case 429:Y="RATE_LIMITED";break;default:Y="UNKNOWN"}throw new b8(Q,Y,$.status)}return $.json()}}export{ZJ as SessionError,iQ as Referrals,o as ReferralError,nQ as InviteFarm,E8 as Invitations,v as InvitationError,tQ as Distributions,b8 as DispenseError};
|
|
1
|
+
var f8=(J)=>BigInt(J),Q$=(J)=>parseInt(J,16),t0=(J)=>{if(J.startsWith("0x"))J=J.slice(2);if(J.length%2!==0)throw Error("Invalid hex string");let $=new Uint8Array(J.length/2);for(let Q=0;Q<J.length;Q+=2)$[Q/2]=parseInt(J.substr(Q,2),16);return $};function o0(J,$){if(typeof $==="string"&&$.startsWith("0x")){let Q=$.slice(2);if(Q.length===40)return $;if(Q.length===64){if(J.toLowerCase().includes("digest")||J.toLowerCase().includes("data")||J.toLowerCase().includes("bytes"))return t0($);try{return f8($)}catch{return $}}try{let Y=Q$($);if(Y<Number.MAX_SAFE_INTEGER)return Y;return f8($)}catch{return $}}if($==="true")return!0;if($==="false")return!1;return $}function p$(J){let{event:$,values:Q}=J,Y={$event:$,blockNumber:Q.blockNumber?Q$(Q.blockNumber):0,timestamp:Q.timestamp?Q$(Q.timestamp):void 0,transactionIndex:Q.transactionIndex?Q$(Q.transactionIndex):0,logIndex:Q.logIndex?Q$(Q.logIndex):0,transactionHash:Q.transactionHash};for(let[G,M]of Object.entries(Q)){if(["blockNumber","timestamp","transactionIndex","logIndex","transactionHash"].includes(G))continue;Y[G]=o0(G,M)}return Y}function I$(J){return J.map(p$)}class lJ{_subscribers=[];subscribe(J){return this._subscribers.push(J),()=>{let $=this._subscribers.indexOf(J);if($>-1)this._subscribers.splice($,1)}}constructor(){this._subscribers=[]}emit(J){this._subscribers.forEach(($)=>$(J))}static create(){let J=new lJ;return{property:J,emit:($)=>J.emit($)}}}class Y$ 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+=`
|
|
2
|
+
Context: ${JSON.stringify(this.context,null,2)}`;return J}}class c extends Y${constructor(J,$){super("RpcError",J,{...$,source:$?.source??"RPC_REQUEST"})}static connectionFailed(J,$){return new c("Failed to connect to RPC endpoint",{code:"RPC_CONNECTION_FAILED",source:"RPC_CONNECTION",cause:$,context:{url:J}})}static timeout(J,$){return new c("RPC request timed out",{code:"RPC_TIMEOUT",source:"RPC_TIMEOUT",context:{method:J,timeout:$}})}static invalidResponse(J,$){return new c("Invalid RPC response",{code:"RPC_INVALID_RESPONSE",source:"RPC_RESPONSE",context:{method:J,response:$}})}static fromJsonRpcError(J){return new c(J.message,{code:J.code,source:"RPC_RESPONSE",context:{data:J.data}})}static websocketError(J,$){return new c(J,{code:"RPC_WEBSOCKET_ERROR",source:"RPC_WEBSOCKET",cause:$})}}class VJ{rpcUrl;requestId=0;websocket=null;websocketConnected=!1;pendingResponses={};subscriptionListeners={};activeSubscriptions=[];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 Y=await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Q)});if(!Y.ok)throw c.connectionFailed(this.rpcUrl,Error(`HTTP ${Y.status}: ${Y.statusText}`));let G=await Y.json();if(G.error)throw c.fromJsonRpcError(G.error);if(G.result===void 0)throw c.invalidResponse(J,G);return G.result}catch(Y){if(Y instanceof c)throw Y;throw c.connectionFailed(this.rpcUrl,Y)}}setRpcUrl(J){this.rpcUrl=J}getRpcUrl(){return this.rpcUrl}connect(){return new Promise((J,$)=>{let Q=this.rpcUrl.replace("http","ws");if(Q.endsWith("/"))Q+="ws/subscribe";else Q+="/ws/subscribe";this.websocket=new WebSocket(Q),this.websocket.onopen=()=>{console.log("WebSocket connected"),this.websocketConnected=!0,this.reconnectAttempt=0,J()},this.websocket.onmessage=(Y)=>{let G=JSON.parse(Y.data),{id:M,method:Z,params:K}=G;if(M!==void 0&&this.pendingResponses[M])this.pendingResponses[M].resolve(G),delete this.pendingResponses[M];if(Z==="circles_subscription"&&K?.result)Object.values(this.subscriptionListeners).forEach((X)=>{X.forEach((q)=>q(K.result))})},this.websocket.onclose=()=>{console.warn("WebSocket closed");let Y=this.websocketConnected;if(this.websocketConnected=!1,Y)this.scheduleReconnect()},this.websocket.onerror=(Y)=>{console.error("WebSocket error:",Y),this.websocketConnected=!1,$(c.connectionFailed(this.rpcUrl,Y instanceof Error?Y:Error("WebSocket connection failed"))),this.scheduleReconnect()}})}scheduleReconnect(){let J=Math.min(this.initialBackoff*Math.pow(2,this.reconnectAttempt),this.maxBackoff),$=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"),await this.resubscribeActive()}catch(J){console.error("Reconnection attempt failed:",J),this.scheduleReconnect()}}async resubscribeActive(){if(this.activeSubscriptions.length===0)return;let J=[...this.activeSubscriptions];this.activeSubscriptions=[];for(let $ of J)try{let Q=$.address?{address:$.address}:{},G=(await this.sendMessage("circles_subscribe",Q)).result,M=this.subscriptionListeners[$.id];if(M)this.subscriptionListeners[G]=M,delete this.subscriptionListeners[$.id];this.activeSubscriptions.push({id:G,address:$.address})}catch(Q){console.error("Failed to re-issue circles_subscribe after reconnect:",Q),this.activeSubscriptions.push($)}}sendMessage(J,$,Q=5000){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)return Promise.reject(c.connectionFailed(this.rpcUrl));let Y=this.requestId++,G={jsonrpc:"2.0",method:J,params:$,id:Y};return new Promise((M,Z)=>{this.pendingResponses[Y]={resolve:M,reject:Z},this.websocket.send(JSON.stringify(G)),setTimeout(()=>{if(this.pendingResponses[Y])this.pendingResponses[Y].reject(c.timeout(J,Q)),delete this.pendingResponses[Y]},Q)})}async subscribe(J){let $=J?.toLowerCase();if(!this.websocketConnected)await this.connect();let Q=lJ.create(),Y=$?{address:$}:{},M=(await this.sendMessage("circles_subscribe",Y)).result;if(!this.subscriptionListeners[M])this.subscriptionListeners[M]=[];return this.subscriptionListeners[M].push((Z)=>{I$(Z).forEach((K)=>Q.emit(K))}),this.activeSubscriptions.push({id:M,address:$}),Q.property}}var H$=BigInt(4294967295),g8=BigInt(32);function s0(J,$=!1){if($)return{h:Number(J&H$),l:Number(J>>g8&H$)};return{h:Number(J>>g8&H$)|0,l:Number(J&H$)|0}}function v8(J,$=!1){let Q=J.length,Y=new Uint32Array(Q),G=new Uint32Array(Q);for(let M=0;M<Q;M++){let{h:Z,l:K}=s0(J[M],$);[Y[M],G[M]]=[Z,K]}return[Y,G]}var u8=(J,$,Q)=>J<<Q|$>>>32-Q,m8=(J,$,Q)=>$<<Q|J>>>32-Q,h8=(J,$,Q)=>$<<Q-32|J>>>64-Q,l8=(J,$,Q)=>J<<Q-32|$>>>64-Q;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function r0(J){return J instanceof Uint8Array||ArrayBuffer.isView(J)&&J.constructor.name==="Uint8Array"}function d$(J,$=""){if(!Number.isSafeInteger(J)||J<0){let Q=$&&`"${$}" `;throw Error(`${Q}expected integer >= 0, got ${J}`)}}function S$(J,$,Q=""){let Y=r0(J),G=J?.length,M=$!==void 0;if(!Y||M&&G!==$){let Z=Q&&`"${Q}" `,K=M?` of length ${$}`:"",X=Y?`length=${G}`:`type=${typeof J}`;throw Error(Z+"expected Uint8Array"+K+", got "+X)}return J}function n$(J,$=!0){if(J.destroyed)throw Error("Hash instance has been destroyed");if($&&J.finished)throw Error("Hash#digest() has already been called")}function c8(J,$){S$(J,void 0,"digestInto() output");let Q=$.outputLen;if(J.length<Q)throw Error('"digestInto() output" expected to be of length >='+Q)}function p8(J){return new Uint32Array(J.buffer,J.byteOffset,Math.floor(J.byteLength/4))}function i$(...J){for(let $=0;$<J.length;$++)J[$].fill(0)}var e0=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function JQ(J){return J<<24&4278190080|J<<8&16711680|J>>>8&65280|J>>>24&255}function $Q(J){for(let $=0;$<J.length;$++)J[$]=JQ(J[$]);return J}var t$=e0?(J)=>J:$Q;function d8(J,$={}){let Q=(G,M)=>J(M).update(G).digest(),Y=J(void 0);return Q.outputLen=Y.outputLen,Q.blockLen=Y.blockLen,Q.create=(G)=>J(G),Object.assign(Q,$),Object.freeze(Q)}var QQ=BigInt(0),G$=BigInt(1),YQ=BigInt(2),GQ=BigInt(7),MQ=BigInt(256),ZQ=BigInt(113),t8=[],o8=[],a8=[];for(let J=0,$=G$,Q=1,Y=0;J<24;J++){[Q,Y]=[Y,(2*Q+3*Y)%5],t8.push(2*(5*Y+Q)),o8.push((J+1)*(J+2)/2%64);let G=QQ;for(let M=0;M<7;M++)if($=($<<G$^($>>GQ)*ZQ)%MQ,$&YQ)G^=G$<<(G$<<BigInt(M))-G$;a8.push(G)}var s8=v8(a8,!0),XQ=s8[0],KQ=s8[1],n8=(J,$,Q)=>Q>32?h8(J,$,Q):u8(J,$,Q),i8=(J,$,Q)=>Q>32?l8(J,$,Q):m8(J,$,Q);function qQ(J,$=24){let Q=new Uint32Array(10);for(let Y=24-$;Y<24;Y++){for(let Z=0;Z<10;Z++)Q[Z]=J[Z]^J[Z+10]^J[Z+20]^J[Z+30]^J[Z+40];for(let Z=0;Z<10;Z+=2){let K=(Z+8)%10,X=(Z+2)%10,q=Q[X],U=Q[X+1],D=n8(q,U,1)^Q[K],V=i8(q,U,1)^Q[K+1];for(let O=0;O<50;O+=10)J[Z+O]^=D,J[Z+O+1]^=V}let G=J[2],M=J[3];for(let Z=0;Z<24;Z++){let K=o8[Z],X=n8(G,M,K),q=i8(G,M,K),U=t8[Z];G=J[U],M=J[U+1],J[U]=X,J[U+1]=q}for(let Z=0;Z<50;Z+=10){for(let K=0;K<10;K++)Q[K]=J[Z+K];for(let K=0;K<10;K++)J[Z+K]^=~Q[(K+2)%10]&Q[(K+4)%10]}J[0]^=XQ[Y],J[1]^=KQ[Y]}i$(Q)}class o${state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(J,$,Q,Y=!1,G=24){if(this.blockLen=J,this.suffix=$,this.outputLen=Q,this.enableXOF=Y,this.rounds=G,d$(Q,"outputLen"),!(0<J&&J<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=p8(this.state)}clone(){return this._cloneInto()}keccak(){t$(this.state32),qQ(this.state32,this.rounds),t$(this.state32),this.posOut=0,this.pos=0}update(J){n$(this),S$(J);let{blockLen:$,state:Q}=this,Y=J.length;for(let G=0;G<Y;){let M=Math.min($-this.pos,Y-G);for(let Z=0;Z<M;Z++)Q[this.pos++]^=J[G++];if(this.pos===$)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:J,suffix:$,pos:Q,blockLen:Y}=this;if(J[Q]^=$,($&128)!==0&&Q===Y-1)this.keccak();J[Y-1]^=128,this.keccak()}writeInto(J){n$(this,!1),S$(J),this.finish();let $=this.state,{blockLen:Q}=this;for(let Y=0,G=J.length;Y<G;){if(this.posOut>=Q)this.keccak();let M=Math.min(Q-this.posOut,G-Y);J.set($.subarray(this.posOut,this.posOut+M),Y),this.posOut+=M,Y+=M}return J}xofInto(J){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(J)}xof(J){return d$(J),this.xofInto(new Uint8Array(J))}digestInto(J){if(c8(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,i$(this.state)}_cloneInto(J){let{blockLen:$,suffix:Q,outputLen:Y,rounds:G,enableXOF:M}=this;return J||=new o$($,Q,Y,M,G),J.state32.set(this.state32),J.pos=this.pos,J.posOut=this.posOut,J.finished=this.finished,J.rounds=G,J.suffix=Q,J.outputLen=Y,J.enableXOF=M,J.destroyed=this.destroyed,J}}var UQ=(J,$,Q,Y={})=>d8(()=>new o$($,J,Q),Y);var cJ=UQ(1,136,32);var r8=[];for(let J=0;J<256;J++)r8[J]=J.toString(16).padStart(2,"0");function _$(J){let $="0x";for(let Q=0;Q<J.length;Q++)$+=r8[J[Q]];return $}function y$(J){let $=J.startsWith("0x")?J.slice(2):J,Q=new Uint8Array($.length/2);for(let Y=0;Y<$.length;Y+=2)Q[Y/2]=parseInt($.slice(Y,Y+2),16);return Q}var g=64,w$=32,A$=(J)=>J.startsWith("0x")?J.slice(2):J;var MJ=(J)=>J.toString(16).padStart(g,"0");function OJ(J){let $=J.toLowerCase().replace("0x",""),Q=_$(cJ(new TextEncoder().encode($))).slice(2),Y="0x";for(let G=0;G<$.length;G++)Y+=parseInt(Q[G],16)>=8?$[G].toUpperCase():$[G];return Y}function a$(J,$){if(J==="tuple"&&$)return`(${$.map((G)=>a$(G.type,G.components)).join(",")})`;let Q=J.match(/^tuple(\[\d*\])$/);if(Q&&$)return`${a$("tuple",$)}${Q[1]}`;return J}function WQ(J){let Q=(J.inputs||[]).map((Y)=>a$(Y.type,Y.components));return`${J.name}(${Q.join(",")})`}function jQ(J){let $=WQ(J),Q=cJ(new TextEncoder().encode($));return _$(Q.slice(0,4))}function pJ(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 e8($);return pJ(Q)}if(J==="tuple")return e8($);return!1}function e8(J){return J?.some(($)=>pJ($.type,$.components))??!1}function NJ(J,$,Q){if(J==="tuple"&&Q)return DQ(Q,$);if(J.includes("["))return zQ(J,$,Q);return VQ(J,$)}function zQ(J,$,Q){let Y=J.slice(0,J.indexOf("[")),G=J.endsWith("[]"),M=pJ(Y,Q),Z;if(M){let K=$.map((U)=>NJ(Y,U,Q)),X=$.length*w$;Z=K.map((U)=>{let D=X;return X+=U.length/2,MJ(D)}).join("")+K.join("")}else Z=$.map((K)=>NJ(Y,K,Q)).join("");return G?MJ($.length)+Z:Z}function DQ(J,$){let Q=Array.isArray($),Y=[],G=[],M=[];for(let Z=0;Z<J.length;Z++){let K=J[Z],X=Q?$[Z]:$[K.name||""],q=pJ(K.type,K.components);if(M.push(q),q)Y.push(""),G.push(NJ(K.type,X,K.components));else Y.push(NJ(K.type,X,K.components))}if(G.length>0){let Z=Y.reduce((q,U,D)=>q+(M[D]?w$:U.length/2),0),K="",X=0;for(let q=0;q<J.length;q++)if(M[q])K+=MJ(Z),Z+=G[X].length/2,X++;else K+=Y[q];return K+G.join("")}return Y.join("")}function VQ(J,$){if(J==="address")return A$($).toLowerCase().padStart(g,"0");if(J==="bool")return MJ($?1:0);if(J.startsWith("uint")){let Q=typeof $==="bigint"?$:BigInt($);return MJ(Q)}if(J.startsWith("int")){let Q=typeof $==="bigint"?$:BigInt($);if(Q<0n){let Y=J==="int"?256:parseInt(J.slice(3));Q=(1n<<BigInt(Y))+Q}return MJ(Q)}if(J.startsWith("bytes")&&J!=="bytes")return A$($).padEnd(g,"0");if(J==="bytes"){let Q=A$($),Y=MJ(Q.length/2),G=Q.padEnd(Math.ceil(Q.length/g)*g,"0");return Y+G}if(J==="string"){let Q=Array.from(new TextEncoder().encode($)).map((M)=>M.toString(16).padStart(2,"0")).join(""),Y=MJ(Q.length/2),G=Q.padEnd(Math.ceil(Q.length/g)*g,"0");return Y+G}throw Error(`Unsupported type: ${J}`)}function M$(J,$,Q=0,Y){if(J==="tuple"&&Y)return OQ(Y,$,Q);if(J.includes("["))return NQ(J,$,Q,Y);return RQ(J,$,Q)}function NQ(J,$,Q,Y){let G=J.slice(0,J.indexOf("[")),M=$.slice(Q,Q+g);if(J.endsWith("[]")){let K=parseInt(M,16)*2,X=parseInt($.slice(K,K+g),16),q=[],U=K+g;for(let D=0;D<X;D++){let V=M$(G,$,U,Y);q.push(V.value),U+=V.consumed}return{value:q,consumed:g}}let Z=J.match(/\[(\d+)\]$/);if(Z){let K=parseInt(Z[1]),X=[],q=0;for(let U=0;U<K;U++){let D=M$(G,$,Q+q,Y);X.push(D.value),q+=D.consumed}return{value:X,consumed:q}}throw Error(`Invalid array type: ${J}`)}function OQ(J,$,Q){let Y=[],G=Q;for(let M of J){let Z=M$(M.type,$,G,M.components);Y.push(Z.value),G+=Z.consumed}return{value:Y,consumed:G-Q}}function RQ(J,$,Q){let Y=$.slice(Q,Q+g);if(J==="address")return{value:OJ("0x"+Y.slice(24)),consumed:g};if(J==="bool")return{value:parseInt(Y,16)!==0,consumed:g};if(J.startsWith("uint"))return{value:BigInt("0x"+Y),consumed:g};if(J.startsWith("int")){let G=BigInt("0x"+Y),M=J==="int"?256:parseInt(J.slice(3)),Z=1n<<BigInt(M-1);return{value:G>=Z?G-(1n<<BigInt(M)):G,consumed:g}}if(J.startsWith("bytes")&&J!=="bytes"){let G=parseInt(J.match(/^bytes(\d+)$/)[1]);return{value:"0x"+Y.slice(0,G*2),consumed:g}}if(J==="bytes"){let G=parseInt(Y,16)*2,M=parseInt($.slice(G,G+g),16)*2;return{value:"0x"+$.slice(G+g,G+g+M),consumed:g}}if(J==="string"){let G=parseInt(Y,16)*2,M=parseInt($.slice(G,G+g),16)*2,Z=$.slice(G+g,G+g+M),K=new Uint8Array(Z.match(/.{2}/g)?.map((X)=>parseInt(X,16))||[]);return{value:new TextDecoder().decode(K),consumed:g}}throw Error(`Unsupported type: ${J}`)}function TJ(J){let{abi:$,functionName:Q,args:Y=[]}=J,G=$.find((O)=>O.type==="function"&&O.name===Q);if(!G)throw Error(`Function "${Q}" not found in ABI`);let M=jQ(G),Z=G.inputs||[];if(Z.length===0)return M;if(Y.length!==Z.length)throw Error(`Expected ${Z.length} arguments, got ${Y.length}`);let K=[],X=[],q=[];for(let O=0;O<Z.length;O++){let L=Z[O],N=L.components,b=pJ(L.type,N);if(q.push(b),b)K.push(""),X.push(NJ(L.type,Y[O],N));else K.push(NJ(L.type,Y[O],N))}if(X.length===0)return M+K.join("");let U=K.reduce((O,L,N)=>O+(q[N]?w$:L.length/2),0),D="",V=0;for(let O=0;O<Z.length;O++)if(q[O])D+=MJ(U),U+=X[V].length/2,V++;else D+=K[O];return M+D+X.join("")}function Z$(J){let{abi:$,functionName:Q,data:Y}=J,G=$.find((q)=>q.type==="function"&&q.name===Q);if(!G)throw Error(`Function "${Q}" not found in ABI`);let M=G.outputs||[];if(M.length===0)return;let Z=A$(Y);if(M.length===1)return M$(M[0].type,Z,0,M[0].components).value;let K=[],X=0;for(let q of M){let U=M$(q.type,Z,X,q.components);K.push(U.value),X+=U.consumed}return K}function r(J,$){if(J.length!==$.length)throw Error(`Type/value length mismatch: ${J.length} types, ${$.length} values`);let Q=[],Y=[],G=[];for(let X=0;X<J.length;X++){let q=J[X],U=pJ(q);if(G.push(U),U)Q.push(""),Y.push(NJ(q,$[X]));else Q.push(NJ(q,$[X]))}if(Y.length===0)return"0x"+Q.join("");let M=Q.reduce((X,q,U)=>X+(G[U]?w$:q.length/2),0),Z="",K=0;for(let X=0;X<J.length;X++)if(G[X])Z+=MJ(M),M+=Y[K].length/2,K++;else Z+=Q[X];return"0x"+Z+Y.join("")}function R(J){return J.toLowerCase()}function CQ(J){return OJ(J)}function PQ(J){if(typeof J!=="string")return!1;let $=J.replace("0x","");return $.length===40&&/^[0-9a-fA-F]{40}$/.test($)}function H(J){if(J===null||J===void 0)return J;if(PQ(J))return CQ(J);if(Array.isArray(J))return J.map(($)=>H($));if(typeof J==="object"&&J!==null){let $={};for(let Q in J)if(Object.prototype.hasOwnProperty.call(J,Q))$[Q]=H(J[Q]);return $}return J}function J0(J){return{Source:R(J.from),Sink:R(J.to),TargetFlow:J.targetFlow.toString(),WithWrap:J.useWrappedBalances,FromTokens:J.fromTokens?.map(R),ToTokens:J.toTokens?.map(R),ExcludedFromTokens:J.excludeFromTokens?.map(R),ExcludedToTokens:J.excludeToTokens?.map(R),SimulatedBalances:J.simulatedBalances?.map(($)=>({Holder:R($.holder),Token:R($.token),Amount:$.amount.toString(),IsWrapped:$.isWrapped,IsStatic:$.isStatic})),SimulatedTrusts:J.simulatedTrusts?.map(($)=>({Truster:R($.truster),Trustee:R($.trustee)})),MaxTransfers:J.maxTransfers}}function XJ(J){let $={};for(let Q in J){let Y=J[Q];if(Y===null||Y===void 0)$[Q]=Y;else if(typeof Y==="string"&&/^\d+$/.test(Y))$[Q]=BigInt(Y);else if(typeof Y==="object"&&!Array.isArray(Y))$[Q]=XJ(Y);else if(Array.isArray(Y))$[Q]=Y.map((G)=>typeof G==="object"&&G!==null?XJ(G):G);else $[Q]=Y}return $}var IJ="0x0000000000000000000000000000000000000000",m=BigInt(96)*BigInt(1000000000000000000),X$=BigInt("9999999999999999999999999999999999999"),s$="0x4e1DCf7AD4e460CfD30791CCC4F9c8a4f820ec67",r$="0x89867a67674bd4bf33165a653cde826b696ab7d050166b71066dfa0b9b6f90f4",e$="0xe298282cefe913ab5d282047161268a8222e4bd4ed106300c547894bbefd31ee",dJ="0xc19bc204eb1c1d5b3fe500e5e5dfabab625f286c",HJ="0x9Eb51E6A39B3F17bB1883B80748b56170039ff1d";class KJ{client;constructor(J){this.client=J}async findPath(J){let $=J0(J),Q=await this.client.call("circlesV2_findPath",[$]),Y=XJ(Q);return H(Y)}async findMaxFlow(J){let $=await this.findPath({...J,targetFlow:X$});return BigInt($.maxFlow)}}class K${client;constructor(J){this.client=J}async query(J){let $=await this.client.call("circles_query",[J]),{columns:Q,rows:Y}=$,G=Y.map((M)=>{let Z={};return Q.forEach((K,X)=>{Z[K]=M[X]}),Z});return H(G)}async tables(){return this.client.call("circles_tables",[])}async events(J=null,$=null,Q=null,Y=null,G=null,M=!1,Z=100,K=null){let X=await this.client.call("circles_events_paginated",[J,$,Q,Y,G,M,Z,K]);return{events:H(X.events),hasMore:X.hasMore,nextCursor:X.nextCursor}}}var BQ=[{name:"blockNumber",sortOrder:"DESC"},{name:"transactionIndex",sortOrder:"DESC"},{name:"logIndex",sortOrder:"DESC"}];class SJ{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=BQ.map(($)=>({...$,sortOrder:this.params.sortOrder}));if(this.params.table==="TransferBatch")J.push({name:"batchIndex",sortOrder:this.params.sortOrder});return J}buildOrderBy(){if(this.orderColumns&&this.orderColumns.length>0)return this.orderColumns;return this.cursorColumns.map((J)=>({Column:J.name,SortOrder:J.sortOrder}))}rowsToObjects(J){let{columns:$,rows:Q}=J;return Q.map((Y)=>{let G={};return $.forEach((M,Z)=>{G[M]=Y[Z]}),this.rowTransformer?this.rowTransformer(G):G})}async queryNextPage(){let J={Namespace:this.params.namespace,Table:this.params.table,Columns:this.params.columns,Filter:this.params.filter||[],Order:this.buildOrderBy(),Limit:this.params.limit},$=this._currentPage?.nextCursor?[J,this._currentPage.nextCursor]:[J],Q=await this.client.call("circles_paginated_query",$),Y=this.rowsToObjects(Q);return this._currentPage={limit:this.params.limit,size:Y.length,sortOrder:this.params.sortOrder,hasMore:Q.hasMore,nextCursor:Q.nextCursor??void 0,results:Y},Y.length>0}reset(){this._currentPage=void 0}}class _J{client;constructor(J){this.client=J}transformQueryResponse(J){let{columns:$,rows:Q}=J;return Q.map((Y)=>{let G={};return $.forEach((M,Z)=>{G[M]=Y[Z]}),G})}async getCommonTrust(J,$){let Q=await this.client.call("circles_getCommonTrust",[R(J),R($)]);return H(Q)}getTrustRelations(J,$=100,Q="DESC"){let Y=R(J),G=[{Type:"Conjunction",ConjunctionType:"And",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"version",Value:2},{Type:"Conjunction",ConjunctionType:"Or",Predicates:[{Type:"FilterPredicate",FilterType:"Equals",Column:"trustee",Value:Y},{Type:"FilterPredicate",FilterType:"Equals",Column:"truster",Value:Y}]}]}];return new SJ(this.client,{namespace:"V_Crc",table:"TrustRelations",sortOrder:Q,columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","version","trustee","truster","expiryTime"],filter:G,limit:$},(M)=>H(M))}async getAggregatedTrustRelations(J){let $=R(J),Q=await this.client.call("circles_getAggregatedTrustRelations",[$]);return H(Q)}async getTrustedBy(J){let $=R(J),Y=(await this.getAggregatedTrustRelations($)).filter((G)=>G.relation==="trustedBy");return H(Y)}async getTrusts(J){let $=R(J),Y=(await this.getAggregatedTrustRelations($)).filter((G)=>G.relation==="trusts");return H(Y)}async getMutualTrusts(J){let $=R(J),Y=(await this.getAggregatedTrustRelations($)).filter((G)=>G.relation==="mutuallyTrusts");return H(Y)}async getTrustNetworkSummary(J,$=2){return this.client.call("circles_getTrustNetworkSummary",[R(J),$])}async getAggregatedTrustRelationsEnriched(J){return this.client.call("circles_getAggregatedTrustRelationsEnriched",[R(J)])}async getValidInviters(J,$){let Q=[R(J)];if($)Q.push($);return this.client.call("circles_getValidInviters",Q)}}class nJ{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,Y=$,G=this.ONE_64;while(Y>0n){if((Y&1n)===1n)G=this.mul64(G,Q);Q=this.mul64(Q,Q),Y>>=1n}return G}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,Y=J,G=$;while(G>0n){if((G&1n)===1n)Q=this.mul36(Q,Y);Y=this.mul36(Y,Y),G>>=1n}return Q}static attoCirclesToCircles(J){if(J===0n)return 0;let $=J/this.ATTO_FACTOR,Q=J%this.ATTO_FACTOR,Y=BigInt(Number.MAX_SAFE_INTEGER);if($>Y||$<-Y)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,Y=Q/this.PERIOD_SEC,G=Q%this.PERIOD_SEC,M=this.v1InflateFactor(Y),Z=this.v1InflateFactor(Y+1n);return this.v1ToDemurrage(J,M,Z,G,this.PERIOD_SEC)}static attoCirclesToAttoCrc(J,$){let Q=$-this.INFLATION_DAY_ZERO_UNIX,Y=Q/this.PERIOD_SEC,G=Q%this.PERIOD_SEC,M=this.v1InflateFactor(Y),Z=this.v1InflateFactor(Y+1n),K=M*(this.PERIOD_SEC-G)+Z*G;return J*3n*this.V1_ACCURACY*this.PERIOD_SEC/K}static v1ToDemurrage(J,$,Q,Y,G){let M=$*(G-Y)+Q*Y;return J*3n*this.V1_ACCURACY*G/M}}class yJ{client;constructor(J){this.client=J}async getTotalBalance(J,$=!0){let Q=await this.client.call("circlesV2_getTotalBalance",[R(J),$]);return nJ.circlesToAttoCircles(Q)}async getTokenBalances(J){let Q=(await this.client.call("circles_getTokenBalances",[R(J)])).map((Y)=>XJ(Y));return H(Q)}}class q${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((Y)=>R(Y)),Q=await this.client.call("circles_getAvatarInfoBatch",[$]);return H(Q)}async getNetworkSnapshot(){let J=await this.client.call("circles_getNetworkSnapshot",[]);return H(J)}}class U${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",[R(J)])}async getProfileByAddressBatch(J){return this.client.call("circles_getProfileByAddressBatch",[J.map(($)=>$===null?null:R($))])}async searchProfiles(J,$=10,Q=0,Y){return this.client.call("circles_searchProfiles",[J.toLowerCase(),$,Q,Y])}async searchByAddressOrName(J,$=10,Q,Y){return this.client.call("circles_searchProfileByAddressOrName",Y?[J,$,Q??null,Y]:[J,$,Q??null])}async getProfileView(J){return this.client.call("circles_getProfileView",[R(J)])}}class AJ{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((G)=>R(G)),Y=(await this.client.call("circles_getTokenInfoBatch",[$])).map((G)=>XJ(G));return H(Y)}async getTokenHolders(J,$=100,Q){let Y=await this.client.call("circles_getTokenHolders",[R(J),$,Q??null]);return{hasMore:Y.hasMore,nextCursor:Y.nextCursor,results:H(Y.results)}}}class W${client;constructor(J){this.client=J}async getInvitationOrigin(J){let $=R(J),Q=await this.client.call("circles_getInvitationOrigin",[$]);return Q?H(Q):null}async getInvitedBy(J){let $=await this.getInvitationOrigin(J);if($?.inviter)return H($.inviter);return}async getTrustInvitations(J,$){let Q=R(J),Y=await this.client.call("circles_getTrustInvitations",$?[Q,$]:[Q]);return H(Y)}async getInvitations(J,$){let Y=(await this.getValidInviters(J,$)).results.map((G)=>G.avatarInfo).filter((G)=>G!==void 0&&G!==null);return H(Y)}async getValidInviters(J,$){let Q=R(J),Y=await this.client.call("circles_getValidInviters",$?[Q,$]:[Q]);return H(Y)}async getInvitationsFrom(J,$=!1){let Q=R(J),Y=await this.client.call("circles_getInvitationsFrom",[Q,$]);return H(Y)}async getEscrowInvitations(J){let $=R(J),Q=await this.client.call("circles_getEscrowInvitations",[$]);return H(Q)}async getAtScaleInvitations(J){let $=R(J),Q=await this.client.call("circles_getAtScaleInvitations",[$]);return H(Q)}async getAllInvitations(J,$){let Q=R(J),Y=await this.client.call("circles_getAllInvitations",$?[Q,$]:[Q]);return H(Y)}}class j${client;constructor(J){this.client=J}async getTransactionHistory(J,$=50,Q){let Y=await this.client.call("circles_getTransactionHistory",[R(J),$,Q??null]);return{hasMore:Y.hasMore,nextCursor:Y.nextCursor,results:H(Y.results)}}async getTransactionHistoryEnriched(J,$=0,Q=null,Y=20,G){let M=await this.client.call("circles_getTransactionHistoryEnriched",[R(J),$,Q,Y,G??null]);return{hasMore:M.hasMore,nextCursor:M.nextCursor,results:H(M.results)}}}class wJ{client;constructor(J){this.client=J}async findGroups(J=50,$,Q){let Y=$?{nameStartsWith:$.nameStartsWith,symbolStartsWith:$.symbolStartsWith,ownerIn:$.ownerIn?.map((Z)=>R(Z))}:void 0,G=await this.client.call("circles_findGroups",[J,Y??null,Q??null]),M=H(G.results).map((Z)=>{let K=Z;if(!K.owner&&K.mint)return{...K,owner:K.mint};return K});return{hasMore:G.hasMore,nextCursor:G.nextCursor,results:M}}async getGroupMemberships(J,$=50,Q){let Y=await this.client.call("circles_getGroupMemberships",[R(J),$,Q??null]);return{hasMore:Y.hasMore,nextCursor:Y.nextCursor,results:H(Y.results)}}async getGroupMembers(J,$=100,Q){let Y=await this.client.call("circles_getGroupMembers",[R(J),$,Q??null]);return{hasMore:Y.hasMore,nextCursor:Y.nextCursor,results:H(Y.results)}}getGroups(J=50,$,Q="DESC"){let Y=[];if($){if($.nameStartsWith)Y.push({Type:"FilterPredicate",FilterType:"Like",Column:"name",Value:$.nameStartsWith+"%"});if($.symbolStartsWith)Y.push({Type:"FilterPredicate",FilterType:"Like",Column:"symbol",Value:$.symbolStartsWith+"%"});if($.groupAddressIn&&$.groupAddressIn.length>0){let M=$.groupAddressIn.map((Z)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"group",Value:R(Z)}));if(M.length===1)Y.push(M[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:M})}if($.groupTypeIn&&$.groupTypeIn.length>0){let M=$.groupTypeIn.map((Z)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"type",Value:Z}));if(M.length===1)Y.push(M[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:M})}if($.ownerIn&&$.ownerIn.length>0){let M=$.ownerIn.map((Z)=>({Type:"FilterPredicate",FilterType:"Equals",Column:"owner",Value:R(Z)}));if(M.length===1)Y.push(M[0]);else Y.push({Type:"Conjunction",ConjunctionType:"Or",Predicates:M})}if($.mintHandlerEquals)Y.push({Type:"FilterPredicate",FilterType:"Equals",Column:"mintHandler",Value:R($.mintHandlerEquals)});if($.treasuryEquals)Y.push({Type:"FilterPredicate",FilterType:"Equals",Column:"treasury",Value:R($.treasuryEquals)})}let G=Y.length>1?[{Type:"Conjunction",ConjunctionType:"And",Predicates:Y}]:Y;return new SJ(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:G,limit:J},(M)=>H(M))}getGroupHolders(J,$=100){let Q=R(J);return new SJ(this.client,{namespace:"V_Crc",table:"TokenBalances",sortOrder:"DESC",columns:["blockNumber","timestamp","transactionIndex","logIndex","transactionHash","token","account","balance","lastChangedAt"],filter:[{Type:"FilterPredicate",FilterType:"Equals",Column:"token",Value:Q}],limit:$},(Y)=>H(Y))}}class E${client;constructor(J){this.client=J}async getProfileView(J){let $=R(J);return this.client.call("circles_getProfileView",[$])}async getTrustNetworkSummary(J,$=2){let Q=R(J);return this.client.call("circles_getTrustNetworkSummary",[Q,$])}async getAggregatedTrustRelations(J){let $=R(J);return this.client.call("circles_getAggregatedTrustRelations",[$])}async getValidInviters(J,$){let Q=R(J),Y=await this.client.call("circles_getValidInviters",$?[Q,$]:[Q]);return H(Y)}async getTransactionHistoryEnriched(J,$=0,Q=null,Y=50,G){let M=R(J),Z=await this.client.call("circles_getTransactionHistoryEnriched",[M,$,Q,Y,G??null]);return{hasMore:Z.hasMore,nextCursor:Z.nextCursor,results:H(Z.results)}}async searchProfileByAddressOrName(J,$=20,Q,Y){return this.client.call("circles_searchProfileByAddressOrName",Y?[J,$,Q??null,Y]:[J,$,Q??null])}}class x${client;_pathfinder;_query;_trust;_balance;_avatar;_profile;_token;_invitation;_transaction;_group;_sdk;constructor(J="https://rpc.aboutcircles.com/"){this.client=new VJ(J)}get pathfinder(){if(!this._pathfinder)this._pathfinder=new KJ(this.client);return this._pathfinder}get query(){if(!this._query)this._query=new K$(this.client);return this._query}get trust(){if(!this._trust)this._trust=new _J(this.client);return this._trust}get balance(){if(!this._balance)this._balance=new yJ(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 U$(this.client);return this._profile}get token(){if(!this._token)this._token=new AJ(this.client);return this._token}get invitation(){if(!this._invitation)this._invitation=new W$(this.client);return this._invitation}get transaction(){if(!this._transaction)this._transaction=new j$(this.client);return this._transaction}get group(){if(!this._group)this._group=new wJ(this.client);return this._group}get sdk(){if(!this._sdk)this._sdk=new E$(this.client);return this._sdk}setRpcUrl(J){this.client.setRpcUrl(J)}getRpcUrl(){return this.client.getRpcUrl()}}class p{address;abi;rpcUrl;constructor(J){this.address=J.address,this.abi=J.abi,this.rpcUrl=J.rpcUrl}async read(J,$,Q){let Y=TJ({abi:this.abi,functionName:J,args:$}),G={to:this.address,data:Y,...Q?.from&&{from:Q.from}},Z=await(await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[G,"latest"]})})).json();if(Z.error)throw Error(`RPC Error: ${Z.error.message}`);if(!Z.result)throw Error("No result returned from RPC call");return Z$({abi:this.abi,functionName:J,data:Z.result})}encodeWrite(J,$){return TJ({abi:this.abi,functionName:J,args:$})}}var $0=[{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 RJ extends p{constructor(J){super({address:J.address,abi:$0,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,Y,G="0x"){return{to:this.address,data:this.encodeWrite("safeTransferFrom",[J,$,Q,Y,G]),value:0n}}operateFlowMatrix(J,$,Q,Y){return{to:this.address,data:this.encodeWrite("operateFlowMatrix",[J,$,Q,Y]),value:0n}}async isHuman(J){return this.read("isHuman",[J])}safeBatchTransferFrom(J,$,Q,Y,G="0x"){return{to:this.address,data:this.encodeWrite("safeBatchTransferFrom",[J,$,Q,Y,G]),value:0n}}}var Q0=[{type:"function",name:"erc20Circles",inputs:[{name:"_circlesType",type:"uint8"},{name:"_avatar",type:"address"}],outputs:[{type:"address"}],stateMutability:"view"}];class k$ extends p{constructor(J){super({address:J.address,abi:Q0,rpcUrl:J.rpcUrl})}async erc20Circles(J,$){return this.read("erc20Circles",[J,$])}}var J8=[{type:"function",name:"unwrap",inputs:[{name:"_amount",type:"uint256"}],outputs:[],stateMutability:"nonpayable"}];class z$ extends p{constructor(J){super({address:J.address,abi:J8,rpcUrl:J.rpcUrl})}unwrap(J){return{to:this.address,data:this.encodeWrite("unwrap",[J]),value:0n}}}class D$ extends p{constructor(J){super({address:J.address,abi:J8,rpcUrl:J.rpcUrl})}unwrap(J){return{to:this.address,data:this.encodeWrite("unwrap",[J]),value:0n}}}var $8=[{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 Q8=[{type:"function",name:"claimInvite",inputs:[],outputs:[{name:"id",type:"uint256"}],stateMutability:"nonpayable"},{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"}];var Y8=[{type:"function",name:"isModuleEnabled",inputs:[{name:"module",type:"address"}],outputs:[{name:"",type:"bool"}],stateMutability:"view"},{type:"function",name:"enableModule",inputs:[{name:"module",type:"address"}],outputs:[],stateMutability:"nonpayable"}];var G8=[{type:"function",name:"trustInviter",inputs:[{name:"inviter",type:"address"}],outputs:[],stateMutability:"nonpayable"}];class iJ extends p{constructor(J){super({address:J.address,abi:$8,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 tJ extends p{constructor(J){super({address:J.address,abi:Q8,rpcUrl:J.rpcUrl})}claimInvite(){return{to:this.address,data:this.encodeWrite("claimInvite",[]),value:0n}}claimInvites(J){return{to:this.address,data:this.encodeWrite("claimInvites",[J]),value:0n}}async inviterQuota(J){return this.read("inviterQuota",[J])}async invitationFee(){return this.read("INVITATION_FEE")}async invitationModule(){return this.read("invitationModule")}}class b$ extends p{constructor(J){super({address:J.address,abi:Y8,rpcUrl:J.rpcUrl})}async isModuleEnabled(J){return this.read("isModuleEnabled",[J])}enableModule(J){return{to:this.address,data:this.encodeWrite("enableModule",[J]),value:0n}}}class F$ extends p{constructor(J){super({address:J.address,abi:G8,rpcUrl:J.rpcUrl})}trustInviter(J){return{to:this.address,data:this.encodeWrite("trustInviter",[J]),value:0n}}}class V$ 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}}var EJ=typeof globalThis==="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function LQ(J){return J instanceof Uint8Array||ArrayBuffer.isView(J)&&J.constructor.name==="Uint8Array"}function f$(J){if(!Number.isSafeInteger(J)||J<0)throw Error("positive integer expected, got "+J)}function xJ(J,...$){if(!LQ(J))throw Error("Uint8Array expected");if($.length>0&&!$.includes(J.length))throw Error("Uint8Array expected of length "+$+", got length="+J.length)}function Y0(J){if(typeof J!=="function"||typeof J.create!=="function")throw Error("Hash should be wrapped by utils.createHasher");f$(J.outputLen),f$(J.blockLen)}function oJ(J,$=!0){if(J.destroyed)throw Error("Hash instance has been destroyed");if($&&J.finished)throw Error("Hash#digest() has already been called")}function G0(J,$){xJ(J);let Q=$.outputLen;if(J.length<Q)throw Error("digestInto() expects output buffer of length at least "+Q)}function kJ(...J){for(let $=0;$<J.length;$++)J[$].fill(0)}function g$(J){return new DataView(J.buffer,J.byteOffset,J.byteLength)}function QJ(J,$){return J<<32-$|J>>>$}function TQ(J){if(typeof J!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(J))}function N$(J){if(typeof J==="string")J=TQ(J);return xJ(J),J}function M0(...J){let $=0;for(let Y=0;Y<J.length;Y++){let G=J[Y];xJ(G),$+=G.length}let Q=new Uint8Array($);for(let Y=0,G=0;Y<J.length;Y++){let M=J[Y];Q.set(M,G),G+=M.length}return Q}class O${}function Z0(J){let $=(Y)=>J().update(N$(Y)).digest(),Q=J();return $.outputLen=Q.outputLen,$.blockLen=Q.blockLen,$.create=()=>J(),$}function X0(J=32){if(EJ&&typeof EJ.getRandomValues==="function")return EJ.getRandomValues(new Uint8Array(J));if(EJ&&typeof EJ.randomBytes==="function")return Uint8Array.from(EJ.randomBytes(J));throw Error("crypto.getRandomValues must be defined")}function IQ(J,$,Q,Y){if(typeof J.setBigUint64==="function")return J.setBigUint64($,Q,Y);let G=BigInt(32),M=BigInt(4294967295),Z=Number(Q>>G&M),K=Number(Q&M),X=Y?4:0,q=Y?0:4;J.setUint32($+X,Z,Y),J.setUint32($+q,K,Y)}function K0(J,$,Q){return J&$^~J&Q}function q0(J,$,Q){return J&$^J&Q^$&Q}class M8 extends O${constructor(J,$,Q,Y){super();this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=J,this.outputLen=$,this.padOffset=Q,this.isLE=Y,this.buffer=new Uint8Array(J),this.view=g$(this.buffer)}update(J){oJ(this),J=N$(J),xJ(J);let{view:$,buffer:Q,blockLen:Y}=this,G=J.length;for(let M=0;M<G;){let Z=Math.min(Y-this.pos,G-M);if(Z===Y){let K=g$(J);for(;Y<=G-M;M+=Y)this.process(K,M);continue}if(Q.set(J.subarray(M,M+Z),this.pos),this.pos+=Z,M+=Z,this.pos===Y)this.process($,0),this.pos=0}return this.length+=J.length,this.roundClean(),this}digestInto(J){oJ(this),G0(J,this),this.finished=!0;let{buffer:$,view:Q,blockLen:Y,isLE:G}=this,{pos:M}=this;if($[M++]=128,kJ(this.buffer.subarray(M)),this.padOffset>Y-M)this.process(Q,0),M=0;for(let U=M;U<Y;U++)$[U]=0;IQ(Q,Y-8,BigInt(this.length*8),G),this.process(Q,0);let Z=g$(J),K=this.outputLen;if(K%4)throw Error("_sha2: outputLen should be aligned to 32bit");let X=K/4,q=this.get();if(X>q.length)throw Error("_sha2: outputLen bigger than state");for(let U=0;U<X;U++)Z.setUint32(4*U,q[U],G)}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:Y,finished:G,destroyed:M,pos:Z}=this;if(J.destroyed=M,J.finished=G,J.length=Y,J.pos=Z,Y%$)J.buffer.set(Q);return J}clone(){return this._cloneInto()}}var qJ=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var HQ=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]),CJ=new Uint32Array(64);class U0 extends M8{constructor(J=32){super(64,J,8,!1);this.A=qJ[0]|0,this.B=qJ[1]|0,this.C=qJ[2]|0,this.D=qJ[3]|0,this.E=qJ[4]|0,this.F=qJ[5]|0,this.G=qJ[6]|0,this.H=qJ[7]|0}get(){let{A:J,B:$,C:Q,D:Y,E:G,F:M,G:Z,H:K}=this;return[J,$,Q,Y,G,M,Z,K]}set(J,$,Q,Y,G,M,Z,K){this.A=J|0,this.B=$|0,this.C=Q|0,this.D=Y|0,this.E=G|0,this.F=M|0,this.G=Z|0,this.H=K|0}process(J,$){for(let U=0;U<16;U++,$+=4)CJ[U]=J.getUint32($,!1);for(let U=16;U<64;U++){let D=CJ[U-15],V=CJ[U-2],O=QJ(D,7)^QJ(D,18)^D>>>3,L=QJ(V,17)^QJ(V,19)^V>>>10;CJ[U]=L+CJ[U-7]+O+CJ[U-16]|0}let{A:Q,B:Y,C:G,D:M,E:Z,F:K,G:X,H:q}=this;for(let U=0;U<64;U++){let D=QJ(Z,6)^QJ(Z,11)^QJ(Z,25),V=q+D+K0(Z,K,X)+HQ[U]+CJ[U]|0,L=(QJ(Q,2)^QJ(Q,13)^QJ(Q,22))+q0(Q,Y,G)|0;q=X,X=K,K=Z,Z=M+V|0,M=G,G=Y,Y=Q,Q=V+L|0}Q=Q+this.A|0,Y=Y+this.B|0,G=G+this.C|0,M=M+this.D|0,Z=Z+this.E|0,K=K+this.F|0,X=X+this.G|0,q=q+this.H|0,this.set(Q,Y,G,M,Z,K,X,q)}roundClean(){kJ(CJ)}destroy(){this.set(0,0,0,0,0,0,0,0),kJ(this.buffer)}}var W0=Z0(()=>new U0);class Z8 extends O${constructor(J,$){super();this.finished=!1,this.destroyed=!1,Y0(J);let Q=N$($);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 Y=this.blockLen,G=new Uint8Array(Y);G.set(Q.length>Y?J.create().update(Q).digest():Q);for(let M=0;M<G.length;M++)G[M]^=54;this.iHash.update(G),this.oHash=J.create();for(let M=0;M<G.length;M++)G[M]^=106;this.oHash.update(G),kJ(G)}update(J){return oJ(this),this.iHash.update(J),this}digestInto(J){oJ(this),xJ(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:Y,destroyed:G,blockLen:M,outputLen:Z}=this;return J=J,J.finished=Y,J.destroyed=G,J.blockLen=M,J.outputLen=Z,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 X8=(J,$,Q)=>new Z8(J,$).update(Q).digest();X8.create=(J,$)=>new Z8(J,$);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var W8=BigInt(0),U8=BigInt(1);function aJ(J){return J instanceof Uint8Array||ArrayBuffer.isView(J)&&J.constructor.name==="Uint8Array"}function j8(J){if(!aJ(J))throw Error("Uint8Array expected")}function sJ(J,$){if(typeof $!=="boolean")throw Error(J+" boolean expected, got "+$)}function R$(J){let $=J.toString(16);return $.length&1?"0"+$:$}function D0(J){if(typeof J!=="string")throw Error("hex string expected, got "+typeof J);return J===""?W8:BigInt("0x"+J)}var V0=typeof Uint8Array.from([]).toHex==="function"&&typeof Uint8Array.fromHex==="function",SQ=Array.from({length:256},(J,$)=>$.toString(16).padStart(2,"0"));function rJ(J){if(j8(J),V0)return J.toHex();let $="";for(let Q=0;Q<J.length;Q++)$+=SQ[J[Q]];return $}var UJ={_0:48,_9:57,A:65,F:70,a:97,f:102};function j0(J){if(J>=UJ._0&&J<=UJ._9)return J-UJ._0;if(J>=UJ.A&&J<=UJ.F)return J-(UJ.A-10);if(J>=UJ.a&&J<=UJ.f)return J-(UJ.a-10);return}function C$(J){if(typeof J!=="string")throw Error("hex string expected, got "+typeof J);if(V0)return Uint8Array.fromHex(J);let $=J.length,Q=$/2;if($%2)throw Error("hex string expected, got unpadded hex of length "+$);let Y=new Uint8Array(Q);for(let G=0,M=0;G<Q;G++,M+=2){let Z=j0(J.charCodeAt(M)),K=j0(J.charCodeAt(M+1));if(Z===void 0||K===void 0){let X=J[M]+J[M+1];throw Error('hex string expected, got non-hex character "'+X+'" at index '+M)}Y[G]=Z*16+K}return Y}function WJ(J){return D0(rJ(J))}function z8(J){return j8(J),D0(rJ(Uint8Array.from(J).reverse()))}function bJ(J,$){return C$(J.toString(16).padStart($*2,"0"))}function D8(J,$){return bJ(J,$).reverse()}function s(J,$,Q){let Y;if(typeof $==="string")try{Y=C$($)}catch(M){throw Error(J+" must be hex string or Uint8Array, cause: "+M)}else if(aJ($))Y=Uint8Array.from($);else throw Error(J+" must be hex string or Uint8Array");let G=Y.length;if(typeof Q==="number"&&G!==Q)throw Error(J+" of length "+Q+" expected, got "+G);return Y}function P$(...J){let $=0;for(let Y=0;Y<J.length;Y++){let G=J[Y];j8(G),$+=G.length}let Q=new Uint8Array($);for(let Y=0,G=0;Y<J.length;Y++){let M=J[Y];Q.set(M,G),G+=M.length}return Q}var K8=(J)=>typeof J==="bigint"&&W8<=J;function v$(J,$,Q){return K8(J)&&K8($)&&K8(Q)&&$<=J&&J<Q}function FJ(J,$,Q,Y){if(!v$($,Q,Y))throw Error("expected valid "+J+": "+Q+" <= n < "+Y+", got "+$)}function N0(J){let $;for($=0;J>W8;J>>=U8,$+=1);return $}var fJ=(J)=>(U8<<BigInt(J))-U8,q8=(J)=>new Uint8Array(J),z0=(J)=>Uint8Array.from(J);function O0(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 Y=q8(J),G=q8(J),M=0,Z=()=>{Y.fill(1),G.fill(0),M=0},K=(...D)=>Q(G,Y,...D),X=(D=q8(0))=>{if(G=K(z0([0]),D),Y=K(),D.length===0)return;G=K(z0([1]),D),Y=K()},q=()=>{if(M++>=1000)throw Error("drbg: tried 1000 values");let D=0,V=[];while(D<$){Y=K();let O=Y.slice();V.push(O),D+=Y.length}return P$(...V)};return(D,V)=>{Z(),X(D);let O=void 0;while(!(O=V(q())))X();return Z(),O}}var _Q={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"||aJ(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 gJ(J,$,Q={}){let Y=(G,M,Z)=>{let K=_Q[M];if(typeof K!=="function")throw Error("invalid validator function");let X=J[G];if(Z&&X===void 0)return;if(!K(X,J))throw Error("param "+String(G)+" is invalid. Expected "+M+", got "+X)};for(let[G,M]of Object.entries($))Y(G,M,!1);for(let[G,M]of Object.entries(Q))Y(G,M,!0);return J}function V8(J){let $=new WeakMap;return(Q,...Y)=>{let G=$.get(Q);if(G!==void 0)return G;let M=J(Q,...Y);return $.set(Q,M),M}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var t=BigInt(0),n=BigInt(1),vJ=BigInt(2),yQ=BigInt(3),C0=BigInt(4),P0=BigInt(5),B0=BigInt(8);function d(J,$){let Q=J%$;return Q>=t?Q:$+Q}function e(J,$,Q){let Y=J;while($-- >t)Y*=Y,Y%=Q;return Y}function u$(J,$){if(J===t)throw Error("invert: expected non-zero number");if($<=t)throw Error("invert: expected positive modulus, got "+$);let Q=d(J,$),Y=$,G=t,M=n,Z=n,K=t;while(Q!==t){let q=Y/Q,U=Y%Q,D=G-Z*q,V=M-K*q;Y=Q,Q=U,G=Z,M=K,Z=D,K=V}if(Y!==n)throw Error("invert: does not exist");return d(G,$)}function L0(J,$){let Q=(J.ORDER+n)/C0,Y=J.pow($,Q);if(!J.eql(J.sqr(Y),$))throw Error("Cannot find square root");return Y}function AQ(J,$){let Q=(J.ORDER-P0)/B0,Y=J.mul($,vJ),G=J.pow(Y,Q),M=J.mul($,G),Z=J.mul(J.mul(M,vJ),G),K=J.mul(M,J.sub(Z,J.ONE));if(!J.eql(J.sqr(K),$))throw Error("Cannot find square root");return K}function wQ(J){if(J<BigInt(3))throw Error("sqrt is not defined for small field");let $=J-n,Q=0;while($%vJ===t)$/=vJ,Q++;let Y=vJ,G=B$(J);while(R0(G,Y)===1)if(Y++>1000)throw Error("Cannot find square root: probably non-prime P");if(Q===1)return L0;let M=G.pow(Y,$),Z=($+n)/vJ;return function(X,q){if(X.is0(q))return q;if(R0(X,q)!==1)throw Error("Cannot find square root");let U=Q,D=X.mul(X.ONE,M),V=X.pow(q,$),O=X.pow(q,Z);while(!X.eql(V,X.ONE)){if(X.is0(V))return X.ZERO;let L=1,N=X.sqr(V);while(!X.eql(N,X.ONE))if(L++,N=X.sqr(N),L===U)throw Error("Cannot find square root");let b=n<<BigInt(U-L-1),y=X.pow(D,b);U=L,D=X.sqr(y),V=X.mul(V,D),O=X.mul(O,y)}return O}}function EQ(J){if(J%C0===yQ)return L0;if(J%B0===P0)return AQ;return wQ(J)}var xQ=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function N8(J){let $={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},Q=xQ.reduce((Y,G)=>{return Y[G]="function",Y},$);return gJ(J,Q)}function kQ(J,$,Q){if(Q<t)throw Error("invalid exponent, negatives unsupported");if(Q===t)return J.ONE;if(Q===n)return $;let Y=J.ONE,G=$;while(Q>t){if(Q&n)Y=J.mul(Y,G);G=J.sqr(G),Q>>=n}return Y}function O8(J,$,Q=!1){let Y=Array($.length).fill(Q?J.ZERO:void 0),G=$.reduce((Z,K,X)=>{if(J.is0(K))return Z;return Y[X]=Z,J.mul(Z,K)},J.ONE),M=J.inv(G);return $.reduceRight((Z,K,X)=>{if(J.is0(K))return Z;return Y[X]=J.mul(Z,Y[X]),J.mul(Z,K)},M),Y}function R0(J,$){let Q=(J.ORDER-n)/vJ,Y=J.pow($,Q),G=J.eql(Y,J.ONE),M=J.eql(Y,J.ZERO),Z=J.eql(Y,J.neg(J.ONE));if(!G&&!M&&!Z)throw Error("invalid Legendre symbol result");return G?1:M?0:-1}function R8(J,$){if($!==void 0)f$($);let Q=$!==void 0?$:J.toString(2).length,Y=Math.ceil(Q/8);return{nBitLength:Q,nByteLength:Y}}function B$(J,$,Q=!1,Y={}){if(J<=t)throw Error("invalid field: expected ORDER > 0, got "+J);let{nBitLength:G,nByteLength:M}=R8(J,$);if(M>2048)throw Error("invalid field: expected ORDER of <= 2048 bytes");let Z,K=Object.freeze({ORDER:J,isLE:Q,BITS:G,BYTES:M,MASK:fJ(G),ZERO:t,ONE:n,create:(X)=>d(X,J),isValid:(X)=>{if(typeof X!=="bigint")throw Error("invalid field element: expected bigint, got "+typeof X);return t<=X&&X<J},is0:(X)=>X===t,isOdd:(X)=>(X&n)===n,neg:(X)=>d(-X,J),eql:(X,q)=>X===q,sqr:(X)=>d(X*X,J),add:(X,q)=>d(X+q,J),sub:(X,q)=>d(X-q,J),mul:(X,q)=>d(X*q,J),pow:(X,q)=>kQ(K,X,q),div:(X,q)=>d(X*u$(q,J),J),sqrN:(X)=>X*X,addN:(X,q)=>X+q,subN:(X,q)=>X-q,mulN:(X,q)=>X*q,inv:(X)=>u$(X,J),sqrt:Y.sqrt||((X)=>{if(!Z)Z=EQ(J);return Z(K,X)}),toBytes:(X)=>Q?D8(X,M):bJ(X,M),fromBytes:(X)=>{if(X.length!==M)throw Error("Field.fromBytes: expected "+M+" bytes, got "+X.length);return Q?z8(X):WJ(X)},invertBatch:(X)=>O8(K,X),cmov:(X,q,U)=>U?q:X});return Object.freeze(K)}function T0(J){if(typeof J!=="bigint")throw Error("field order must be bigint");let $=J.toString(2).length;return Math.ceil($/8)}function C8(J){let $=T0(J);return $+Math.ceil($/2)}function I0(J,$,Q=!1){let Y=J.length,G=T0($),M=C8($);if(Y<16||Y<M||Y>1024)throw Error("expected "+M+"-1024 bytes of input, got "+Y);let Z=Q?z8(J):WJ(J),K=d(Z,$-n)+n;return Q?D8(K,G):bJ(K,G)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var H0=BigInt(0),I8=BigInt(1);function P8(J,$){let Q=$.negate();return J?Q:$}function _0(J,$){if(!Number.isSafeInteger(J)||J<=0||J>$)throw Error("invalid window size, expected [1.."+$+"], got W="+J)}function B8(J,$){_0(J,$);let Q=Math.ceil($/J)+1,Y=2**(J-1),G=2**J,M=fJ(J),Z=BigInt(J);return{windows:Q,windowSize:Y,mask:M,maxNumber:G,shiftBy:Z}}function S0(J,$,Q){let{windowSize:Y,mask:G,maxNumber:M,shiftBy:Z}=Q,K=Number(J&G),X=J>>Z;if(K>Y)K-=M,X+=I8;let q=$*Y,U=q+Math.abs(K)-1,D=K===0,V=K<0,O=$%2!==0;return{nextN:X,offset:U,isZero:D,isNeg:V,isNegF:O,offsetF:q}}function bQ(J,$){if(!Array.isArray(J))throw Error("array expected");J.forEach((Q,Y)=>{if(!(Q instanceof $))throw Error("invalid point at index "+Y)})}function FQ(J,$){if(!Array.isArray(J))throw Error("array of scalars expected");J.forEach((Q,Y)=>{if(!$.isValid(Q))throw Error("invalid scalar at index "+Y)})}var L8=new WeakMap,y0=new WeakMap;function T8(J){return y0.get(J)||1}function A0(J,$){return{constTimeNegate:P8,hasPrecomputes(Q){return T8(Q)!==1},unsafeLadder(Q,Y,G=J.ZERO){let M=Q;while(Y>H0){if(Y&I8)G=G.add(M);M=M.double(),Y>>=I8}return G},precomputeWindow(Q,Y){let{windows:G,windowSize:M}=B8(Y,$),Z=[],K=Q,X=K;for(let q=0;q<G;q++){X=K,Z.push(X);for(let U=1;U<M;U++)X=X.add(K),Z.push(X);K=X.double()}return Z},wNAF(Q,Y,G){let{ZERO:M,BASE:Z}=J,K=B8(Q,$);for(let X=0;X<K.windows;X++){let{nextN:q,offset:U,isZero:D,isNeg:V,isNegF:O,offsetF:L}=S0(G,X,K);if(G=q,D)Z=Z.add(P8(O,Y[L]));else M=M.add(P8(V,Y[U]))}return{p:M,f:Z}},wNAFUnsafe(Q,Y,G,M=J.ZERO){let Z=B8(Q,$);for(let K=0;K<Z.windows;K++){if(G===H0)break;let{nextN:X,offset:q,isZero:U,isNeg:D}=S0(G,K,Z);if(G=X,U)continue;else{let V=Y[q];M=M.add(D?V.negate():V)}}return M},getPrecomputes(Q,Y,G){let M=L8.get(Y);if(!M){if(M=this.precomputeWindow(Y,Q),Q!==1)L8.set(Y,G(M))}return M},wNAFCached(Q,Y,G){let M=T8(Q);return this.wNAF(M,this.getPrecomputes(M,Q,G),Y)},wNAFCachedUnsafe(Q,Y,G,M){let Z=T8(Q);if(Z===1)return this.unsafeLadder(Q,Y,M);return this.wNAFUnsafe(Z,this.getPrecomputes(Z,Q,G),Y,M)},setWindowSize(Q,Y){_0(Y,$),y0.set(Q,Y),L8.delete(Q)}}}function w0(J,$,Q,Y){bQ(Q,J),FQ(Y,$);let G=Q.length,M=Y.length;if(G!==M)throw Error("arrays of points and scalars must have equal length");let Z=J.ZERO,K=N0(BigInt(G)),X=1;if(K>12)X=K-3;else if(K>4)X=K-2;else if(K>0)X=2;let q=fJ(X),U=Array(Number(q)+1).fill(Z),D=Math.floor(($.BITS-1)/X)*X,V=Z;for(let O=D;O>=0;O-=X){U.fill(Z);for(let N=0;N<M;N++){let b=Y[N],y=Number(b>>BigInt(O)&q);U[y]=U[y].add(Q[N])}let L=Z;for(let N=U.length-1,b=Z;N>0;N--)b=b.add(U[N]),L=L.add(b);if(V=V.add(L),O!==0)for(let N=0;N<X;N++)V=V.double()}return V}function H8(J){return N8(J.Fp),gJ(J,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...R8(J.n,J.nBitLength),...J,...{p:J.Fp.ORDER}})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function E0(J){if(J.lowS!==void 0)sJ("lowS",J.lowS);if(J.prehash!==void 0)sJ("prehash",J.prehash)}function fQ(J){let $=H8(J);gJ($,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});let{endo:Q,Fp:Y,a:G}=$;if(Q){if(!Y.eql(G,Y.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 x0 extends Error{constructor(J=""){super(J)}}var jJ={Err:x0,_tlv:{encode:(J,$)=>{let{Err:Q}=jJ;if(J<0||J>256)throw new Q("tlv.encode: wrong tag");if($.length&1)throw new Q("tlv.encode: unpadded data");let Y=$.length/2,G=R$(Y);if(G.length/2&128)throw new Q("tlv.encode: long form length too big");let M=Y>127?R$(G.length/2|128):"";return R$(J)+M+G+$},decode(J,$){let{Err:Q}=jJ,Y=0;if(J<0||J>256)throw new Q("tlv.encode: wrong tag");if($.length<2||$[Y++]!==J)throw new Q("tlv.decode: wrong tlv");let G=$[Y++],M=!!(G&128),Z=0;if(!M)Z=G;else{let X=G&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 q=$.subarray(Y,Y+X);if(q.length!==X)throw new Q("tlv.decode: length bytes not complete");if(q[0]===0)throw new Q("tlv.decode(long): zero leftmost byte");for(let U of q)Z=Z<<8|U;if(Y+=X,Z<128)throw new Q("tlv.decode(long): not minimal encoding")}let K=$.subarray(Y,Y+Z);if(K.length!==Z)throw new Q("tlv.decode: wrong value length");return{v:K,l:$.subarray(Y+Z)}}},_int:{encode(J){let{Err:$}=jJ;if(J<zJ)throw new $("integer: negative integers are not allowed");let Q=R$(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:$}=jJ;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 WJ(J)}},toSig(J){let{Err:$,_int:Q,_tlv:Y}=jJ,G=s("signature",J),{v:M,l:Z}=Y.decode(48,G);if(Z.length)throw new $("invalid signature: left bytes after parsing");let{v:K,l:X}=Y.decode(2,M),{v:q,l:U}=Y.decode(2,X);if(U.length)throw new $("invalid signature: left bytes after parsing");return{r:Q.decode(K),s:Q.decode(q)}},hexFromSig(J){let{_tlv:$,_int:Q}=jJ,Y=$.encode(2,Q.encode(J.r)),G=$.encode(2,Q.encode(J.s)),M=Y+G;return $.encode(48,M)}};function S8(J,$){return rJ(bJ(J,$))}var zJ=BigInt(0),h=BigInt(1),hM=BigInt(2),_8=BigInt(3),gQ=BigInt(4);function vQ(J){let $=fQ(J),{Fp:Q}=$,Y=B$($.n,$.nBitLength),G=$.toBytes||((W,j,P)=>{let B=j.toAffine();return P$(Uint8Array.from([4]),Q.toBytes(B.x),Q.toBytes(B.y))}),M=$.fromBytes||((W)=>{let j=W.subarray(1),P=Q.fromBytes(j.subarray(0,Q.BYTES)),B=Q.fromBytes(j.subarray(Q.BYTES,2*Q.BYTES));return{x:P,y:B}});function Z(W){let{a:j,b:P}=$,B=Q.sqr(W),E=Q.mul(B,W);return Q.add(Q.add(E,Q.mul(W,j)),P)}function K(W,j){let P=Q.sqr(j),B=Z(W);return Q.eql(P,B)}if(!K($.Gx,$.Gy))throw Error("bad curve params: generator point");let X=Q.mul(Q.pow($.a,_8),gQ),q=Q.mul(Q.sqr($.b),BigInt(27));if(Q.is0(Q.add(X,q)))throw Error("bad curve params: a or b");function U(W){return v$(W,h,$.n)}function D(W){let{allowedPrivateKeyLengths:j,nByteLength:P,wrapPrivateKey:B,n:E}=$;if(j&&typeof W!=="bigint"){if(aJ(W))W=rJ(W);if(typeof W!=="string"||!j.includes(W.length))throw Error("invalid private key");W=W.padStart(P*2,"0")}let x;try{x=typeof W==="bigint"?W:WJ(s("private key",W,P))}catch(k){throw Error("invalid private key, expected hex or "+P+" bytes, got "+typeof W)}if(B)x=d(x,E);return FJ("private key",x,h,E),x}function V(W){if(!(W instanceof N))throw Error("ProjectivePoint expected")}let O=V8((W,j)=>{let{px:P,py:B,pz:E}=W;if(Q.eql(E,Q.ONE))return{x:P,y:B};let x=W.is0();if(j==null)j=x?Q.ONE:Q.inv(E);let k=Q.mul(P,j),S=Q.mul(B,j),A=Q.mul(E,j);if(x)return{x:Q.ZERO,y:Q.ZERO};if(!Q.eql(A,Q.ONE))throw Error("invZ was invalid");return{x:k,y:S}}),L=V8((W)=>{if(W.is0()){if($.allowInfinityPoint&&!Q.is0(W.py))return;throw Error("bad point: ZERO")}let{x:j,y:P}=W.toAffine();if(!Q.isValid(j)||!Q.isValid(P))throw Error("bad point: x or y not FE");if(!K(j,P))throw Error("bad point: equation left != right");if(!W.isTorsionFree())throw Error("bad point: not in prime-order subgroup");return!0});class N{constructor(W,j,P){if(W==null||!Q.isValid(W))throw Error("x required");if(j==null||!Q.isValid(j)||Q.is0(j))throw Error("y required");if(P==null||!Q.isValid(P))throw Error("z required");this.px=W,this.py=j,this.pz=P,Object.freeze(this)}static fromAffine(W){let{x:j,y:P}=W||{};if(!W||!Q.isValid(j)||!Q.isValid(P))throw Error("invalid affine point");if(W instanceof N)throw Error("projective point not allowed");let B=(E)=>Q.eql(E,Q.ZERO);if(B(j)&&B(P))return N.ZERO;return new N(j,P,Q.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(W){let j=O8(Q,W.map((P)=>P.pz));return W.map((P,B)=>P.toAffine(j[B])).map(N.fromAffine)}static fromHex(W){let j=N.fromAffine(M(s("pointHex",W)));return j.assertValidity(),j}static fromPrivateKey(W){return N.BASE.multiply(D(W))}static msm(W,j){return w0(N,Y,W,j)}_setWindowSize(W){f.setWindowSize(this,W)}assertValidity(){L(this)}hasEvenY(){let{y:W}=this.toAffine();if(Q.isOdd)return!Q.isOdd(W);throw Error("Field doesn't support isOdd")}equals(W){V(W);let{px:j,py:P,pz:B}=this,{px:E,py:x,pz:k}=W,S=Q.eql(Q.mul(j,k),Q.mul(E,B)),A=Q.eql(Q.mul(P,k),Q.mul(x,B));return S&&A}negate(){return new N(this.px,Q.neg(this.py),this.pz)}double(){let{a:W,b:j}=$,P=Q.mul(j,_8),{px:B,py:E,pz:x}=this,k=Q.ZERO,S=Q.ZERO,A=Q.ZERO,_=Q.mul(B,B),l=Q.mul(E,E),u=Q.mul(x,x),z=Q.mul(B,E);return z=Q.add(z,z),A=Q.mul(B,x),A=Q.add(A,A),k=Q.mul(W,A),S=Q.mul(P,u),S=Q.add(k,S),k=Q.sub(l,S),S=Q.add(l,S),S=Q.mul(k,S),k=Q.mul(z,k),A=Q.mul(P,A),u=Q.mul(W,u),z=Q.sub(_,u),z=Q.mul(W,z),z=Q.add(z,A),A=Q.add(_,_),_=Q.add(A,_),_=Q.add(_,u),_=Q.mul(_,z),S=Q.add(S,_),u=Q.mul(E,x),u=Q.add(u,u),_=Q.mul(u,z),k=Q.sub(k,_),A=Q.mul(u,l),A=Q.add(A,A),A=Q.add(A,A),new N(k,S,A)}add(W){V(W);let{px:j,py:P,pz:B}=this,{px:E,py:x,pz:k}=W,S=Q.ZERO,A=Q.ZERO,_=Q.ZERO,l=$.a,u=Q.mul($.b,_8),z=Q.mul(j,E),C=Q.mul(P,x),T=Q.mul(B,k),F=Q.add(j,P),I=Q.add(E,x);F=Q.mul(F,I),I=Q.add(z,C),F=Q.sub(F,I),I=Q.add(j,B);let w=Q.add(E,k);return I=Q.mul(I,w),w=Q.add(z,T),I=Q.sub(I,w),w=Q.add(P,B),S=Q.add(x,k),w=Q.mul(w,S),S=Q.add(C,T),w=Q.sub(w,S),_=Q.mul(l,I),S=Q.mul(u,T),_=Q.add(S,_),S=Q.sub(C,_),_=Q.add(C,_),A=Q.mul(S,_),C=Q.add(z,z),C=Q.add(C,z),T=Q.mul(l,T),I=Q.mul(u,I),C=Q.add(C,T),T=Q.sub(z,T),T=Q.mul(l,T),I=Q.add(I,T),z=Q.mul(C,I),A=Q.add(A,z),z=Q.mul(w,I),S=Q.mul(F,S),S=Q.sub(S,z),z=Q.mul(F,C),_=Q.mul(w,_),_=Q.add(_,z),new N(S,A,_)}subtract(W){return this.add(W.negate())}is0(){return this.equals(N.ZERO)}wNAF(W){return f.wNAFCached(this,W,N.normalizeZ)}multiplyUnsafe(W){let{endo:j,n:P}=$;FJ("scalar",W,zJ,P);let B=N.ZERO;if(W===zJ)return B;if(this.is0()||W===h)return this;if(!j||f.hasPrecomputes(this))return f.wNAFCachedUnsafe(this,W,N.normalizeZ);let{k1neg:E,k1:x,k2neg:k,k2:S}=j.splitScalar(W),A=B,_=B,l=this;while(x>zJ||S>zJ){if(x&h)A=A.add(l);if(S&h)_=_.add(l);l=l.double(),x>>=h,S>>=h}if(E)A=A.negate();if(k)_=_.negate();return _=new N(Q.mul(_.px,j.beta),_.py,_.pz),A.add(_)}multiply(W){let{endo:j,n:P}=$;FJ("scalar",W,h,P);let B,E;if(j){let{k1neg:x,k1:k,k2neg:S,k2:A}=j.splitScalar(W),{p:_,f:l}=this.wNAF(k),{p:u,f:z}=this.wNAF(A);_=f.constTimeNegate(x,_),u=f.constTimeNegate(S,u),u=new N(Q.mul(u.px,j.beta),u.py,u.pz),B=_.add(u),E=l.add(z)}else{let{p:x,f:k}=this.wNAF(W);B=x,E=k}return N.normalizeZ([B,E])[0]}multiplyAndAddUnsafe(W,j,P){let B=N.BASE,E=(k,S)=>S===zJ||S===h||!k.equals(B)?k.multiplyUnsafe(S):k.multiply(S),x=E(this,j).add(E(W,P));return x.is0()?void 0:x}toAffine(W){return O(this,W)}isTorsionFree(){let{h:W,isTorsionFree:j}=$;if(W===h)return!0;if(j)return j(N,this);throw Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:W,clearCofactor:j}=$;if(W===h)return this;if(j)return j(N,this);return this.multiplyUnsafe($.h)}toRawBytes(W=!0){return sJ("isCompressed",W),this.assertValidity(),G(N,this,W)}toHex(W=!0){return sJ("isCompressed",W),rJ(this.toRawBytes(W))}}N.BASE=new N($.Gx,$.Gy,Q.ONE),N.ZERO=new N(Q.ZERO,Q.ONE,Q.ZERO);let{endo:b,nBitLength:y}=$,f=A0(N,b?Math.ceil(y/2):y);return{CURVE:$,ProjectivePoint:N,normPrivateKeyToScalar:D,weierstrassEquation:Z,isWithinCurveOrder:U}}function uQ(J){let $=H8(J);return gJ($,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...$})}function k0(J){let $=uQ(J),{Fp:Q,n:Y,nByteLength:G,nBitLength:M}=$,Z=Q.BYTES+1,K=2*Q.BYTES+1;function X(z){return d(z,Y)}function q(z){return u$(z,Y)}let{ProjectivePoint:U,normPrivateKeyToScalar:D,weierstrassEquation:V,isWithinCurveOrder:O}=vQ({...$,toBytes(z,C,T){let F=C.toAffine(),I=Q.toBytes(F.x),w=P$;if(sJ("isCompressed",T),T)return w(Uint8Array.from([C.hasEvenY()?2:3]),I);else return w(Uint8Array.from([4]),I,Q.toBytes(F.y))},fromBytes(z){let C=z.length,T=z[0],F=z.subarray(1);if(C===Z&&(T===2||T===3)){let I=WJ(F);if(!v$(I,h,Q.ORDER))throw Error("Point is not on curve");let w=V(I),$J;try{$J=Q.sqrt(w)}catch(GJ){let a=GJ instanceof Error?": "+GJ.message:"";throw Error("Point is not on curve"+a)}let i=($J&h)===h;if((T&1)===1!==i)$J=Q.neg($J);return{x:I,y:$J}}else if(C===K&&T===4){let I=Q.fromBytes(F.subarray(0,Q.BYTES)),w=Q.fromBytes(F.subarray(Q.BYTES,2*Q.BYTES));return{x:I,y:w}}else{let I=Z,w=K;throw Error("invalid Point, expected length of "+I+", or uncompressed "+w+", got "+C)}}});function L(z){let C=Y>>h;return z>C}function N(z){return L(z)?X(-z):z}let b=(z,C,T)=>WJ(z.slice(C,T));class y{constructor(z,C,T){if(FJ("r",z,h,Y),FJ("s",C,h,Y),this.r=z,this.s=C,T!=null)this.recovery=T;Object.freeze(this)}static fromCompact(z){let C=G;return z=s("compactSignature",z,C*2),new y(b(z,0,C),b(z,C,2*C))}static fromDER(z){let{r:C,s:T}=jJ.toSig(s("DER",z));return new y(C,T)}assertValidity(){}addRecoveryBit(z){return new y(this.r,this.s,z)}recoverPublicKey(z){let{r:C,s:T,recovery:F}=this,I=E(s("msgHash",z));if(F==null||![0,1,2,3].includes(F))throw Error("recovery id invalid");let w=F===2||F===3?C+$.n:C;if(w>=Q.ORDER)throw Error("recovery id 2 or 3 invalid");let $J=(F&1)===0?"02":"03",i=U.fromHex($J+S8(w,Q.BYTES)),YJ=q(w),GJ=X(-I*YJ),a=X(T*YJ),DJ=U.BASE.multiplyAndAddUnsafe(i,GJ,a);if(!DJ)throw Error("point at infinify");return DJ.assertValidity(),DJ}hasHighS(){return L(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,X(-this.s),this.recovery):this}toDERRawBytes(){return C$(this.toDERHex())}toDERHex(){return jJ.hexFromSig(this)}toCompactRawBytes(){return C$(this.toCompactHex())}toCompactHex(){let z=G;return S8(this.r,z)+S8(this.s,z)}}let f={isValidPrivateKey(z){try{return D(z),!0}catch(C){return!1}},normPrivateKeyToScalar:D,randomPrivateKey:()=>{let z=C8($.n);return I0($.randomBytes(z),$.n)},precompute(z=8,C=U.BASE){return C._setWindowSize(z),C.multiply(BigInt(3)),C}};function W(z,C=!0){return U.fromPrivateKey(z).toRawBytes(C)}function j(z){if(typeof z==="bigint")return!1;if(z instanceof U)return!0;let T=s("key",z).length,F=Q.BYTES,I=F+1,w=2*F+1;if($.allowedPrivateKeyLengths||G===I)return;else return T===I||T===w}function P(z,C,T=!0){if(j(z)===!0)throw Error("first arg must be private key");if(j(C)===!1)throw Error("second arg must be public key");return U.fromHex(C).multiply(D(z)).toRawBytes(T)}let B=$.bits2int||function(z){if(z.length>8192)throw Error("input is too large");let C=WJ(z),T=z.length*8-M;return T>0?C>>BigInt(T):C},E=$.bits2int_modN||function(z){return X(B(z))},x=fJ(M);function k(z){return FJ("num < 2^"+M,z,zJ,x),bJ(z,G)}function S(z,C,T=A){if(["recovered","canonical"].some((BJ)=>(BJ in T)))throw Error("sign() legacy options not supported");let{hash:F,randomBytes:I}=$,{lowS:w,prehash:$J,extraEntropy:i}=T;if(w==null)w=!0;if(z=s("msgHash",z),E0(T),$J)z=s("prehashed msgHash",F(z));let YJ=E(z),GJ=D(C),a=[k(GJ),k(YJ)];if(i!=null&&i!==!1){let BJ=i===!0?I(Q.BYTES):i;a.push(s("extraEntropy",BJ))}let DJ=P$(...a),T$=YJ;function l$(BJ){let mJ=B(BJ);if(!O(mJ))return;let c$=q(mJ),J$=U.BASE.multiply(mJ).toAffine(),LJ=X(J$.x);if(LJ===zJ)return;let $$=X(c$*X(T$+LJ*GJ));if($$===zJ)return;let hJ=(J$.x===LJ?0:2)|Number(J$.y&h),F8=$$;if(w&&L($$))F8=N($$),hJ^=1;return new y(LJ,F8,hJ)}return{seed:DJ,k2sig:l$}}let A={lowS:$.lowS,prehash:!1},_={lowS:$.lowS,prehash:!1};function l(z,C,T=A){let{seed:F,k2sig:I}=S(z,C,T),w=$;return O0(w.hash.outputLen,w.nByteLength,w.hmac)(F,I)}U.BASE._setWindowSize(8);function u(z,C,T,F=_){let I=z;C=s("msgHash",C),T=s("publicKey",T);let{lowS:w,prehash:$J,format:i}=F;if(E0(F),"strict"in F)throw Error("options.strict was renamed to lowS");if(i!==void 0&&i!=="compact"&&i!=="der")throw Error("format must be compact or der");let YJ=typeof I==="string"||aJ(I),GJ=!YJ&&!i&&typeof I==="object"&&I!==null&&typeof I.r==="bigint"&&typeof I.s==="bigint";if(!YJ&&!GJ)throw Error("invalid signature, expected Uint8Array, hex string or Signature instance");let a=void 0,DJ;try{if(GJ)a=new y(I.r,I.s);if(YJ){try{if(i!=="compact")a=y.fromDER(I)}catch(hJ){if(!(hJ instanceof jJ.Err))throw hJ}if(!a&&i!=="der")a=y.fromCompact(I)}DJ=U.fromHex(T)}catch(hJ){return!1}if(!a)return!1;if(w&&a.hasHighS())return!1;if($J)C=$.hash(C);let{r:T$,s:l$}=a,BJ=E(C),mJ=q(l$),c$=X(BJ*mJ),J$=X(T$*mJ),LJ=U.BASE.multiplyAndAddUnsafe(DJ,c$,J$)?.toAffine();if(!LJ)return!1;return X(LJ.x)===T$}return{CURVE:$,getPublicKey:W,getSharedSecret:P,sign:l,verify:u,ProjectivePoint:U,Signature:y,utils:f}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function mQ(J){return{hash:J,hmac:($,...Q)=>X8(J,$,M0(...Q)),randomBytes:X0}}function b0(J,$){let Q=(Y)=>k0({...J,...mQ(Y)});return{...Q($),create:Q}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */var g0=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),F0=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),hQ=BigInt(0),lQ=BigInt(1),y8=BigInt(2),f0=(J,$)=>(J+$/y8)/$;function cQ(J){let $=g0,Q=BigInt(3),Y=BigInt(6),G=BigInt(11),M=BigInt(22),Z=BigInt(23),K=BigInt(44),X=BigInt(88),q=J*J*J%$,U=q*q*J%$,D=e(U,Q,$)*U%$,V=e(D,Q,$)*U%$,O=e(V,y8,$)*q%$,L=e(O,G,$)*O%$,N=e(L,M,$)*L%$,b=e(N,K,$)*N%$,y=e(b,X,$)*b%$,f=e(y,K,$)*N%$,W=e(f,Q,$)*U%$,j=e(W,Z,$)*L%$,P=e(j,Y,$)*q%$,B=e(P,y8,$);if(!A8.eql(A8.sqr(B),J))throw Error("Cannot find square root");return B}var A8=B$(g0,void 0,void 0,{sqrt:cQ}),w8=b0({a:hQ,b:BigInt(7),Fp:A8,n:F0,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:(J)=>{let $=F0,Q=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),Y=-lQ*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),G=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),M=Q,Z=BigInt("0x100000000000000000000000000000000"),K=f0(M*J,$),X=f0(-Y*J,$),q=d(J-K*Q-X*G,$),U=d(-K*Y-X*M,$),D=q>Z,V=U>Z;if(D)q=$-q;if(V)U=$-U;if(q>Z||U>Z)throw Error("splitScalar: Endomorphism failed, k="+J);return{k1neg:D,k1:q,k2neg:V,k2:U}}}},W0);function m$(){let J=w8.utils.randomPrivateKey();return"0x"+Buffer.from(J).toString("hex")}function eJ(J){let $=J.startsWith("0x")?J.slice(2):J,Q=Buffer.from($,"hex"),Y=w8.getPublicKey(Q,!1),M=cJ(Y.slice(1)).slice(-20),Z="0x"+Buffer.from(M).toString("hex");return OJ(Z)}function h$(J){let $;if(typeof J==="string"){let Y=J.startsWith("0x")?J.slice(2):J;$=Buffer.from(Y,"hex")}else $=J;let Q=cJ($);return"0x"+Buffer.from(Q).toString("hex")}class o extends V${httpStatus;constructor(J,$){super("ReferralError",J,{...$,source:$?.source||"REFERRALS"});this.httpStatus=$?.httpStatus}static notFoundOnChain(J){return new o(`Referral not found on-chain for signer ${J}`,{code:"REFERRAL_NOT_FOUND_ONCHAIN",source:"ONCHAIN",httpStatus:404,context:{signer:J}})}static alreadyClaimed(J){return new o(`Referral for signer ${J} has already been claimed`,{code:"REFERRAL_ALREADY_CLAIMED",source:"ONCHAIN",httpStatus:410,context:{signer:J}})}static storeFailed(J){return new o(`Failed to store referral: ${J}`,{code:"REFERRAL_STORE_FAILED"})}static storeBatchFailed(J){return new o(`Failed to store referral batch: ${J}`,{code:"REFERRAL_STORE_BATCH_FAILED"})}static retrieveFailed(J,$){return new o(`Failed to retrieve referral: ${J}`,{code:"REFERRAL_RETRIEVE_FAILED",httpStatus:$})}static listFailed(J){return new o(`Failed to list referrals: ${J}`,{code:"REFERRAL_LIST_FAILED"})}static authRequired(){return new o("Authentication required to list referrals",{code:"REFERRAL_AUTH_REQUIRED",source:"VALIDATION"})}}class v extends V${constructor(J,$){super("InvitationError",J,{...$,source:$?.source||"INVITATIONS"})}static noPathFound(J,$,Q){return new v(`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 v(`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,Y,G,M){let Z=Number(Q)/1000000000000000000,K=Number(Y)/1000000000000000000;return new v(`Insufficient balance for ${J} invitation(s). Can only afford ${$} invitation(s). Requested: ${Z.toFixed(6)} CRC, Available: ${K.toFixed(6)} CRC.`,{code:"INVITATION_INSUFFICIENT_BALANCE",source:"VALIDATION",context:{from:G,to:M,requestedInvites:J,availableInvites:$,requested:Q.toString(),available:Y.toString(),requestedCrc:Z,availableCrc:K}})}static inviteeAlreadyRegistered(J,$){return new v(`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 v("At least one address must be provided for invitation.",{code:"INVITATION_NO_ADDRESSES_PROVIDED",source:"VALIDATION"})}}var v0=[];for(let J=0;J<256;J++)v0[J]=J.toString(16).padStart(2,"0");function L$(J){let $="0x";for(let Q=0;Q<J.length;Q++)$+=v0[J[Q]];return $}function u0(J){let $=new Uint8Array(J.length*2);return J.forEach((Q,Y)=>{let G=Q>>8,M=Q&255,Z=2*Y;$[Z]=G,$[Z+1]=M}),L$($)}function m0(J,$,Q){let Y=new Set([$.toLowerCase(),Q.toLowerCase()]);J.forEach((Z)=>{Y.add(Z.from.toLowerCase()),Y.add(Z.to.toLowerCase()),Y.add(Z.tokenOwner.toLowerCase())});let G=[...Y].sort((Z,K)=>{let X=BigInt(Z),q=BigInt(K),U=X<q,D=X>q;return U?-1:D?1:0}),M={};return G.forEach((Z,K)=>{M[Z]=K}),{sorted:G,idx:M}}function pQ(J,$){let Q=new Set,Y=[],G=null;if(J.forEach((M,Z)=>{let K=M.from.toLowerCase(),X=M.to.toLowerCase();if(K===$&&X===$)G=Z;else if(X===$)Y.push(Z)}),G!==null)Q.add(G);else Y.forEach((M)=>Q.add(M));return Q}function h0(J,$,Q,Y){let G=J.toLowerCase(),M=$.toLowerCase(),{sorted:Z,idx:K}=m0(Y,G,M),X=pQ(Y,M),q=Y.map((y,f)=>{return{streamSinkId:X.has(f)?1:0,amount:y.value}});if(X.size===0)throw Error(`No terminal edges detected. Flow must have at least one edge delivering to receiver ${M}`);let U=Array.from(X),D=[{sourceCoordinate:K[G],flowEdgeIds:U,data:new Uint8Array(0)}],V=[];Y.forEach((y)=>{V.push(K[y.tokenOwner.toLowerCase()]),V.push(K[y.from.toLowerCase()]),V.push(K[y.to.toLowerCase()])});let O=u0(V),L=BigInt(Q),N=q.filter((y)=>y.streamSinkId===1).reduce((y,f)=>y+BigInt(f.amount.toString()),BigInt(0));if(N!==L)throw Error(`Terminal sum ${N} does not equal expected ${L}`);return{flowVertices:Z,flowEdges:q,streams:D,packedCoordinates:O,sourceCoordinate:K[G]}}function l0(J,$){let Q=J.streams.map((Y)=>({sourceCoordinate:Y.sourceCoordinate,flowEdgeIds:Y.flowEdgeIds,data:Y.data instanceof Uint8Array?L$(Y.data):Y.data}));if($&&Q.length>0)Q[0].data=$ instanceof Uint8Array?L$($):$;return Q}async function c0(J,$,Q){let Y=new Map,G=new Set;return Q.transfers.forEach((K)=>{if(J.toLowerCase()===K.from.toLowerCase())G.add(K.tokenOwner.toLowerCase())}),(await new x$($).token.getTokenInfoBatch(Array.from(G))).forEach((K)=>{if(K.isWrapped&&!K.isInflationary)K.tokenType="CrcV2_ERC20WrapperDeployed_Demurraged";Y.set(K.tokenAddress.toLowerCase(),K)}),Y}function p0(J,$){let Q={};return J.transfers.forEach((Y)=>{let G=$.get(Y.tokenOwner.toLowerCase());if(G&&G.tokenType.startsWith("CrcV2_ERC20WrapperDeployed")){if(!Q[Y.tokenOwner])Q[Y.tokenOwner]=[BigInt(0),G.tokenType];Q[Y.tokenOwner][0]+=BigInt(Y.value)}}),Q}function d0(J,$){let Q=J.transfers.map((Y)=>{let G=$.get(Y.tokenOwner.toLowerCase());if(G&&G.tokenType.startsWith("CrcV2_ERC20WrapperDeployed"))return{...Y,tokenOwner:G.tokenOwner};return Y});return{...J,transfers:Q}}class JJ extends Y${constructor(J,$){super("TransferError",J,{...$,source:$?.source||"TRANSFERS"})}static noPathFound(J,$,Q){return new JJ(`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,Y){let G=Number(J)/1000000000000000000,M=Number($)/1000000000000000000;return new JJ(`Insufficient balance for transfer. Requested: ${G.toFixed(6)} CRC, Available: ${M.toFixed(6)} CRC.`,{code:"TRANSFER_INSUFFICIENT_BALANCE",source:"VALIDATION",context:{from:Q,to:Y,requested:J.toString(),available:$.toString(),requestedCrc:G,availableCrc:M}})}static wrappedTokensRequired(){return new JJ("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 JJ(`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 JJ(`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 JJ(`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 RJ({address:J.v2HubAddress,rpcUrl:J.circlesRpcUrl}),this.liftERC20=new k$({address:J.liftERC20Address,rpcUrl:J.circlesRpcUrl}),this.rpcClient=new VJ(J.circlesRpcUrl),this.pathfinder=new KJ(this.rpcClient),this.balance=new yJ(this.rpcClient),this.group=new wJ(this.rpcClient)}async buildFlowMatrixTx(J,$,Q,Y,G=!1){let M=J.toLowerCase(),Z=$.toLowerCase();if(!Q.transfers||Q.transfers.length===0)throw JJ.noPathFound(M,Z);let K={...Q};if(G&&Y?.toTokens?.length===1){let f=Y.toTokens[0].toLowerCase();if(Q.maxFlow>0n)K.transfers.push({from:Z,to:Z,tokenOwner:f,value:Q.maxFlow})}let X=await c0(M,this.config.circlesRpcUrl,K),q=p0(K,X),U=Object.keys(q).length>0;if(U&&!Y?.useWrappedBalances)throw JJ.wrappedTokensRequired();let D=[],V=[];if(U){let f=await this._getTokenBalanceMap(M),W=this._createDemurragedUnwrapCalls(q),{unwrapCalls:j,wrapCalls:P}=this._createInflationaryUnwrapAndWrapCalls(q,X,f);D=[...W,...j],V=P,K=d0(K,X)}let O=h0(M,Z,K.maxFlow,K.transfers),L=l0(O,Y?.txData),N=this.hubV2.operateFlowMatrix(O.flowVertices,O.flowEdges,L,O.packedCoordinates),b=!1;try{b=await this.hubV2.isApprovedForAll(M,M)}catch(f){console.warn("Failed to check approval status, including approval transaction:",f)}return[...b?[]:[this.hubV2.setApprovalForAll(M,!0)],...D,N,...V]}async constructAdvancedTransfer(J,$,Q,Y,G=!1){let M=J.toLowerCase(),Z=$.toLowerCase(),K=BigInt(Q);if(M===Z&&Y?.fromTokens?.length===1&&Y?.toTokens?.length===1){let O=Y.fromTokens[0],L=Y.toTokens[0],[N,b]=await Promise.all([this.liftERC20.erc20Circles(0,L),this.liftERC20.erc20Circles(1,L)]);if(O.toLowerCase()===N.toLowerCase()&&N!==IJ){let f=new z$({address:O,rpcUrl:this.config.circlesRpcUrl}).unwrap(K);return[{to:f.to,data:f.data,value:f.value??0n}]}if(O.toLowerCase()===b.toLowerCase()&&b!==IJ){let y=new D$({address:O,rpcUrl:this.config.circlesRpcUrl}),f=nJ.attoCirclesToAttoStaticCircles(K),W=y.unwrap(f);return[{to:W.to,data:W.data,value:W.value??0n}]}}let X=this._truncateToSixDecimals(K),q=await this._getDefaultTokenExcludeList(Z,Y?.excludeFromTokens),{...U}=Y||{},D={...U,...q?{excludeFromTokens:q}:{}},V=await this.pathfinder.findPath({from:M,to:Z,targetFlow:X,...D});if(!V.transfers||V.transfers.length===0)throw JJ.noPathFound(M,Z);if(V.maxFlow<X)throw JJ.insufficientBalance(X,V.maxFlow,M,Z);return this.buildFlowMatrixTx(M,Z,V,Y,G)}async _getTokenBalanceMap(J){let $=await this.balance.getTokenBalances(J),Q=new Map;return $.forEach((Y)=>{Q.set(Y.tokenAddress.toLowerCase(),Y.staticAttoCircles)}),Q}_createDemurragedUnwrapCalls(J){let $=[];for(let[Q,[Y,G]]of Object.entries(J)){if(G!=="CrcV2_ERC20WrapperDeployed_Demurraged")continue;let Z=new z$({address:Q,rpcUrl:this.config.circlesRpcUrl}).unwrap(Y);$.push({to:Z.to,data:Z.data,value:Z.value??0n})}return $}_createInflationaryUnwrapAndWrapCalls(J,$,Q){let Y=[],G=[];for(let[M,[Z,K]]of Object.entries(J)){if(K!=="CrcV2_ERC20WrapperDeployed_Inflationary")continue;let X=$.get(M.toLowerCase()),q=Q.get(M.toLowerCase())||0n;if(q===0n)continue;let D=new D$({address:M,rpcUrl:this.config.circlesRpcUrl}).unwrap(q);Y.push({to:D.to,data:D.data,value:D.value??0n});let V=X?.tokenOwner,O=nJ.attoStaticCirclesToAttoCircles(q)-Z;if(O>0n){let L=this.hubV2.wrap(V,O,1);G.push({to:L.to,data:L.data,value:L.value??0n})}}return{unwrapCalls:Y,wrapCalls:G}}_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}),Y=new Set;if(Q.results.length>0){let G=Q.results[0];if(Y.add(G.group.toLowerCase()),G.erc20WrapperDemurraged)Y.add(G.erc20WrapperDemurraged.toLowerCase());if(G.erc20WrapperStatic)Y.add(G.erc20WrapperStatic.toLowerCase())}if($?.forEach((G)=>Y.add(G.toLowerCase())),Y.size===0)return;return Array.from(Y)}}var n0=dJ;class E8{config;rpcClient;pathfinder;trust;token;hubV2;referralsModule;invitationFarm;invitationModuleContract;constructor(J){if(!J.referralsServiceUrl)throw new v("referralsServiceUrl is required in config",{code:"INVITATION_MISSING_CONFIG",source:"INVITATIONS",context:{missingField:"referralsServiceUrl"}});this.config=J,this.rpcClient=new VJ(J.circlesRpcUrl),this.pathfinder=new KJ(this.rpcClient),this.trust=new _J(this.rpcClient),this.token=new AJ(this.rpcClient),this.hubV2=new RJ({address:J.v2HubAddress,rpcUrl:J.circlesRpcUrl}),this.referralsModule=new iJ({address:J.referralsModuleAddress,rpcUrl:J.circlesRpcUrl}),this.invitationFarm=new tJ({address:J.invitationFarmAddress,rpcUrl:J.circlesRpcUrl}),this.invitationModuleContract=new F$({address:J.invitationModuleAddress,rpcUrl:J.circlesRpcUrl})}async ensureInviterSetup(J){let $=J.toLowerCase(),Q=this.config.invitationModuleAddress,Y=[],G=new b$({address:$,rpcUrl:this.config.circlesRpcUrl});if(!await G.isModuleEnabled(Q))Y.push(G.enableModule(Q)),Y.push(this.invitationModuleContract.trustInviter($));else if(!await this.hubV2.isTrusted(Q,$))Y.push(this.invitationModuleContract.trustInviter($));return Y}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 v(`HTTP error! status: ${Q.status}`,{code:"INVITATION_HTTP_ERROR",source:"INVITATIONS",context:{status:Q.status,url:`${this.config.referralsServiceUrl}/store`}})}catch(Q){throw new v(`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 Y=new URL(`${this.config.referralsServiceUrl}/list/${J}`);Y.searchParams.set("limit",String($)),Y.searchParams.set("offset",String(Q));let G=await fetch(Y.toString(),{method:"GET",headers:{accept:"application/json"}});if(!G.ok)throw new v(`HTTP error! status: ${G.status}`,{code:"INVITATION_HTTP_ERROR",source:"INVITATIONS",context:{status:G.status,url:Y.toString()}});return await G.json()}catch(Y){if(Y instanceof v)throw Y;throw new v(`Failed to list referrals: ${Y instanceof Error?Y.message:"Unknown error"}`,{code:"INVITATION_LIST_REFERRALS_FAILED",source:"INVITATIONS",cause:Y})}}orderRealInviters(J,$){let Q=$.toLowerCase();return J.sort((Y,G)=>{let M=Y.address.toLowerCase()===Q,Z=G.address.toLowerCase()===Q;if(M&&!Z)return-1;if(!M&&Z)return 1;return 0})}async generateInvite(J,$){let Q=J.toLowerCase(),Y=$.toLowerCase();if(await this.hubV2.isHuman(Y))throw v.inviteeAlreadyRegistered(Q,Y);let M=await this.ensureInviterSetup(Q),Z=await this.getRealInviters(Q),K=[...M];if(Z.length>0){console.log("[generateInvite] Using STANDARD PATH (proxy inviters available)");let X=Z[0].address,q=await this.findInvitePath(Q,X),U=await this.generateInviteData([Y],!1),V=await new uJ(this.config).buildFlowMatrixTx(Q,this.config.invitationModuleAddress,q,{toTokens:[X],useWrappedBalances:!0,txData:y$(U)},!0);K.push(...V)}else{console.log("[generateInvite] Using FARM FALLBACK PATH (no proxy inviters available)");let X=new uJ(this.config),q=await this.findFarmInvitePath(Q),U=await X.buildFlowMatrixTx(Q,HJ,q,{toTokens:[dJ],useWrappedBalances:!0},!0);K.push(...U);let D="0x20EcD8bDeb2F48d8a7c94E542aA4feC5790D9676",V=await this.invitationFarm.read("claimInvite",[],{from:D}),O=this.invitationFarm.claimInvite();K.push(O);let L=await this.invitationFarm.invitationModule(),N=r(["address"],[Y]),b=this.hubV2.safeTransferFrom(Q,L,V,m,N);K.push(b)}return K}async findInvitePath(J,$){let Q=J.toLowerCase(),Y;if($)Y=$.toLowerCase();else{let M=await this.getRealInviters(Q);if(M.length===0)throw v.noPathFound(Q,this.config.invitationModuleAddress);Y=M[0].address}let G=await this.pathfinder.findPath({from:Q,to:this.config.invitationModuleAddress,targetFlow:m,toTokens:[Y],useWrappedBalances:!0,simulatedTrusts:[{truster:this.config.invitationModuleAddress,trustee:Q}]});if(!G.transfers||G.transfers.length===0)throw v.noPathFound(Q,this.config.invitationModuleAddress);if(G.maxFlow<m){let Z=Number(G.maxFlow/m);throw v.insufficientBalance(1,Z,m,G.maxFlow,Q,this.config.invitationModuleAddress)}return G}async findFarmInvitePath(J){let $=J.toLowerCase(),Q=await this.pathfinder.findPath({from:$,to:HJ,targetFlow:m,toTokens:[n0],useWrappedBalances:!0});if(!Q.transfers||Q.transfers.length===0)throw v.noPathFound($,HJ);if(Q.maxFlow<m){let G=Number(Q.maxFlow/m);throw v.insufficientBalance(1,G,m,Q.maxFlow,$,HJ)}return Q}async getRealInviters(J){let $=J.toLowerCase(),[Q,Y,G,M,Z]=await Promise.all([dJ!=="0x0000000000000000000000000000000000000000"?this.trust.getTrusts(dJ):Promise.resolve([]),this.trust.getTrustedBy($),this.trust.getMutualTrusts($),this.trust.getTrusts(this.config.invitationModuleAddress),this.trust.getMutualTrusts(this.config.invitationModuleAddress)]),K=new Set(Q.map((j)=>j.objectAvatar.toLowerCase())),X=new Set([...Y.map((j)=>j.objectAvatar.toLowerCase()),...G.map((j)=>j.objectAvatar.toLowerCase())]),q=new Set([...M.map((j)=>j.objectAvatar.toLowerCase()),...Z.map((j)=>j.objectAvatar.toLowerCase())]),D=[...[...X].filter((j)=>q.has(j)&&!K.has(j)),$];if(D.length===0)return[];let V=await this.pathfinder.findPath({from:$,to:this.config.invitationModuleAddress,useWrappedBalances:!0,targetFlow:X$,toTokens:D,simulatedTrusts:[{truster:this.config.invitationModuleAddress,trustee:$}]});if(!V.transfers||V.transfers.length===0)return[];let O=this.config.invitationModuleAddress.toLowerCase(),L=V.transfers.filter((j)=>j.to.toLowerCase()===O),N=[...new Set(L.map((j)=>j.tokenOwner.toLowerCase()))],b=await this.token.getTokenInfoBatch(N),y=new Map;for(let j of b){let P=j.tokenAddress??j.token;if(P&&j?.tokenOwner)y.set(P.toLowerCase(),j.tokenOwner.toLowerCase())}let f=new Map;for(let j of L){let P=j.tokenOwner.toLowerCase(),B=y.get(P)??P;f.set(B,(f.get(B)??0n)+j.value)}let W=[];for(let[j,P]of f.entries()){let B=Number(P/m);if(B>=1)W.push({address:j,possibleInvites:B})}return this.orderRealInviters(W,$)}async generateReferral(J){let $=J.toLowerCase(),Q=m$(),Y=eJ(Q),G=await this.ensureInviterSetup($),M=await this.getRealInviters($),Z=[...G];if(M.length>0){console.log("[generateReferral] Using STANDARD PATH (proxy inviters available)");let K=new uJ(this.config),X=await this.generateInviteData([Y],!0),q=M[0].address,U=await this.findInvitePath($,q),D=await K.buildFlowMatrixTx($,this.config.invitationModuleAddress,U,{toTokens:[q],useWrappedBalances:!0,txData:y$(X)},!0);Z.push(...D)}else{console.log("[generateReferral] Using FARM FALLBACK PATH (no proxy inviters available)");let K=new uJ(this.config),X=await this.findFarmInvitePath($),q=await K.buildFlowMatrixTx($,HJ,X,{toTokens:[n0],useWrappedBalances:!0},!0);Z.push(...q);let U="0x20EcD8bDeb2F48d8a7c94E542aA4feC5790D9676",D=await this.invitationFarm.read("claimInvite",[],{from:U}),V=this.invitationFarm.claimInvite();Z.push(V);let O=await this.invitationFarm.invitationModule(),L=this.referralsModule.createAccount(Y).data,N=r(["address","bytes"],[this.config.referralsModuleAddress,L]),b=this.hubV2.safeTransferFrom($,O,D,m,N);Z.push(b)}return{transactions:Z,privateKey:Q}}async generateInviteData(J,$=!0){if(J.length===0)throw v.noAddressesProvided();if(!$)if(J.length===1)return r(["address"],[J[0]]);else return r(["address[]"],[J]);if(J.length===1){let Y=this.referralsModule.createAccount(J[0]).data;return r(["address","bytes"],[this.config.referralsModuleAddress,Y])}else{let Y=this.referralsModule.createAccounts(J).data;return r(["address","bytes"],[this.config.referralsModuleAddress,Y])}}computeAddress(J){let Q=J.toLowerCase().replace("0x","").padStart(64,"0"),Y=r$.replace("0x","")+Q,G=h$("0x"+Y),M="ff",Z=s$.toLowerCase().replace("0x",""),K=G.replace("0x",""),X=e$.replace("0x",""),q="ff"+Z+K+X,D="0x"+h$("0x"+q).slice(-40);return OJ(D)}generateSecrets(J){return Array.from({length:J},()=>{let $=m$(),Q=eJ($).toLowerCase();return{secret:$,signer:Q}})}}class nQ{referralsModuleAddress;invitations;invitationFarm;referralsModule;hubV2;constructor(J){this.referralsModuleAddress=J.referralsModuleAddress,this.invitations=new E8(J),this.invitationFarm=new tJ({address:J.invitationFarmAddress,rpcUrl:J.circlesRpcUrl}),this.referralsModule=new iJ({address:J.referralsModuleAddress,rpcUrl:J.circlesRpcUrl}),this.hubV2=new RJ({address:J.v2HubAddress,rpcUrl:J.circlesRpcUrl})}async getQuota(J){return this.invitationFarm.inviterQuota(J)}async getInvitationFee(){return this.invitationFarm.invitationFee()}async getInvitationModule(){return this.invitationFarm.invitationModule()}async generateReferrals(J,$){if($<=0)throw new v("Count must be greater than 0",{code:"INVITATION_INVALID_COUNT",source:"VALIDATION",context:{count:$}});let Q=J.toLowerCase(),Y=$===1,G=await this.simulateClaim(Q,$);if(!G.length)throw new v("No invitation IDs returned from claim",{code:"INVITATION_NO_IDS",source:"INVITATIONS",context:{inviter:Q,count:$}});let M=this.invitations.generateSecrets($),Z=M.map((U)=>U.signer),K=await this.invitationFarm.invitationModule(),X=Y?this.invitationFarm.claimInvite():this.invitationFarm.claimInvites(BigInt($)),q=Y?this.buildReferralTransfer(Q,K,G[0],Z[0]):this.buildBatchReferralTransfer(Q,K,G,Z);return{referrals:M,transactions:[X,q]}}async generateInvites(J,$){if($.length===0)throw new v("At least one invitee address must be provided",{code:"INVITATION_INVALID_COUNT",source:"VALIDATION",context:{count:0}});let Q=J.toLowerCase(),Y=$.map((U)=>U.toLowerCase()),G=Y.length,M=G===1,Z=await this.simulateClaim(Q,G);if(!Z.length)throw new v("No invitation IDs returned from claim",{code:"INVITATION_NO_IDS",source:"INVITATIONS",context:{inviter:Q,count:G}});let K=await this.invitationFarm.invitationModule(),X=M?this.invitationFarm.claimInvite():this.invitationFarm.claimInvites(BigInt(G)),q=M?this.buildInviteTransfer(Q,K,Z[0],Y[0]):this.buildBatchInviteTransfer(Q,K,Z,Y);return{invitees:Y,transactions:[X,q]}}async listReferrals(J,$=10,Q=0){return this.invitations.listReferrals(J,$,Q)}async simulateClaim(J,$){if($===1)return[await this.invitationFarm.read("claimInvite",[],{from:J})];return this.invitationFarm.read("claimInvites",[BigInt($)],{from:J})}buildReferralTransfer(J,$,Q,Y){let G=this.referralsModule.createAccount(Y).data,M=r(["address","bytes"],[this.referralsModuleAddress,G]);return this.hubV2.safeTransferFrom(J,$,Q,m,M)}buildBatchReferralTransfer(J,$,Q,Y){let G=this.referralsModule.createAccounts(Y).data,M=r(["address","bytes"],[this.referralsModuleAddress,G]),Z=Q.map(()=>m);return this.hubV2.safeBatchTransferFrom(J,$,Q,Z,M)}buildInviteTransfer(J,$,Q,Y){let G=r(["address"],[Y]);return this.hubV2.safeTransferFrom(J,$,Q,m,G)}buildBatchInviteTransfer(J,$,Q,Y){let G=r(["address[]"],[Y]),M=Q.map(()=>m);return this.hubV2.safeBatchTransferFrom(J,$,Q,M,G)}}class x8{address;abi;rpcUrl;constructor(J){this.address=J.address,this.abi=J.abi,this.rpcUrl=J.rpcUrl}async read(J,$,Q){let Y=TJ({abi:this.abi,functionName:J,args:$}),G={to:this.address,data:Y,...Q?.from&&{from:Q.from}},Z=await(await fetch(this.rpcUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[G,"latest"]})})).json();if(Z.error)throw Error(`RPC Error: ${Z.error.message}`);if(!Z.result)throw Error("No result returned from RPC call");return Z$({abi:this.abi,functionName:J,data:Z.result})}encodeWrite(J,$){return TJ({abi:this.abi,functionName:J,args:$})}}var i0=[{type:"constructor",inputs:[{name:"invitationModule",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"AFFILIATE_GROUP_REGISTRY",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"DOMAIN_SEPARATOR",inputs:[],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"function",name:"GENERIC_CALL_PROXY",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"HUB",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"INVITATION_MODULE",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"NAME_REGISTRY",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"SAFE_4337_MODULE",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"SAFE_MODULE_SETUP",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"SAFE_PROXY_FACTORY",inputs:[],outputs:[{name:"",type:"address",internalType:"contract ISafeProxyFactory"}],stateMutability:"view"},{type:"function",name:"SAFE_SINGLETON",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"SAFE_WEB_AUTHN_SHARED_SIGNER",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"WELCOME_BONUS",inputs:[],outputs:[{name:"",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"accounts",inputs:[{name:"signer",type:"address",internalType:"address"}],outputs:[{name:"account",type:"address",internalType:"address"},{name:"claimed",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"claimAccount",inputs:[{name:"x",type:"uint256",internalType:"uint256"},{name:"y",type:"uint256",internalType:"uint256"},{name:"verifier",type:"address",internalType:"address"},{name:"signature",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"claimAccount",inputs:[{name:"x",type:"uint256",internalType:"uint256"},{name:"y",type:"uint256",internalType:"uint256"},{name:"verifier",type:"address",internalType:"address"},{name:"signature",type:"bytes",internalType:"bytes"},{name:"metadataDigest",type:"bytes32",internalType:"bytes32"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"claimAccount",inputs:[{name:"x",type:"uint256",internalType:"uint256"},{name:"y",type:"uint256",internalType:"uint256"},{name:"verifier",type:"address",internalType:"address"},{name:"signature",type:"bytes",internalType:"bytes"},{name:"affiliateGroup",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"claimAccount",inputs:[{name:"x",type:"uint256",internalType:"uint256"},{name:"y",type:"uint256",internalType:"uint256"},{name:"verifier",type:"address",internalType:"address"},{name:"signature",type:"bytes",internalType:"bytes"},{name:"metadataDigest",type:"bytes32",internalType:"bytes32"},{name:"affiliateGroup",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"computeAddress",inputs:[{name:"signer",type:"address",internalType:"address"}],outputs:[{name:"predictedAddress",type:"address",internalType:"address"}],stateMutability:"pure"},{type:"function",name:"createAccount",inputs:[{name:"signer",type:"address",internalType:"address"}],outputs:[{name:"account",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"createAccounts",inputs:[{name:"signers",type:"address[]",internalType:"address[]"}],outputs:[{name:"_accounts",type:"address[]",internalType:"address[]"}],stateMutability:"nonpayable"},{type:"function",name:"encodePasskeyData",inputs:[{name:"x",type:"uint256",internalType:"uint256"},{name:"y",type:"uint256",internalType:"uint256"},{name:"verifier",type:"address",internalType:"address"}],outputs:[{name:"",type:"bytes",internalType:"bytes"}],stateMutability:"view"},{type:"function",name:"getPasskeyHash",inputs:[{name:"x",type:"uint256",internalType:"uint256"},{name:"y",type:"uint256",internalType:"uint256"},{name:"verifier",type:"address",internalType:"address"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"view"},{type:"event",name:"AccountClaimed",inputs:[{name:"account",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"AccountCreated",inputs:[{name:"account",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"error",name:"AccountAlreadyClaimed",inputs:[]},{type:"error",name:"InvalidSignature",inputs:[]},{type:"error",name:"OnlyGenericCallProxy",inputs:[]},{type:"error",name:"SignerAlreadyUsed",inputs:[]}];class k8 extends x8{constructor(J){super({address:J.address,abi:i0,rpcUrl:J.rpcUrl})}createAccount(J){return{to:this.address,data:this.encodeWrite("createAccount",[J]),value:BigInt(0)}}createAccounts(J){return{to:this.address,data:this.encodeWrite("createAccounts",[J]),value:BigInt(0)}}async computeAddress(J){return this.read("computeAddress",[J])}claimAccount(J,$,Q,Y){return{to:this.address,data:this.encodeWrite("claimAccount",[J,$,Q,Y]),value:BigInt(0)}}claimAccountWithMetadata(J,$,Q,Y,G){return{to:this.address,data:this.encodeWrite("claimAccount",[J,$,Q,Y,G]),value:BigInt(0)}}claimAccountWithAffiliateGroup(J,$,Q,Y,G){return{to:this.address,data:this.encodeWrite("claimAccount",[J,$,Q,Y,G]),value:BigInt(0)}}claimAccountWithMetadataAndAffiliateGroup(J,$,Q,Y,G,M){return{to:this.address,data:this.encodeWrite("claimAccount",[J,$,Q,Y,G,M]),value:BigInt(0)}}async accounts(J){let[$,Q]=await this.read("accounts",[J]);return{account:$,claimed:Q}}async domainSeparator(){return this.read("DOMAIN_SEPARATOR")}async welcomeBonus(){return this.read("WELCOME_BONUS")}async hub(){return this.read("HUB")}async invitationModule(){return this.read("INVITATION_MODULE")}async genericCallProxy(){return this.read("GENERIC_CALL_PROXY")}async nameRegistry(){return this.read("NAME_REGISTRY")}async affiliateGroupRegistry(){return this.read("AFFILIATE_GROUP_REGISTRY")}async safeProxyFactory(){return this.read("SAFE_PROXY_FACTORY")}async safeSingleton(){return this.read("SAFE_SINGLETON")}async safe4337Module(){return this.read("SAFE_4337_MODULE")}async safeModuleSetup(){return this.read("SAFE_MODULE_SETUP")}async safeWebAuthnSharedSigner(){return this.read("SAFE_WEB_AUTHN_SHARED_SIGNER")}}class iQ{baseUrl;getToken;referralsModule;constructor(J,$,Q,Y){this.baseUrl=J;this.getToken=Y;this.referralsModule=new k8({address:$,rpcUrl:Q})}getBaseUrl(){return this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}async getAuthHeaders(){let J={"Content-Type":"application/json"};if(!this.getToken)return J;let $=await this.getToken();return{...J,Authorization:`Bearer ${$}`}}async store(J,$){let Q=await fetch(`${this.getBaseUrl()}/store`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({privateKey:J,inviter:$})});if(!Q.ok){let Y=await Q.json();throw o.storeFailed(Y.error||Q.statusText)}}async storeBatch(J){let $=await fetch(`${this.getBaseUrl()}/store-batch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({invitations:J})});if(!$.ok){let Q=await $.json();throw o.storeBatchFailed(Q.error||$.statusText)}return $.json()}async retrieve(J){let $=eJ(J),{account:Q,claimed:Y}=await this.referralsModule.accounts($),G=await fetch(`${this.getBaseUrl()}/retrieve?key=${encodeURIComponent(J)}`);if(G.ok||G.status===410||Y){let Z=await G.json();if(Q===IJ)return{...Z,error:`Referral not found on-chain for signer ${$}`};return Z}if(Q===IJ)return{error:`Referral not found on-chain for signer ${$}`};let M=await G.json().catch(()=>null);throw o.retrieveFailed(M?.error||G.statusText,G.status)}async listMine(J){if(!this.getToken)throw o.authRequired();let $=new URLSearchParams;if(J?.limit!==void 0)$.set("limit",String(J.limit));if(J?.offset!==void 0)$.set("offset",String(J.offset));if(J?.inSession!==void 0)$.set("inSession",String(J.inSession));if(J?.status!==void 0)$.set("status",J.status);let Q=$.toString()?`?${$}`:"",Y=await this.getAuthHeaders(),G=await fetch(`${this.getBaseUrl()}/my-referrals${Q}`,{headers:Y});if(!G.ok){let M=await G.json();throw o.listFailed(M.error||G.statusText)}return G.json()}async listPublic(J,$){let Q=new URLSearchParams;if($?.limit!==void 0)Q.set("limit",String($.limit));if($?.offset!==void 0)Q.set("offset",String($.offset));if($?.inSession!==void 0)Q.set("inSession",String($.inSession));let Y=Q.toString()?`?${Q}`:"",G=await fetch(`${this.getBaseUrl()}/list/${encodeURIComponent(J)}${Y}`);if(!G.ok){let M=await G.json();throw o.listFailed(M.error||G.statusText)}return G.json()}}class b8 extends Error{code;httpStatus;constructor(J,$,Q){super(J);this.code=$;this.httpStatus=Q;this.name="DispenseError"}}class ZJ extends Error{code;httpStatus;constructor(J,$,Q){super(J);this.code=$;this.httpStatus=Q;this.name="SessionError"}}function PJ(J){if(J===400)return"VALIDATION_ERROR";if(J===404)return"NOT_FOUND";if(J===409)return"CONFLICT";return"SERVER_ERROR"}class tQ{baseUrl;getToken;constructor(J,$){this.baseUrl=J;this.getToken=$}getBaseUrl(){return this.baseUrl.endsWith("/")?this.baseUrl.slice(0,-1):this.baseUrl}async getAuthHeaders(){let J={"Content-Type":"application/json"};if(!this.getToken)return J;let $=await this.getToken();return{...J,Authorization:`Bearer ${$}`}}async createSession(J){let $=await fetch(`${this.getBaseUrl()}/distributions/sessions`,{method:"POST",headers:await this.getAuthHeaders(),body:JSON.stringify(J)});if(!$.ok){let Q=await $.json();throw new ZJ(Q.error||`Failed to create session: ${$.statusText}`,PJ($.status),$.status)}return $.json()}async listSessions(J,$){let Q=new URLSearchParams({inviter:J});if($?.limit!==void 0)Q.set("limit",String($.limit));if($?.offset!==void 0)Q.set("offset",String($.offset));let Y=await fetch(`${this.getBaseUrl()}/distributions/sessions?${Q}`,{headers:await this.getAuthHeaders()});if(!Y.ok){let G=await Y.json();throw new ZJ(G.error||`Failed to list sessions: ${Y.statusText}`,PJ(Y.status),Y.status)}return Y.json()}async getSession(J){let $=await fetch(`${this.getBaseUrl()}/distributions/sessions/${encodeURIComponent(J)}`,{headers:await this.getAuthHeaders()});if(!$.ok){let Q=await $.json();throw new ZJ(Q.error||`Failed to get session: ${$.statusText}`,PJ($.status),$.status)}return $.json()}async updateSession(J,$){let Q=await fetch(`${this.getBaseUrl()}/distributions/sessions/${encodeURIComponent(J)}`,{method:"PATCH",headers:await this.getAuthHeaders(),body:JSON.stringify($)});if(!Q.ok){let Y=await Q.json();throw new ZJ(Y.error||`Failed to update session: ${Q.statusText}`,PJ(Q.status),Q.status)}return Q.json()}async deleteSession(J){let $=await fetch(`${this.getBaseUrl()}/distributions/sessions/${encodeURIComponent(J)}`,{method:"DELETE",headers:await this.getAuthHeaders()});if(!$.ok){let Q=await $.json();throw new ZJ(Q.error||`Failed to delete session: ${$.statusText}`,PJ($.status),$.status)}}async addKeys(J,$){let Q=await fetch(`${this.getBaseUrl()}/distributions/sessions/${encodeURIComponent(J)}/keys`,{method:"POST",headers:await this.getAuthHeaders(),body:JSON.stringify({keys:$})});if(!Q.ok){let Y=await Q.json();throw new ZJ(Y.error||`Failed to add keys: ${Q.statusText}`,PJ(Q.status),Q.status)}return Q.json()}async listKeys(J,$){let Q=new URLSearchParams;if($?.limit!==void 0)Q.set("limit",String($.limit));if($?.offset!==void 0)Q.set("offset",String($.offset));let Y=Q.toString()?`?${Q}`:"",G=await fetch(`${this.getBaseUrl()}/distributions/sessions/${encodeURIComponent(J)}/keys${Y}`,{headers:await this.getAuthHeaders()});if(!G.ok){let M=await G.json();throw new ZJ(M.error||`Failed to list keys: ${G.statusText}`,PJ(G.status),G.status)}return G.json()}async removeKey(J,$){let Q=await fetch(`${this.getBaseUrl()}/distributions/sessions/${encodeURIComponent(J)}/keys/${encodeURIComponent($)}`,{method:"DELETE",headers:await this.getAuthHeaders()});if(!Q.ok){let Y=await Q.json();throw new ZJ(Y.error||`Failed to remove key: ${Q.statusText}`,PJ(Q.status),Q.status)}}async dispense(J){let $=await fetch(`${this.getBaseUrl()}/d/${encodeURIComponent(J)}`,{headers:{Accept:"application/json"}});if(!$.ok){let Q,Y;try{Q=(await $.json()).error}catch{Q=$.statusText}switch($.status){case 404:Y=Q.includes("keys available")?"POOL_EMPTY":"SESSION_NOT_FOUND";break;case 410:Y=Q.includes("quota")?"QUOTA_EXHAUSTED":"SESSION_EXPIRED";break;case 423:Y="SESSION_PAUSED";break;case 429:Y="RATE_LIMITED";break;default:Y="UNKNOWN"}throw new b8(Q,Y,$.status)}return $.json()}}export{ZJ as SessionError,iQ as Referrals,o as ReferralError,nQ as InviteFarm,E8 as Invitations,v as InvitationError,tQ as Distributions,b8 as DispenseError};
|