@gardenfi/core 2.3.1-beta.5 → 2.3.1-beta.6
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/{ccip-BgiZlV2r.cjs → ccip-BerK0Wjb.cjs} +1 -1
- package/dist/{ccip-BvneCfmq.js → ccip-iOjGQGlA.js} +1 -1
- package/dist/{index-BIFPohSC.js → index-C4i5UzzH.js} +2 -2
- package/dist/{index-PCd3qeA8.cjs → index-K8fs0tKV.cjs} +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-K8fs0tKV.cjs");class w extends e.BaseError{constructor({callbackSelector:o,cause:a,data:c,extraData:u,sender:d,urls:r}){var n;super(a.shortMessage||"An error occurred while fetching for an offchain result.",{cause:a,metaMessages:[...a.metaMessages||[],(n=a.metaMessages)!=null&&n.length?"":[],"Offchain Gateway Call:",r&&[" Gateway URL(s):",...r.map(f=>` ${e.getUrl(f)}`)],` Sender: ${d}`,` Data: ${c}`,` Callback selector: ${o}`,` Extra data: ${u}`].flat(),name:"OffchainLookupError"})}}class k extends e.BaseError{constructor({result:o,url:a}){super("Offchain gateway response is malformed. Response data must be a hex value.",{metaMessages:[`Gateway URL: ${e.getUrl(a)}`,`Response: ${e.stringify(o)}`],name:"OffchainLookupResponseMalformedError"})}}class b extends e.BaseError{constructor({sender:o,to:a}){super("Reverted sender address does not match target contract address (`to`).",{metaMessages:[`Contract address: ${a}`,`OffchainLookup sender address: ${o}`],name:"OffchainLookupSenderMismatchError"})}}const L="0x556f1830",y={name:"OffchainLookup",type:"error",inputs:[{name:"sender",type:"address"},{name:"urls",type:"string[]"},{name:"callData",type:"bytes"},{name:"callbackFunction",type:"bytes4"},{name:"extraData",type:"bytes"}]};async function E(i,{blockNumber:o,blockTag:a,data:c,to:u}){const{args:d}=e.decodeErrorResult({data:c,abi:[y]}),[r,n,f,l,s]=d,{ccipRead:t}=i,h=t&&typeof(t==null?void 0:t.request)=="function"?t.request:m;try{if(!e.isAddressEqual(u,r))throw new b({sender:r,to:u});const p=n.includes(e.localBatchGatewayUrl)?await e.localBatchGatewayRequest({data:f,ccipRequest:h}):await h({data:f,sender:r,urls:n}),{data:g}=await e.call(i,{blockNumber:o,blockTag:a,data:e.concat([l,e.encodeAbiParameters([{type:"bytes"},{type:"bytes"}],[p,s])]),to:u});return g}catch(p){throw new w({callbackSelector:l,cause:p,data:c,extraData:s,sender:r,urls:n})}}async function m({data:i,sender:o,urls:a}){var u;let c=new Error("An unknown error occurred.");for(let d=0;d<a.length;d++){const r=a[d],n=r.includes("{data}")?"GET":"POST",f=n==="POST"?{data:i,sender:o}:void 0,l=n==="POST"?{"Content-Type":"application/json"}:{};try{const s=await fetch(r.replace("{sender}",o.toLowerCase()).replace("{data}",i),{body:JSON.stringify(f),headers:l,method:n});let t;if((u=s.headers.get("Content-Type"))!=null&&u.startsWith("application/json")?t=(await s.json()).data:t=await s.text(),!s.ok){c=new e.HttpRequestError({body:f,details:t!=null&&t.error?e.stringify(t.error):s.statusText,headers:s.headers,status:s.status,url:r});continue}if(!e.isHex(t)){c=new k({result:t,url:r});continue}return t}catch(s){c=new e.HttpRequestError({body:f,details:s.message,url:r})}}throw c}exports.ccipRequest=m;exports.offchainLookup=E;exports.offchainLookupAbiItem=y;exports.offchainLookupSignature=L;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { B as p, g as m, s as w, d as k, i as b, l as L, a as O, c as E, b as x, e as R, H as y, f as M } from "./index-
|
|
1
|
+
import { B as p, g as m, s as w, d as k, i as b, l as L, a as O, c as E, b as x, e as R, H as y, f as M } from "./index-C4i5UzzH.js";
|
|
2
2
|
class S extends p {
|
|
3
3
|
constructor({ callbackSelector: r, cause: a, data: n, extraData: i, sender: f, urls: t }) {
|
|
4
4
|
var o;
|
|
@@ -5442,7 +5442,7 @@ async function To(e, t) {
|
|
|
5442
5442
|
});
|
|
5443
5443
|
return Z === "0x" ? { data: void 0 } : { data: Z };
|
|
5444
5444
|
} catch (J) {
|
|
5445
|
-
const M = n1(J), { offchainLookup: k, offchainLookupSignature: q } = await import("./ccip-
|
|
5445
|
+
const M = n1(J), { offchainLookup: k, offchainLookupSignature: q } = await import("./ccip-iOjGQGlA.js");
|
|
5446
5446
|
if (e.ccipRead !== !1 && (M == null ? void 0 : M.slice(0, 10)) === q && A)
|
|
5447
5447
|
return { data: await k(e, { data: M, to: A }) };
|
|
5448
5448
|
throw O && (M == null ? void 0 : M.slice(0, 10)) === "0x101bb98d" ? new Ub({ factory: y }) : zh(J, {
|
|
@@ -23425,7 +23425,7 @@ class N_ {
|
|
|
23425
23425
|
this.program.programId
|
|
23426
23426
|
)[0];
|
|
23427
23427
|
try {
|
|
23428
|
-
const a = await this.program.methods.initiate(i - 100, s, r, n).accounts({ initiator: this.provider.publicKey }).transaction();
|
|
23428
|
+
const a = await this.program.methods.initiate(i - BigInt(100), s, r, n).accounts({ initiator: this.provider.publicKey }).transaction();
|
|
23429
23429
|
return em(t.source_swap.chain, t.source_swap.asset) ? this.initiateViaHTLC(a, t) : this.sendViaRelayer(a, t.create_order.create_id);
|
|
23430
23430
|
} catch (a) {
|
|
23431
23431
|
return H("Error initiating swap: ", a);
|
|
@@ -38,7 +38,7 @@ ${tb(p)}`),super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessa
|
|
|
38
38
|
`),{cause:t,metaMessages:["This error could arise when the account does not have enough funds to:"," - pay for the total gas fee,"," - pay for the value to send."," ","The cost of the transaction is calculated as `gas * gas fee + value`, where:"," - `gas` is the amount of gas needed for transaction to execute,"," - `gas fee` is the gas fee,"," - `value` is the amount of ether to send to the recipient."],name:"InsufficientFundsError"})}}Object.defineProperty(Bc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/insufficient funds|exceeds transaction sender account balance/});class Oc extends D{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction exceeds the limit allowed for the block.`,{cause:t,name:"IntrinsicGasTooHighError"})}}Object.defineProperty(Oc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too high|gas limit reached/});class Cc extends D{constructor({cause:t,gas:r}={}){super(`The amount of gas ${r?`(${r}) `:""}provided for the transaction is too low.`,{cause:t,name:"IntrinsicGasTooLowError"})}}Object.defineProperty(Cc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/intrinsic gas too low/});class Rc extends D{constructor({cause:t}){super("The transaction type is not supported for this chain.",{cause:t,name:"TransactionTypeNotSupportedError"})}}Object.defineProperty(Rc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/transaction type not valid/});class Gi extends D{constructor({cause:t,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${it(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${it(n)} gwei`:""}).`].join(`
|
|
39
39
|
`),{cause:t,name:"TipAboveFeeCapError"})}}Object.defineProperty(Gi,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class ns extends D{constructor({cause:t}){super(`An error occurred while executing: ${t==null?void 0:t.shortMessage}`,{cause:t,name:"UnknownNodeError"})}}function ao(e,t){const r=(e.details||"").toLowerCase(),n=e instanceof D?e.walk(i=>(i==null?void 0:i.code)===_n.code):e;return n instanceof D?new _n({cause:e,message:n.details}):_n.nodeMessage.test(r)?new _n({cause:e,message:e.details}):en.nodeMessage.test(r)?new en({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas}):Pc.nodeMessage.test(r)?new Pc({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas}):Tc.nodeMessage.test(r)?new Tc({cause:e,nonce:t==null?void 0:t.nonce}):Ic.nodeMessage.test(r)?new Ic({cause:e,nonce:t==null?void 0:t.nonce}):kc.nodeMessage.test(r)?new kc({cause:e,nonce:t==null?void 0:t.nonce}):Bc.nodeMessage.test(r)?new Bc({cause:e}):Oc.nodeMessage.test(r)?new Oc({cause:e,gas:t==null?void 0:t.gas}):Cc.nodeMessage.test(r)?new Cc({cause:e,gas:t==null?void 0:t.gas}):Rc.nodeMessage.test(r)?new Rc({cause:e}):Gi.nodeMessage.test(r)?new Gi({cause:e,maxFeePerGas:t==null?void 0:t.maxFeePerGas,maxPriorityFeePerGas:t==null?void 0:t.maxPriorityFeePerGas}):new ns({cause:e})}function Eb(e,{docsPath:t,...r}){const n=(()=>{const i=ao(e,r);return i instanceof ns?e:i})();return new vb(n,{docsPath:t,...r})}function co(e,{format:t}){if(!t)return{};const r={};function n(s){const o=Object.keys(s);for(const a of o)a in e&&(r[a]=e[a]),s[a]&&typeof s[a]=="object"&&!Array.isArray(s[a])&&n(s[a])}const i=t(e||{});return n(i),r}function xu(e,t){return({exclude:r,format:n})=>({exclude:r,format:i=>{const s=t(i);if(r)for(const o of r)delete s[o];return{...s,...n(i)}},type:e})}const xb={legacy:"0x0",eip2930:"0x1",eip1559:"0x2",eip4844:"0x3",eip7702:"0x4"};function Zn(e){const t={};return typeof e.authorizationList<"u"&&(t.authorizationList=Ab(e.authorizationList)),typeof e.accessList<"u"&&(t.accessList=e.accessList),typeof e.blobVersionedHashes<"u"&&(t.blobVersionedHashes=e.blobVersionedHashes),typeof e.blobs<"u"&&(typeof e.blobs[0]!="string"?t.blobs=e.blobs.map(r=>Ce(r)):t.blobs=e.blobs),typeof e.data<"u"&&(t.data=e.data),typeof e.from<"u"&&(t.from=e.from),typeof e.gas<"u"&&(t.gas=K(e.gas)),typeof e.gasPrice<"u"&&(t.gasPrice=K(e.gasPrice)),typeof e.maxFeePerBlobGas<"u"&&(t.maxFeePerBlobGas=K(e.maxFeePerBlobGas)),typeof e.maxFeePerGas<"u"&&(t.maxFeePerGas=K(e.maxFeePerGas)),typeof e.maxPriorityFeePerGas<"u"&&(t.maxPriorityFeePerGas=K(e.maxPriorityFeePerGas)),typeof e.nonce<"u"&&(t.nonce=K(e.nonce)),typeof e.to<"u"&&(t.to=e.to),typeof e.type<"u"&&(t.type=xb[e.type]),typeof e.value<"u"&&(t.value=K(e.value)),t}function Ab(e){return e.map(t=>({address:t.address,r:t.r?K(BigInt(t.r)):t.r,s:t.s?K(BigInt(t.s)):t.s,chainId:K(t.chainId),nonce:K(t.nonce),...typeof t.yParity<"u"?{yParity:K(t.yParity)}:{},...typeof t.v<"u"&&typeof t.yParity>"u"?{v:K(t.v)}:{}}))}function zf(e){if(!(!e||e.length===0))return e.reduce((t,{slot:r,value:n})=>{if(r.length!==66)throw new If({size:r.length,targetSize:66,type:"hex"});if(n.length!==66)throw new If({size:n.length,targetSize:66,type:"hex"});return t[r]=n,t},{})}function _b(e){const{balance:t,nonce:r,state:n,stateDiff:i,code:s}=e,o={};if(s!==void 0&&(o.code=s),t!==void 0&&(o.balance=K(t)),r!==void 0&&(o.nonce=K(r)),n!==void 0&&(o.state=zf(n)),i!==void 0){if(o.state)throw new eb;o.stateDiff=zf(i)}return o}function Au(e){if(!e)return;const t={};for(const{address:r,...n}of e){if(!Fe(r,{strict:!1}))throw new tt({address:r});if(t[r])throw new Qg({address:r});t[r]=_b(n)}return t}const uo=2n**256n-1n;function an(e){const{account:t,gasPrice:r,maxFeePerGas:n,maxPriorityFeePerGas:i,to:s}=e,o=t?ke(t):void 0;if(o&&!Fe(o.address))throw new tt({address:o.address});if(s&&!Fe(s))throw new tt({address:s});if(typeof r<"u"&&(typeof n<"u"||typeof i<"u"))throw new rb;if(n&&n>uo)throw new en({maxFeePerGas:n});if(i&&n&&i>n)throw new Gi({maxFeePerGas:n,maxPriorityFeePerGas:i})}class Sb extends D{constructor(){super("`baseFeeMultiplier` must be greater than 1.",{name:"BaseFeeScalarError"})}}class _u extends D{constructor(){super("Chain does not support EIP-1559 fees.",{name:"Eip1559FeesNotSupportedError"})}}class Pb extends D{constructor({maxPriorityFeePerGas:t}){super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${it(t)} gwei).`,{name:"MaxFeePerGasTooLowError"})}}class Vp extends D{constructor({blockHash:t,blockNumber:r}){let n="Block";t&&(n=`Block at hash "${t}"`),r&&(n=`Block at number "${r}"`),super(`${n} could not be found.`,{name:"BlockNotFoundError"})}}const Wp={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function fo(e){const t={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,chainId:e.chainId?vt(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?vt(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?Wp[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(t.authorizationList=Ib(e.authorizationList)),t.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof t.v=="bigint"){if(t.v===0n||t.v===27n)return 0;if(t.v===1n||t.v===28n)return 1;if(t.v>=35n)return t.v%2n===0n?1:0}})(),t.type==="legacy"&&(delete t.accessList,delete t.maxFeePerBlobGas,delete t.maxFeePerGas,delete t.maxPriorityFeePerGas,delete t.yParity),t.type==="eip2930"&&(delete t.maxFeePerBlobGas,delete t.maxFeePerGas,delete t.maxPriorityFeePerGas),t.type==="eip1559"&&delete t.maxFeePerBlobGas,t}const Tb=xu("transaction",fo);function Ib(e){return e.map(t=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}function Su(e){const t=(e.transactions??[]).map(r=>typeof r=="string"?r:fo(r));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:t,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}const kb=xu("block",Su);async function Gt(e,{blockHash:t,blockNumber:r,blockTag:n,includeTransactions:i}={}){var u,d,y;const s=n??"latest",o=i??!1,a=r!==void 0?K(r):void 0;let c=null;if(t?c=await e.request({method:"eth_getBlockByHash",params:[t,o]},{dedupe:!0}):c=await e.request({method:"eth_getBlockByNumber",params:[a||s,o]},{dedupe:!!a}),!c)throw new Vp({blockHash:t,blockNumber:r});return(((y=(d=(u=e.chain)==null?void 0:u.formatters)==null?void 0:d.block)==null?void 0:y.format)||Su)(c)}async function Pu(e){const t=await e.request({method:"eth_gasPrice"});return BigInt(t)}async function Bb(e,t){return Kp(e,t)}async function Kp(e,t){var s,o;const{block:r,chain:n=e.chain,request:i}=t||{};try{const a=((s=n==null?void 0:n.fees)==null?void 0:s.maxPriorityFeePerGas)??((o=n==null?void 0:n.fees)==null?void 0:o.defaultPriorityFee);if(typeof a=="function"){const f=r||await ee(e,Gt,"getBlock")({}),u=await a({block:f,client:e,request:i});if(u===null)throw new Error;return u}if(typeof a<"u")return a;const c=await e.request({method:"eth_maxPriorityFeePerGas"});return Ue(c)}catch{const[a,c]=await Promise.all([r?Promise.resolve(r):ee(e,Gt,"getBlock")({}),ee(e,Pu,"getGasPrice")({})]);if(typeof a.baseFeePerGas!="bigint")throw new _u;const f=c-a.baseFeePerGas;return f<0n?0n:f}}async function Ob(e,t){return Nc(e,t)}async function Nc(e,t){var y,p;const{block:r,chain:n=e.chain,request:i,type:s="eip1559"}=t||{},o=await(async()=>{var g,b;return typeof((g=n==null?void 0:n.fees)==null?void 0:g.baseFeeMultiplier)=="function"?n.fees.baseFeeMultiplier({block:r,client:e,request:i}):((b=n==null?void 0:n.fees)==null?void 0:b.baseFeeMultiplier)??1.2})();if(o<1)throw new Sb;const c=10**(((y=o.toString().split(".")[1])==null?void 0:y.length)??0),f=g=>g*BigInt(Math.ceil(o*c))/BigInt(c),u=r||await ee(e,Gt,"getBlock")({});if(typeof((p=n==null?void 0:n.fees)==null?void 0:p.estimateFeesPerGas)=="function"){const g=await n.fees.estimateFeesPerGas({block:r,client:e,multiply:f,request:i,type:s});if(g!==null)return g}if(s==="eip1559"){if(typeof u.baseFeePerGas!="bigint")throw new _u;const g=typeof(i==null?void 0:i.maxPriorityFeePerGas)=="bigint"?i.maxPriorityFeePerGas:await Kp(e,{block:u,chain:n,request:i}),b=f(u.baseFeePerGas);return{maxFeePerGas:(i==null?void 0:i.maxFeePerGas)??b+g,maxPriorityFeePerGas:g}}return{gasPrice:(i==null?void 0:i.gasPrice)??f(await ee(e,Pu,"getGasPrice")({}))}}async function Tu(e,{address:t,blockTag:r="latest",blockNumber:n}){const i=await e.request({method:"eth_getTransactionCount",params:[t,typeof n=="bigint"?K(n):r]},{dedupe:!!n});return vt(i)}function Iu(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(s=>kt(s)):e.blobs,i=[];for(const s of n)i.push(Uint8Array.from(t.blobToKzgCommitment(s)));return r==="bytes"?i:i.map(s=>Ce(s))}function ku(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(o=>kt(o)):e.blobs,i=typeof e.commitments[0]=="string"?e.commitments.map(o=>kt(o)):e.commitments,s=[];for(let o=0;o<n.length;o++){const a=n[o],c=i[o];s.push(Uint8Array.from(t.computeBlobKzgProof(a,c)))}return r==="bytes"?s:s.map(o=>Ce(o))}function Cb(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,f=n?0:4;e.setUint32(t+c,o,n),e.setUint32(t+f,a,n)}function Rb(e,t,r){return e&t^~e&r}function Nb(e,t,r){return e&t^e&r^t&r}let Yp=class extends pu{constructor(t,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(t),this.view=Lo(this.buffer)}update(t){Fn(this),t=eo(t),Bt(t);const{view:r,buffer:n,blockLen:i}=this,s=t.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=Lo(t);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Fn(this),wp(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:o}=this;r[o++]=128,Or(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let d=o;d<i;d++)r[d]=0;Cb(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=Lo(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const f=c/4,u=this.get();if(f>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<f;d++)a.setUint32(4*d,u[d],s)}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=s,t.length=i,t.pos=a,i%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}};const mr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),gr=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),Fb=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]),br=new Uint32Array(64);let Bu=class extends Yp{constructor(t=32){super(64,t,8,!1),this.A=mr[0]|0,this.B=mr[1]|0,this.C=mr[2]|0,this.D=mr[3]|0,this.E=mr[4]|0,this.F=mr[5]|0,this.G=mr[6]|0,this.H=mr[7]|0}get(){const{A:t,B:r,C:n,D:i,E:s,F:o,G:a,H:c}=this;return[t,r,n,i,s,o,a,c]}set(t,r,n,i,s,o,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(t,r){for(let d=0;d<16;d++,r+=4)br[d]=t.getUint32(r,!1);for(let d=16;d<64;d++){const y=br[d-15],p=br[d-2],g=Ft(y,7)^Ft(y,18)^y>>>3,b=Ft(p,17)^Ft(p,19)^p>>>10;br[d]=b+br[d-7]+g+br[d-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:f,H:u}=this;for(let d=0;d<64;d++){const y=Ft(a,6)^Ft(a,11)^Ft(a,25),p=u+y+Rb(a,c,f)+Fb[d]+br[d]|0,b=(Ft(n,2)^Ft(n,13)^Ft(n,22))+Nb(n,i,s)|0;u=f,f=c,c=a,a=o+p|0,o=s,s=i,i=n,n=p+b|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,i,s,o,a,c,f,u)}roundClean(){Or(br)}destroy(){this.set(0,0,0,0,0,0,0,0),Or(this.buffer)}},Zp=class extends Bu{constructor(){super(28),this.A=gr[0]|0,this.B=gr[1]|0,this.C=gr[2]|0,this.D=gr[3]|0,this.E=gr[4]|0,this.F=gr[5]|0,this.G=gr[6]|0,this.H=gr[7]|0}};const Xp=to(()=>new Bu),$b=to(()=>new Zp),Ub=Bu,Jp=Xp,Hb=Zp,Lb=$b,Mb=Object.freeze(Object.defineProperty({__proto__:null,SHA224:Hb,SHA256:Ub,sha224:Lb,sha256:Jp},Symbol.toStringTag,{value:"Module"}));function di(e,t){const r=t||"hex",n=Jp(It(e,{strict:!1})?Yn(e):e);return r==="bytes"?n:ze(n)}function Db(e){const{commitment:t,version:r=1}=e,n=e.to??(typeof t=="string"?"hex":"bytes"),i=di(t,"bytes");return i.set([r],0),n==="bytes"?i:Ce(i)}function Qp(e){const{commitments:t,version:r}=e,n=e.to??(typeof t[0]=="string"?"hex":"bytes"),i=[];for(const s of t)i.push(Db({commitment:s,to:n,version:r}));return i}const qf=6,eh=32,Ou=4096,th=eh*Ou,Gf=th*qf-1-1*Ou*qf,rh=1;class jb extends D{constructor({maxSize:t,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${t} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}}class nh extends D{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class zb extends D{constructor({hash:t,size:r}){super(`Versioned hash "${t}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}}class qb extends D{constructor({hash:t,version:r}){super(`Versioned hash "${t}" version is invalid.`,{metaMessages:[`Expected: ${rh}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}function Gb(e){const t=e.to??(typeof e.data=="string"?"hex":"bytes"),r=typeof e.data=="string"?kt(e.data):e.data,n=Se(r);if(!n)throw new nh;if(n>Gf)throw new jb({maxSize:Gf,size:n});const i=[];let s=!0,o=0;for(;s;){const a=wu(new Uint8Array(th));let c=0;for(;c<Ou;){const f=r.slice(o,o+(eh-1));if(a.pushByte(0),a.pushBytes(f),f.length<31){a.pushByte(128),s=!1;break}c++,o+=31}i.push(a)}return t==="bytes"?i.map(a=>a.bytes):i.map(a=>Ce(a.bytes))}function ih(e){const{data:t,kzg:r,to:n}=e,i=e.blobs??Gb({data:t,to:n}),s=e.commitments??Iu({blobs:i,kzg:r,to:n}),o=e.proofs??ku({blobs:i,commitments:s,kzg:r,to:n}),a=[];for(let c=0;c<i.length;c++)a.push({blob:i[c],commitment:s[c],proof:o[c]});return a}function sh(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u")return typeof e.accessList<"u"?"eip2930":"legacy";throw new ib({transaction:e})}async function Xn(e){const t=await e.request({method:"eth_chainId"},{dedupe:!0});return vt(t)}const oh=["blobVersionedHashes","chainId","fees","gas","nonce","type"],Vf=new Map;async function lo(e,t){const{account:r=e.account,blobs:n,chain:i,gas:s,kzg:o,nonce:a,nonceManager:c,parameters:f=oh,type:u}=t,d=r&&ke(r),y={...t,...d?{from:d==null?void 0:d.address}:{}};let p;async function g(){return p||(p=await ee(e,Gt,"getBlock")({blockTag:"latest"}),p)}let b;async function E(){return b||(i?i.id:typeof t.chainId<"u"?t.chainId:(b=await ee(e,Xn,"getChainId")({}),b))}if(f.includes("nonce")&&typeof a>"u"&&d)if(c){const x=await E();y.nonce=await c.consume({address:d.address,chainId:x,client:e})}else y.nonce=await ee(e,Tu,"getTransactionCount")({address:d.address,blockTag:"pending"});if((f.includes("blobVersionedHashes")||f.includes("sidecars"))&&n&&o){const x=Iu({blobs:n,kzg:o});if(f.includes("blobVersionedHashes")){const P=Qp({commitments:x,to:"hex"});y.blobVersionedHashes=P}if(f.includes("sidecars")){const P=ku({blobs:n,commitments:x,kzg:o}),w=ih({blobs:n,commitments:x,proofs:P,to:"hex"});y.sidecars=w}}if(f.includes("chainId")&&(y.chainId=await E()),(f.includes("fees")||f.includes("type"))&&typeof u>"u")try{y.type=sh(y)}catch{let x=Vf.get(e.uid);if(typeof x>"u"){const P=await g();x=typeof(P==null?void 0:P.baseFeePerGas)=="bigint",Vf.set(e.uid,x)}y.type=x?"eip1559":"legacy"}if(f.includes("fees"))if(y.type!=="legacy"&&y.type!=="eip2930"){if(typeof y.maxFeePerGas>"u"||typeof y.maxPriorityFeePerGas>"u"){const x=await g(),{maxFeePerGas:P,maxPriorityFeePerGas:w}=await Nc(e,{block:x,chain:i,request:y});if(typeof t.maxPriorityFeePerGas>"u"&&t.maxFeePerGas&&t.maxFeePerGas<w)throw new Pb({maxPriorityFeePerGas:w});y.maxPriorityFeePerGas=w,y.maxFeePerGas=P}}else{if(typeof t.maxFeePerGas<"u"||typeof t.maxPriorityFeePerGas<"u")throw new _u;if(typeof t.gasPrice>"u"){const x=await g(),{gasPrice:P}=await Nc(e,{block:x,chain:i,request:y,type:"legacy"});y.gasPrice=P}}return f.includes("gas")&&typeof s>"u"&&(y.gas=await ee(e,Cu,"estimateGas")({...y,account:d&&{address:d.address,type:"json-rpc"}})),an(y),delete y.parameters,y}async function ah(e,{address:t,blockNumber:r,blockTag:n="latest"}){const i=typeof r=="bigint"?K(r):void 0,s=await e.request({method:"eth_getBalance",params:[t,i||n]});return BigInt(s)}async function Cu(e,t){var i,s,o;const{account:r=e.account}=t,n=r?ke(r):void 0;try{let V=function(X){const{block:J,request:M,rpcStateOverride:B}=X;return e.request({method:"eth_estimateGas",params:B?[M,J??"latest",B]:J?[M,J]:[M]})};const{accessList:a,authorizationList:c,blobs:f,blobVersionedHashes:u,blockNumber:d,blockTag:y,data:p,gas:g,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:x,maxPriorityFeePerGas:P,nonce:w,value:A,stateOverride:T,...I}=await lo(e,{...t,parameters:(n==null?void 0:n.type)==="local"?void 0:["blobVersionedHashes"]}),L=(typeof d=="bigint"?K(d):void 0)||y,S=Au(T),$=await(async()=>{if(I.to)return I.to;if(c&&c.length>0)return await Gp({authorization:c[0]}).catch(()=>{throw new D("`to` is required. Could not infer from `authorizationList`")})})();an(t);const C=(o=(s=(i=e.chain)==null?void 0:i.formatters)==null?void 0:s.transactionRequest)==null?void 0:o.format,j=(C||Zn)({...co(I,{format:C}),from:n==null?void 0:n.address,accessList:a,authorizationList:c,blobs:f,blobVersionedHashes:u,data:p,gas:g,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:x,maxPriorityFeePerGas:P,nonce:w,to:$,value:A});let Y=BigInt(await V({block:L,request:j,rpcStateOverride:S}));if(c){const X=await ah(e,{address:j.from}),J=await Promise.all(c.map(async M=>{const{address:B}=M,q=await V({block:L,request:{authorizationList:void 0,data:p,from:n==null?void 0:n.address,to:B,value:K(X)},rpcStateOverride:S}).catch(()=>100000n);return 2n*BigInt(q)}));Y+=J.reduce((M,B)=>M+B,0n)}return Y}catch(a){throw Eb(a,{...t,account:n,chain:e.chain})}}async function ch(e,t){const{abi:r,address:n,args:i,functionName:s,dataSuffix:o,...a}=t,c=xt({abi:r,args:i,functionName:s});try{return await ee(e,Cu,"estimateGas")({data:`${c}${o?o.replace("0x",""):""}`,to:n,...a})}catch(f){const u=a.account?ke(a.account):void 0;throw Qr(f,{abi:r,address:n,args:i,docsPath:"/docs/contract/estimateContractGas",functionName:s,sender:u==null?void 0:u.address})}}function is(e,t){if(!Fe(e,{strict:!1}))throw new tt({address:e});if(!Fe(t,{strict:!1}))throw new tt({address:t});return e.toLowerCase()===t.toLowerCase()}const Wf="/docs/contract/decodeEventLog";function Ru(e){const{abi:t,data:r,strict:n,topics:i}=e,s=n??!0,[o,...a]=i;if(!o)throw new Fm({docsPath:Wf});const c=t.find(b=>b.type==="event"&&o===ro(Tt(b)));if(!(c&&"name"in c)||c.type!=="event")throw new lp(o,{docsPath:Wf});const{name:f,inputs:u}=c,d=u==null?void 0:u.some(b=>!("name"in b&&b.name)),y=d?[]:{},p=u.map((b,E)=>[b,E]).filter(([b])=>"indexed"in b&&b.indexed);for(let b=0;b<p.length;b++){const[E,x]=p[b],P=a[b];if(!P)throw new Qs({abiItem:c,param:E});y[d?x:E.name||x]=Vb({param:E,value:P})}const g=u.filter(b=>!("indexed"in b&&b.indexed));if(g.length>0){if(r&&r!=="0x")try{const b=ts(g,r);if(b)if(d)for(let E=0;E<u.length;E++)y[E]=y[E]??b.shift();else for(let E=0;E<g.length;E++)y[g[E].name]=b[E]}catch(b){if(s)throw b instanceof fp||b instanceof Fp?new Ai({abiItem:c,data:r,params:g,size:Se(r)}):b}else if(s)throw new Ai({abiItem:c,data:"0x",params:g,size:0})}return{eventName:f,args:Object.values(y).length>0?y:void 0}}function Vb({param:e,value:t}){return e.type==="string"||e.type==="bytes"||e.type==="tuple"||e.type.match(/^(.*)\[(\d+)?\]$/)?t:(ts([e],t)||[])[0]}function Nu(e){const{abi:t,args:r,logs:n,strict:i=!0}=e,s=(()=>{if(e.eventName)return Array.isArray(e.eventName)?e.eventName:[e.eventName]})();return n.map(o=>{var a;try{const c=t.find(u=>u.type==="event"&&o.topics[0]===ro(u));if(!c)return null;const f=Ru({...o,abi:[c],strict:i});return s&&!s.includes(f.eventName)||!Wb({args:f.args,inputs:c.inputs,matchArgs:r})?null:{...f,...o}}catch(c){let f,u;if(c instanceof lp)return null;if(c instanceof Ai||c instanceof Qs){if(i)return null;f=c.abiItem.name,u=(a=c.abiItem.inputs)==null?void 0:a.some(d=>!("name"in d&&d.name))}return{...o,args:u?[]:{},eventName:f}}}).filter(Boolean)}function Wb(e){const{args:t,inputs:r,matchArgs:n}=e;if(!n)return!0;if(!t)return!1;function i(s,o,a){try{return s.type==="address"?is(o,a):s.type==="string"||s.type==="bytes"?je(Yn(o))===a:o===a}catch{return!1}}return Array.isArray(t)&&Array.isArray(n)?n.every((s,o)=>{if(s==null)return!0;const a=r[o];return a?(Array.isArray(s)?s:[s]).some(f=>i(a,f,t[o])):!1}):typeof t=="object"&&!Array.isArray(t)&&typeof n=="object"&&!Array.isArray(n)?Object.entries(n).every(([s,o])=>{if(o==null)return!0;const a=r.find(f=>f.name===s);return a?(Array.isArray(o)?o:[o]).some(f=>i(a,f,t[s])):!1}):!1}function cr(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}async function Fu(e,{address:t,blockHash:r,fromBlock:n,toBlock:i,event:s,events:o,args:a,strict:c}={}){const f=c??!1,u=o??(s?[s]:void 0);let d=[];u&&(d=[u.flatMap(b=>es({abi:[b],eventName:b.name,args:o?void 0:a}))],s&&(d=d[0]));let y;r?y=await e.request({method:"eth_getLogs",params:[{address:t,topics:d,blockHash:r}]}):y=await e.request({method:"eth_getLogs",params:[{address:t,topics:d,fromBlock:typeof n=="bigint"?K(n):n,toBlock:typeof i=="bigint"?K(i):i}]});const p=y.map(g=>cr(g));return u?Nu({abi:u,args:a,logs:p,strict:f}):p}async function $u(e,t){const{abi:r,address:n,args:i,blockHash:s,eventName:o,fromBlock:a,toBlock:c,strict:f}=t,u=o?on({abi:r,name:o}):void 0,d=u?void 0:r.filter(y=>y.type==="event");return ee(e,Fu,"getLogs")({address:n,args:i,blockHash:s,event:u,events:d,fromBlock:a,toBlock:c,strict:f})}const jo="/docs/contract/decodeFunctionResult";function cn(e){const{abi:t,args:r,functionName:n,data:i}=e;let s=t[0];if(n){const a=on({abi:t,args:r,name:n});if(!a)throw new Rn(n,{docsPath:jo});s=a}if(s.type!=="function")throw new Rn(void 0,{docsPath:jo});if(!s.outputs)throw new pp(s.name,{docsPath:jo});const o=ts(s.outputs,i);if(o&&o.length>1)return o;if(o&&o.length===1)return o[0]}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Uu=BigInt(0),Fc=BigInt(1);function Ws(e,t){if(typeof t!="boolean")throw new Error(e+" boolean expected, got "+t)}function ms(e){const t=e.toString(16);return t.length&1?"0"+t:t}function uh(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?Uu:BigInt("0x"+e)}function po(e){return uh(Si(e))}function fh(e){return Bt(e),uh(Si(Uint8Array.from(e).reverse()))}function Hu(e,t){return lu(e.toString(16).padStart(t*2,"0"))}function dh(e,t){return Hu(e,t).reverse()}function yt(e,t,r){let n;if(typeof t=="string")try{n=lu(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(du(t))n=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");const i=n.length;if(typeof r=="number"&&i!==r)throw new Error(e+" of length "+r+" expected, got "+i);return n}const zo=e=>typeof e=="bigint"&&Uu<=e;function Kb(e,t,r){return zo(e)&&zo(t)&&zo(r)&&t<=e&&e<r}function Yb(e,t,r,n){if(!Kb(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Zb(e){let t;for(t=0;e>Uu;e>>=Fc,t+=1);return t}const ho=e=>(Fc<<BigInt(e))-Fc;function Xb(e,t,r){if(typeof e!="number"||e<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");const n=p=>new Uint8Array(p),i=p=>Uint8Array.of(p);let s=n(e),o=n(e),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},f=(...p)=>r(o,s,...p),u=(p=n(0))=>{o=f(i(0),p),s=f(),p.length!==0&&(o=f(i(1),p),s=f())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0;const g=[];for(;p<t;){s=f();const b=s.slice();g.push(b),p+=s.length}return Lr(...g)};return(p,g)=>{c(),u(p);let b;for(;!(b=g(d()));)u();return c(),b}}function Lu(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(i,s,o){const a=e[i];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${c}`)}Object.entries(t).forEach(([i,s])=>n(i,s,!1)),Object.entries(r).forEach(([i,s])=>n(i,s,!0))}function Kf(e){const t=new WeakMap;return(r,...n)=>{const i=t.get(r);if(i!==void 0)return i;const s=e(r,...n);return t.set(r,s),s}}const Jb="0.1.1";function Qb(){return Jb}class xe extends Error{constructor(t,r={}){const n=(()=>{var c;if(r.cause instanceof xe){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),i=r.cause instanceof xe&&r.cause.docsPath||r.docsPath,o=`https://oxlib.sh${i??""}`,a=[t||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||i?["",n?`Details: ${n}`:void 0,i?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
|
|
40
40
|
`);super(a,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${Qb()}`}),this.cause=r.cause,this.details=n,this.docs=o,this.docsPath=i,this.shortMessage=t}walk(t){return lh(this,t)}}function lh(e,t){return t!=null&&t(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause?lh(e.cause,t):t?null:e}const ew="#__bigint";function tw(e,t,r){return JSON.stringify(e,(n,i)=>typeof i=="bigint"?i.toString()+ew:i,r)}function rw(e,t){if(Zf(e)>t)throw new lw({givenSize:Zf(e),maxSize:t})}const Xt={zero:48,nine:57,A:65,F:70,a:97,f:102};function Yf(e){if(e>=Xt.zero&&e<=Xt.nine)return e-Xt.zero;if(e>=Xt.A&&e<=Xt.F)return e-(Xt.A-10);if(e>=Xt.a&&e<=Xt.f)return e-(Xt.a-10)}function nw(e,t={}){const{dir:r,size:n=32}=t;if(n===0)return e;if(e.length>n)throw new pw({size:e.length,targetSize:n,type:"Bytes"});const i=new Uint8Array(n);for(let s=0;s<n;s++){const o=r==="right";i[o?s:n-s-1]=e[o?s:e.length-s-1]}return i}function Mu(e,t){if(Et(e)>t)throw new bw({givenSize:Et(e),maxSize:t})}function iw(e,t){if(typeof t=="number"&&t>0&&t>Et(e)-1)throw new gh({offset:t,position:"start",size:Et(e)})}function sw(e,t,r){if(typeof t=="number"&&typeof r=="number"&&Et(e)!==r-t)throw new gh({offset:r,position:"end",size:Et(e)})}function ph(e,t={}){const{dir:r,size:n=32}=t;if(n===0)return e;const i=e.replace("0x","");if(i.length>n*2)throw new ww({size:Math.ceil(i.length/2),targetSize:n,type:"Hex"});return`0x${i[r==="right"?"padEnd":"padStart"](n*2,"0")}`}const ow=new TextEncoder;function aw(e){return e instanceof Uint8Array?e:typeof e=="string"?uw(e):cw(e)}function cw(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function uw(e,t={}){const{size:r}=t;let n=e;r&&(Mu(e,r),n=rn(e,r));let i=n.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,o=new Uint8Array(s);for(let a=0,c=0;a<s;a++){const f=Yf(i.charCodeAt(c++)),u=Yf(i.charCodeAt(c++));if(f===void 0||u===void 0)throw new xe(`Invalid byte sequence ("${i[c-2]}${i[c-1]}" in "${i}").`);o[a]=f*16+u}return o}function fw(e,t={}){const{size:r}=t,n=ow.encode(e);return typeof r=="number"?(rw(n,r),dw(n,r)):n}function dw(e,t){return nw(e,{dir:"right",size:t})}function Zf(e){return e.length}let lw=class extends xe{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}},pw=class extends xe{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}};const hw=new TextEncoder,yw=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function mw(e,t={}){const{strict:r=!1}=t;if(!e)throw new Xf(e);if(typeof e!="string")throw new Xf(e);if(r&&!/^0x[0-9a-fA-F]*$/.test(e))throw new Jf(e);if(!e.startsWith("0x"))throw new Jf(e)}function Vt(...e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}function hh(e,t={}){const r=`0x${Number(e)}`;return typeof t.size=="number"?(Mu(r,t.size),tn(r,t.size)):r}function yh(e,t={}){let r="";for(let i=0;i<e.length;i++)r+=yw[e[i]];const n=`0x${r}`;return typeof t.size=="number"?(Mu(n,t.size),rn(n,t.size)):n}function Je(e,t={}){const{signed:r,size:n}=t,i=BigInt(e);let s;n?r?s=(1n<<BigInt(n)*8n-1n)-1n:s=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&r?-s-1n:0;if(s&&i>s||i<o){const f=typeof e=="bigint"?"n":"";throw new mh({max:s?`${s}${f}`:void 0,min:`${o}${f}`,signed:r,size:n,value:`${e}${f}`})}const c=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?tn(c,n):c}function Du(e,t={}){return yh(hw.encode(e),t)}function tn(e,t){return ph(e,{dir:"left",size:t})}function rn(e,t){return ph(e,{dir:"right",size:t})}function ju(e,t,r,n={}){const{strict:i}=n;iw(e,t);const s=`0x${e.replace("0x","").slice((t??0)*2,(r??e.length)*2)}`;return i&&sw(s,t,r),s}function Et(e){return Math.ceil((e.length-2)/2)}function gw(e,t={}){const{strict:r=!1}=t;try{return mw(e,{strict:r}),!0}catch{return!1}}class mh extends xe{constructor({max:t,min:r,signed:n,size:i,value:s}){super(`Number \`${s}\` is not in safe${i?` ${i*8}-bit`:""}${n?" signed":" unsigned"} integer range ${t?`(\`${r}\` to \`${t}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class Xf extends xe{constructor(t){super(`Value \`${typeof t=="object"?tw(t):t}\` of type \`${typeof t}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class Jf extends xe{constructor(t){super(`Value \`${t}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}class bw extends xe{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${t}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class gh extends xe{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${t}\` is out-of-bounds (size: \`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class ww extends xe{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${t}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}function vw(e){return{address:e.address,amount:Je(e.amount),index:Je(e.index),validatorIndex:Je(e.validatorIndex)}}function bh(e){return{...typeof e.baseFeePerGas=="bigint"&&{baseFeePerGas:Je(e.baseFeePerGas)},...typeof e.blobBaseFee=="bigint"&&{blobBaseFee:Je(e.blobBaseFee)},...typeof e.feeRecipient=="string"&&{feeRecipient:e.feeRecipient},...typeof e.gasLimit=="bigint"&&{gasLimit:Je(e.gasLimit)},...typeof e.number=="bigint"&&{number:Je(e.number)},...typeof e.prevRandao=="bigint"&&{prevRandao:Je(e.prevRandao)},...typeof e.time=="bigint"&&{time:Je(e.time)},...e.withdrawals&&{withdrawals:e.withdrawals.map(vw)}}}const $c=[{inputs:[{components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"aggregate3",outputs:[{components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}],name:"returnData",type:"tuple[]"}],stateMutability:"view",type:"function"}],Uc=[{name:"query",type:"function",stateMutability:"view",inputs:[{type:"tuple[]",name:"queries",components:[{type:"address",name:"sender"},{type:"string[]",name:"urls"},{type:"bytes",name:"data"}]}],outputs:[{type:"bool[]",name:"failures"},{type:"bytes[]",name:"responses"}]},{name:"HttpError",type:"error",inputs:[{type:"uint16",name:"status"},{type:"string",name:"message"}]}],wh=[{inputs:[],name:"ResolverNotFound",type:"error"},{inputs:[],name:"ResolverWildcardNotSupported",type:"error"},{inputs:[],name:"ResolverNotContract",type:"error"},{inputs:[{name:"returnData",type:"bytes"}],name:"ResolverError",type:"error"},{inputs:[{components:[{name:"status",type:"uint16"},{name:"message",type:"string"}],name:"errors",type:"tuple[]"}],name:"HttpError",type:"error"}],vh=[...wh,{name:"resolve",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]},{name:"resolve",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes"},{name:"data",type:"bytes"},{name:"gateways",type:"string[]"}],outputs:[{name:"",type:"bytes"},{name:"address",type:"address"}]}],Ew=[...wh,{name:"reverse",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolvedAddress"},{type:"address",name:"reverseResolver"},{type:"address",name:"resolver"}]},{name:"reverse",type:"function",stateMutability:"view",inputs:[{type:"bytes",name:"reverseName"},{type:"string[]",name:"gateways"}],outputs:[{type:"string",name:"resolvedName"},{type:"address",name:"resolvedAddress"},{type:"address",name:"reverseResolver"},{type:"address",name:"resolver"}]}],Qf=[{name:"text",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"key",type:"string"}],outputs:[{name:"",type:"string"}]}],ed=[{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"}],outputs:[{name:"",type:"address"}]},{name:"addr",type:"function",stateMutability:"view",inputs:[{name:"name",type:"bytes32"},{name:"coinType",type:"uint256"}],outputs:[{name:"",type:"bytes"}]}],td=[{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"_signer",type:"address"},{name:"_hash",type:"bytes32"},{name:"_signature",type:"bytes"}],outputs:[{type:"bool"}],stateMutability:"nonpayable",type:"function",name:"isValidSig"}],xw="0x82ad56cb",Eh="0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe",Aw="0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe",_w="0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572";class Hc extends D{constructor({blockNumber:t,chain:r,contract:n}){super(`Chain "${r.name}" does not support contract "${n.name}".`,{metaMessages:["This could be due to any of the following:",...t&&n.blockCreated&&n.blockCreated>t?[`- The contract "${n.name}" was not deployed until block ${n.blockCreated} (current block ${t}).`]:[`- The chain does not have the contract "${n.name}" configured.`]],name:"ChainDoesNotSupportContract"})}}class Sw extends D{constructor({chain:t,currentChainId:r}){super(`The current chain of the wallet (id: ${r}) does not match the target chain for the transaction (id: ${t.id} – ${t.name}).`,{metaMessages:[`Current Chain ID: ${r}`,`Expected Chain ID: ${t.id} – ${t.name}`],name:"ChainMismatchError"})}}class Pw extends D{constructor(){super(["No chain was provided to the request.","Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient."].join(`
|
|
41
|
-
`),{name:"ChainNotFoundError"})}}class xh extends D{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class yo extends D{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const qo="/docs/contract/encodeDeployData";function mo(e){const{abi:t,args:r,bytecode:n}=e;if(!r||r.length===0)return n;const i=t.find(o=>"type"in o&&o.type==="constructor");if(!i)throw new Bm({docsPath:qo});if(!("inputs"in i))throw new Sf({docsPath:qo});if(!i.inputs||i.inputs.length===0)throw new Sf({docsPath:qo});const s=pr(i.inputs,r);return Ct([n,s])}function Jn({blockNumber:e,chain:t,contract:r}){var i;const n=(i=t==null?void 0:t.contracts)==null?void 0:i[r];if(!n)throw new Hc({chain:t,contract:{name:r}});if(e&&n.blockCreated&&n.blockCreated>e)throw new Hc({blockNumber:e,chain:t,contract:{name:r,blockCreated:n.blockCreated}});return n.address}function Ah(e,{docsPath:t,...r}){const n=(()=>{const i=ao(e,r);return i instanceof ns?e:i})();return new Dp(n,{docsPath:t,...r})}function zu(){let e=()=>{},t=()=>{};return{promise:new Promise((n,i)=>{e=n,t=i}),resolve:e,reject:t}}const Go=new Map;function _h({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:i}){const s=async()=>{const u=c();o();const d=u.map(({args:y})=>y);d.length!==0&&e(d).then(y=>{i&&Array.isArray(y)&&y.sort(i);for(let p=0;p<u.length;p++){const{resolve:g}=u[p];g==null||g([y[p],y])}}).catch(y=>{for(let p=0;p<u.length;p++){const{reject:g}=u[p];g==null||g(y)}})},o=()=>Go.delete(t),a=()=>c().map(({args:u})=>u),c=()=>Go.get(t)||[],f=u=>Go.set(t,[...c(),u]);return{flush:o,async schedule(u){const{promise:d,resolve:y,reject:p}=zu();return(r==null?void 0:r([...a(),u]))&&s(),c().length>0?(f({args:u,resolve:y,reject:p}),d):(f({args:u,resolve:y,reject:p}),setTimeout(s,n),d)}}}async function ss(e,t){var j,V,Y,X;const{account:r=e.account,authorizationList:n,batch:i=!!((j=e.batch)!=null&&j.multicall),blockNumber:s,blockTag:o="latest",accessList:a,blobs:c,blockOverrides:f,code:u,data:d,factory:y,factoryData:p,gas:g,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:x,maxPriorityFeePerGas:P,nonce:w,to:A,value:T,stateOverride:I,...R}=t,L=r?ke(r):void 0;if(u&&(y||p))throw new D("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(u&&A)throw new D("Cannot provide both `code` & `to` as parameters.");const S=u&&d,$=y&&p&&A&&d,C=S||$,U=S?kw({code:u,data:d}):$?Bw({data:d,factory:y,factoryData:p,to:A}):d;try{an(t);const M=(typeof s=="bigint"?K(s):void 0)||o,B=f?bh(f):void 0,q=Au(I),W=(X=(Y=(V=e.chain)==null?void 0:V.formatters)==null?void 0:Y.transactionRequest)==null?void 0:X.format,N=(W||Zn)({...co(R,{format:W}),from:L==null?void 0:L.address,accessList:a,authorizationList:n,blobs:c,data:U,gas:g,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:x,maxPriorityFeePerGas:P,nonce:w,to:C?void 0:A,value:T});if(i&&Tw({request:N})&&!q&&!B)try{return await Iw(e,{...N,blockNumber:s,blockTag:o})}catch(Q){if(!(Q instanceof xh)&&!(Q instanceof Hc))throw Q}const H=(()=>{const Q=[N,M];return q&&B?[...Q,q,B]:q?[...Q,q]:B?[...Q,{},B]:Q})(),Z=await e.request({method:"eth_call",params:H});return Z==="0x"?{data:void 0}:{data:Z}}catch(J){const M=Ow(J),{offchainLookup:B,offchainLookupSignature:q}=await Promise.resolve().then(()=>require("./ccip-BgiZlV2r.cjs"));if(e.ccipRead!==!1&&(M==null?void 0:M.slice(0,10))===q&&A)return{data:await B(e,{data:M,to:A})};throw C&&(M==null?void 0:M.slice(0,10))==="0x101bb98d"?new db({factory:y}):Ah(J,{...t,account:L,chain:e.chain})}}function Tw({request:e}){const{data:t,to:r,...n}=e;return!(!t||t.startsWith(xw)||!r||Object.values(n).filter(i=>typeof i<"u").length>0)}async function Iw(e,t){var b;const{batchSize:r=1024,wait:n=0}=typeof((b=e.batch)==null?void 0:b.multicall)=="object"?e.batch.multicall:{},{blockNumber:i,blockTag:s="latest",data:o,multicallAddress:a,to:c}=t;let f=a;if(!f){if(!e.chain)throw new xh;f=Jn({blockNumber:i,chain:e.chain,contract:"multicall3"})}const d=(typeof i=="bigint"?K(i):void 0)||s,{schedule:y}=_h({id:`${e.uid}.${d}`,wait:n,shouldSplitBatch(E){return E.reduce((P,{data:w})=>P+(w.length-2),0)>r*2},fn:async E=>{const x=E.map(A=>({allowFailure:!0,callData:A.data,target:A.to})),P=xt({abi:$c,args:[x],functionName:"aggregate3"}),w=await e.request({method:"eth_call",params:[{data:P,to:f},d]});return cn({abi:$c,args:[x],functionName:"aggregate3",data:w||"0x"})}}),[{returnData:p,success:g}]=await y({data:o,to:c});if(!g)throw new oo({data:p});return p==="0x"?{data:void 0}:{data:p}}function kw(e){const{code:t,data:r}=e;return mo({abi:ap(["constructor(bytes, bytes)"]),bytecode:Eh,args:[t,r]})}function Bw(e){const{data:t,factory:r,factoryData:n,to:i}=e;return mo({abi:ap(["constructor(address, bytes, address, bytes)"]),bytecode:Aw,args:[i,t,r,n]})}function Ow(e){var r;if(!(e instanceof D))return;const t=e.walk();return typeof(t==null?void 0:t.data)=="object"?(r=t.data)==null?void 0:r.data:t.data}async function Wt(e,t){const{abi:r,address:n,args:i,functionName:s,...o}=t,a=xt({abi:r,args:i,functionName:s});try{const{data:c}=await ee(e,ss,"call")({...o,data:a,to:n});return cn({abi:r,args:i,functionName:s,data:c||"0x"})}catch(c){throw Qr(c,{abi:r,address:n,args:i,docsPath:"/docs/contract/readContract",functionName:s})}}async function Sh(e,t){const{abi:r,address:n,args:i,dataSuffix:s,functionName:o,...a}=t,c=a.account?ke(a.account):e.account,f=xt({abi:r,args:i,functionName:o});try{const{data:u}=await ee(e,ss,"call")({batch:!1,data:`${f}${s?s.replace("0x",""):""}`,to:n,...a,account:c}),d=cn({abi:r,args:i,functionName:o,data:u||"0x"}),y=r.filter(p=>"name"in p&&p.name===t.functionName);return{result:d,request:{abi:y,address:n,args:i,dataSuffix:s,functionName:o,...a,account:c}}}catch(u){throw Qr(u,{abi:r,address:n,args:i,docsPath:"/docs/contract/simulateContract",functionName:o,sender:c==null?void 0:c.address})}}const Vo=new Map,rd=new Map;let Cw=0;function ur(e,t,r){const n=++Cw,i=()=>Vo.get(e)||[],s=()=>{const u=i();Vo.set(e,u.filter(d=>d.id!==n))},o=()=>{const u=i();if(!u.some(y=>y.id===n))return;const d=rd.get(e);if(u.length===1&&d){const y=d();y instanceof Promise&&y.catch(()=>{})}s()},a=i();if(Vo.set(e,[...a,{id:n,fns:t}]),a&&a.length>0)return o;const c={};for(const u in t)c[u]=(...d)=>{var p,g;const y=i();if(y.length!==0)for(const b of y)(g=(p=b.fns)[u])==null||g.call(p,...d)};const f=r(c);return typeof f=="function"&&rd.set(e,f),o}async function Lc(e){return new Promise(t=>setTimeout(t,e))}function Qn(e,{emitOnBegin:t,initialWaitTime:r,interval:n}){let i=!0;const s=()=>i=!1;return(async()=>{let a;t&&(a=await e({unpoll:s}));const c=await(r==null?void 0:r(a))??n;await Lc(c);const f=async()=>{i&&(await e({unpoll:s}),await Lc(n),f())};f()})(),s}const Rw=new Map,Nw=new Map;function Fw(e){const t=(i,s)=>({clear:()=>s.delete(i),get:()=>s.get(i),set:o=>s.set(i,o)}),r=t(e,Rw),n=t(e,Nw);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function $w(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){const n=Fw(t),i=n.response.get();if(i&&r>0&&new Date().getTime()-i.created.getTime()<r)return i.data;let s=n.promise.get();s||(s=e(),n.promise.set(s));try{const o=await s;return n.response.set({created:new Date,data:o}),o}finally{n.promise.clear()}}const Uw=e=>`blockNumber.${e}`;async function os(e,{cacheTime:t=e.cacheTime}={}){const r=await $w(()=>e.request({method:"eth_blockNumber"}),{cacheKey:Uw(e.uid),cacheTime:t});return BigInt(r)}async function go(e,{filter:t}){const r="strict"in t&&t.strict,n=await t.request({method:"eth_getFilterChanges",params:[t.id]});if(typeof n[0]=="string")return n;const i=n.map(s=>cr(s));return!("abi"in t)||!t.abi?i:Nu({abi:t.abi,logs:i,strict:r})}async function bo(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}function Ph(e,t){const{abi:r,address:n,args:i,batch:s=!0,eventName:o,fromBlock:a,onError:c,onLogs:f,poll:u,pollingInterval:d=e.pollingInterval,strict:y}=t;return(typeof u<"u"?u:typeof a=="bigint"?!0:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")))?(()=>{const E=y??!1,x=Oe(["watchContractEvent",n,i,s,e.uid,o,d,E,a]);return ur(x,{onLogs:f,onError:c},P=>{let w;a!==void 0&&(w=a-1n);let A,T=!1;const I=Qn(async()=>{var R;if(!T){try{A=await ee(e,bu,"createContractEventFilter")({abi:r,address:n,args:i,eventName:o,strict:E,fromBlock:a})}catch{}T=!0;return}try{let L;if(A)L=await ee(e,go,"getFilterChanges")({filter:A});else{const S=await ee(e,os,"getBlockNumber")({});w&&w<S?L=await ee(e,$u,"getContractEvents")({abi:r,address:n,args:i,eventName:o,fromBlock:w+1n,toBlock:S,strict:E}):L=[],w=S}if(L.length===0)return;if(s)P.onLogs(L);else for(const S of L)P.onLogs([S])}catch(L){A&&L instanceof Jr&&(T=!1),(R=P.onError)==null||R.call(P,L)}},{emitOnBegin:!0,interval:d});return async()=>{A&&await ee(e,bo,"uninstallFilter")({filter:A}),I()}})})():(()=>{const E=y??!1,x=Oe(["watchContractEvent",n,i,s,e.uid,o,d,E]);let P=!0,w=()=>P=!1;return ur(x,{onLogs:f,onError:c},A=>((async()=>{try{const T=(()=>{if(e.transport.type==="fallback"){const L=e.transport.transports.find(S=>S.config.type==="webSocket"||S.config.type==="ipc");return L?L.value:e.transport}return e.transport})(),I=o?es({abi:r,eventName:o,args:i}):[],{unsubscribe:R}=await T.subscribe({params:["logs",{address:n,topics:I}],onData(L){var $;if(!P)return;const S=L.result;try{const{eventName:C,args:U}=Ru({abi:r,data:S.data,topics:S.topics,strict:y}),j=cr(S,{args:U,eventName:C});A.onLogs([j])}catch(C){let U,j;if(C instanceof Ai||C instanceof Qs){if(y)return;U=C.abiItem.name,j=($=C.abiItem.inputs)==null?void 0:$.some(Y=>!("name"in Y&&Y.name))}const V=cr(S,{args:j?[]:{},eventName:U});A.onLogs([V])}},onError(L){var S;(S=A.onError)==null||S.call(A,L)}});w=R,P||w()}catch(T){c==null||c(T)}})(),()=>w()))})()}class un extends D{constructor({docsPath:t}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(`
|
|
41
|
+
`),{name:"ChainNotFoundError"})}}class xh extends D{constructor(){super("No chain was provided to the Client.",{name:"ClientChainNotConfiguredError"})}}class yo extends D{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}const qo="/docs/contract/encodeDeployData";function mo(e){const{abi:t,args:r,bytecode:n}=e;if(!r||r.length===0)return n;const i=t.find(o=>"type"in o&&o.type==="constructor");if(!i)throw new Bm({docsPath:qo});if(!("inputs"in i))throw new Sf({docsPath:qo});if(!i.inputs||i.inputs.length===0)throw new Sf({docsPath:qo});const s=pr(i.inputs,r);return Ct([n,s])}function Jn({blockNumber:e,chain:t,contract:r}){var i;const n=(i=t==null?void 0:t.contracts)==null?void 0:i[r];if(!n)throw new Hc({chain:t,contract:{name:r}});if(e&&n.blockCreated&&n.blockCreated>e)throw new Hc({blockNumber:e,chain:t,contract:{name:r,blockCreated:n.blockCreated}});return n.address}function Ah(e,{docsPath:t,...r}){const n=(()=>{const i=ao(e,r);return i instanceof ns?e:i})();return new Dp(n,{docsPath:t,...r})}function zu(){let e=()=>{},t=()=>{};return{promise:new Promise((n,i)=>{e=n,t=i}),resolve:e,reject:t}}const Go=new Map;function _h({fn:e,id:t,shouldSplitBatch:r,wait:n=0,sort:i}){const s=async()=>{const u=c();o();const d=u.map(({args:y})=>y);d.length!==0&&e(d).then(y=>{i&&Array.isArray(y)&&y.sort(i);for(let p=0;p<u.length;p++){const{resolve:g}=u[p];g==null||g([y[p],y])}}).catch(y=>{for(let p=0;p<u.length;p++){const{reject:g}=u[p];g==null||g(y)}})},o=()=>Go.delete(t),a=()=>c().map(({args:u})=>u),c=()=>Go.get(t)||[],f=u=>Go.set(t,[...c(),u]);return{flush:o,async schedule(u){const{promise:d,resolve:y,reject:p}=zu();return(r==null?void 0:r([...a(),u]))&&s(),c().length>0?(f({args:u,resolve:y,reject:p}),d):(f({args:u,resolve:y,reject:p}),setTimeout(s,n),d)}}}async function ss(e,t){var j,V,Y,X;const{account:r=e.account,authorizationList:n,batch:i=!!((j=e.batch)!=null&&j.multicall),blockNumber:s,blockTag:o="latest",accessList:a,blobs:c,blockOverrides:f,code:u,data:d,factory:y,factoryData:p,gas:g,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:x,maxPriorityFeePerGas:P,nonce:w,to:A,value:T,stateOverride:I,...R}=t,L=r?ke(r):void 0;if(u&&(y||p))throw new D("Cannot provide both `code` & `factory`/`factoryData` as parameters.");if(u&&A)throw new D("Cannot provide both `code` & `to` as parameters.");const S=u&&d,$=y&&p&&A&&d,C=S||$,U=S?kw({code:u,data:d}):$?Bw({data:d,factory:y,factoryData:p,to:A}):d;try{an(t);const M=(typeof s=="bigint"?K(s):void 0)||o,B=f?bh(f):void 0,q=Au(I),W=(X=(Y=(V=e.chain)==null?void 0:V.formatters)==null?void 0:Y.transactionRequest)==null?void 0:X.format,N=(W||Zn)({...co(R,{format:W}),from:L==null?void 0:L.address,accessList:a,authorizationList:n,blobs:c,data:U,gas:g,gasPrice:b,maxFeePerBlobGas:E,maxFeePerGas:x,maxPriorityFeePerGas:P,nonce:w,to:C?void 0:A,value:T});if(i&&Tw({request:N})&&!q&&!B)try{return await Iw(e,{...N,blockNumber:s,blockTag:o})}catch(Q){if(!(Q instanceof xh)&&!(Q instanceof Hc))throw Q}const H=(()=>{const Q=[N,M];return q&&B?[...Q,q,B]:q?[...Q,q]:B?[...Q,{},B]:Q})(),Z=await e.request({method:"eth_call",params:H});return Z==="0x"?{data:void 0}:{data:Z}}catch(J){const M=Ow(J),{offchainLookup:B,offchainLookupSignature:q}=await Promise.resolve().then(()=>require("./ccip-BerK0Wjb.cjs"));if(e.ccipRead!==!1&&(M==null?void 0:M.slice(0,10))===q&&A)return{data:await B(e,{data:M,to:A})};throw C&&(M==null?void 0:M.slice(0,10))==="0x101bb98d"?new db({factory:y}):Ah(J,{...t,account:L,chain:e.chain})}}function Tw({request:e}){const{data:t,to:r,...n}=e;return!(!t||t.startsWith(xw)||!r||Object.values(n).filter(i=>typeof i<"u").length>0)}async function Iw(e,t){var b;const{batchSize:r=1024,wait:n=0}=typeof((b=e.batch)==null?void 0:b.multicall)=="object"?e.batch.multicall:{},{blockNumber:i,blockTag:s="latest",data:o,multicallAddress:a,to:c}=t;let f=a;if(!f){if(!e.chain)throw new xh;f=Jn({blockNumber:i,chain:e.chain,contract:"multicall3"})}const d=(typeof i=="bigint"?K(i):void 0)||s,{schedule:y}=_h({id:`${e.uid}.${d}`,wait:n,shouldSplitBatch(E){return E.reduce((P,{data:w})=>P+(w.length-2),0)>r*2},fn:async E=>{const x=E.map(A=>({allowFailure:!0,callData:A.data,target:A.to})),P=xt({abi:$c,args:[x],functionName:"aggregate3"}),w=await e.request({method:"eth_call",params:[{data:P,to:f},d]});return cn({abi:$c,args:[x],functionName:"aggregate3",data:w||"0x"})}}),[{returnData:p,success:g}]=await y({data:o,to:c});if(!g)throw new oo({data:p});return p==="0x"?{data:void 0}:{data:p}}function kw(e){const{code:t,data:r}=e;return mo({abi:ap(["constructor(bytes, bytes)"]),bytecode:Eh,args:[t,r]})}function Bw(e){const{data:t,factory:r,factoryData:n,to:i}=e;return mo({abi:ap(["constructor(address, bytes, address, bytes)"]),bytecode:Aw,args:[i,t,r,n]})}function Ow(e){var r;if(!(e instanceof D))return;const t=e.walk();return typeof(t==null?void 0:t.data)=="object"?(r=t.data)==null?void 0:r.data:t.data}async function Wt(e,t){const{abi:r,address:n,args:i,functionName:s,...o}=t,a=xt({abi:r,args:i,functionName:s});try{const{data:c}=await ee(e,ss,"call")({...o,data:a,to:n});return cn({abi:r,args:i,functionName:s,data:c||"0x"})}catch(c){throw Qr(c,{abi:r,address:n,args:i,docsPath:"/docs/contract/readContract",functionName:s})}}async function Sh(e,t){const{abi:r,address:n,args:i,dataSuffix:s,functionName:o,...a}=t,c=a.account?ke(a.account):e.account,f=xt({abi:r,args:i,functionName:o});try{const{data:u}=await ee(e,ss,"call")({batch:!1,data:`${f}${s?s.replace("0x",""):""}`,to:n,...a,account:c}),d=cn({abi:r,args:i,functionName:o,data:u||"0x"}),y=r.filter(p=>"name"in p&&p.name===t.functionName);return{result:d,request:{abi:y,address:n,args:i,dataSuffix:s,functionName:o,...a,account:c}}}catch(u){throw Qr(u,{abi:r,address:n,args:i,docsPath:"/docs/contract/simulateContract",functionName:o,sender:c==null?void 0:c.address})}}const Vo=new Map,rd=new Map;let Cw=0;function ur(e,t,r){const n=++Cw,i=()=>Vo.get(e)||[],s=()=>{const u=i();Vo.set(e,u.filter(d=>d.id!==n))},o=()=>{const u=i();if(!u.some(y=>y.id===n))return;const d=rd.get(e);if(u.length===1&&d){const y=d();y instanceof Promise&&y.catch(()=>{})}s()},a=i();if(Vo.set(e,[...a,{id:n,fns:t}]),a&&a.length>0)return o;const c={};for(const u in t)c[u]=(...d)=>{var p,g;const y=i();if(y.length!==0)for(const b of y)(g=(p=b.fns)[u])==null||g.call(p,...d)};const f=r(c);return typeof f=="function"&&rd.set(e,f),o}async function Lc(e){return new Promise(t=>setTimeout(t,e))}function Qn(e,{emitOnBegin:t,initialWaitTime:r,interval:n}){let i=!0;const s=()=>i=!1;return(async()=>{let a;t&&(a=await e({unpoll:s}));const c=await(r==null?void 0:r(a))??n;await Lc(c);const f=async()=>{i&&(await e({unpoll:s}),await Lc(n),f())};f()})(),s}const Rw=new Map,Nw=new Map;function Fw(e){const t=(i,s)=>({clear:()=>s.delete(i),get:()=>s.get(i),set:o=>s.set(i,o)}),r=t(e,Rw),n=t(e,Nw);return{clear:()=>{r.clear(),n.clear()},promise:r,response:n}}async function $w(e,{cacheKey:t,cacheTime:r=Number.POSITIVE_INFINITY}){const n=Fw(t),i=n.response.get();if(i&&r>0&&new Date().getTime()-i.created.getTime()<r)return i.data;let s=n.promise.get();s||(s=e(),n.promise.set(s));try{const o=await s;return n.response.set({created:new Date,data:o}),o}finally{n.promise.clear()}}const Uw=e=>`blockNumber.${e}`;async function os(e,{cacheTime:t=e.cacheTime}={}){const r=await $w(()=>e.request({method:"eth_blockNumber"}),{cacheKey:Uw(e.uid),cacheTime:t});return BigInt(r)}async function go(e,{filter:t}){const r="strict"in t&&t.strict,n=await t.request({method:"eth_getFilterChanges",params:[t.id]});if(typeof n[0]=="string")return n;const i=n.map(s=>cr(s));return!("abi"in t)||!t.abi?i:Nu({abi:t.abi,logs:i,strict:r})}async function bo(e,{filter:t}){return t.request({method:"eth_uninstallFilter",params:[t.id]})}function Ph(e,t){const{abi:r,address:n,args:i,batch:s=!0,eventName:o,fromBlock:a,onError:c,onLogs:f,poll:u,pollingInterval:d=e.pollingInterval,strict:y}=t;return(typeof u<"u"?u:typeof a=="bigint"?!0:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")))?(()=>{const E=y??!1,x=Oe(["watchContractEvent",n,i,s,e.uid,o,d,E,a]);return ur(x,{onLogs:f,onError:c},P=>{let w;a!==void 0&&(w=a-1n);let A,T=!1;const I=Qn(async()=>{var R;if(!T){try{A=await ee(e,bu,"createContractEventFilter")({abi:r,address:n,args:i,eventName:o,strict:E,fromBlock:a})}catch{}T=!0;return}try{let L;if(A)L=await ee(e,go,"getFilterChanges")({filter:A});else{const S=await ee(e,os,"getBlockNumber")({});w&&w<S?L=await ee(e,$u,"getContractEvents")({abi:r,address:n,args:i,eventName:o,fromBlock:w+1n,toBlock:S,strict:E}):L=[],w=S}if(L.length===0)return;if(s)P.onLogs(L);else for(const S of L)P.onLogs([S])}catch(L){A&&L instanceof Jr&&(T=!1),(R=P.onError)==null||R.call(P,L)}},{emitOnBegin:!0,interval:d});return async()=>{A&&await ee(e,bo,"uninstallFilter")({filter:A}),I()}})})():(()=>{const E=y??!1,x=Oe(["watchContractEvent",n,i,s,e.uid,o,d,E]);let P=!0,w=()=>P=!1;return ur(x,{onLogs:f,onError:c},A=>((async()=>{try{const T=(()=>{if(e.transport.type==="fallback"){const L=e.transport.transports.find(S=>S.config.type==="webSocket"||S.config.type==="ipc");return L?L.value:e.transport}return e.transport})(),I=o?es({abi:r,eventName:o,args:i}):[],{unsubscribe:R}=await T.subscribe({params:["logs",{address:n,topics:I}],onData(L){var $;if(!P)return;const S=L.result;try{const{eventName:C,args:U}=Ru({abi:r,data:S.data,topics:S.topics,strict:y}),j=cr(S,{args:U,eventName:C});A.onLogs([j])}catch(C){let U,j;if(C instanceof Ai||C instanceof Qs){if(y)return;U=C.abiItem.name,j=($=C.abiItem.inputs)==null?void 0:$.some(Y=>!("name"in Y&&Y.name))}const V=cr(S,{args:j?[]:{},eventName:U});A.onLogs([V])}},onError(L){var S;(S=A.onError)==null||S.call(A,L)}});w=R,P||w()}catch(T){c==null||c(T)}})(),()=>w()))})()}class un extends D{constructor({docsPath:t}={}){super(["Could not find an Account to execute with this Action.","Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client."].join(`
|
|
42
42
|
`),{docsPath:t,docsSlug:"account",name:"AccountNotFoundError"})}}class Fs extends D{constructor({docsPath:t,metaMessages:r,type:n}){super(`Account type "${n}" is not supported.`,{docsPath:t,metaMessages:r,name:"AccountTypeNotSupportedError"})}}function Th({chain:e,currentChainId:t}){if(!e)throw new Pw;if(t!==e.id)throw new Sw({chain:e,currentChainId:t})}function Ih(e,{docsPath:t,...r}){const n=(()=>{const i=ao(e,r);return i instanceof ns?e:i})();return new ob(n,{docsPath:t,...r})}async function qu(e,{serializedTransaction:t}){return e.request({method:"eth_sendRawTransaction",params:[t]},{retryCount:0})}const Wo=new no(128);async function wo(e,t){var P,w,A,T;const{account:r=e.account,chain:n=e.chain,accessList:i,authorizationList:s,blobs:o,data:a,gas:c,gasPrice:f,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:y,nonce:p,type:g,value:b,...E}=t;if(typeof r>"u")throw new un({docsPath:"/docs/actions/wallet/sendTransaction"});const x=r?ke(r):null;try{an(t);const I=await(async()=>{if(t.to)return t.to;if(t.to!==null&&s&&s.length>0)return await Gp({authorization:s[0]}).catch(()=>{throw new D("`to` is required. Could not infer from `authorizationList`.")})})();if((x==null?void 0:x.type)==="json-rpc"||x===null){let R;n!==null&&(R=await ee(e,Xn,"getChainId")({}),Th({currentChainId:R,chain:n}));const L=(A=(w=(P=e.chain)==null?void 0:P.formatters)==null?void 0:w.transactionRequest)==null?void 0:A.format,$=(L||Zn)({...co(E,{format:L}),accessList:i,authorizationList:s,blobs:o,chainId:R,data:a,from:x==null?void 0:x.address,gas:c,gasPrice:f,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:y,nonce:p,to:I,type:g,value:b}),C=Wo.get(e.uid),U=C?"wallet_sendTransaction":"eth_sendTransaction";try{return await e.request({method:U,params:[$]},{retryCount:0})}catch(j){if(C===!1)throw j;const V=j;if(V.name==="InvalidInputRpcError"||V.name==="InvalidParamsRpcError"||V.name==="MethodNotFoundRpcError"||V.name==="MethodNotSupportedRpcError")return await e.request({method:"wallet_sendTransaction",params:[$]},{retryCount:0}).then(Y=>(Wo.set(e.uid,!0),Y)).catch(Y=>{const X=Y;throw X.name==="MethodNotFoundRpcError"||X.name==="MethodNotSupportedRpcError"?(Wo.set(e.uid,!1),V):X});throw V}}if((x==null?void 0:x.type)==="local"){const R=await ee(e,lo,"prepareTransactionRequest")({account:x,accessList:i,authorizationList:s,blobs:o,chain:n,data:a,gas:c,gasPrice:f,maxFeePerBlobGas:u,maxFeePerGas:d,maxPriorityFeePerGas:y,nonce:p,nonceManager:x.nonceManager,parameters:[...oh,"sidecars"],type:g,value:b,...E,to:I}),L=(T=n==null?void 0:n.serializers)==null?void 0:T.transaction,S=await x.signTransaction(R,{serializer:L});return await ee(e,qu,"sendRawTransaction")({serializedTransaction:S})}throw(x==null?void 0:x.type)==="smart"?new Fs({metaMessages:["Consider using the `sendUserOperation` Action instead."],docsPath:"/docs/actions/bundler/sendUserOperation",type:"smart"}):new Fs({docsPath:"/docs/actions/wallet/sendTransaction",type:x==null?void 0:x.type})}catch(I){throw I instanceof Fs?I:Ih(I,{...t,account:x,chain:t.chain||void 0})}}async function kh(e,t){const{abi:r,account:n=e.account,address:i,args:s,dataSuffix:o,functionName:a,...c}=t;if(typeof n>"u")throw new un({docsPath:"/docs/contract/writeContract"});const f=n?ke(n):null,u=xt({abi:r,args:s,functionName:a});try{return await ee(e,wo,"sendTransaction")({data:`${u}${o?o.replace("0x",""):""}`,to:i,account:f,...c})}catch(d){throw Qr(d,{abi:r,address:i,args:s,docsPath:"/docs/contract/writeContract",functionName:a,sender:f==null?void 0:f.address})}}function Ko({abi:e,address:t,client:r}){const n=r,[i,s]=n?"public"in n&&"wallet"in n?[n.public,n.wallet]:"public"in n?[n.public,void 0]:"wallet"in n?[void 0,n.wallet]:[n,n]:[void 0,void 0],o=i!=null,a=s!=null,c={};let f=!1,u=!1,d=!1;for(const y of e)if(y.type==="function"?y.stateMutability==="view"||y.stateMutability==="pure"?f=!0:u=!0:y.type==="event"&&(d=!0),f&&u&&d)break;return o&&(f&&(c.read=new Proxy({},{get(y,p){return(...g)=>{const{args:b,options:E}=gs(g);return ee(i,Wt,"readContract")({abi:e,address:t,functionName:p,args:b,...E})}}})),u&&(c.simulate=new Proxy({},{get(y,p){return(...g)=>{const{args:b,options:E}=gs(g);return ee(i,Sh,"simulateContract")({abi:e,address:t,functionName:p,args:b,...E})}}})),d&&(c.createEventFilter=new Proxy({},{get(y,p){return(...g)=>{const b=e.find(P=>P.type==="event"&&P.name===p),{args:E,options:x}=Yo(g,b);return ee(i,bu,"createContractEventFilter")({abi:e,address:t,eventName:p,args:E,...x})}}}),c.getEvents=new Proxy({},{get(y,p){return(...g)=>{const b=e.find(P=>P.type==="event"&&P.name===p),{args:E,options:x}=Yo(g,b);return ee(i,$u,"getContractEvents")({abi:e,address:t,eventName:p,args:E,...x})}}}),c.watchEvent=new Proxy({},{get(y,p){return(...g)=>{const b=e.find(P=>P.type==="event"&&P.name===p),{args:E,options:x}=Yo(g,b);return ee(i,Ph,"watchContractEvent")({abi:e,address:t,eventName:p,args:E,...x})}}}))),a&&u&&(c.write=new Proxy({},{get(y,p){return(...g)=>{const{args:b,options:E}=gs(g);return ee(s,kh,"writeContract")({abi:e,address:t,functionName:p,args:b,...E})}}})),(o||a)&&u&&(c.estimateGas=new Proxy({},{get(y,p){return(...g)=>{const{args:b,options:E}=gs(g);return ee(i??s,ch,"estimateContractGas")({abi:e,address:t,functionName:p,args:b,...E,account:E.account??s.account})}}})),c.address=t,c.abi=e,c}function gs(e){const t=e.length&&Array.isArray(e[0]),r=t?e[0]:[],n=(t?e[1]:e[0])??{};return{args:r,options:n}}function Yo(e,t){let r=!1;Array.isArray(e[0])?r=!0:e.length===1?r=t.inputs.some(s=>s.indexed):e.length===2&&(r=!0);const n=r?e[0]:void 0,i=(r?e[1]:e[0])??{};return{args:n,options:i}}const Bh={"0x0":"reverted","0x1":"success"};function Oh(e){const t={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(r=>cr(r)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?vt(e.transactionIndex):null,status:e.status?Bh[e.status]:null,type:e.type?Wp[e.type]||e.type:null};return e.blobGasPrice&&(t.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(t.blobGasUsed=BigInt(e.blobGasUsed)),t}const Hw=xu("transactionReceipt",Oh),Ch="0x5792579257925792579257925792579257925792579257925792579257925792",Rh=K(0,{size:32});async function Lw(e,t){const{account:r=e.account,capabilities:n,chain:i=e.chain,experimental_fallback:s,experimental_fallbackDelay:o=32,forceAtomic:a=!1,id:c,version:f="2.0.0"}=t,u=r?ke(r):null,d=t.calls.map(y=>{const p=y,g=p.abi?xt({abi:p.abi,functionName:p.functionName,args:p.args}):p.data;return{data:p.dataSuffix&&g?ct([g,p.dataSuffix]):g,to:p.to,value:p.value?K(p.value):void 0}});try{const y=await e.request({method:"wallet_sendCalls",params:[{atomicRequired:a,calls:d,capabilities:n,chainId:K(i.id),from:u==null?void 0:u.address,id:c,version:f}]},{retryCount:0});return typeof y=="string"?{id:y}:y}catch(y){const p=y;if(s&&(p.name==="MethodNotFoundRpcError"||p.name==="MethodNotSupportedRpcError"||p.name==="UnknownRpcError"||p.details.toLowerCase().includes("does not exist / is not available")||p.details.toLowerCase().includes("missing or invalid. request()")||p.details.toLowerCase().includes("did not match any variant of untagged enum")||p.details.toLowerCase().includes("account upgraded to unsupported contract")||p.details.toLowerCase().includes("eip-7702 not supported")||p.details.toLowerCase().includes("unsupported wc_ method"))){if(n&&Object.values(n).some(P=>!P.optional)){const P="non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`.";throw new Un(new D(P,{details:P}))}if(a&&d.length>1){const x="`forceAtomic` is not supported on fallback to `eth_sendTransaction`.";throw new Hn(new D(x,{details:x}))}const g=[];for(const x of d){const P=wo(e,{account:u,chain:i,data:x.data,to:x.to,value:x.value?Ue(x.value):void 0});g.push(P),o>0&&await new Promise(w=>setTimeout(w,o))}const b=await Promise.allSettled(g);if(b.every(x=>x.status==="rejected"))throw b[0].reason;const E=b.map(x=>x.status==="fulfilled"?x.value:Rh);return{id:ct([...E,K(i.id,{size:32}),Ch])}}throw Ih(y,{...t,account:u,chain:t.chain})}}async function Nh(e,t){async function r(u){if(u.endsWith(Ch.slice(2))){const y=wt(Vs(u,-64,-32)),p=Vs(u,0,-64).slice(2).match(/.{1,64}/g),g=await Promise.all(p.map(E=>Rh.slice(2)!==E?e.request({method:"eth_getTransactionReceipt",params:[`0x${E}`]},{dedupe:!0}):void 0)),b=g.some(E=>E===null)?100:g.every(E=>(E==null?void 0:E.status)==="0x1")?200:g.every(E=>(E==null?void 0:E.status)==="0x0")?500:600;return{atomic:!1,chainId:vt(y),receipts:g.filter(Boolean),status:b,version:"2.0.0"}}return e.request({method:"wallet_getCallsStatus",params:[u]})}const{atomic:n=!1,chainId:i,receipts:s,version:o="2.0.0",...a}=await r(t.id),[c,f]=(()=>{const u=a.status;return u>=100&&u<200?["pending",u]:u>=200&&u<300?["success",u]:u>=300&&u<700?["failure",u]:u==="CONFIRMED"?["success",200]:u==="PENDING"?["pending",100]:[void 0,u]})();return{...a,atomic:n,chainId:i?vt(i):void 0,receipts:(s==null?void 0:s.map(u=>({...u,blockNumber:Ue(u.blockNumber),gasUsed:Ue(u.gasUsed),status:Bh[u.status]})))??[],statusCode:f,status:c,version:o}}async function Mw(e,t){const{id:r,pollingInterval:n=e.pollingInterval,status:i=({statusCode:y})=>y>=200,timeout:s=6e4}=t,o=Oe(["waitForCallsStatus",e.uid,r]),{promise:a,resolve:c,reject:f}=zu();let u;const d=ur(o,{resolve:c,reject:f},y=>{const p=Qn(async()=>{const g=b=>{clearTimeout(u),p(),b(),d()};try{const b=await Nh(e,{id:r});if(!i(b))return;g(()=>y.resolve(b))}catch(b){g(()=>y.reject(b))}},{interval:n,emitOnBegin:!0});return p});return u=s?setTimeout(()=>{d(),clearTimeout(u),f(new Dw({id:r}))},s):void 0,await a}class Dw extends D{constructor({id:t}){super(`Timed out while waiting for call bundle with id "${t}" to be confirmed.`,{name:"WaitForCallsStatusTimeoutError"})}}const Mc=256;let bs=Mc,ws;function Fh(e=11){if(!ws||bs+e>Mc*2){ws="",bs=0;for(let t=0;t<Mc;t++)ws+=(256+Math.random()*256|0).toString(16).substring(1)}return ws.substring(bs,bs+++e)}function $h(e){const{batch:t,chain:r,ccipRead:n,key:i="base",name:s="Base Client",type:o="base"}=e,a=(r==null?void 0:r.blockTime)??12e3,c=Math.min(Math.max(Math.floor(a/2),500),4e3),f=e.pollingInterval??c,u=e.cacheTime??f,d=e.account?ke(e.account):void 0,{config:y,request:p,value:g}=e.transport({chain:r,pollingInterval:f}),b={...y,...g},E={account:d,batch:t,cacheTime:u,ccipRead:n,chain:r,key:i,name:s,pollingInterval:f,request:p,transport:b,type:o,uid:Fh()};function x(P){return w=>{const A=w(P);for(const I in E)delete A[I];const T={...P,...A};return Object.assign(T,{extend:x(T)})}}return Object.assign(E,{extend:x(E)})}const vs=new no(8192);function jw(e,{enabled:t=!0,id:r}){if(!t||!r)return e();if(vs.get(r))return vs.get(r);const n=e().finally(()=>vs.delete(r));return vs.set(r,n),n}function Dc(e,{delay:t=100,retryCount:r=2,shouldRetry:n=()=>!0}={}){return new Promise((i,s)=>{const o=async({count:a=0}={})=>{const c=async({error:f})=>{const u=typeof t=="function"?t({count:a,error:f}):t;u&&await Lc(u),o({count:a+1})};try{const f=await e();i(f)}catch(f){if(a<r&&await n({count:a,error:f}))return c({error:f});s(f)}};o()})}function zw(e,t={}){return async(r,n={})=>{var d;const{dedupe:i=!1,methods:s,retryDelay:o=150,retryCount:a=3,uid:c}={...t,...n},{method:f}=r;if((d=s==null?void 0:s.exclude)!=null&&d.includes(f))throw new Mr(new Error("method not supported"),{method:f});if(s!=null&&s.include&&!s.include.includes(f))throw new Mr(new Error("method not supported"),{method:f});const u=i?Nn(`${c}.${Oe(r)}`):void 0;return jw(()=>Dc(async()=>{try{return await e(r)}catch(y){const p=y;switch(p.code){case Ti.code:throw new Ti(p);case Ii.code:throw new Ii(p);case ki.code:throw new ki(p,{method:r.method});case Bi.code:throw new Bi(p);case Xr.code:throw new Xr(p);case Jr.code:throw new Jr(p);case Oi.code:throw new Oi(p);case Ci.code:throw new Ci(p);case Ri.code:throw new Ri(p);case Mr.code:throw new Mr(p,{method:r.method});case $n.code:throw new $n(p);case Ni.code:throw new Ni(p);case In.code:throw new In(p);case Fi.code:throw new Fi(p);case $i.code:throw new $i(p);case Ui.code:throw new Ui(p);case Hi.code:throw new Hi(p);case Li.code:throw new Li(p);case Un.code:throw new Un(p);case Mi.code:throw new Mi(p);case Di.code:throw new Di(p);case ji.code:throw new ji(p);case zi.code:throw new zi(p);case qi.code:throw new qi(p);case Hn.code:throw new Hn(p);case 5e3:throw new In(p);default:throw y instanceof D?y:new pb(p)}}},{delay:({count:y,error:p})=>{var g;if(p&&p instanceof Tn){const b=(g=p==null?void 0:p.headers)==null?void 0:g.get("Retry-After");if(b!=null&&b.match(/\d/))return Number.parseInt(b)*1e3}return~~(1<<y)*o},retryCount:a,shouldRetry:({error:y})=>qw(y)}),{enabled:i,id:u})}}function qw(e){return"code"in e&&typeof e.code=="number"?e.code===-1||e.code===$n.code||e.code===Xr.code:e instanceof Tn&&e.status?e.status===403||e.status===408||e.status===413||e.status===429||e.status===500||e.status===502||e.status===503||e.status===504:!0}function Uh({key:e,methods:t,name:r,request:n,retryCount:i=3,retryDelay:s=150,timeout:o,type:a},c){const f=Fh();return{config:{key:e,methods:t,name:r,request:n,retryCount:i,retryDelay:s,timeout:o,type:a},request:zw(n,{methods:t,retryCount:i,retryDelay:s,uid:f}),value:c}}function nd(e,t={}){const{key:r="custom",methods:n,name:i="Custom Provider",retryDelay:s}=t;return({retryCount:o})=>Uh({key:r,methods:n,name:i,request:e.request.bind(e),retryCount:t.retryCount??o,retryDelay:s,type:"custom"})}class Gw extends D{constructor(){super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",{docsPath:"/docs/clients/intro",name:"UrlRequiredError"})}}function Vw(e,{errorInstance:t=new Error("timed out"),timeout:r,signal:n}){return new Promise((i,s)=>{(async()=>{let o;try{const a=new AbortController;r>0&&(o=setTimeout(()=>{n&&a.abort()},r)),i(await e({signal:(a==null?void 0:a.signal)||null}))}catch(a){(a==null?void 0:a.name)==="AbortError"&&s(t),s(a)}finally{clearTimeout(o)}})()})}function Ww(){return{current:0,take(){return this.current++},reset(){this.current=0}}}const id=Ww();function Kw(e,t={}){return{async request(r){var d;const{body:n,onRequest:i=t.onRequest,onResponse:s=t.onResponse,timeout:o=t.timeout??1e4}=r,a={...t.fetchOptions??{},...r.fetchOptions??{}},{headers:c,method:f,signal:u}=a;try{const y=await Vw(async({signal:g})=>{const b={...a,body:Array.isArray(n)?Oe(n.map(w=>({jsonrpc:"2.0",id:w.id??id.take(),...w}))):Oe({jsonrpc:"2.0",id:n.id??id.take(),...n}),headers:{"Content-Type":"application/json",...c},method:f||"POST",signal:u||(o>0?g:null)},E=new Request(e,b),x=await(i==null?void 0:i(E,b))??{...b,url:e};return await fetch(x.url??e,x)},{errorInstance:new Df({body:n,url:e}),timeout:o,signal:!0});s&&await s(y);let p;if((d=y.headers.get("Content-Type"))!=null&&d.startsWith("application/json"))p=await y.json();else{p=await y.text();try{p=JSON.parse(p||"{}")}catch(g){if(y.ok)throw g;p={error:p}}}if(!y.ok)throw new Tn({body:n,details:Oe(p.error)||y.statusText,headers:y.headers,status:y.status,url:e});return p}catch(y){throw y instanceof Tn||y instanceof Df?y:new Tn({body:n,cause:y,url:e})}}}}function Hh(e,t={}){const{batch:r,fetchOptions:n,key:i="http",methods:s,name:o="HTTP JSON-RPC",onFetchRequest:a,onFetchResponse:c,retryDelay:f,raw:u}=t;return({chain:d,retryCount:y,timeout:p})=>{const{batchSize:g=1e3,wait:b=0}=typeof r=="object"?r:{},E=t.retryCount??y,x=p??t.timeout??1e4,P=d==null?void 0:d.rpcUrls.default.http[0];if(!P)throw new Gw;const w=Kw(P,{fetchOptions:n,onRequest:a,onResponse:c,timeout:x});return Uh({key:i,methods:s,name:o,async request({method:A,params:T}){const I={method:A,params:T},{schedule:R}=_h({id:P,wait:b,shouldSplitBatch(C){return C.length>g},fn:C=>w.request({body:C}),sort:(C,U)=>C.id-U.id}),L=async C=>r?R(C):[await w.request({body:C})],[{error:S,result:$}]=await L(I);if(u)return{error:S,result:$};if(S)throw new Eu({body:I,error:S,url:P});return $},retryCount:E,retryDelay:f,timeout:x,type:"http"},{fetchOptions:n,url:P})}}function Gu(e,t){var n,i,s,o,a,c;if(!(e instanceof D))return!1;const r=e.walk(f=>f instanceof Sc);return r instanceof Sc?!!(((n=r.data)==null?void 0:n.errorName)==="ResolverNotFound"||((i=r.data)==null?void 0:i.errorName)==="ResolverWildcardNotSupported"||((s=r.data)==null?void 0:s.errorName)==="ResolverNotContract"||((o=r.data)==null?void 0:o.errorName)==="ResolverError"||((a=r.data)==null?void 0:a.errorName)==="HttpError"||(c=r.reason)!=null&&c.includes("Wildcard on non-extended resolvers is not supported")||t==="reverse"&&r.reason===Rp[50]):!1}function Yw(e){const{abi:t,data:r}=e,n=Zr(r,0,4),i=t.find(s=>s.type==="function"&&n===Qi(Tt(s)));if(!i)throw new $m(n,{docsPath:"/docs/contract/decodeFunctionData"});return{functionName:i.name,args:"inputs"in i&&i.inputs&&i.inputs.length>0?ts(i.inputs,Zr(r,4)):void 0}}const Zo="/docs/contract/encodeErrorResult";function sd(e){const{abi:t,errorName:r,args:n}=e;let i=t[0];if(r){const c=on({abi:t,args:n,name:r});if(!c)throw new Pf(r,{docsPath:Zo});i=c}if(i.type!=="error")throw new Pf(void 0,{docsPath:Zo});const s=Tt(i),o=Qi(s);let a="0x";if(n&&n.length>0){if(!i.inputs)throw new Nm(i.name,{docsPath:Zo});a=pr(i.inputs,n)}return Ct([o,a])}const Xo="/docs/contract/encodeFunctionResult";function Zw(e){const{abi:t,functionName:r,result:n}=e;let i=t[0];if(r){const o=on({abi:t,name:r});if(!o)throw new Rn(r,{docsPath:Xo});i=o}if(i.type!=="function")throw new Rn(void 0,{docsPath:Xo});if(!i.outputs)throw new pp(i.name,{docsPath:Xo});const s=(()=>{if(i.outputs.length===0)return[];if(i.outputs.length===1)return[n];if(Array.isArray(n))return n;throw new hp(n)})();return pr(i.outputs,s)}const vo="x-batch-gateway:true";async function Lh(e){const{data:t,ccipRequest:r}=e,{args:[n]}=Yw({abi:Uc,data:t}),i=[],s=[];return await Promise.all(n.map(async(o,a)=>{try{s[a]=o.urls.includes(vo)?await Lh({data:o.data,ccipRequest:r}):await r(o),i[a]=!1}catch(c){i[a]=!0,s[a]=Xw(c)}})),Zw({abi:Uc,functionName:"query",result:[i,s]})}function Xw(e){return e.name==="HttpRequestError"&&e.status?sd({abi:Uc,errorName:"HttpError",args:[e.status,e.shortMessage]}):sd({abi:[Np],errorName:"Error",args:["shortMessage"in e?e.shortMessage:e.message]})}function Mh(e){if(e.length!==66||e.indexOf("[")!==0||e.indexOf("]")!==65)return null;const t=`0x${e.slice(1,65)}`;return It(t)?t:null}function $s(e){let t=new Uint8Array(32).fill(0);if(!e)return Ce(t);const r=e.split(".");for(let n=r.length-1;n>=0;n-=1){const i=Mh(r[n]),s=i?Yn(i):je(qr(r[n]),"bytes");t=je(ct([t,s]),"bytes")}return Ce(t)}function Jw(e){return`[${e.slice(2)}]`}function Qw(e){const t=new Uint8Array(32).fill(0);return e?Mh(e)||je(qr(e)):Ce(t)}function Eo(e){const t=e.replace(/^\.|\.$/gm,"");if(t.length===0)return new Uint8Array(1);const r=new Uint8Array(qr(t).byteLength+2);let n=0;const i=t.split(".");for(let s=0;s<i.length;s++){let o=qr(i[s]);o.byteLength>255&&(o=qr(Jw(Qw(i[s])))),r[n]=o.length,r.set(o,n+1),n+=o.length+1}return r.byteLength!==n+1?r.slice(0,n+1):r}async function e1(e,t){const{blockNumber:r,blockTag:n,coinType:i,name:s,gatewayUrls:o,strict:a}=t,{chain:c}=e,f=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Jn({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),u=c==null?void 0:c.ensTlds;if(u&&!u.some(d=>s.endsWith(d)))return null;try{const d=xt({abi:ed,functionName:"addr",...i!=null?{args:[$s(s),BigInt(i)]}:{args:[$s(s)]}}),y={address:f,abi:vh,functionName:"resolve",args:[ze(Eo(s)),d,o??[vo]],blockNumber:r,blockTag:n},g=await ee(e,Wt,"readContract")(y);if(g[0]==="0x")return null;const b=cn({abi:ed,args:i!=null?[$s(s),BigInt(i)]:void 0,functionName:"addr",data:g[0]});return b==="0x"||wt(b)==="0x00"?null:b}catch(d){if(a)throw d;if(Gu(d,"resolve"))return null;throw d}}class t1 extends D{constructor({data:t}){super("Unable to extract image from metadata. The metadata may be malformed or invalid.",{metaMessages:["- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.","",`Provided data: ${JSON.stringify(t)}`],name:"EnsAvatarInvalidMetadataError"})}}class ii extends D{constructor({reason:t}){super(`ENS NFT avatar URI is invalid. ${t}`,{name:"EnsAvatarInvalidNftUriError"})}}class Vu extends D{constructor({uri:t}){super(`Unable to resolve ENS avatar URI "${t}". The URI may be malformed, invalid, or does not respond with a valid image.`,{name:"EnsAvatarUriResolutionError"})}}class r1 extends D{constructor({namespace:t}){super(`ENS NFT avatar namespace "${t}" is not supported. Must be "erc721" or "erc1155".`,{name:"EnsAvatarUnsupportedNamespaceError"})}}const n1=/(?<protocol>https?:\/\/[^\/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/,i1=/^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/,s1=/^data:([a-zA-Z\-/+]*);base64,([^"].*)/,o1=/^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;async function a1(e){try{const t=await fetch(e,{method:"HEAD"});if(t.status===200){const r=t.headers.get("content-type");return r==null?void 0:r.startsWith("image/")}return!1}catch(t){return typeof t=="object"&&typeof t.response<"u"||!globalThis.hasOwnProperty("Image")?!1:new Promise(r=>{const n=new Image;n.onload=()=>{r(!0)},n.onerror=()=>{r(!1)},n.src=e})}}function od(e,t){return e?e.endsWith("/")?e.slice(0,-1):e:t}function Dh({uri:e,gatewayUrls:t}){const r=s1.test(e);if(r)return{uri:e,isOnChain:!0,isEncoded:r};const n=od(t==null?void 0:t.ipfs,"https://ipfs.io"),i=od(t==null?void 0:t.arweave,"https://arweave.net"),s=e.match(n1),{protocol:o,subpath:a,target:c,subtarget:f=""}=(s==null?void 0:s.groups)||{},u=o==="ipns:/"||a==="ipns/",d=o==="ipfs:/"||a==="ipfs/"||i1.test(e);if(e.startsWith("http")&&!u&&!d){let p=e;return t!=null&&t.arweave&&(p=e.replace(/https:\/\/arweave.net/g,t==null?void 0:t.arweave)),{uri:p,isOnChain:!1,isEncoded:!1}}if((u||d)&&c)return{uri:`${n}/${u?"ipns":"ipfs"}/${c}${f}`,isOnChain:!1,isEncoded:!1};if(o==="ar:/"&&c)return{uri:`${i}/${c}${f||""}`,isOnChain:!1,isEncoded:!1};let y=e.replace(o1,"");if(y.startsWith("<svg")&&(y=`data:image/svg+xml;base64,${btoa(y)}`),y.startsWith("data:")||y.startsWith("{"))return{uri:y,isOnChain:!0,isEncoded:!1};throw new Vu({uri:e})}function jh(e){if(typeof e!="object"||!("image"in e)&&!("image_url"in e)&&!("image_data"in e))throw new t1({data:e});return e.image||e.image_url||e.image_data}async function c1({gatewayUrls:e,uri:t}){try{const r=await fetch(t).then(i=>i.json());return await Wu({gatewayUrls:e,uri:jh(r)})}catch{throw new Vu({uri:t})}}async function Wu({gatewayUrls:e,uri:t}){const{uri:r,isOnChain:n}=Dh({uri:t,gatewayUrls:e});if(n||await a1(r))return r;throw new Vu({uri:t})}function u1(e){let t=e;t.startsWith("did:nft:")&&(t=t.replace("did:nft:","").replace(/_/g,"/"));const[r,n,i]=t.split("/"),[s,o]=r.split(":"),[a,c]=n.split(":");if(!s||s.toLowerCase()!=="eip155")throw new ii({reason:"Only EIP-155 supported"});if(!o)throw new ii({reason:"Chain ID not found"});if(!c)throw new ii({reason:"Contract address not found"});if(!i)throw new ii({reason:"Token ID not found"});if(!a)throw new ii({reason:"ERC namespace not found"});return{chainID:Number.parseInt(o),namespace:a.toLowerCase(),contractAddress:c,tokenID:i}}async function f1(e,{nft:t}){if(t.namespace==="erc721")return Wt(e,{address:t.contractAddress,abi:[{name:"tokenURI",type:"function",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"tokenURI",args:[BigInt(t.tokenID)]});if(t.namespace==="erc1155")return Wt(e,{address:t.contractAddress,abi:[{name:"uri",type:"function",stateMutability:"view",inputs:[{name:"_id",type:"uint256"}],outputs:[{name:"",type:"string"}]}],functionName:"uri",args:[BigInt(t.tokenID)]});throw new r1({namespace:t.namespace})}async function d1(e,{gatewayUrls:t,record:r}){return/eip155:/i.test(r)?l1(e,{gatewayUrls:t,record:r}):Wu({uri:r,gatewayUrls:t})}async function l1(e,{gatewayUrls:t,record:r}){const n=u1(r),i=await f1(e,{nft:n}),{uri:s,isOnChain:o,isEncoded:a}=Dh({uri:i,gatewayUrls:t});if(o&&(s.includes("data:application/json;base64,")||s.startsWith("{"))){const f=a?atob(s.replace("data:application/json;base64,","")):s,u=JSON.parse(f);return Wu({uri:jh(u),gatewayUrls:t})}let c=n.tokenID;return n.namespace==="erc1155"&&(c=c.replace("0x","").padStart(64,"0")),c1({gatewayUrls:t,uri:s.replace(/(?:0x)?{id}/,c)})}async function zh(e,t){const{blockNumber:r,blockTag:n,key:i,name:s,gatewayUrls:o,strict:a}=t,{chain:c}=e,f=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!c)throw new Error("client chain not configured. universalResolverAddress is required.");return Jn({blockNumber:r,chain:c,contract:"ensUniversalResolver"})})(),u=c==null?void 0:c.ensTlds;if(u&&!u.some(d=>s.endsWith(d)))return null;try{const d={address:f,abi:vh,functionName:"resolve",args:[ze(Eo(s)),xt({abi:Qf,functionName:"text",args:[$s(s),i]}),o??[vo]],blockNumber:r,blockTag:n},p=await ee(e,Wt,"readContract")(d);if(p[0]==="0x")return null;const g=cn({abi:Qf,functionName:"text",data:p[0]});return g===""?null:g}catch(d){if(a)throw d;if(Gu(d,"resolve"))return null;throw d}}async function p1(e,{blockNumber:t,blockTag:r,assetGatewayUrls:n,name:i,gatewayUrls:s,strict:o,universalResolverAddress:a}){const c=await ee(e,zh,"getEnsText")({blockNumber:t,blockTag:r,key:"avatar",name:i,universalResolverAddress:a,gatewayUrls:s,strict:o});if(!c)return null;try{return await d1(e,{record:c,gatewayUrls:n})}catch{return null}}async function h1(e,{address:t,blockNumber:r,blockTag:n,gatewayUrls:i,strict:s,universalResolverAddress:o}){let a=o;if(!a){if(!e.chain)throw new Error("client chain not configured. universalResolverAddress is required.");a=Jn({blockNumber:r,chain:e.chain,contract:"ensUniversalResolver"})}const c=`${t.toLowerCase().substring(2)}.addr.reverse`;try{const f={address:a,abi:Ew,functionName:"reverse",args:[ze(Eo(c))],blockNumber:r,blockTag:n},u=ee(e,Wt,"readContract"),[d,y]=i?await u({...f,args:[...f.args,i]}):await u(f);return t.toLowerCase()!==y.toLowerCase()?null:d}catch(f){if(s)throw f;if(Gu(f,"reverse"))return null;throw f}}async function y1(e,t){const{blockNumber:r,blockTag:n,name:i}=t,{chain:s}=e,o=(()=>{if(t.universalResolverAddress)return t.universalResolverAddress;if(!s)throw new Error("client chain not configured. universalResolverAddress is required.");return Jn({blockNumber:r,chain:s,contract:"ensUniversalResolver"})})(),a=s==null?void 0:s.ensTlds;if(a&&!a.some(f=>i.endsWith(f)))throw new Error(`${i} is not a valid ENS TLD (${a==null?void 0:a.join(", ")}) for chain "${s.name}" (id: ${s.id}).`);const[c]=await ee(e,Wt,"readContract")({address:o,abi:[{inputs:[{type:"bytes"}],name:"findResolver",outputs:[{type:"address"},{type:"bytes32"}],stateMutability:"view",type:"function"}],functionName:"findResolver",args:[ze(Eo(i))],blockNumber:r,blockTag:n});return c}async function qh(e,t){var E,x,P;const{account:r=e.account,blockNumber:n,blockTag:i="latest",blobs:s,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:f,maxFeePerGas:u,maxPriorityFeePerGas:d,to:y,value:p,...g}=t,b=r?ke(r):void 0;try{an(t);const A=(typeof n=="bigint"?K(n):void 0)||i,T=(P=(x=(E=e.chain)==null?void 0:E.formatters)==null?void 0:x.transactionRequest)==null?void 0:P.format,R=(T||Zn)({...co(g,{format:T}),from:b==null?void 0:b.address,blobs:s,data:o,gas:a,gasPrice:c,maxFeePerBlobGas:f,maxFeePerGas:u,maxPriorityFeePerGas:d,to:y,value:p}),L=await e.request({method:"eth_createAccessList",params:[R,A]});return{accessList:L.accessList,gasUsed:BigInt(L.gasUsed)}}catch(w){throw Ah(w,{...t,account:b,chain:e.chain})}}async function m1(e){const t=io(e,{method:"eth_newBlockFilter"}),r=await e.request({method:"eth_newBlockFilter"});return{id:r,request:t(r),type:"block"}}async function Gh(e,{address:t,args:r,event:n,events:i,fromBlock:s,strict:o,toBlock:a}={}){const c=i??(n?[n]:void 0),f=io(e,{method:"eth_newFilter"});let u=[];c&&(u=[c.flatMap(p=>es({abi:[p],eventName:p.name,args:r}))],n&&(u=u[0]));const d=await e.request({method:"eth_newFilter",params:[{address:t,fromBlock:typeof s=="bigint"?K(s):s,toBlock:typeof a=="bigint"?K(a):a,...u.length?{topics:u}:{}}]});return{abi:c,args:r,eventName:n?n.name:void 0,fromBlock:s,id:d,request:f(d),strict:!!o,toBlock:a,type:"event"}}async function Vh(e){const t=io(e,{method:"eth_newPendingTransactionFilter"}),r=await e.request({method:"eth_newPendingTransactionFilter"});return{id:r,request:t(r),type:"transaction"}}async function g1(e){const t=await e.request({method:"eth_blobBaseFee"});return BigInt(t)}async function b1(e,{blockHash:t,blockNumber:r,blockTag:n="latest"}={}){const i=r!==void 0?K(r):void 0;let s;return t?s=await e.request({method:"eth_getBlockTransactionCountByHash",params:[t]},{dedupe:!0}):s=await e.request({method:"eth_getBlockTransactionCountByNumber",params:[i||n]},{dedupe:!!i}),vt(s)}async function ad(e,{address:t,blockNumber:r,blockTag:n="latest"}){const i=r!==void 0?K(r):void 0,s=await e.request({method:"eth_getCode",params:[t,i||n]},{dedupe:!!i});if(s!=="0x")return s}class w1 extends D{constructor({address:t}){super(`No EIP-712 domain found on contract "${t}".`,{metaMessages:["Ensure that:",`- The contract is deployed at the address "${t}".`,"- `eip712Domain()` function exists on the contract.","- `eip712Domain()` function matches signature to ERC-5267 specification."],name:"Eip712DomainNotFoundError"})}}async function v1(e,t){const{address:r,factory:n,factoryData:i}=t;try{const[s,o,a,c,f,u,d]=await ee(e,Wt,"readContract")({abi:E1,address:r,functionName:"eip712Domain",factory:n,factoryData:i});return{domain:{name:o,version:a,chainId:Number(c),verifyingContract:f,salt:u},extensions:d,fields:s}}catch(s){const o=s;throw o.name==="ContractFunctionExecutionError"&&o.cause.name==="ContractFunctionZeroDataError"?new w1({address:r}):o}}const E1=[{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"}];function x1(e){var t;return{baseFeePerGas:e.baseFeePerGas.map(r=>BigInt(r)),gasUsedRatio:e.gasUsedRatio,oldestBlock:BigInt(e.oldestBlock),reward:(t=e.reward)==null?void 0:t.map(r=>r.map(n=>BigInt(n)))}}async function A1(e,{blockCount:t,blockNumber:r,blockTag:n="latest",rewardPercentiles:i}){const s=typeof r=="bigint"?K(r):void 0,o=await e.request({method:"eth_feeHistory",params:[K(t),s||n,i]},{dedupe:!!s});return x1(o)}async function _1(e,{filter:t}){const r=t.strict??!1,i=(await t.request({method:"eth_getFilterLogs",params:[t.id]})).map(s=>cr(s));return t.abi?Nu({abi:t.abi,logs:i,strict:r}):i}function At(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}class S1 extends D{constructor({domain:t}){super(`Invalid domain "${Oe(t)}".`,{metaMessages:["Must be a valid EIP-712 domain."]})}}class P1 extends D{constructor({primaryType:t,types:r}){super(`Invalid primary type \`${t}\` must be one of \`${JSON.stringify(Object.keys(r))}\`.`,{docsPath:"/api/glossary/Errors#typeddatainvalidprimarytypeerror",metaMessages:["Check that the primary type is a key in `types`."]})}}class T1 extends D{constructor({type:t}){super(`Struct type "${t}" is invalid.`,{metaMessages:["Struct type must not be a Solidity type."],name:"InvalidStructTypeError"})}}function I1(e){const{domain:t={},message:r,primaryType:n}=e,i={EIP712Domain:Jh({domain:t}),...e.types};Xh({domain:t,message:r,primaryType:n,types:i});const s=["0x1901"];return t&&s.push(k1({domain:t,types:i})),n!=="EIP712Domain"&&s.push(Wh({data:r,primaryType:n,types:i})),je(ct(s))}function k1({domain:e,types:t}){return Wh({data:e,primaryType:"EIP712Domain",types:t})}function Wh({data:e,primaryType:t,types:r}){const n=Kh({data:e,primaryType:t,types:r});return je(n)}function Kh({data:e,primaryType:t,types:r}){const n=[{type:"bytes32"}],i=[B1({primaryType:t,types:r})];for(const s of r[t]){const[o,a]=Zh({types:r,name:s.name,type:s.type,value:e[s.name]});n.push(o),i.push(a)}return pr(n,i)}function B1({primaryType:e,types:t}){const r=ze(O1({primaryType:e,types:t}));return je(r)}function O1({primaryType:e,types:t}){let r="";const n=Yh({primaryType:e,types:t});n.delete(e);const i=[e,...Array.from(n).sort()];for(const s of i)r+=`${s}(${t[s].map(({name:o,type:a})=>`${a} ${o}`).join(",")})`;return r}function Yh({primaryType:e,types:t},r=new Set){const n=e.match(/^\w*/u),i=n==null?void 0:n[0];if(r.has(i)||t[i]===void 0)return r;r.add(i);for(const s of t[i])Yh({primaryType:s.type,types:t},r);return r}function Zh({types:e,name:t,type:r,value:n}){if(e[r]!==void 0)return[{type:"bytes32"},je(Kh({data:n,primaryType:r,types:e}))];if(r==="bytes")return n=`0x${(n.length%2?"0":"")+n.slice(2)}`,[{type:"bytes32"},je(n)];if(r==="string")return[{type:"bytes32"},je(ze(n))];if(r.lastIndexOf("]")===r.length-1){const i=r.slice(0,r.lastIndexOf("[")),s=n.map(o=>Zh({name:t,type:i,types:e,value:o}));return[{type:"bytes32"},je(pr(s.map(([o])=>o),s.map(([,o])=>o)))]}return[{type:r},n]}function C1(e){const{domain:t,message:r,primaryType:n,types:i}=e,s=(c,f)=>{const u={...f};for(const d of c){const{name:y,type:p}=d;p==="address"&&(u[y]=u[y].toLowerCase())}return u},o=i.EIP712Domain?t?s(i.EIP712Domain,t):{}:{},a=(()=>{if(n!=="EIP712Domain")return s(i[n],r)})();return Oe({domain:o,message:a,primaryType:n,types:i})}function Xh(e){const{domain:t,message:r,primaryType:n,types:i}=e,s=(o,a)=>{for(const c of o){const{name:f,type:u}=c,d=a[f],y=u.match(Op);if(y&&(typeof d=="number"||typeof d=="bigint")){const[b,E,x]=y;K(d,{signed:E==="int",size:Number.parseInt(x)/8})}if(u==="address"&&typeof d=="string"&&!Fe(d))throw new tt({address:d});const p=u.match(Ig);if(p){const[b,E]=p;if(E&&Se(d)!==Number.parseInt(E))throw new Hm({expectedSize:Number.parseInt(E),givenSize:Se(d)})}const g=i[u];g&&(R1(u),s(g,d))}};if(i.EIP712Domain&&t){if(typeof t!="object")throw new S1({domain:t});s(i.EIP712Domain,t)}if(n!=="EIP712Domain")if(i[n])s(i[n],r);else throw new P1({primaryType:n,types:i})}function Jh({domain:e}){return[typeof(e==null?void 0:e.name)=="string"&&{name:"name",type:"string"},(e==null?void 0:e.version)&&{name:"version",type:"string"},(typeof(e==null?void 0:e.chainId)=="number"||typeof(e==null?void 0:e.chainId)=="bigint")&&{name:"chainId",type:"uint256"},(e==null?void 0:e.verifyingContract)&&{name:"verifyingContract",type:"address"},(e==null?void 0:e.salt)&&{name:"salt",type:"bytes32"}].filter(Boolean)}function R1(e){if(e==="address"||e==="bool"||e==="string"||e.startsWith("bytes")||e.startsWith("uint")||e.startsWith("int"))throw new T1({type:e})}function N1(e){const{authorizationList:t}=e;if(t)for(const r of t){const{chainId:n}=r,i=r.address;if(!Fe(i))throw new tt({address:i});if(n<0)throw new yo({chainId:n})}Ku(e)}function F1(e){const{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new nh;for(const r of t){const n=Se(r),i=vt(Zr(r,0,1));if(n!==32)throw new zb({hash:r,size:n});if(i!==rh)throw new qb({hash:r,version:i})}}Ku(e)}function Ku(e){const{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:i}=e;if(t<=0)throw new yo({chainId:t});if(i&&!Fe(i))throw new tt({address:i});if(n&&n>uo)throw new en({maxFeePerGas:n});if(r&&n&&r>n)throw new Gi({maxFeePerGas:n,maxPriorityFeePerGas:r})}function $1(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:s}=e;if(t<=0)throw new yo({chainId:t});if(s&&!Fe(s))throw new tt({address:s});if(r||i)throw new D("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>uo)throw new en({maxFeePerGas:n})}function U1(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:s}=e;if(s&&!Fe(s))throw new tt({address:s});if(typeof t<"u"&&t<=0)throw new yo({chainId:t});if(r||i)throw new D("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>uo)throw new en({maxFeePerGas:n})}function xo(e){if(!e||e.length===0)return[];const t=[];for(let r=0;r<e.length;r++){const{address:n,storageKeys:i}=e[r];for(let s=0;s<i.length;s++)if(i[s].length-2!==64)throw new sb({storageKey:i[s]});if(!Fe(n,{strict:!1}))throw new tt({address:n});t.push([n,i])}return t}function H1(e,t){const r=sh(e);return r==="eip1559"?D1(e,t):r==="eip2930"?j1(e,t):r==="eip4844"?M1(e,t):r==="eip7702"?L1(e,t):z1(e,t)}function L1(e,t){const{authorizationList:r,chainId:n,gas:i,nonce:s,to:o,value:a,maxFeePerGas:c,maxPriorityFeePerGas:f,accessList:u,data:d}=e;N1(e);const y=xo(u),p=q1(r);return Ct(["0x04",Cr([K(n),s?K(s):"0x",f?K(f):"0x",c?K(c):"0x",i?K(i):"0x",o??"0x",a?K(a):"0x",d??"0x",y,p,...as(e,t)])])}function M1(e,t){const{chainId:r,gas:n,nonce:i,to:s,value:o,maxFeePerBlobGas:a,maxFeePerGas:c,maxPriorityFeePerGas:f,accessList:u,data:d}=e;F1(e);let y=e.blobVersionedHashes,p=e.sidecars;if(e.blobs&&(typeof y>"u"||typeof p>"u")){const w=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(I=>Ce(I)),A=e.kzg,T=Iu({blobs:w,kzg:A});if(typeof y>"u"&&(y=Qp({commitments:T})),typeof p>"u"){const I=ku({blobs:w,commitments:T,kzg:A});p=ih({blobs:w,commitments:T,proofs:I})}}const g=xo(u),b=[K(r),i?K(i):"0x",f?K(f):"0x",c?K(c):"0x",n?K(n):"0x",s??"0x",o?K(o):"0x",d??"0x",g,a?K(a):"0x",y??[],...as(e,t)],E=[],x=[],P=[];if(p)for(let w=0;w<p.length;w++){const{blob:A,commitment:T,proof:I}=p[w];E.push(A),x.push(T),P.push(I)}return Ct(["0x03",Cr(p?[b,E,x,P]:b)])}function D1(e,t){const{chainId:r,gas:n,nonce:i,to:s,value:o,maxFeePerGas:a,maxPriorityFeePerGas:c,accessList:f,data:u}=e;Ku(e);const d=xo(f),y=[K(r),i?K(i):"0x",c?K(c):"0x",a?K(a):"0x",n?K(n):"0x",s??"0x",o?K(o):"0x",u??"0x",d,...as(e,t)];return Ct(["0x02",Cr(y)])}function j1(e,t){const{chainId:r,gas:n,data:i,nonce:s,to:o,value:a,accessList:c,gasPrice:f}=e;$1(e);const u=xo(c),d=[K(r),s?K(s):"0x",f?K(f):"0x",n?K(n):"0x",o??"0x",a?K(a):"0x",i??"0x",u,...as(e,t)];return Ct(["0x01",Cr(d)])}function z1(e,t){const{chainId:r=0,gas:n,data:i,nonce:s,to:o,value:a,gasPrice:c}=e;U1(e);let f=[s?K(s):"0x",c?K(c):"0x",n?K(n):"0x",o??"0x",a?K(a):"0x",i??"0x"];if(t){const u=(()=>{if(t.v>=35n)return(t.v-35n)/2n>0?t.v:27n+(t.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);const p=27n+(t.v===27n?0n:1n);if(t.v!==p)throw new nb({v:t.v});return p})(),d=wt(t.r),y=wt(t.s);f=[...f,K(u),d==="0x00"?"0x":d,y==="0x00"?"0x":y]}else r>0&&(f=[...f,K(r),"0x","0x"]);return Cr(f)}function as(e,t){const r=t??e,{v:n,yParity:i}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof i>"u")return[];const s=wt(r.r),o=wt(r.s);return[typeof i=="number"?i?K(1):"0x":n===0n?"0x":n===1n?K(1):n===27n?"0x":K(1),s==="0x00"?"0x":s,o==="0x00"?"0x":o]}function q1(e){if(!e||e.length===0)return[];const t=[];for(const r of e){const{chainId:n,nonce:i,...s}=r,o=r.address;t.push([n?ze(n):"0x",o,i?ze(i):"0x",...as({},s)])}return t}const G1=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Qh=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),V1=Qh.map(e=>(9*e+5)%16),e0=(()=>{const r=[[Qh],[V1]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(s=>G1[s]));return r})(),t0=e0[0],r0=e0[1],n0=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(e=>Uint8Array.from(e)),W1=t0.map((e,t)=>e.map(r=>n0[t][r])),K1=r0.map((e,t)=>e.map(r=>n0[t][r])),Y1=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Z1=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function cd(e,t,r,n){return e===0?t^r^n:e===1?t&r|~t&n:e===2?(t|~r)^n:e===3?t&n|r&~n:t^(r|~n)}const Es=new Uint32Array(16);let i0=class extends Yp{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:t,h1:r,h2:n,h3:i,h4:s}=this;return[t,r,n,i,s]}set(t,r,n,i,s){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=s|0}process(t,r){for(let p=0;p<16;p++,r+=4)Es[p]=t.getUint32(r,!0);let n=this.h0|0,i=n,s=this.h1|0,o=s,a=this.h2|0,c=a,f=this.h3|0,u=f,d=this.h4|0,y=d;for(let p=0;p<5;p++){const g=4-p,b=Y1[p],E=Z1[p],x=t0[p],P=r0[p],w=W1[p],A=K1[p];for(let T=0;T<16;T++){const I=ys(n+cd(p,s,a,f)+Es[x[T]]+b,w[T])+d|0;n=d,d=f,f=ys(a,10)|0,a=s,s=I}for(let T=0;T<16;T++){const I=ys(i+cd(g,o,c,u)+Es[P[T]]+E,A[T])+y|0;i=y,y=u,u=ys(c,10)|0,c=o,o=I}}this.set(this.h1+a+u|0,this.h2+f+y|0,this.h3+d+i|0,this.h4+n+o|0,this.h0+s+c|0)}roundClean(){Or(Es)}destroy(){this.destroyed=!0,Or(this.buffer),this.set(0,0,0,0,0)}};const X1=to(()=>new i0),J1=i0,Q1=X1,e2=Object.freeze(Object.defineProperty({__proto__:null,RIPEMD160:J1,ripemd160:Q1},Symbol.toStringTag,{value:"Module"})),t2=`Ethereum Signed Message:
|
|
43
43
|
`;function r2(e){const t=typeof e=="string"?Nn(e):typeof e.raw=="string"?e.raw:Ce(e.raw),r=Nn(`${t2}${Se(t)}`);return ct([r,t])}function s0(e,t){return je(r2(e),t)}const o0="0x6492649264926492649264926492649264926492649264926492649264926492";function n2(e){return Vs(e,-32)===o0}function i2(e){const{address:t,data:r,signature:n,to:i="hex"}=e,s=Ct([pr([{type:"address"},{type:"bytes"},{type:"bytes"}],[t,r,n]),o0]);return i==="hex"?s:kt(s)}function s2(e){return e.map(t=>({...t,value:BigInt(t.value)}))}function o2(e){return{...e,balance:e.balance?BigInt(e.balance):void 0,nonce:e.nonce?vt(e.nonce):void 0,storageProof:e.storageProof?s2(e.storageProof):void 0}}async function a2(e,{address:t,blockNumber:r,blockTag:n,storageKeys:i}){const s=n??"latest",o=r!==void 0?K(r):void 0,a=await e.request({method:"eth_getProof",params:[t,i,o||s]});return o2(a)}async function c2(e,{address:t,blockNumber:r,blockTag:n="latest",slot:i}){const s=r!==void 0?K(r):void 0;return await e.request({method:"eth_getStorageAt",params:[t,i,s||n]})}async function Yu(e,{blockHash:t,blockNumber:r,blockTag:n,hash:i,index:s}){var u,d,y;const o=n||"latest",a=r!==void 0?K(r):void 0;let c=null;if(i?c=await e.request({method:"eth_getTransactionByHash",params:[i]},{dedupe:!0}):t?c=await e.request({method:"eth_getTransactionByBlockHashAndIndex",params:[t,K(s)]},{dedupe:!0}):c=await e.request({method:"eth_getTransactionByBlockNumberAndIndex",params:[a||o,K(s)]},{dedupe:!!a}),!c)throw new Lp({blockHash:t,blockNumber:r,blockTag:o,hash:i,index:s});return(((y=(d=(u=e.chain)==null?void 0:u.formatters)==null?void 0:d.transaction)==null?void 0:y.format)||fo)(c)}async function u2(e,{hash:t,transactionReceipt:r}){const[n,i]=await Promise.all([ee(e,os,"getBlockNumber")({}),t?ee(e,Yu,"getTransaction")({hash:t}):void 0]),s=(r==null?void 0:r.blockNumber)||(i==null?void 0:i.blockNumber);return s?n-s+1n:0n}async function jc(e,{hash:t}){var i,s,o;const r=await e.request({method:"eth_getTransactionReceipt",params:[t]},{dedupe:!0});if(!r)throw new Mp({hash:t});return(((o=(s=(i=e.chain)==null?void 0:i.formatters)==null?void 0:s.transactionReceipt)==null?void 0:o.format)||Oh)(r)}async function f2(e,t){var x;const{account:r,allowFailure:n=!0,batchSize:i,blockNumber:s,blockTag:o,multicallAddress:a,stateOverride:c}=t,f=t.contracts,u=i??(typeof((x=e.batch)==null?void 0:x.multicall)=="object"&&e.batch.multicall.batchSize||1024);let d=a;if(!d){if(!e.chain)throw new Error("client chain not configured. multicallAddress is required.");d=Jn({blockNumber:s,chain:e.chain,contract:"multicall3"})}const y=[[]];let p=0,g=0;for(let P=0;P<f.length;P++){const{abi:w,address:A,args:T,functionName:I}=f[P];try{const R=xt({abi:w,args:T,functionName:I});g+=(R.length-2)/2,u>0&&g>u&&y[p].length>0&&(p++,g=(R.length-2)/2,y[p]=[]),y[p]=[...y[p],{allowFailure:!0,callData:R,target:A}]}catch(R){const L=Qr(R,{abi:w,address:A,args:T,docsPath:"/docs/contract/multicall",functionName:I,sender:r});if(!n)throw L;y[p]=[...y[p],{allowFailure:!0,callData:"0x",target:A}]}}const b=await Promise.allSettled(y.map(P=>ee(e,Wt,"readContract")({abi:$c,account:r,address:d,args:[P],blockNumber:s,blockTag:o,functionName:"aggregate3",stateOverride:c}))),E=[];for(let P=0;P<b.length;P++){const w=b[P];if(w.status==="rejected"){if(!n)throw w.reason;for(let T=0;T<y[P].length;T++)E.push({status:"failure",error:w.reason,result:void 0});continue}const A=w.value;for(let T=0;T<A.length;T++){const{returnData:I,success:R}=A[T],{callData:L}=y[P][T],{abi:S,address:$,functionName:C,args:U}=f[E.length];try{if(L==="0x")throw new Xi;if(!R)throw new oo({data:I});const j=cn({abi:S,args:U,data:I,functionName:C});E.push(n?{result:j,status:"success"}:j)}catch(j){const V=Qr(j,{abi:S,address:$,args:U,docsPath:"/docs/contract/multicall",functionName:C});if(!n)throw V;E.push({error:V,result:void 0,status:"failure"})}}}if(E.length!==f.length)throw new D("multicall results mismatch");return E}async function zc(e,t){const{blockNumber:r,blockTag:n="latest",blocks:i,returnFullTransactions:s,traceTransfers:o,validation:a}=t;try{const c=[];for(const y of i){const p=y.blockOverrides?bh(y.blockOverrides):void 0,g=y.calls.map(E=>{const x=E,P=x.account?ke(x.account):void 0,w=x.abi?xt(x):x.data,A={...x,data:x.dataSuffix?ct([w||"0x",x.dataSuffix]):w,from:x.from??(P==null?void 0:P.address)};return an(A),Zn(A)}),b=y.stateOverrides?Au(y.stateOverrides):void 0;c.push({blockOverrides:p,calls:g,stateOverrides:b})}const u=(typeof r=="bigint"?K(r):void 0)||n;return(await e.request({method:"eth_simulateV1",params:[{blockStateCalls:c,returnFullTransactions:s,traceTransfers:o,validation:a},u]})).map((y,p)=>({...Su(y),calls:y.calls.map((g,b)=>{var $,C;const{abi:E,args:x,functionName:P,to:w}=i[p].calls[b],A=(($=g.error)==null?void 0:$.data)??g.returnData,T=BigInt(g.gasUsed),I=(C=g.logs)==null?void 0:C.map(U=>cr(U)),R=g.status==="0x1"?"success":"failure",L=E&&R==="success"&&A!=="0x"?cn({abi:E,data:A,functionName:P}):null,S=(()=>{var j;if(R==="success")return;let U;if(((j=g.error)==null?void 0:j.data)==="0x"?U=new Xi:g.error&&(U=new oo(g.error)),!!U)return Qr(U,{abi:E??[],address:w??"0x",args:x,functionName:P??"<unknown>"})})();return{data:A,gasUsed:T,logs:I,status:R,...R==="success"?{result:L}:{error:S}}})}))}catch(c){const f=c,u=ao(f,{});throw u instanceof ns?f:u}}function a0(e,t={}){const{as:r=typeof e=="string"?"Hex":"Bytes"}=t,n=Sp(aw(e));return r==="Bytes"?n:yh(n)}class d2 extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){const r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const l2={checksum:new d2(8192)},Jo=l2.checksum,p2=/^0x[a-fA-F0-9]{40}$/;function Ao(e,t={}){const{strict:r=!0}=t;if(!p2.test(e))throw new ud({address:e,cause:new y2});if(r){if(e.toLowerCase()===e)return;if(h2(e)!==e)throw new ud({address:e,cause:new m2})}}function h2(e){if(Jo.has(e))return Jo.get(e);Ao(e,{strict:!1});const t=e.substring(2).toLowerCase(),r=a0(fw(t),{as:"Bytes"}),n=t.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&n[s]&&(n[s]=n[s].toUpperCase()),(r[s>>1]&15)>=8&&n[s+1]&&(n[s+1]=n[s+1].toUpperCase());const i=`0x${n.join("")}`;return Jo.set(e,i),i}function qc(e,t={}){const{strict:r=!0}=t??{};try{return Ao(e,{strict:r}),!0}catch{return!1}}class ud extends xe{constructor({address:t,cause:r}){super(`Address "${t}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class y2 extends xe{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class m2 extends xe{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}function Gc(e){let t=!0,r="",n=0,i="",s=!1;for(let o=0;o<e.length;o++){const a=e[o];if(["(",")",","].includes(a)&&(t=!0),a==="("&&n++,a===")"&&n--,!!t){if(n===0){if(a===" "&&["event","function","error",""].includes(i))i="";else if(i+=a,a===")"){s=!0;break}continue}if(a===" "){e[o-1]!==","&&r!==","&&r!==",("&&(r="",t=!1);continue}i+=a,r+=a}}if(!s)throw new xe("Unable to normalize signature.");return i}function Vc(e,t){const r=typeof e,n=t.type;switch(n){case"address":return qc(e,{strict:!1});case"bool":return r==="boolean";case"function":return r==="string";case"string":return r==="string";default:return n==="tuple"&&"components"in t?Object.values(t.components).every((i,s)=>Vc(Object.values(e)[s],i)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(n)?r==="number"||r==="bigint":/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(n)?r==="string"||e instanceof Uint8Array:/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(n)?Array.isArray(e)&&e.every(i=>Vc(i,{...t,type:n.replace(/(\[[0-9]{0,}\])$/,"")})):!1}}function c0(e,t,r){for(const n in e){const i=e[n],s=t[n];if(i.type==="tuple"&&s.type==="tuple"&&"components"in i&&"components"in s)return c0(i.components,s.components,r[n]);const o=[i.type,s.type];if(o.includes("address")&&o.includes("bytes20")?!0:o.includes("address")&&o.includes("string")?qc(r[n],{strict:!1}):o.includes("address")&&o.includes("bytes")?qc(r[n],{strict:!1}):!1)return o}}function u0(e,t={}){const{prepare:r=!0}=t,n=Array.isArray(e)||typeof e=="string"?_f(e):e;return{...n,...r?{hash:Sn(n)}:{}}}function g2(e,t,r){const{args:n=[],prepare:i=!0}=r??{},s=gw(t,{strict:!1}),o=e.filter(f=>s?f.type==="function"||f.type==="error"?f0(f)===ju(t,0,4):f.type==="event"?Sn(f)===t:!1:"name"in f&&f.name===t);if(o.length===0)throw new Wc({name:t});if(o.length===1)return{...o[0],...i?{hash:Sn(o[0])}:{}};let a;for(const f of o){if(!("inputs"in f))continue;if(!n||n.length===0){if(!f.inputs||f.inputs.length===0)return{...f,...i?{hash:Sn(f)}:{}};continue}if(!f.inputs||f.inputs.length===0||f.inputs.length!==n.length)continue;if(n.every((d,y)=>{const p="inputs"in f&&f.inputs[y];return p?Vc(d,p):!1})){if(a&&"inputs"in a&&a.inputs){const d=c0(f.inputs,a.inputs,n);if(d)throw new w2({abiItem:f,type:d[0]},{abiItem:a,type:d[1]})}a=f}}const c=(()=>{if(a)return a;const[f,...u]=o;return{...f,overloads:u}})();if(!c)throw new Wc({name:t});return{...c,...i?{hash:Sn(c)}:{}}}function f0(e){return ju(Sn(e),0,4)}function b2(e){const t=typeof e=="string"?e:Gs(e);return Gc(t)}function Sn(e){return typeof e!="string"&&"hash"in e&&e.hash?e.hash:a0(Du(b2(e)))}class w2 extends xe{constructor(t,r){super("Found ambiguous types in overloaded ABI Items.",{metaMessages:[`\`${t.type}\` in \`${Gc(Gs(t.abiItem))}\`, and`,`\`${r.type}\` in \`${Gc(Gs(r.abiItem))}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.AmbiguityError"})}}class Wc extends xe{constructor({name:t,data:r,type:n="item"}){const i=t?` with name "${t}"`:r?` with data "${r}"`:"";super(`ABI ${n}${i} not found.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiItem.NotFoundError"})}}const v2=/^(.*)\[([0-9]*)\]$/,E2=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,d0=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;function x2({checksumAddress:e,parameters:t,values:r}){const n=[];for(let i=0;i<t.length;i++)n.push(Zu({checksumAddress:e,parameter:t[i],value:r[i]}));return n}function Zu({checksumAddress:e=!1,parameter:t,value:r}){const n=t,i=B2(n.type);if(i){const[s,o]=i;return _2(r,{checksumAddress:e,length:s,parameter:{...n,type:o}})}if(n.type==="tuple")return k2(r,{checksumAddress:e,parameter:n});if(n.type==="address")return A2(r,{checksum:e});if(n.type==="bool")return P2(r);if(n.type.startsWith("uint")||n.type.startsWith("int")){const s=n.type.startsWith("int"),[,,o="256"]=d0.exec(n.type)??[];return T2(r,{signed:s,size:Number(o)})}if(n.type.startsWith("bytes"))return S2(r,{type:n.type});if(n.type==="string")return I2(r);throw new y0(n.type)}function Xu(e){let t=0;for(let s=0;s<e.length;s++){const{dynamic:o,encoded:a}=e[s];o?t+=32:t+=Et(a)}const r=[],n=[];let i=0;for(let s=0;s<e.length;s++){const{dynamic:o,encoded:a}=e[s];o?(r.push(Je(t+i,{size:32})),n.push(a),i+=Et(a)):r.push(a)}return Vt(...r,...n)}function A2(e,t){const{checksum:r=!1}=t;return Ao(e,{strict:r}),{dynamic:!1,encoded:tn(e.toLowerCase())}}function _2(e,t){const{checksumAddress:r,length:n,parameter:i}=t,s=n===null;if(!Array.isArray(e))throw new C2(e);if(!s&&e.length!==n)throw new O2({expectedLength:n,givenLength:e.length,type:`${i.type}[${n}]`});let o=!1;const a=[];for(let c=0;c<e.length;c++){const f=Zu({checksumAddress:r,parameter:i,value:e[c]});f.dynamic&&(o=!0),a.push(f)}if(s||o){const c=Xu(a);if(s){const f=Je(a.length,{size:32});return{dynamic:!0,encoded:a.length>0?Vt(f,c):f}}if(o)return{dynamic:!0,encoded:c}}return{dynamic:!1,encoded:Vt(...a.map(({encoded:c})=>c))}}function S2(e,{type:t}){const[,r]=t.split("bytes"),n=Et(e);if(!r){let i=e;return n%32!==0&&(i=rn(i,Math.ceil((e.length-2)/2/32)*32)),{dynamic:!0,encoded:Vt(tn(Je(n,{size:32})),i)}}if(n!==Number.parseInt(r))throw new p0({expectedSize:Number.parseInt(r),value:e});return{dynamic:!1,encoded:rn(e)}}function P2(e){if(typeof e!="boolean")throw new xe(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:tn(hh(e))}}function T2(e,{signed:t,size:r}){if(typeof r=="number"){const n=2n**(BigInt(r)-(t?1n:0n))-1n,i=t?-n-1n:0n;if(e>n||e<i)throw new mh({max:n.toString(),min:i.toString(),signed:t,size:r/8,value:e.toString()})}return{dynamic:!1,encoded:Je(e,{size:32,signed:t})}}function I2(e){const t=Du(e),r=Math.ceil(Et(t)/32),n=[];for(let i=0;i<r;i++)n.push(rn(ju(t,i*32,(i+1)*32)));return{dynamic:!0,encoded:Vt(rn(Je(Et(t),{size:32})),...n)}}function k2(e,t){const{checksumAddress:r,parameter:n}=t;let i=!1;const s=[];for(let o=0;o<n.components.length;o++){const a=n.components[o],c=Array.isArray(e)?o:a.name,f=Zu({checksumAddress:r,parameter:a,value:e[c]});s.push(f),f.dynamic&&(i=!0)}return{dynamic:i,encoded:i?Xu(s):Vt(...s.map(({encoded:o})=>o))}}function B2(e){const t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}function l0(e,t,r){const{checksumAddress:n=!1}={};if(e.length!==t.length)throw new h0({expectedLength:e.length,givenLength:t.length});const i=x2({checksumAddress:n,parameters:e,values:t}),s=Xu(i);return s.length===0?"0x":s}function Kc(e,t){if(e.length!==t.length)throw new h0({expectedLength:e.length,givenLength:t.length});const r=[];for(let n=0;n<e.length;n++){const i=e[n],s=t[n];r.push(Kc.encode(i,s))}return Vt(...r)}(function(e){function t(r,n,i=!1){if(r==="address"){const c=n;return Ao(c),tn(c.toLowerCase(),i?32:0)}if(r==="string")return Du(n);if(r==="bytes")return n;if(r==="bool")return tn(hh(n),i?32:1);const s=r.match(d0);if(s){const[c,f,u="256"]=s,d=Number.parseInt(u)/8;return Je(n,{size:i?32:d,signed:f==="int"})}const o=r.match(E2);if(o){const[c,f]=o;if(Number.parseInt(f)!==(n.length-2)/2)throw new p0({expectedSize:Number.parseInt(f),value:n});return rn(n,i?32:0)}const a=r.match(v2);if(a&&Array.isArray(n)){const[c,f]=a,u=[];for(let d=0;d<n.length;d++)u.push(t(f,n[d],!0));return u.length===0?"0x":Vt(...u)}throw new y0(r)}e.encode=t})(Kc||(Kc={}));class O2 extends xe{constructor({expectedLength:t,givenLength:r,type:n}){super(`Array length mismatch for type \`${n}\`. Expected: \`${t}\`. Given: \`${r}\`.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.ArrayLengthMismatchError"})}}class p0 extends xe{constructor({expectedSize:t,value:r}){super(`Size of bytes "${r}" (bytes${Et(r)}) does not match expected size (bytes${t}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class h0 extends xe{constructor({expectedLength:t,givenLength:r}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${t}`,`Given length (values): ${r}`].join(`
|
|
44
44
|
`)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class C2 extends xe{constructor(t){super(`Value \`${t}\` is not a valid array.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidArrayError"})}}class y0 extends xe{constructor(t){super(`Type \`${t}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}function R2(e,t){var i;const{bytecode:r,args:n}=t;return Vt(r,(i=e.inputs)!=null&&i.length&&(n!=null&&n.length)?l0(e.inputs,n):"0x")}function N2(e){return u0(e)}function F2(e,...t){const{overloads:r}=e,n=r?$2([e,...r],e.name,{args:t[0]}):e,i=U2(n),s=t.length>0?l0(n.inputs,t[0]):void 0;return s?Vt(i,s):i}function yn(e,t={}){return u0(e,t)}function $2(e,t,r){const n=g2(e,t,r);if(n.type!=="function")throw new Wc({name:t,type:"function"});return n}function U2(e){return f0(e)}const H2="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",$t="0x0000000000000000000000000000000000000000",L2="0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";async function M2(e,t){const{blockNumber:r,blockTag:n,calls:i,stateOverrides:s,traceAssetChanges:o,traceTransfers:a,validation:c}=t,f=t.account?ke(t.account):void 0;if(o&&!f)throw new D("`account` is required when `traceAssetChanges` is true");const u=f?R2(N2("constructor(bytes, bytes)"),{bytecode:Eh,args:[L2,F2(yn("function getBalance(address)"),[f.address])]}):void 0,d=o?await Promise.all(t.calls.map(async M=>{if(!M.data&&!M.abi)return;const{accessList:B}=await qh(e,{account:f.address,...M,data:M.abi?xt(M):M.data});return B.map(({address:q,storageKeys:W})=>W.length>0?q:null)})).then(M=>M.flat().filter(Boolean)):[],y=await zc(e,{blockNumber:r,blockTag:n,blocks:[...o?[{calls:[{data:u}],stateOverrides:s},{calls:d.map((M,B)=>({abi:[yn("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[f.address],to:M,from:$t,nonce:B})),stateOverrides:[{address:$t,nonce:0}]}]:[],{calls:[...i,{}].map(M=>({...M,from:f==null?void 0:f.address})),stateOverrides:s},...o?[{calls:[{data:u}]},{calls:d.map((M,B)=>({abi:[yn("function balanceOf(address) returns (uint256)")],functionName:"balanceOf",args:[f.address],to:M,from:$t,nonce:B})),stateOverrides:[{address:$t,nonce:0}]},{calls:d.map((M,B)=>({to:M,abi:[yn("function decimals() returns (uint256)")],functionName:"decimals",from:$t,nonce:B})),stateOverrides:[{address:$t,nonce:0}]},{calls:d.map((M,B)=>({to:M,abi:[yn("function tokenURI(uint256) returns (string)")],functionName:"tokenURI",args:[0n],from:$t,nonce:B})),stateOverrides:[{address:$t,nonce:0}]},{calls:d.map((M,B)=>({to:M,abi:[yn("function symbol() returns (string)")],functionName:"symbol",from:$t,nonce:B})),stateOverrides:[{address:$t,nonce:0}]}]:[]],traceTransfers:a,validation:c}),p=o?y[2]:y[0],[g,b,,E,x,P,w,A]=o?y:[],{calls:T,...I}=p,R=T.slice(0,-1)??[],L=(g==null?void 0:g.calls)??[],S=(b==null?void 0:b.calls)??[],$=[...L,...S].map(M=>M.status==="success"?Ue(M.data):null),C=(E==null?void 0:E.calls)??[],U=(x==null?void 0:x.calls)??[],j=[...C,...U].map(M=>M.status==="success"?Ue(M.data):null),V=((P==null?void 0:P.calls)??[]).map(M=>M.status==="success"?M.result:null),Y=((A==null?void 0:A.calls)??[]).map(M=>M.status==="success"?M.result:null),X=((w==null?void 0:w.calls)??[]).map(M=>M.status==="success"?M.result:null),J=[];for(const[M,B]of j.entries()){const q=$[M];if(typeof B!="bigint"||typeof q!="bigint")continue;const W=V[M-1],k=Y[M-1],N=X[M-1],H=M===0?{address:H2,decimals:18,symbol:"ETH"}:{address:d[M-1],decimals:N||W?Number(W??1):void 0,symbol:k??void 0};J.some(Z=>Z.token.address===H.address)||J.push({token:H,value:{pre:q,post:B,diff:B-q}})}return{assetChanges:J,block:I,results:R}}class m0 extends pu{constructor(t,r){super(),this.finished=!1,this.destroyed=!1,sg(t);const n=eo(r);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(n.length>i?t.create().update(n).digest():n);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=t.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Or(s)}update(t){return Fn(this),this.iHash.update(t),this}digestInto(t){Fn(this),Bt(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){const t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:n,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return t=t,t.finished=i,t.destroyed=s,t.blockLen=o,t.outputLen=a,t.oHash=r._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const g0=(e,t,r)=>new m0(e,t).update(r).digest();g0.create=(e,t)=>new m0(e,t);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const nt=BigInt(0),et=BigInt(1),Dr=BigInt(2),D2=BigInt(3),b0=BigInt(4),w0=BigInt(5),v0=BigInt(8);function gt(e,t){const r=e%t;return r>=nt?r:t+r}function pt(e,t,r){let n=e;for(;t-- >nt;)n*=n,n%=r;return n}function fd(e,t){if(e===nt)throw new Error("invert: expected non-zero number");if(t<=nt)throw new Error("invert: expected positive modulus, got "+t);let r=gt(e,t),n=t,i=nt,s=et;for(;r!==nt;){const a=n/r,c=n%r,f=i-s*a;n=r,r=c,i=s,s=f}if(n!==et)throw new Error("invert: does not exist");return gt(i,t)}function E0(e,t){const r=(e.ORDER+et)/b0,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function j2(e,t){const r=(e.ORDER-w0)/v0,n=e.mul(t,Dr),i=e.pow(n,r),s=e.mul(t,i),o=e.mul(e.mul(s,Dr),i),a=e.mul(s,e.sub(o,e.ONE));if(!e.eql(e.sqr(a),t))throw new Error("Cannot find square root");return a}function z2(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");let t=e-et,r=0;for(;t%Dr===nt;)t/=Dr,r++;let n=Dr;const i=_o(e);for(;dd(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return E0;let s=i.pow(n,t);const o=(t+et)/Dr;return function(c,f){if(c.is0(f))return f;if(dd(c,f)!==1)throw new Error("Cannot find square root");let u=r,d=c.mul(c.ONE,s),y=c.pow(f,t),p=c.pow(f,o);for(;!c.eql(y,c.ONE);){if(c.is0(y))return c.ZERO;let g=1,b=c.sqr(y);for(;!c.eql(b,c.ONE);)if(g++,b=c.sqr(b),g===u)throw new Error("Cannot find square root");const E=et<<BigInt(u-g-1),x=c.pow(d,E);u=g,d=c.sqr(x),y=c.mul(y,d),p=c.mul(p,x)}return p}}function q2(e){return e%b0===D2?E0:e%v0===w0?j2:z2(e)}const G2=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function V2(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=G2.reduce((n,i)=>(n[i]="function",n),t);return Lu(e,r),e}function W2(e,t,r){if(r<nt)throw new Error("invalid exponent, negatives unsupported");if(r===nt)return e.ONE;if(r===et)return t;let n=e.ONE,i=t;for(;r>nt;)r&et&&(n=e.mul(n,i)),i=e.sqr(i),r>>=et;return n}function x0(e,t,r=!1){const n=new Array(t.length).fill(r?e.ZERO:void 0),i=t.reduce((o,a,c)=>e.is0(a)?o:(n[c]=o,e.mul(o,a)),e.ONE),s=e.inv(i);return t.reduceRight((o,a,c)=>e.is0(a)?o:(n[c]=e.mul(o,n[c]),e.mul(o,a)),s),n}function dd(e,t){const r=(e.ORDER-et)/Dr,n=e.pow(t,r),i=e.eql(n,e.ONE),s=e.eql(n,e.ZERO),o=e.eql(n,e.neg(e.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function K2(e,t){t!==void 0&&_i(t);const r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function _o(e,t,r=!1,n={}){if(e<=nt)throw new Error("invalid field: expected ORDER > 0, got "+e);let i,s;if(typeof t=="object"&&t!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const u=t;u.BITS&&(i=u.BITS),u.sqrt&&(s=u.sqrt),typeof u.isLE=="boolean"&&(r=u.isLE)}else typeof t=="number"&&(i=t),n.sqrt&&(s=n.sqrt);const{nBitLength:o,nByteLength:a}=K2(e,i);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c;const f=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:a,MASK:ho(o),ZERO:nt,ONE:et,create:u=>gt(u,e),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return nt<=u&&u<e},is0:u=>u===nt,isValidNot0:u=>!f.is0(u)&&f.isValid(u),isOdd:u=>(u&et)===et,neg:u=>gt(-u,e),eql:(u,d)=>u===d,sqr:u=>gt(u*u,e),add:(u,d)=>gt(u+d,e),sub:(u,d)=>gt(u-d,e),mul:(u,d)=>gt(u*d,e),pow:(u,d)=>W2(f,u,d),div:(u,d)=>gt(u*fd(d,e),e),sqrN:u=>u*u,addN:(u,d)=>u+d,subN:(u,d)=>u-d,mulN:(u,d)=>u*d,inv:u=>fd(u,e),sqrt:s||(u=>(c||(c=q2(e)),c(f,u))),toBytes:u=>r?dh(u,a):Hu(u,a),fromBytes:u=>{if(u.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);return r?fh(u):po(u)},invertBatch:u=>x0(f,u),cmov:(u,d,y)=>y?d:u});return Object.freeze(f)}function A0(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function _0(e){const t=A0(e);return t+Math.ceil(t/2)}function Y2(e,t,r=!1){const n=e.length,i=A0(t),s=_0(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const o=r?fh(e):po(e),a=gt(o,t-et)+et;return r?dh(a,i):Hu(a,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ln=BigInt(0),jr=BigInt(1);function yi(e,t){const r=t.negate();return e?r:t}function Z2(e,t,r){const n=o=>o.pz,i=x0(e.Fp,r.map(n));return r.map((o,a)=>o.toAffine(i[a])).map(e.fromAffine)}function S0(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Qo(e,t){S0(e,t);const r=Math.ceil(t/e)+1,n=2**(e-1),i=2**e,s=ho(e),o=BigInt(e);return{windows:r,windowSize:n,mask:s,maxNumber:i,shiftBy:o}}function ld(e,t,r){const{windowSize:n,mask:i,maxNumber:s,shiftBy:o}=r;let a=Number(e&i),c=e>>o;a>n&&(a-=s,c+=jr);const f=t*n,u=f+Math.abs(a)-1,d=a===0,y=a<0,p=t%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:y,isNegF:p,offsetF:f}}function X2(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function J2(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}const ea=new WeakMap,P0=new WeakMap;function ta(e){return P0.get(e)||1}function pd(e){if(e!==Ln)throw new Error("invalid wNAF")}function Q2(e,t){return{constTimeNegate:yi,hasPrecomputes(r){return ta(r)!==1},unsafeLadder(r,n,i=e.ZERO){let s=r;for(;n>Ln;)n&jr&&(i=i.add(s)),s=s.double(),n>>=jr;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=Qo(n,t),o=[];let a=r,c=a;for(let f=0;f<i;f++){c=a,o.push(c);for(let u=1;u<s;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,n,i){let s=e.ZERO,o=e.BASE;const a=Qo(r,t);for(let c=0;c<a.windows;c++){const{nextN:f,offset:u,isZero:d,isNeg:y,isNegF:p,offsetF:g}=ld(i,c,a);i=f,d?o=o.add(yi(p,n[g])):s=s.add(yi(y,n[u]))}return pd(i),{p:s,f:o}},wNAFUnsafe(r,n,i,s=e.ZERO){const o=Qo(r,t);for(let a=0;a<o.windows&&i!==Ln;a++){const{nextN:c,offset:f,isZero:u,isNeg:d}=ld(i,a,o);if(i=c,!u){const y=n[f];s=s.add(d?y.negate():y)}}return pd(i),s},getPrecomputes(r,n,i){let s=ea.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&(typeof i=="function"&&(s=i(s)),ea.set(n,s))),s},wNAFCached(r,n,i){const s=ta(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=ta(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){S0(n,t),P0.set(r,n),ea.delete(r)}}}function ev(e,t,r,n){let i=t,s=e.ZERO,o=e.ZERO;for(;r>Ln||n>Ln;)r&jr&&(s=s.add(i)),n&jr&&(o=o.add(i)),i=i.double(),r>>=jr,n>>=jr;return{p1:s,p2:o}}function tv(e,t,r,n){X2(r,e),J2(n,t);const i=r.length,s=n.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,a=Zb(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const f=ho(c),u=new Array(Number(f)+1).fill(o),d=Math.floor((t.BITS-1)/c)*c;let y=o;for(let p=d;p>=0;p-=c){u.fill(o);for(let b=0;b<s;b++){const E=n[b],x=Number(E>>BigInt(p)&f);u[x]=u[x].add(r[b])}let g=o;for(let b=u.length-1,E=o;b>0;b--)E=E.add(u[b]),g=g.add(E);if(y=y.add(g),p!==0)for(let b=0;b<c;b++)y=y.double()}return y}function hd(e,t){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return V2(t),t}else return _o(e)}function rv(e,t,r={}){if(!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(const a of["p","n","h"]){const c=t[a];if(!(typeof c=="bigint"&&c>Ln))throw new Error(`CURVE.${a} must be positive bigint`)}const n=hd(t.p,r.Fp),i=hd(t.n,r.Fn),o=["Gx","Gy","a","b"];for(const a of o)if(!n.isValid(t[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return{Fp:n,Fn:i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function yd(e){e.lowS!==void 0&&Ws("lowS",e.lowS),e.prehash!==void 0&&Ws("prehash",e.prehash)}class nv extends Error{constructor(t=""){super(t)}}const nr={Err:nv,_tlv:{encode:(e,t)=>{const{Err:r}=nr;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length&1)throw new r("tlv.encode: unpadded data");const n=t.length/2,i=ms(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?ms(i.length/2|128):"";return ms(e)+s+i+t},decode(e,t){const{Err:r}=nr;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const i=t[n++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const f=t.subarray(n,n+c);if(f.length!==c)throw new r("tlv.decode: length bytes not complete");if(f[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of f)o=o<<8|u;if(n+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=t.subarray(n,n+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+o)}}},_int:{encode(e){const{Err:t}=nr;if(e<mi)throw new t("integer: negative integers are not allowed");let r=ms(e);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=nr;if(e[0]&128)throw new t("invalid signature integer: negative");if(e[0]===0&&!(e[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return po(e)}},toSig(e){const{Err:t,_int:r,_tlv:n}=nr,i=yt("signature",e),{v:s,l:o}=n.decode(48,i);if(o.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,s),{v:f,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(f)}},hexFromSig(e){const{_tlv:t,_int:r}=nr,n=t.encode(2,r.encode(e.r)),i=t.encode(2,r.encode(e.s)),s=n+i;return t.encode(48,s)}},mi=BigInt(0),gi=BigInt(1),iv=BigInt(2),xs=BigInt(3),sv=BigInt(4);function ov(e,t,r){function n(i){const s=e.sqr(i),o=e.mul(s,i);return e.add(e.add(o,e.mul(i,t)),r)}return n}function T0(e,t,r){const{BYTES:n}=e;function i(s){let o;if(typeof s=="bigint")o=s;else{let a=yt("private key",s);if(t){if(!t.includes(a.length*2))throw new Error("invalid private key");const c=new Uint8Array(n);c.set(a,c.length-a.length),a=c}try{o=e.fromBytes(a)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof s}`)}}if(r&&(o=e.create(o)),!e.isValidNot0(o))throw new Error("invalid private key: out of range [1..N-1]");return o}return i}function av(e,t={}){const{Fp:r,Fn:n}=rv("weierstrass",e,t),{h:i,n:s}=e;Lu(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:o}=t;if(o&&(!r.is0(e.a)||typeof o.beta!="bigint"||typeof o.splitScalar!="function"))throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');function a(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function c(L,S,$){const{x:C,y:U}=S.toAffine(),j=r.toBytes(C);if(Ws("isCompressed",$),$){a();const V=!r.isOdd(U);return Lr(I0(V),j)}else return Lr(Uint8Array.of(4),j,r.toBytes(U))}function f(L){Bt(L);const S=r.BYTES,$=S+1,C=2*S+1,U=L.length,j=L[0],V=L.subarray(1);if(U===$&&(j===2||j===3)){const Y=r.fromBytes(V);if(!r.isValid(Y))throw new Error("bad point: is not on curve, wrong x");const X=y(Y);let J;try{J=r.sqrt(X)}catch(q){const W=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+W)}a();const M=r.isOdd(J);return(j&1)===1!==M&&(J=r.neg(J)),{x:Y,y:J}}else if(U===C&&j===4){const Y=r.fromBytes(V.subarray(S*0,S*1)),X=r.fromBytes(V.subarray(S*1,S*2));if(!p(Y,X))throw new Error("bad point: is not on curve");return{x:Y,y:X}}else throw new Error(`bad point: got length ${U}, expected compressed=${$} or uncompressed=${C}`)}const u=t.toBytes||c,d=t.fromBytes||f,y=ov(r,e.a,e.b);function p(L,S){const $=r.sqr(S),C=y(L);return r.eql($,C)}if(!p(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const g=r.mul(r.pow(e.a,xs),sv),b=r.mul(r.sqr(e.b),BigInt(27));if(r.is0(r.add(g,b)))throw new Error("bad curve params: a or b");function E(L,S,$=!1){if(!r.isValid(S)||$&&r.is0(S))throw new Error(`bad point coordinate ${L}`);return S}function x(L){if(!(L instanceof T))throw new Error("ProjectivePoint expected")}const P=Kf((L,S)=>{const{px:$,py:C,pz:U}=L;if(r.eql(U,r.ONE))return{x:$,y:C};const j=L.is0();S==null&&(S=j?r.ONE:r.inv(U));const V=r.mul($,S),Y=r.mul(C,S),X=r.mul(U,S);if(j)return{x:r.ZERO,y:r.ZERO};if(!r.eql(X,r.ONE))throw new Error("invZ was invalid");return{x:V,y:Y}}),w=Kf(L=>{if(L.is0()){if(t.allowInfinityPoint&&!r.is0(L.py))return;throw new Error("bad point: ZERO")}const{x:S,y:$}=L.toAffine();if(!r.isValid(S)||!r.isValid($))throw new Error("bad point: x or y not field elements");if(!p(S,$))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function A(L,S,$,C,U){return $=new T(r.mul($.px,L),$.py,$.pz),S=yi(C,S),$=yi(U,$),S.add($)}class T{constructor(S,$,C){this.px=E("x",S),this.py=E("y",$,!0),this.pz=E("z",C),Object.freeze(this)}static fromAffine(S){const{x:$,y:C}=S||{};if(!S||!r.isValid($)||!r.isValid(C))throw new Error("invalid affine point");if(S instanceof T)throw new Error("projective point not allowed");return r.is0($)&&r.is0(C)?T.ZERO:new T($,C,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(S){return Z2(T,"pz",S)}static fromBytes(S){return Bt(S),T.fromHex(S)}static fromHex(S){const $=T.fromAffine(d(yt("pointHex",S)));return $.assertValidity(),$}static fromPrivateKey(S){const $=T0(n,t.allowedPrivateKeyLengths,t.wrapPrivateKey);return T.BASE.multiply($(S))}static msm(S,$){return tv(T,n,S,$)}precompute(S=8,$=!0){return R.setWindowSize(this,S),$||this.multiply(xs),this}_setWindowSize(S){this.precompute(S)}assertValidity(){w(this)}hasEvenY(){const{y:S}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(S)}equals(S){x(S);const{px:$,py:C,pz:U}=this,{px:j,py:V,pz:Y}=S,X=r.eql(r.mul($,Y),r.mul(j,U)),J=r.eql(r.mul(C,Y),r.mul(V,U));return X&&J}negate(){return new T(this.px,r.neg(this.py),this.pz)}double(){const{a:S,b:$}=e,C=r.mul($,xs),{px:U,py:j,pz:V}=this;let Y=r.ZERO,X=r.ZERO,J=r.ZERO,M=r.mul(U,U),B=r.mul(j,j),q=r.mul(V,V),W=r.mul(U,j);return W=r.add(W,W),J=r.mul(U,V),J=r.add(J,J),Y=r.mul(S,J),X=r.mul(C,q),X=r.add(Y,X),Y=r.sub(B,X),X=r.add(B,X),X=r.mul(Y,X),Y=r.mul(W,Y),J=r.mul(C,J),q=r.mul(S,q),W=r.sub(M,q),W=r.mul(S,W),W=r.add(W,J),J=r.add(M,M),M=r.add(J,M),M=r.add(M,q),M=r.mul(M,W),X=r.add(X,M),q=r.mul(j,V),q=r.add(q,q),M=r.mul(q,W),Y=r.sub(Y,M),J=r.mul(q,B),J=r.add(J,J),J=r.add(J,J),new T(Y,X,J)}add(S){x(S);const{px:$,py:C,pz:U}=this,{px:j,py:V,pz:Y}=S;let X=r.ZERO,J=r.ZERO,M=r.ZERO;const B=e.a,q=r.mul(e.b,xs);let W=r.mul($,j),k=r.mul(C,V),N=r.mul(U,Y),H=r.add($,C),Z=r.add(j,V);H=r.mul(H,Z),Z=r.add(W,k),H=r.sub(H,Z),Z=r.add($,U);let Q=r.add(j,Y);return Z=r.mul(Z,Q),Q=r.add(W,N),Z=r.sub(Z,Q),Q=r.add(C,U),X=r.add(V,Y),Q=r.mul(Q,X),X=r.add(k,N),Q=r.sub(Q,X),M=r.mul(B,Z),X=r.mul(q,N),M=r.add(X,M),X=r.sub(k,M),M=r.add(k,M),J=r.mul(X,M),k=r.add(W,W),k=r.add(k,W),N=r.mul(B,N),Z=r.mul(q,Z),k=r.add(k,N),N=r.sub(W,N),N=r.mul(B,N),Z=r.add(Z,N),W=r.mul(k,Z),J=r.add(J,W),W=r.mul(Q,Z),X=r.mul(H,X),X=r.sub(X,W),W=r.mul(H,k),M=r.mul(Q,M),M=r.add(M,W),new T(X,J,M)}subtract(S){return this.add(S.negate())}is0(){return this.equals(T.ZERO)}multiply(S){const{endo:$}=t;if(!n.isValidNot0(S))throw new Error("invalid scalar: out of range");let C,U;const j=V=>R.wNAFCached(this,V,T.normalizeZ);if($){const{k1neg:V,k1:Y,k2neg:X,k2:J}=$.splitScalar(S),{p:M,f:B}=j(Y),{p:q,f:W}=j(J);U=B.add(W),C=A($.beta,M,q,V,X)}else{const{p:V,f:Y}=j(S);C=V,U=Y}return T.normalizeZ([C,U])[0]}multiplyUnsafe(S){const{endo:$}=t,C=this;if(!n.isValid(S))throw new Error("invalid scalar: out of range");if(S===mi||C.is0())return T.ZERO;if(S===gi)return C;if(R.hasPrecomputes(this))return this.multiply(S);if($){const{k1neg:U,k1:j,k2neg:V,k2:Y}=$.splitScalar(S),{p1:X,p2:J}=ev(T,C,j,Y);return A($.beta,X,J,U,V)}else return R.wNAFCachedUnsafe(C,S)}multiplyAndAddUnsafe(S,$,C){const U=this.multiplyUnsafe($).add(S.multiplyUnsafe(C));return U.is0()?void 0:U}toAffine(S){return P(this,S)}isTorsionFree(){const{isTorsionFree:S}=t;return i===gi?!0:S?S(T,this):R.wNAFCachedUnsafe(this,s).is0()}clearCofactor(){const{clearCofactor:S}=t;return i===gi?this:S?S(T,this):this.multiplyUnsafe(i)}toBytes(S=!0){return Ws("isCompressed",S),this.assertValidity(),u(T,this,S)}toRawBytes(S=!0){return this.toBytes(S)}toHex(S=!0){return Si(this.toBytes(S))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}T.BASE=new T(e.Gx,e.Gy,r.ONE),T.ZERO=new T(r.ZERO,r.ONE,r.ZERO),T.Fp=r,T.Fn=n;const I=n.BITS,R=Q2(T,t.endo?Math.ceil(I/2):I);return T}function I0(e){return Uint8Array.of(e?2:3)}function cv(e,t,r={}){Lu(t,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=t.randomBytes||lg,i=t.hmac||((C,...U)=>g0(t.hash,C,Lr(...U))),{Fp:s,Fn:o}=e,{ORDER:a,BITS:c}=o;function f(C){const U=a>>gi;return C>U}function u(C){return f(C)?o.neg(C):C}function d(C,U){if(!o.isValidNot0(U))throw new Error(`invalid signature ${C}: out of range 1..CURVE.n`)}class y{constructor(U,j,V){d("r",U),d("s",j),this.r=U,this.s=j,V!=null&&(this.recovery=V),Object.freeze(this)}static fromCompact(U){const j=o.BYTES,V=yt("compactSignature",U,j*2);return new y(o.fromBytes(V.subarray(0,j)),o.fromBytes(V.subarray(j,j*2)))}static fromDER(U){const{r:j,s:V}=nr.toSig(yt("DER",U));return new y(j,V)}assertValidity(){}addRecoveryBit(U){return new y(this.r,this.s,U)}recoverPublicKey(U){const j=s.ORDER,{r:V,s:Y,recovery:X}=this;if(X==null||![0,1,2,3].includes(X))throw new Error("recovery id invalid");if(a*iv<j&&X>1)throw new Error("recovery id is ambiguous for h>1 curve");const M=X===2||X===3?V+a:V;if(!s.isValid(M))throw new Error("recovery id 2 or 3 invalid");const B=s.toBytes(M),q=e.fromHex(Lr(I0((X&1)===0),B)),W=o.inv(M),k=w(yt("msgHash",U)),N=o.create(-k*W),H=o.create(Y*W),Z=e.BASE.multiplyUnsafe(N).add(q.multiplyUnsafe(H));if(Z.is0())throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return f(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,o.neg(this.s),this.recovery):this}toBytes(U){if(U==="compact")return Lr(o.toBytes(this.r),o.toBytes(this.s));if(U==="der")return lu(nr.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Si(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Si(this.toBytes("compact"))}}const p=T0(o,r.allowedPrivateKeyLengths,r.wrapPrivateKey),g={isValidPrivateKey(C){try{return p(C),!0}catch{return!1}},normPrivateKeyToScalar:p,randomPrivateKey:()=>{const C=a;return Y2(n(_0(C)),C)},precompute(C=8,U=e.BASE){return U.precompute(C,!1)}};function b(C,U=!0){return e.fromPrivateKey(C).toBytes(U)}function E(C){if(typeof C=="bigint")return!1;if(C instanceof e)return!0;const j=yt("key",C).length,V=s.BYTES,Y=V+1,X=2*V+1;if(!(r.allowedPrivateKeyLengths||o.BYTES===Y))return j===Y||j===X}function x(C,U,j=!0){if(E(C)===!0)throw new Error("first arg must be private key");if(E(U)===!1)throw new Error("second arg must be public key");return e.fromHex(U).multiply(p(C)).toBytes(j)}const P=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");const U=po(C),j=C.length*8-c;return j>0?U>>BigInt(j):U},w=t.bits2int_modN||function(C){return o.create(P(C))},A=ho(c);function T(C){return Yb("num < 2^"+c,C,mi,A),o.toBytes(C)}function I(C,U,j=R){if(["recovered","canonical"].some(H=>H in j))throw new Error("sign() legacy options not supported");const{hash:V}=t;let{lowS:Y,prehash:X,extraEntropy:J}=j;Y==null&&(Y=!0),C=yt("msgHash",C),yd(j),X&&(C=yt("prehashed msgHash",V(C)));const M=w(C),B=p(U),q=[T(B),T(M)];if(J!=null&&J!==!1){const H=J===!0?n(s.BYTES):J;q.push(yt("extraEntropy",H))}const W=Lr(...q),k=M;function N(H){const Z=P(H);if(!o.isValidNot0(Z))return;const Q=o.inv(Z),ie=e.BASE.multiply(Z).toAffine(),ne=o.create(ie.x);if(ne===mi)return;const re=o.create(Q*o.create(k+ne*B));if(re===mi)return;let te=(ie.x===ne?0:2)|Number(ie.y&gi),se=re;return Y&&f(re)&&(se=u(re),te^=1),new y(ne,se,te)}return{seed:W,k2sig:N}}const R={lowS:t.lowS,prehash:!1},L={lowS:t.lowS,prehash:!1};function S(C,U,j=R){const{seed:V,k2sig:Y}=I(C,U,j);return Xb(t.hash.outputLen,o.BYTES,i)(V,Y)}e.BASE.precompute(8);function $(C,U,j,V=L){const Y=C;U=yt("msgHash",U),j=yt("publicKey",j),yd(V);const{lowS:X,prehash:J,format:M}=V;if("strict"in V)throw new Error("options.strict was renamed to lowS");if(M!==void 0&&!["compact","der","js"].includes(M))throw new Error('format must be "compact", "der" or "js"');const B=typeof Y=="string"||du(Y),q=!B&&!M&&typeof Y=="object"&&Y!==null&&typeof Y.r=="bigint"&&typeof Y.s=="bigint";if(!B&&!q)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let W,k;try{if(q)if(M===void 0||M==="js")W=new y(Y.r,Y.s);else throw new Error("invalid format");if(B){try{M!=="compact"&&(W=y.fromDER(Y))}catch(se){if(!(se instanceof nr.Err))throw se}!W&&M!=="der"&&(W=y.fromCompact(Y))}k=e.fromHex(j)}catch{return!1}if(!W||X&&W.hasHighS())return!1;J&&(U=t.hash(U));const{r:N,s:H}=W,Z=w(U),Q=o.inv(H),ie=o.create(Z*Q),ne=o.create(N*Q),re=e.BASE.multiplyUnsafe(ie).add(k.multiplyUnsafe(ne));return re.is0()?!1:o.create(re.x)===N}return Object.freeze({getPublicKey:b,getSharedSecret:x,sign:S,verify:$,utils:g,Point:e,Signature:y})}function uv(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=_o(t.n,e.nBitLength),i={Fp:r,Fn:n,allowedPrivateKeyLengths:e.allowedPrivateKeyLengths,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,wrapPrivateKey:e.wrapPrivateKey,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:i}}function fv(e){const{CURVE:t,curveOpts:r}=uv(e),n={hash:e.hash,hmac:e.hmac,randomBytes:e.randomBytes,lowS:e.lowS,bits2int:e.bits2int,bits2int_modN:e.bits2int_modN};return{CURVE:t,curveOpts:r,ecdsaOpts:n}}function dv(e,t){return Object.assign({},t,{ProjectivePoint:t.Point,CURVE:e})}function lv(e){const{CURVE:t,curveOpts:r,ecdsaOpts:n}=fv(e),i=av(t,r),s=cv(i,n,r);return dv(e,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function pv(e,t){const r=n=>lv({...e,hash:n});return{...r(t),create:r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ks={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")};BigInt(0);const hv=BigInt(1),Yc=BigInt(2),md=(e,t)=>(e+t/Yc)/t;function yv(e){const t=Ks.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),f=e*e*e%t,u=f*f*e%t,d=pt(u,r,t)*u%t,y=pt(d,r,t)*u%t,p=pt(y,Yc,t)*f%t,g=pt(p,i,t)*p%t,b=pt(g,s,t)*g%t,E=pt(b,a,t)*b%t,x=pt(E,c,t)*E%t,P=pt(x,a,t)*b%t,w=pt(P,r,t)*u%t,A=pt(w,o,t)*g%t,T=pt(A,n,t)*f%t,I=pt(T,Yc,t);if(!Zc.eql(Zc.sqr(I),e))throw new Error("Cannot find square root");return I}const Zc=_o(Ks.p,void 0,void 0,{sqrt:yv}),k0=pv({...Ks,Fp:Zc,lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Ks.n,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-hv*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,o=BigInt("0x100000000000000000000000000000000"),a=md(s*e,t),c=md(-n*e,t);let f=gt(e-a*r-c*i,t),u=gt(-a*n-c*s,t);const d=f>o,y=u>o;if(d&&(f=t-f),y&&(u=t-u),f>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:d,k1:f,k2neg:y,k2:u}}}},Xp),mv=Object.freeze(Object.defineProperty({__proto__:null,secp256k1:k0},Symbol.toStringTag,{value:"Module"}));function gv({r:e,s:t,to:r="hex",v:n,yParity:i}){const s=(()=>{if(i===0||i===1)return i;if(n&&(n===27n||n===28n||n>=35n))return n%2n===0n?1:0;throw new Error("Invalid `v` or `yParity` value")})(),o=`0x${new k0.Signature(Ue(e),Ue(t)).toCompactHex()}${s===0?"1b":"1c"}`;return r==="hex"?o:kt(o)}async function Ju(e,t){var d,y,p;const{address:r,factory:n,factoryData:i,hash:s,signature:o,universalSignatureVerifierAddress:a=(p=(y=(d=e.chain)==null?void 0:d.contracts)==null?void 0:y.universalSignatureVerifier)==null?void 0:p.address,...c}=t,f=It(o)?o:typeof o=="object"&&"r"in o&&"s"in o?gv(o):Ce(o),u=await(async()=>!n&&!i||n2(f)?f:i2({address:n,data:i,signature:f}))();try{const g=a?{to:a,data:xt({abi:td,functionName:"isValidSig",args:[r,s,u]}),...c}:{data:mo({abi:td,args:[r,s,u],bytecode:_w}),...c},{data:b}=await ee(e,ss,"call")(g);return Wm(b??"0x0")}catch(g){try{if(is(Tp(r),await jp({hash:s,signature:o})))return!0}catch{}if(g instanceof Dp)return!1;throw g}}async function bv(e,{address:t,message:r,factory:n,factoryData:i,signature:s,...o}){const a=s0(r);return Ju(e,{address:t,factory:n,factoryData:i,hash:a,signature:s,...o})}async function wv(e,t){const{address:r,factory:n,factoryData:i,signature:s,message:o,primaryType:a,types:c,domain:f,...u}=t,d=I1({message:o,primaryType:a,types:c,domain:f});return Ju(e,{address:r,factory:n,factoryData:i,hash:d,signature:s,...u})}function B0(e,{emitOnBegin:t=!1,emitMissed:r=!1,onBlockNumber:n,onError:i,poll:s,pollingInterval:o=e.pollingInterval}){const a=typeof s<"u"?s:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc"));let c;return a?(()=>{const d=Oe(["watchBlockNumber",e.uid,t,r,o]);return ur(d,{onBlockNumber:n,onError:i},y=>Qn(async()=>{var p;try{const g=await ee(e,os,"getBlockNumber")({cacheTime:0});if(c){if(g===c)return;if(g-c>1&&r)for(let b=c+1n;b<g;b++)y.onBlockNumber(b,c),c=b}(!c||g>c)&&(y.onBlockNumber(g,c),c=g)}catch(g){(p=y.onError)==null||p.call(y,g)}},{emitOnBegin:t,interval:o}))})():(()=>{const d=Oe(["watchBlockNumber",e.uid,t,r]);return ur(d,{onBlockNumber:n,onError:i},y=>{let p=!0,g=()=>p=!1;return(async()=>{try{const b=(()=>{if(e.transport.type==="fallback"){const x=e.transport.transports.find(P=>P.config.type==="webSocket"||P.config.type==="ipc");return x?x.value:e.transport}return e.transport})(),{unsubscribe:E}=await b.subscribe({params:["newHeads"],onData(x){var w;if(!p)return;const P=Ue((w=x.result)==null?void 0:w.number);y.onBlockNumber(P,c),c=P},onError(x){var P;(P=y.onError)==null||P.call(y,x)}});g=E,p||g()}catch(b){i==null||i(b)}})(),()=>g()})})()}async function vv(e,{confirmations:t=1,hash:r,onReplaced:n,pollingInterval:i=e.pollingInterval,retryCount:s=6,retryDelay:o=({count:c})=>~~(1<<c)*200,timeout:a=18e4}){const c=Oe(["waitForTransactionReceipt",e.uid,r]);let f,u,d,y=!1,p,g;const{promise:b,resolve:E,reject:x}=zu(),P=a?setTimeout(()=>{g(),p(),x(new ab({hash:r}))},a):void 0;return p=ur(c,{onReplaced:n,resolve:E,reject:x},w=>{g=ee(e,B0,"watchBlockNumber")({emitMissed:!0,emitOnBegin:!0,poll:!0,pollingInterval:i,async onBlockNumber(A){const T=R=>{clearTimeout(P),g(),R(),p()};let I=A;if(!y)try{if(d){if(t>1&&(!d.blockNumber||I-d.blockNumber+1n<t))return;T(()=>w.resolve(d));return}if(f||(y=!0,await Dc(async()=>{f=await ee(e,Yu,"getTransaction")({hash:r}),f.blockNumber&&(I=f.blockNumber)},{delay:o,retryCount:s}),y=!1),d=await ee(e,jc,"getTransactionReceipt")({hash:r}),t>1&&(!d.blockNumber||I-d.blockNumber+1n<t))return;T(()=>w.resolve(d))}catch(R){if(R instanceof Lp||R instanceof Mp){if(!f){y=!1;return}try{u=f,y=!0;const L=await Dc(()=>ee(e,Gt,"getBlock")({blockNumber:I,includeTransactions:!0}),{delay:o,retryCount:s,shouldRetry:({error:C})=>C instanceof Vp});y=!1;const S=L.transactions.find(({from:C,nonce:U})=>C===u.from&&U===u.nonce);if(!S||(d=await ee(e,jc,"getTransactionReceipt")({hash:S.hash}),t>1&&(!d.blockNumber||I-d.blockNumber+1n<t)))return;let $="replaced";S.to===u.to&&S.value===u.value&&S.input===u.input?$="repriced":S.from===S.to&&S.value===0n&&($="cancelled"),T(()=>{var C;(C=w.onReplaced)==null||C.call(w,{reason:$,replacedTransaction:u,transaction:S,transactionReceipt:d}),w.resolve(d)})}catch(L){T(()=>w.reject(L))}}else T(()=>w.reject(R))}}})}),b}function Ev(e,{blockTag:t="latest",emitMissed:r=!1,emitOnBegin:n=!1,onBlock:i,onError:s,includeTransactions:o,poll:a,pollingInterval:c=e.pollingInterval}){const f=typeof a<"u"?a:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")),u=o??!1;let d;return f?(()=>{const g=Oe(["watchBlocks",e.uid,t,r,n,u,c]);return ur(g,{onBlock:i,onError:s},b=>Qn(async()=>{var E;try{const x=await ee(e,Gt,"getBlock")({blockTag:t,includeTransactions:u});if(x.number!==null&&(d==null?void 0:d.number)!=null){if(x.number===d.number)return;if(x.number-d.number>1&&r)for(let P=(d==null?void 0:d.number)+1n;P<x.number;P++){const w=await ee(e,Gt,"getBlock")({blockNumber:P,includeTransactions:u});b.onBlock(w,d),d=w}}((d==null?void 0:d.number)==null||t==="pending"&&(x==null?void 0:x.number)==null||x.number!==null&&x.number>d.number)&&(b.onBlock(x,d),d=x)}catch(x){(E=b.onError)==null||E.call(b,x)}},{emitOnBegin:n,interval:c}))})():(()=>{let g=!0,b=!0,E=()=>g=!1;return(async()=>{try{n&&ee(e,Gt,"getBlock")({blockTag:t,includeTransactions:u}).then(w=>{g&&b&&(i(w,void 0),b=!1)}).catch(s);const x=(()=>{if(e.transport.type==="fallback"){const w=e.transport.transports.find(A=>A.config.type==="webSocket"||A.config.type==="ipc");return w?w.value:e.transport}return e.transport})(),{unsubscribe:P}=await x.subscribe({params:["newHeads"],async onData(w){var T;if(!g)return;const A=await ee(e,Gt,"getBlock")({blockNumber:(T=w.result)==null?void 0:T.number,includeTransactions:u}).catch(()=>{});g&&(i(A,d),b=!1,d=A)},onError(w){s==null||s(w)}});E=P,g||E()}catch(x){s==null||s(x)}})(),()=>E()})()}function xv(e,{address:t,args:r,batch:n=!0,event:i,events:s,fromBlock:o,onError:a,onLogs:c,poll:f,pollingInterval:u=e.pollingInterval,strict:d}){const y=typeof f<"u"?f:typeof o=="bigint"?!0:!(e.transport.type==="webSocket"||e.transport.type==="ipc"||e.transport.type==="fallback"&&(e.transport.transports[0].config.type==="webSocket"||e.transport.transports[0].config.type==="ipc")),p=d??!1;return y?(()=>{const E=Oe(["watchEvent",t,r,n,e.uid,i,u,o]);return ur(E,{onLogs:c,onError:a},x=>{let P;o!==void 0&&(P=o-1n);let w,A=!1;const T=Qn(async()=>{var I;if(!A){try{w=await ee(e,Gh,"createEventFilter")({address:t,args:r,event:i,events:s,strict:p,fromBlock:o})}catch{}A=!0;return}try{let R;if(w)R=await ee(e,go,"getFilterChanges")({filter:w});else{const L=await ee(e,os,"getBlockNumber")({});P&&P!==L?R=await ee(e,Fu,"getLogs")({address:t,args:r,event:i,events:s,fromBlock:P+1n,toBlock:L}):R=[],P=L}if(R.length===0)return;if(n)x.onLogs(R);else for(const L of R)x.onLogs([L])}catch(R){w&&R instanceof Jr&&(A=!1),(I=x.onError)==null||I.call(x,R)}},{emitOnBegin:!0,interval:u});return async()=>{w&&await ee(e,bo,"uninstallFilter")({filter:w}),T()}})})():(()=>{let E=!0,x=()=>E=!1;return(async()=>{try{const P=(()=>{if(e.transport.type==="fallback"){const I=e.transport.transports.find(R=>R.config.type==="webSocket"||R.config.type==="ipc");return I?I.value:e.transport}return e.transport})(),w=s??(i?[i]:void 0);let A=[];w&&(A=[w.flatMap(R=>es({abi:[R],eventName:R.name,args:r}))],i&&(A=A[0]));const{unsubscribe:T}=await P.subscribe({params:["logs",{address:t,topics:A}],onData(I){var L;if(!E)return;const R=I.result;try{const{eventName:S,args:$}=Ru({abi:w??[],data:R.data,topics:R.topics,strict:p}),C=cr(R,{args:$,eventName:S});c([C])}catch(S){let $,C;if(S instanceof Ai||S instanceof Qs){if(d)return;$=S.abiItem.name,C=(L=S.abiItem.inputs)==null?void 0:L.some(j=>!("name"in j&&j.name))}const U=cr(R,{args:C?[]:{},eventName:$});c([U])}},onError(I){a==null||a(I)}});x=T,E||x()}catch(P){a==null||a(P)}})(),()=>x()})()}function Av(e,{batch:t=!0,onError:r,onTransactions:n,poll:i,pollingInterval:s=e.pollingInterval}){return(typeof i<"u"?i:e.transport.type!=="webSocket"&&e.transport.type!=="ipc")?(()=>{const f=Oe(["watchPendingTransactions",e.uid,t,s]);return ur(f,{onTransactions:n,onError:r},u=>{let d;const y=Qn(async()=>{var p;try{if(!d)try{d=await ee(e,Vh,"createPendingTransactionFilter")({});return}catch(b){throw y(),b}const g=await ee(e,go,"getFilterChanges")({filter:d});if(g.length===0)return;if(t)u.onTransactions(g);else for(const b of g)u.onTransactions([b])}catch(g){(p=u.onError)==null||p.call(u,g)}},{emitOnBegin:!0,interval:s});return async()=>{d&&await ee(e,bo,"uninstallFilter")({filter:d}),y()}})})():(()=>{let f=!0,u=()=>f=!1;return(async()=>{try{const{unsubscribe:d}=await e.transport.subscribe({params:["newPendingTransactions"],onData(y){if(!f)return;const p=y.result;n([p])},onError(y){r==null||r(y)}});u=d,f||u()}catch(d){r==null||r(d)}})(),()=>u()})()}function _v(e){var d,y,p;const{scheme:t,statement:r,...n}=((d=e.match(Sv))==null?void 0:d.groups)??{},{chainId:i,expirationTime:s,issuedAt:o,notBefore:a,requestId:c,...f}=((y=e.match(Pv))==null?void 0:y.groups)??{},u=(p=e.split("Resources:")[1])==null?void 0:p.split(`
|
|
@@ -96,4 +96,4 @@ ${tb(p)}`),super(t.shortMessage,{cause:t,docsPath:n,metaMessages:[...t.metaMessa
|
|
|
96
96
|
`))):re=k.stylize("[Circular]","special")),R(ne)){if(ie&&Q.match(/^\d+$/))return re;ne=JSON.stringify(""+Q),ne.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(ne=ne.slice(1,-1),ne=k.stylize(ne,"name")):(ne=ne.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),ne=k.stylize(ne,"string"))}return ne+": "+re}function b(k,N,H){var Z=k.reduce(function(Q,ie){return ie.indexOf(`
|
|
97
97
|
`)>=0,Q+ie.replace(/\u001b\[\d\d?m/g,"").length+1},0);return Z>60?H[0]+(N===""?"":N+`
|
|
98
98
|
`)+" "+k.join(`,
|
|
99
|
-
`)+" "+H[1]:H[0]+N+" "+k.join(", ")+" "+H[1]}e.types=RA();function E(k){return Array.isArray(k)}e.isArray=E;function x(k){return typeof k=="boolean"}e.isBoolean=x;function P(k){return k===null}e.isNull=P;function w(k){return k==null}e.isNullOrUndefined=w;function A(k){return typeof k=="number"}e.isNumber=A;function T(k){return typeof k=="string"}e.isString=T;function I(k){return typeof k=="symbol"}e.isSymbol=I;function R(k){return k===void 0}e.isUndefined=R;function L(k){return S(k)&&V(k)==="[object RegExp]"}e.isRegExp=L,e.types.isRegExp=L;function S(k){return typeof k=="object"&&k!==null}e.isObject=S;function $(k){return S(k)&&V(k)==="[object Date]"}e.isDate=$,e.types.isDate=$;function C(k){return S(k)&&(V(k)==="[object Error]"||k instanceof Error)}e.isError=C,e.types.isNativeError=C;function U(k){return typeof k=="function"}e.isFunction=U;function j(k){return k===null||typeof k=="boolean"||typeof k=="number"||typeof k=="string"||typeof k=="symbol"||typeof k>"u"}e.isPrimitive=j,e.isBuffer=NA();function V(k){return Object.prototype.toString.call(k)}function Y(k){return k<10?"0"+k.toString(10):k.toString(10)}var X=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function J(){var k=new Date,N=[Y(k.getHours()),Y(k.getMinutes()),Y(k.getSeconds())].join(":");return[k.getDate(),X[k.getMonth()],N].join(" ")}e.log=function(){console.log("%s - %s",J(),e.format.apply(e,arguments))},e.inherits=FA(),e._extend=function(k,N){if(!N||!S(N))return k;for(var H=Object.keys(N),Z=H.length;Z--;)k[H[Z]]=N[H[Z]];return k};function M(k,N){return Object.prototype.hasOwnProperty.call(k,N)}var B=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;e.promisify=function(N){if(typeof N!="function")throw new TypeError('The "original" argument must be of type Function');if(B&&N[B]){var H=N[B];if(typeof H!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(H,B,{value:H,enumerable:!1,writable:!1,configurable:!0}),H}function H(){for(var Z,Q,ie=new Promise(function(te,se){Z=te,Q=se}),ne=[],re=0;re<arguments.length;re++)ne.push(arguments[re]);ne.push(function(te,se){te?Q(te):Z(se)});try{N.apply(this,ne)}catch(te){Q(te)}return ie}return Object.setPrototypeOf(H,Object.getPrototypeOf(N)),B&&Object.defineProperty(H,B,{value:H,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(H,t(N))},e.promisify.custom=B;function q(k,N){if(!k){var H=new Error("Promise was rejected with a falsy value");H.reason=k,k=H}return N(k)}function W(k){if(typeof k!="function")throw new TypeError('The "original" argument must be of type Function');function N(){for(var H=[],Z=0;Z<arguments.length;Z++)H.push(arguments[Z]);var Q=H.pop();if(typeof Q!="function")throw new TypeError("The last argument must be of type Function");var ie=this,ne=function(){return Q.apply(ie,arguments)};k.apply(this,H).then(function(re){process.nextTick(ne.bind(null,null,re))},function(re){process.nextTick(q.bind(null,re,ne))})}return Object.setPrototypeOf(N,Object.getPrototypeOf(k)),Object.defineProperties(N,t(k)),N}e.callbackify=W}(ba)),ba}Object.defineProperty(qn,"__esModule",{value:!0});qn.encode=qn.decode=void 0;const Fy=Br;function $A(e){return(Fy.isBrowser?new TextDecoder("utf-8"):new(Ny()).TextDecoder("utf-8")).decode(e)}qn.decode=$A;function UA(e){return(Fy.isBrowser?new TextEncoder:new(Ny()).TextEncoder("utf-8")).encode(e)}qn.encode=UA;var Gn={},cu={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(e,t){var r=fn,n=r.Buffer;function i(o,a){for(var c in o)a[c]=o[c]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=s);function s(o,a,c){return n(o,a,c)}s.prototype=Object.create(n.prototype),i(n,s),s.from=function(o,a,c){if(typeof o=="number")throw new TypeError("Argument must not be a number");return n(o,a,c)},s.alloc=function(o,a,c){if(typeof o!="number")throw new TypeError("Argument must be a number");var f=n(o);return a!==void 0?typeof c=="string"?f.fill(a,c):f.fill(a):f.fill(0),f},s.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return n(o)},s.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(o)}})(cu,cu.exports);var HA=cu.exports,Rs=HA.Buffer;function LA(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<e.length;n++){var i=e.charAt(n),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=n}var o=e.length,a=e.charAt(0),c=Math.log(o)/Math.log(256),f=Math.log(256)/Math.log(o);function u(p){if((Array.isArray(p)||p instanceof Uint8Array)&&(p=Rs.from(p)),!Rs.isBuffer(p))throw new TypeError("Expected Buffer");if(p.length===0)return"";for(var g=0,b=0,E=0,x=p.length;E!==x&&p[E]===0;)E++,g++;for(var P=(x-E)*f+1>>>0,w=new Uint8Array(P);E!==x;){for(var A=p[E],T=0,I=P-1;(A!==0||T<b)&&I!==-1;I--,T++)A+=256*w[I]>>>0,w[I]=A%o>>>0,A=A/o>>>0;if(A!==0)throw new Error("Non-zero carry");b=T,E++}for(var R=P-b;R!==P&&w[R]===0;)R++;for(var L=a.repeat(g);R<P;++R)L+=e.charAt(w[R]);return L}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return Rs.alloc(0);for(var g=0,b=0,E=0;p[g]===a;)b++,g++;for(var x=(p.length-g)*c+1>>>0,P=new Uint8Array(x);g<p.length;){var w=p.charCodeAt(g);if(w>255)return;var A=t[w];if(A===255)return;for(var T=0,I=x-1;(A!==0||T<E)&&I!==-1;I--,T++)A+=o*P[I]>>>0,P[I]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");E=T,g++}for(var R=x-E;R!==x&&P[R]===0;)R++;var L=Rs.allocUnsafe(b+(x-R));L.fill(0,0,b);for(var S=b;R!==x;)L[S++]=P[R++];return L}function y(p){var g=d(p);if(g)return g;throw new Error("Non-base"+o+" character")}return{encode:u,decodeUnsafe:d,decode:y}}var MA=LA,DA=MA,jA="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",zA=DA(jA),qA=Kt&&Kt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Gn,"__esModule",{value:!0});Gn.decode=Gn.encode=void 0;const $y=qA(zA);function GA(e){return $y.default.encode(e)}Gn.encode=GA;function VA(e){return $y.default.decode(e)}Gn.decode=VA;var Vn={};Object.defineProperty(Vn,"__esModule",{value:!0});Vn.decode=Vn.encode=void 0;const WA=fn;function KA(e){return e.toString("base64")}Vn.encode=KA;function YA(e){return WA.Buffer.from(e,"base64")}Vn.decode=YA;var ZA=Kt&&Kt.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),XA=Kt&&Kt.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Uo=Kt&&Kt.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&ZA(t,e,r);return XA(t,e),t};Object.defineProperty(sr,"__esModule",{value:!0});sr.base64=sr.bs58=sr.utf8=Xs=sr.hex=void 0;var Xs=sr.hex=Uo(zn);sr.utf8=Uo(qn);sr.bs58=Uo(Gn);sr.base64=Uo(Vn);class Pr{constructor(t,r,n,i,s){try{this.swapId=[...Xs.decode(t)],this.secretHash=[...Xs.decode(n)]}catch(o){throw new Error("Error decoding swapId or secretHash",{cause:o})}if(this.secretHash.length!=32||this.swapId.length!=32)throw new Error("swapId or secretHash must be exactly 32 bits in size");try{this.redeemer=new Pt.web3.PublicKey(r)}catch(o){throw new Error("Error decoding redeemer. Ensure it is a valid base58 encoded",{cause:o})}try{this.amount=new Pt.BN(i.toString(10),10),this.expiresIn=new Pt.BN(s)}catch(o){throw new Error("Error decoding amount. Invalid value for amount",{cause:o})}if(!(Number.isInteger(s)&&s>0))throw new Error("expiresIn must be a positive integer.")}static from(t){let r;if(t.source_swap.chain.includes("solana"))r=t.source_swap;else if(t.destination_swap.chain.includes("solana"))r=t.destination_swap;else throw new Error("Expected source_swap or destination_swap to be one of 'solana', 'solana_localnet', 'solana_devnet'");const{swap_id:n,redeemer:i,secret_hash:s,timelock:o}=r,a=BigInt(r.amount);return new Pr(n,i,s,a,o)}}function Uy(e){let t;try{t=[...Xs.decode(e)]}catch(r){throw new Error("Error decoding secret. Ensure it is a hex string",{cause:r})}if(t.length!=32)throw new Error("Invalid Secret size. Expected 32 bytes, got "+t.length);return t}class Hy{constructor(t,r,n,i){if(this.provider=t,this.url=r,!t)throw new Error("Provider is required");if(!r)throw new Error("Endpoint URL is required");if(!n)throw new Error("Relayer address is required");if(!i)throw new Error("Program address is required");try{this.relayer=new Pt.web3.PublicKey(n)}catch(o){throw new Error("Error decoding relayer public key. Ensure it is base58 encoded.",{cause:o})}const s={...au,metadata:{...au.metadata??{}},address:i};try{this.program=new Pt.Program(s,this.provider)}catch(o){throw new Error("Error creating Program instance. Ensure the IDL and provider are correct.",{cause:o})}}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async sendViaRelayer(t,r){try{t.recentBlockhash=(await this.provider.connection.getLatestBlockhash()).blockhash,t.feePayer=this.relayer;const i=(await this.provider.wallet.signTransaction(t)).serialize({requireAllSignatures:!1}).toString("base64"),s={order_id:r,serialized_tx:i,perform_on:"source"},o=await _.Fetcher.post(this.url.endpoint("/spl-initiate"),{body:JSON.stringify(s),headers:{"Content-Type":"application/json"}});return o.error?_.Err(`Error from Relayer: ${o.error}`):o.result?_.Ok(o.result):_.Err("No result returned from relayer")}catch(n){return _.Err(`Failed to send transaction: ${n instanceof Error?n.message:String(n)}`)}}async initiateViaHTLC(t,r){if(!r)return _.Err("Order is required");try{const n=await this.provider.sendAndConfirm(t);return n?await bd(this.provider.connection,n)?_.Ok(n):_.Err("HTLC: Failed to Initiate swap, confirmation timed out"):_.Err("Failed to initiate HTLC transaction")}catch(n){return _.Err(`Error initiating swap: ${n instanceof Error?n.message:String(n)}`)}}async initiate(t){const{redeemer:r,secretHash:n,amount:i,expiresIn:s}=Pr.from(t),o=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(o,this.program.programId)[0];try{const a=await this.program.methods.initiate(i-100,s,r,n).accounts({initiator:this.provider.publicKey}).transaction();return de.isSolanaNativeToken(t.source_swap.chain,t.source_swap.asset)?this.initiateViaHTLC(a,t):this.sendViaRelayer(a,t.create_order.create_id)}catch(a){return _.Err("Error initiating swap: ",a)}}async redeem(t,r){const{secretHash:n}=Pr.from(t),i=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(i,this.program.programId)[0];try{const s=Uy(r),o={order_id:t.create_order.create_id,secret:Buffer.from(s).toString("hex"),perform_on:"destination"},a=await _.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify(o),headers:{"Content-Type":"application/json"}});if(a.error)return _.Err(`Redeem: Error from relayer: ${a.error}`);if(!a.result)return _.Err("Redeem: No transaction hash returned from relayer");const c=a.result;return await bd(this.provider.connection,c)?_.Ok(c):_.Err("Redeem: Timed out waiting for confirmation")}catch(s){return console.error("Redeem: Caught exception:",s),_.Err(`Error redeeming: ${s instanceof Error?s.message:String(s)}`)}}async refund(){return _.Err("Refund is automatically handled by the relayer.")}}class wf extends _.EventBroker{constructor(t){super(),this.environment=_.Environment.TESTNET,this.getOrderThreshold=20,this.refundSacpCache=new Map,this.bitcoinRedeemCache=new fx;const{api:r,environment:n}=Jc(t.environment);if(this.environment=n,this._api=r,typeof t.digestKey=="string"){const s=_.DigestKey.from(t.digestKey);if(!s.ok)throw new Error(s.error);this._digestKey=s.val}else this._digestKey=t.digestKey;this._quote=t.quote??new dy(this._api.quote),this._auth=t.auth??_.Siwe.fromDigestKey(new _.Url(this._api.auth),this._digestKey),this._orderbook=t.orderbook??new de.Orderbook(new _.Url(this._api.orderbook)),this._evmHTLC=t.htlc.evm,this._starknetHTLC=t.htlc.starknet,this._solanaHTLC=t.htlc.solana,this._secretManager=t.secretManager??Zi.fromDigestKey(this._digestKey.digestKey),this.orderExecutorCache=new ux,this._blockNumberFetcher=t.blockNumberFetcher??new fy(this._api.info,this.environment);const i=new xy(Jv(this.environment));this._btcWallet=zr.fromPrivateKey(this._digestKey.digestKey,i)}static fromWallets(t){let r;if(typeof t.digestKey=="string"){const s=_.DigestKey.from(t.digestKey);if(!s.ok)throw new Error(s.error);r=s.val}else r=t.digestKey;const{api:n}=Jc(t.environment);if(!n)throw new Error("API not found, invalid environment "+t.environment);const i={evm:t.wallets.evm?new my(n.evmRelay,t.wallets.evm,_.Siwe.fromDigestKey(new _.Url(n.auth),r)):void 0,starknet:t.wallets.starknet?new Ey(n.starknetRelay,t.wallets.starknet,t.environment===_.Environment.MAINNET?_.Network.MAINNET:_.Network.TESTNET):void 0,solana:t.wallets.solana?new Hy(t.wallets.solana,new _.Url(n.solanaRelay),t.environment===_.Environment.MAINNET?Xc.mainnet:Xc.testnet,t.solanaProgramAddress?t.solanaProgramAddress:C0.mainnet):void 0};return new wf({htlc:i,...t})}get evmHTLC(){return this._evmHTLC}get starknetHTLC(){return this._starknetHTLC}get solanaHTLC(){return this._solanaHTLC}get quote(){return this._quote}get btcWallet(){return this._btcWallet}get orderbook(){return this._orderbook}get blockNumberFetcher(){return this._blockNumberFetcher}get secretManager(){return this._secretManager}get auth(){return this._auth}get digestKey(){return this._digestKey}async swap(t){const r=await this.validateAndFillParams(t);if(!r.ok)return _.Err(r.error);const{sendAddress:n,receiveAddress:i,timelock:s}=r.val,o=Date.now().toString(),a=await this._secretManager.generateSecret(o);if(!a.ok)return _.Err(a.error);const{strategyId:c,btcAddress:f}=t.additionalData,u={strategy_id:c,...f&&{bitcoin_optional_recipient:f}},d={source_chain:t.fromAsset.chain,destination_chain:t.toAsset.chain,source_asset:t.fromAsset.atomicSwapAddress,destination_asset:t.toAsset.atomicSwapAddress,initiator_source_address:n,initiator_destination_address:i,source_amount:t.sendAmount,destination_amount:t.receiveAmount,fee:"1",nonce:o,timelock:s,secret_hash:_.trim0x(a.val.secretHash),min_destination_confirmations:t.minDestinationConfirmations??0,additional_data:u,affiliate_fees:this.withDefaultAffiliateFees(t.affiliateFee)},y=await this._quote.getAttestedQuote(d);if(!y.ok)return _.Err(y.error);const p=await this._orderbook.createOrder(y.val,this._auth);if(!p.ok)return _.Err(p.error);const g=await this.pollOrder(p.val);return g.ok?_.Ok(g.val):_.Err(g.error)}withDefaultAffiliateFees(t){return(t??[]).map(r=>({fee:r.fee,address:r.address,chain:r.chain??gd.chain,asset:r.asset??gd.asset}))}async validateAndFillParams(t){if(!t.additionalData.strategyId)return _.Err("StrategyId is required");if(!t.fromAsset||!t.toAsset)return _.Err("Source and destination assets are required for swap");if(t.fromAsset.chain===t.toAsset.chain&&t.fromAsset.atomicSwapAddress===t.toAsset.atomicSwapAddress)return _.Err("Source and destination assets cannot be the same");if(de.isMainnet(t.fromAsset.chain)&&!de.isMainnet(t.toAsset.chain)||!de.isMainnet(t.fromAsset.chain)&&de.isMainnet(t.toAsset.chain))return _.Err("Both assets should be on the same network (either mainnet or testnet)");const r=this.validateAmount(t.sendAmount);if(!r.ok)return _.Err(r.error);const n=this.validateAmount(t.receiveAmount);if(!n.ok)return _.Err(n.error);if(r<n)return _.Err("Send amount should be greater than receive amount");const i=de.getTimeLock(t.fromAsset.chain);if(!i)return _.Err("Unsupported chain for timelock");if((de.isBitcoin(t.fromAsset.chain)||de.isBitcoin(t.toAsset.chain))&&!t.additionalData.btcAddress)return _.Err("btcAddress in additionalData is required if source or destination chain is bitcoin, it is used as refund or redeem address.");const s=await this.getAddresses(t.fromAsset.chain);if(!s.ok)return _.Err(s.error);const o=await this.getAddresses(t.toAsset.chain);return o.ok?_.Ok({sendAddress:s.val,receiveAddress:o.val,timelock:t.timelock??i}):_.Err(o.error)}async getAddresses(t){var n;switch(de.getBlockchainType(t)){case de.BlockchainType.EVM:return this._evmHTLC?_.Ok(this._evmHTLC.htlcActorAddress):_.Err("Please provide evmHTLC when initializing garden");case de.BlockchainType.Bitcoin:{const i=await((n=this._btcWallet)==null?void 0:n.getPublicKey());return!i||!Zv(i)?_.Err("Invalid btc public key"):_.Ok(Ar(i))}case de.BlockchainType.Solana:return this._solanaHTLC?_.Ok(this._solanaHTLC.htlcActorAddress):_.Err("Please provide solanaHTLC when initializing garden");case de.BlockchainType.Starknet:return this._starknetHTLC?_.Ok(this._starknetHTLC.htlcActorAddress):_.Err("Please provide starknetHTLC when initializing garden");default:return _.Err("Unsupported chain")}}validateAmount(t){if(t==null||t.includes("."))return _.Err("Invalid amount ",t);const r=new Dy(t);return!r.isInteger()||r.isNaN()||r.lt(0)||r.isLessThanOrEqualTo(0)?_.Err("Invalid amount ",t):_.Ok(r)}async pollOrder(t){let r=await this._orderbook.getOrder(t,!0),n=0;for(;n<this.getOrderThreshold;){if(await _.sleep(1e3),n++,r.ok){if(r.val&&r.val.create_order.create_id.toLowerCase()===t.toLowerCase())return _.Ok(r.val)}else if(!r.error.includes("result is undefined"))return _.Err(r.error);r=await this._orderbook.getOrder(t,!0)}return _.Err(`Order not found, createOrder id: ${t}`)}async execute(t=5e3){return await this._orderbook.subscribeOrders(this._digestKey.userId,!0,t,async r=>{const n=await this.filterExpiredAndAssignStatus(r.data);if(n.ok&&(this.emit("onPendingOrdersChanged",n.val),r.data.length!==0))for(let i=0;i<n.val.length;i++){const s=n.val[i],o=ef(s.status);if(de.isBitcoin(s.source_swap.chain)&&s.status===be.InitiateDetected){const a=this._btcWallet;if(!a){this.emit("error",s,"BTC wallet not found");continue}await this.postRefundSACP(s,a)}switch(o){case ve.Redeem:{const a=await this._secretManager.generateSecret(s.create_order.nonce);if(!a.ok){this.emit("error",s,a.error);return}switch(de.getBlockchainType(s.destination_swap.chain)){case de.BlockchainType.EVM:{await this.evmRedeem(s,a.val.secret);break}case de.BlockchainType.Bitcoin:{const c=this.btcWallet;if(!c){this.emit("error",s,"BTC wallet not found");return}await this.btcRedeem(c,s,a.val.secret);break}case de.BlockchainType.Starknet:{await this.starknetRedeem(s,a.val.secret);break}case de.BlockchainType.Solana:await this.solRedeem(s,a.val.secret);break;default:this.emit("error",s,"Unsupported chain: "+s.destination_swap.chain)}break}case ve.Refund:{switch(de.getBlockchainType(s.source_swap.chain)){case de.BlockchainType.Solana:{this.emit("error",s,"Solana refund is automatically done by relay service");break}case de.BlockchainType.EVM:{this.emit("error",s,"EVM refund is automatically done by relay service");break}case de.BlockchainType.Bitcoin:{const a=this.btcWallet;if(!a){this.emit("error",s,"BTC wallet not found");return}await this.btcRefund(a,s);break}case de.BlockchainType.Starknet:{this.emit("error",s,"Starknet refund is automatically done by relay service");break}default:this.emit("error",s,"Unsupported chain: "+s.source_swap.chain)}break}}}},"pending",{per_page:500})}async solRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing sol redeem"),this.orderExecutorCache.get(t,ve.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._solanaHTLC){this.emit("error",t,"Solana HTLC is required");return}const i=await this._solanaHTLC.redeem(t,r);if(i.error){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,ve.Redeem,t.destination_swap.redeem_tx_hash);return}i.val&&(this.orderExecutorCache.set(t,ve.Redeem,i.val),this.emit("success",t,ve.Redeem,i.val))}async evmRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing evm redeem"),this.orderExecutorCache.get(t,ve.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._evmHTLC){this.emit("error",t,"EVMHTLC is required");return}const i=await this._evmHTLC.redeem(t,r);if(!i.ok){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,ve.Redeem,t.destination_swap.redeem_tx_hash);return}this.orderExecutorCache.set(t,ve.Redeem,i.val),this.emit("success",t,ve.Redeem,i.val)}async starknetRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing starknet redeem"),this.orderExecutorCache.get(t,ve.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._starknetHTLC){this.emit("error",t,"StarknetHTLC is required");return}const i=await this._starknetHTLC.redeem(t,r);if(!i.ok){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,ve.Redeem,t.destination_swap.redeem_tx_hash);return}i.val&&(this.orderExecutorCache.set(t,ve.Redeem,i.val),this.emit("success",t,ve.Redeem,i.val))}async btcRedeem(t,r,n){var a,c;const i=this.bitcoinRedeemCache.get(r.create_order.create_id),s=(a=r.destination_swap.initiate_tx_hash.split(",").at(-1))==null?void 0:a.split(":").at(0);if(!s){this.emit("error",r,"Failed to get initiate_tx_hash");return}let o=!1;if(i)if(i.redeemedFromUTXO&&i.redeemedFromUTXO!==s)o=!0,this.emit("log",r.create_order.create_id,"rbf btc redeem");else if(i.redeemedAt&&Date.now()-i.redeemedAt>1e3*60*15)this.emit("log",r.create_order.create_id,"redeem not confirmed in last 15 minutes"),o=!0;else{this.emit("log",r.create_order.create_id,"btcRedeem: already redeemed");return}else if(r.destination_swap.redeem_tx_hash&&!Number(r.destination_swap.redeem_block_number))try{const f=await(await t.getProvider()).getTransaction(r.destination_swap.redeem_tx_hash);let u=!1;for(const d of f.vin)if(d.txid===s){u=!0;break}if(u){this.emit("log",r.create_order.create_id,"already a valid redeem");let d=0;try{const[y]=await(await t.getProvider()).getTransactionTimes([r.destination_swap.redeem_tx_hash]);y!==0&&(d=y)}catch{d=Date.now()}this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:s,redeemedAt:d,redeemTxHash:r.destination_swap.redeem_tx_hash});return}o=!0}catch(f){if(f.message.includes("Transaction not found"))o=!0;else{this.emit("error",r,"Failed to get redeem tx: "+f);return}}this.emit("log",r.create_order.create_id,"executing btc redeem");try{const u=await(await vi.from(t,Number(r.destination_swap.amount),r.create_order.secret_hash,Ar(r.destination_swap.initiator),Ar(r.destination_swap.redeemer),r.destination_swap.timelock,o?[s]:[])).getRedeemHex(_.trim0x(n),(c=r.create_order.additional_data)==null?void 0:c.bitcoin_optional_recipient),d=await this.broadcastRedeemTx(u,r.create_order.create_id);if(!d.ok){this.emit("error",r,d.error||"Failed to broadcast redeem tx");return}o?(this.emit("log",r.create_order.create_id,"rbf: btc redeem success"),this.emit("rbf",r,d.val)):this.emit("success",r,ve.Redeem,d.val),this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:s,redeemedAt:Date.now(),redeemTxHash:d.val})}catch(f){this.emit("error",r,"Failed btc redeem: "+f)}}async btcRefund(t,r){var n;if(!this.orderExecutorCache.get(r,ve.Refund)){this.emit("log",r.create_order.create_id,"executing btc refund");try{const s=await(await vi.from(t,Number(r.source_swap.amount),r.create_order.secret_hash,Ar(r.source_swap.initiator),Ar(r.source_swap.redeemer),r.source_swap.timelock)).refund((n=r.create_order.additional_data)==null?void 0:n.bitcoin_optional_recipient);this.orderExecutorCache.set(r,ve.Refund,s),this.emit("success",r,ve.Refund,s)}catch(i){this.emit("error",r,"Failed btc refund: "+i)}}}async postRefundSACP(t,r){const n=this.refundSacpCache.get(t.create_order.create_id);if((n==null?void 0:n.initTxHash)===t.source_swap.initiate_tx_hash)return;const i=await vi.from(r,Number(t.source_swap.amount),t.create_order.secret_hash,Ar(t.source_swap.initiator),Ar(t.source_swap.redeemer),t.source_swap.timelock),s=t.create_order.additional_data.bitcoin_optional_recipient;if(s)try{const o=await i.generateInstantRefundSACP(s);if(!this._api)return;const a=new _.Url(this._api.orderbook).endpoint("orders/bitcoin/"+t.create_order.create_id+"/instant-refund");(await _.Fetcher.post(a,{headers:{"Content-Type":"application/json"},body:JSON.stringify({instant_refund_tx_bytes:o})})).status==="Ok"&&this.refundSacpCache.set(t.create_order.create_id,{initTxHash:t.source_swap.initiate_tx_hash})}catch(o){this.emit("error",t,"Failed to generate and post SACP: "+o);return}}async filterExpiredAndAssignStatus(t){var i;if(t.length===0)return _.Ok([]);const r=await((i=this._blockNumberFetcher)==null?void 0:i.fetchBlockNumbers());if(!r.ok)return _.Err(r.error);const n=[];for(let s=0;s<t.length;s++){const o=t[s];if(R0(o))continue;const a=o.source_swap.chain,c=o.destination_swap.chain,f=r==null?void 0:r.val[a],u=r==null?void 0:r.val[c];if(!f||!u){this.emit("error",o,"Error while fetching CurrentBlockNumbers");continue}const d=Qu(o,f,u);n.push({...o,status:d})}return _.Ok(n)}async broadcastRedeemTx(t,r){try{if(!this._api)return _.Err("API not found");const n=new _.Url(this._api.evmRelay).endpoint("/bitcoin/redeem "),i=await this._auth.getAuthHeaders(),o=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...i.val},body:JSON.stringify({redeem_tx_bytes:t,order_id:r})})).json();return o.status==="Ok"&&o.result?_.Ok(o.result):_.Err(o.error)}catch(n){return _.Err("Failed to broadcast redeem tx: "+n)}}}class JA{constructor(t,r,n){this.callData=new $e.CallData(gy),this.account=t,this.starknetProvider=new $e.RpcProvider({nodeUrl:r||(n?Vi[n].nodeUrl:Vi.mainnet.nodeUrl)})}get htlcActorAddress(){return this.account.address}async getHTLCContract(t,r=!1){const n=r?t.destination_swap.asset:t.source_swap.asset;return new $e.Contract(vy,n,this.account)}async initiate(t){try{const n=await(await this.getHTLCContract(t)).token();if(!n)throw new Error("Token address retrieval failed");const i=$e.num.toHex(n),s=$e.cairo.uint256(BigInt(t.source_swap.amount));try{const a=await by(this.account,i,t.source_swap.asset,BigInt(t.source_swap.amount),this.starknetProvider);if(a.error)return _.Err(a.error)}catch(a){return _.Err(`Allowance check failed: ${a}`)}const o=await this.account.execute({contractAddress:t.source_swap.asset,entrypoint:"initiate",calldata:[t.source_swap.redeemer,BigInt(t.source_swap.timelock),s.low,s.high,..._.hexToU32Array(t.create_order.secret_hash)]});if(!o.transaction_hash)throw new Error("Failed to initiate HTLC transaction");return _.Ok(o.transaction_hash)}catch(r){return _.Err(`HTLC Initiation Error: ${r}`)}}async redeem(t,r){try{const n=await this.getHTLCContract(t,!0),i=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,s=await this.account.execute({contractAddress:n.address,entrypoint:"redeem",calldata:$e.CallData.compile({swap_id:i,secret:_.hexToU32Array(r)})});return s.transaction_hash?_.Ok(s.transaction_hash):_.Err("Failed to redeem HTLC transaction")}catch{return _.Err("HTLC Redeem Error")}}async refund(t){try{const r=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,n=await this.getHTLCContract(t),i=await this.account.execute({contractAddress:n.address,entrypoint:"refund",calldata:{orderId:r}});return i.transaction_hash?_.Ok(i.transaction_hash):_.Err("Failed to refund HTLC transaction")}catch{return _.Err("HTLC Refund Error")}}}class QA{constructor(t){if(this.provider=t,!t)throw new Error("Provider is required");this.provider=t,this.program=new Pt.Program(au,t)}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async initiate(t){if(!t)return _.Err("Order is required");try{const{redeemer:r,secretHash:n,amount:i,expiresIn:s}=Pr.from(t),o=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(o,this.program.programId)[0];const a=await this.program.methods.initiate(i,s,r,n).accounts({initiator:this.provider.publicKey}).transaction(),c=await this.provider.sendAndConfirm(a);return c?_.Ok(c):_.Err("Failed to initiate HTLC transaction")}catch(r){return _.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async redeem(t,r){if(!t)return _.Err("Order is required");if(!r)return _.Err("Secret is required");const{secretHash:n}=Pr.from(t),i=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(i,this.program.programId)[0];try{const{redeemer:s}=Pr.from(t);if(!this.swapAccount)return _.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const o=await this.program.methods.redeem(Uy(r)).accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey,redeemer:s}).transaction(),a=await this.provider.sendAndConfirm(o);return a?_.Ok(a):_.Err("Failed to redeem HTLC transaction")}catch(s){return _.Err(`Error redeeming swap: ${s instanceof Error?s.message:String(s)}`)}}async refund(t){if(!t)return _.Err("Order is required");const{secretHash:r}=Pr.from(t),n=[Buffer.from("swap_account"),Buffer.from(r)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(n,this.program.programId)[0];try{if(console.log("Initiating refund for ::",t.source_swap.swap_id),!this.swapAccount)return _.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const i=await this.program.methods.refund().accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey}).transaction(),s=await this.provider.sendAndConfirm(i);return s?_.Ok(s):_.Err("Failed to refund HTLC transaction")}catch(i){return _.Err(`Error refunding swap: ${i instanceof Error?i.message:String(i)}`)}}}exports.API=Us;exports.BaseError=D;exports.BitcoinNetwork=at;exports.BitcoinProvider=xy;exports.BitcoinWallet=zr;exports.BlockNumberFetcher=fy;exports.EvmRelay=my;exports.Garden=wf;exports.HttpRequestError=Tn;exports.OrderActions=ve;exports.OrderStatus=be;exports.ParseOrderStatus=Qu;exports.ParseSwapStatus=nu;exports.Quote=dy;exports.STARKNET_CONFIG=Vi;exports.SecretManager=Zi;exports.SolanaHTLC=QA;exports.SolanaRelay=Hy;exports.SolanaRelayerAddress=Xc;exports.StarknetHTLC=JA;exports.StarknetRelay=Ey;exports.SwapStatus=Ee;exports.botanixMainnet=ly;exports.call=ss;exports.checkAllowance=Ei;exports.checkAllowanceAndApprove=by;exports.concat=ct;exports.constructOrderPair=eu;exports.decodeErrorResult=$p;exports.encodeAbiParameters=pr;exports.evmToViemChainMap=hf;exports.filterDeadlineExpiredOrders=rE;exports.getUrl=so;exports.hyperliquid=hy;exports.hyperliquidTestnet=py;exports.isAddressEqual=is;exports.isAllowanceSufficient=wy;exports.isExpired=Wi;exports.isHex=It;exports.localBatchGatewayRequest=Lh;exports.localBatchGatewayUrl=vo;exports.parseAction=tE;exports.parseActionFromStatus=ef;exports.resolveApiConfig=Jc;exports.solanaProgramAddress=C0;exports.stringify=Oe;exports.switchOrAddNetwork=yy;exports.toXOnly=Ar;exports.validateBTCAddress=Xv;
|
|
99
|
+
`)+" "+H[1]:H[0]+N+" "+k.join(", ")+" "+H[1]}e.types=RA();function E(k){return Array.isArray(k)}e.isArray=E;function x(k){return typeof k=="boolean"}e.isBoolean=x;function P(k){return k===null}e.isNull=P;function w(k){return k==null}e.isNullOrUndefined=w;function A(k){return typeof k=="number"}e.isNumber=A;function T(k){return typeof k=="string"}e.isString=T;function I(k){return typeof k=="symbol"}e.isSymbol=I;function R(k){return k===void 0}e.isUndefined=R;function L(k){return S(k)&&V(k)==="[object RegExp]"}e.isRegExp=L,e.types.isRegExp=L;function S(k){return typeof k=="object"&&k!==null}e.isObject=S;function $(k){return S(k)&&V(k)==="[object Date]"}e.isDate=$,e.types.isDate=$;function C(k){return S(k)&&(V(k)==="[object Error]"||k instanceof Error)}e.isError=C,e.types.isNativeError=C;function U(k){return typeof k=="function"}e.isFunction=U;function j(k){return k===null||typeof k=="boolean"||typeof k=="number"||typeof k=="string"||typeof k=="symbol"||typeof k>"u"}e.isPrimitive=j,e.isBuffer=NA();function V(k){return Object.prototype.toString.call(k)}function Y(k){return k<10?"0"+k.toString(10):k.toString(10)}var X=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function J(){var k=new Date,N=[Y(k.getHours()),Y(k.getMinutes()),Y(k.getSeconds())].join(":");return[k.getDate(),X[k.getMonth()],N].join(" ")}e.log=function(){console.log("%s - %s",J(),e.format.apply(e,arguments))},e.inherits=FA(),e._extend=function(k,N){if(!N||!S(N))return k;for(var H=Object.keys(N),Z=H.length;Z--;)k[H[Z]]=N[H[Z]];return k};function M(k,N){return Object.prototype.hasOwnProperty.call(k,N)}var B=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;e.promisify=function(N){if(typeof N!="function")throw new TypeError('The "original" argument must be of type Function');if(B&&N[B]){var H=N[B];if(typeof H!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(H,B,{value:H,enumerable:!1,writable:!1,configurable:!0}),H}function H(){for(var Z,Q,ie=new Promise(function(te,se){Z=te,Q=se}),ne=[],re=0;re<arguments.length;re++)ne.push(arguments[re]);ne.push(function(te,se){te?Q(te):Z(se)});try{N.apply(this,ne)}catch(te){Q(te)}return ie}return Object.setPrototypeOf(H,Object.getPrototypeOf(N)),B&&Object.defineProperty(H,B,{value:H,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(H,t(N))},e.promisify.custom=B;function q(k,N){if(!k){var H=new Error("Promise was rejected with a falsy value");H.reason=k,k=H}return N(k)}function W(k){if(typeof k!="function")throw new TypeError('The "original" argument must be of type Function');function N(){for(var H=[],Z=0;Z<arguments.length;Z++)H.push(arguments[Z]);var Q=H.pop();if(typeof Q!="function")throw new TypeError("The last argument must be of type Function");var ie=this,ne=function(){return Q.apply(ie,arguments)};k.apply(this,H).then(function(re){process.nextTick(ne.bind(null,null,re))},function(re){process.nextTick(q.bind(null,re,ne))})}return Object.setPrototypeOf(N,Object.getPrototypeOf(k)),Object.defineProperties(N,t(k)),N}e.callbackify=W}(ba)),ba}Object.defineProperty(qn,"__esModule",{value:!0});qn.encode=qn.decode=void 0;const Fy=Br;function $A(e){return(Fy.isBrowser?new TextDecoder("utf-8"):new(Ny()).TextDecoder("utf-8")).decode(e)}qn.decode=$A;function UA(e){return(Fy.isBrowser?new TextEncoder:new(Ny()).TextEncoder("utf-8")).encode(e)}qn.encode=UA;var Gn={},cu={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(e,t){var r=fn,n=r.Buffer;function i(o,a){for(var c in o)a[c]=o[c]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=s);function s(o,a,c){return n(o,a,c)}s.prototype=Object.create(n.prototype),i(n,s),s.from=function(o,a,c){if(typeof o=="number")throw new TypeError("Argument must not be a number");return n(o,a,c)},s.alloc=function(o,a,c){if(typeof o!="number")throw new TypeError("Argument must be a number");var f=n(o);return a!==void 0?typeof c=="string"?f.fill(a,c):f.fill(a):f.fill(0),f},s.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return n(o)},s.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(o)}})(cu,cu.exports);var HA=cu.exports,Rs=HA.Buffer;function LA(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<e.length;n++){var i=e.charAt(n),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=n}var o=e.length,a=e.charAt(0),c=Math.log(o)/Math.log(256),f=Math.log(256)/Math.log(o);function u(p){if((Array.isArray(p)||p instanceof Uint8Array)&&(p=Rs.from(p)),!Rs.isBuffer(p))throw new TypeError("Expected Buffer");if(p.length===0)return"";for(var g=0,b=0,E=0,x=p.length;E!==x&&p[E]===0;)E++,g++;for(var P=(x-E)*f+1>>>0,w=new Uint8Array(P);E!==x;){for(var A=p[E],T=0,I=P-1;(A!==0||T<b)&&I!==-1;I--,T++)A+=256*w[I]>>>0,w[I]=A%o>>>0,A=A/o>>>0;if(A!==0)throw new Error("Non-zero carry");b=T,E++}for(var R=P-b;R!==P&&w[R]===0;)R++;for(var L=a.repeat(g);R<P;++R)L+=e.charAt(w[R]);return L}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return Rs.alloc(0);for(var g=0,b=0,E=0;p[g]===a;)b++,g++;for(var x=(p.length-g)*c+1>>>0,P=new Uint8Array(x);g<p.length;){var w=p.charCodeAt(g);if(w>255)return;var A=t[w];if(A===255)return;for(var T=0,I=x-1;(A!==0||T<E)&&I!==-1;I--,T++)A+=o*P[I]>>>0,P[I]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");E=T,g++}for(var R=x-E;R!==x&&P[R]===0;)R++;var L=Rs.allocUnsafe(b+(x-R));L.fill(0,0,b);for(var S=b;R!==x;)L[S++]=P[R++];return L}function y(p){var g=d(p);if(g)return g;throw new Error("Non-base"+o+" character")}return{encode:u,decodeUnsafe:d,decode:y}}var MA=LA,DA=MA,jA="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",zA=DA(jA),qA=Kt&&Kt.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Gn,"__esModule",{value:!0});Gn.decode=Gn.encode=void 0;const $y=qA(zA);function GA(e){return $y.default.encode(e)}Gn.encode=GA;function VA(e){return $y.default.decode(e)}Gn.decode=VA;var Vn={};Object.defineProperty(Vn,"__esModule",{value:!0});Vn.decode=Vn.encode=void 0;const WA=fn;function KA(e){return e.toString("base64")}Vn.encode=KA;function YA(e){return WA.Buffer.from(e,"base64")}Vn.decode=YA;var ZA=Kt&&Kt.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),XA=Kt&&Kt.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Uo=Kt&&Kt.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r in e)r!=="default"&&Object.prototype.hasOwnProperty.call(e,r)&&ZA(t,e,r);return XA(t,e),t};Object.defineProperty(sr,"__esModule",{value:!0});sr.base64=sr.bs58=sr.utf8=Xs=sr.hex=void 0;var Xs=sr.hex=Uo(zn);sr.utf8=Uo(qn);sr.bs58=Uo(Gn);sr.base64=Uo(Vn);class Pr{constructor(t,r,n,i,s){try{this.swapId=[...Xs.decode(t)],this.secretHash=[...Xs.decode(n)]}catch(o){throw new Error("Error decoding swapId or secretHash",{cause:o})}if(this.secretHash.length!=32||this.swapId.length!=32)throw new Error("swapId or secretHash must be exactly 32 bits in size");try{this.redeemer=new Pt.web3.PublicKey(r)}catch(o){throw new Error("Error decoding redeemer. Ensure it is a valid base58 encoded",{cause:o})}try{this.amount=new Pt.BN(i.toString(10),10),this.expiresIn=new Pt.BN(s)}catch(o){throw new Error("Error decoding amount. Invalid value for amount",{cause:o})}if(!(Number.isInteger(s)&&s>0))throw new Error("expiresIn must be a positive integer.")}static from(t){let r;if(t.source_swap.chain.includes("solana"))r=t.source_swap;else if(t.destination_swap.chain.includes("solana"))r=t.destination_swap;else throw new Error("Expected source_swap or destination_swap to be one of 'solana', 'solana_localnet', 'solana_devnet'");const{swap_id:n,redeemer:i,secret_hash:s,timelock:o}=r,a=BigInt(r.amount);return new Pr(n,i,s,a,o)}}function Uy(e){let t;try{t=[...Xs.decode(e)]}catch(r){throw new Error("Error decoding secret. Ensure it is a hex string",{cause:r})}if(t.length!=32)throw new Error("Invalid Secret size. Expected 32 bytes, got "+t.length);return t}class Hy{constructor(t,r,n,i){if(this.provider=t,this.url=r,!t)throw new Error("Provider is required");if(!r)throw new Error("Endpoint URL is required");if(!n)throw new Error("Relayer address is required");if(!i)throw new Error("Program address is required");try{this.relayer=new Pt.web3.PublicKey(n)}catch(o){throw new Error("Error decoding relayer public key. Ensure it is base58 encoded.",{cause:o})}const s={...au,metadata:{...au.metadata??{}},address:i};try{this.program=new Pt.Program(s,this.provider)}catch(o){throw new Error("Error creating Program instance. Ensure the IDL and provider are correct.",{cause:o})}}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async sendViaRelayer(t,r){try{t.recentBlockhash=(await this.provider.connection.getLatestBlockhash()).blockhash,t.feePayer=this.relayer;const i=(await this.provider.wallet.signTransaction(t)).serialize({requireAllSignatures:!1}).toString("base64"),s={order_id:r,serialized_tx:i,perform_on:"source"},o=await _.Fetcher.post(this.url.endpoint("/spl-initiate"),{body:JSON.stringify(s),headers:{"Content-Type":"application/json"}});return o.error?_.Err(`Error from Relayer: ${o.error}`):o.result?_.Ok(o.result):_.Err("No result returned from relayer")}catch(n){return _.Err(`Failed to send transaction: ${n instanceof Error?n.message:String(n)}`)}}async initiateViaHTLC(t,r){if(!r)return _.Err("Order is required");try{const n=await this.provider.sendAndConfirm(t);return n?await bd(this.provider.connection,n)?_.Ok(n):_.Err("HTLC: Failed to Initiate swap, confirmation timed out"):_.Err("Failed to initiate HTLC transaction")}catch(n){return _.Err(`Error initiating swap: ${n instanceof Error?n.message:String(n)}`)}}async initiate(t){const{redeemer:r,secretHash:n,amount:i,expiresIn:s}=Pr.from(t),o=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(o,this.program.programId)[0];try{const a=await this.program.methods.initiate(i-BigInt(100),s,r,n).accounts({initiator:this.provider.publicKey}).transaction();return de.isSolanaNativeToken(t.source_swap.chain,t.source_swap.asset)?this.initiateViaHTLC(a,t):this.sendViaRelayer(a,t.create_order.create_id)}catch(a){return _.Err("Error initiating swap: ",a)}}async redeem(t,r){const{secretHash:n}=Pr.from(t),i=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(i,this.program.programId)[0];try{const s=Uy(r),o={order_id:t.create_order.create_id,secret:Buffer.from(s).toString("hex"),perform_on:"destination"},a=await _.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify(o),headers:{"Content-Type":"application/json"}});if(a.error)return _.Err(`Redeem: Error from relayer: ${a.error}`);if(!a.result)return _.Err("Redeem: No transaction hash returned from relayer");const c=a.result;return await bd(this.provider.connection,c)?_.Ok(c):_.Err("Redeem: Timed out waiting for confirmation")}catch(s){return console.error("Redeem: Caught exception:",s),_.Err(`Error redeeming: ${s instanceof Error?s.message:String(s)}`)}}async refund(){return _.Err("Refund is automatically handled by the relayer.")}}class wf extends _.EventBroker{constructor(t){super(),this.environment=_.Environment.TESTNET,this.getOrderThreshold=20,this.refundSacpCache=new Map,this.bitcoinRedeemCache=new fx;const{api:r,environment:n}=Jc(t.environment);if(this.environment=n,this._api=r,typeof t.digestKey=="string"){const s=_.DigestKey.from(t.digestKey);if(!s.ok)throw new Error(s.error);this._digestKey=s.val}else this._digestKey=t.digestKey;this._quote=t.quote??new dy(this._api.quote),this._auth=t.auth??_.Siwe.fromDigestKey(new _.Url(this._api.auth),this._digestKey),this._orderbook=t.orderbook??new de.Orderbook(new _.Url(this._api.orderbook)),this._evmHTLC=t.htlc.evm,this._starknetHTLC=t.htlc.starknet,this._solanaHTLC=t.htlc.solana,this._secretManager=t.secretManager??Zi.fromDigestKey(this._digestKey.digestKey),this.orderExecutorCache=new ux,this._blockNumberFetcher=t.blockNumberFetcher??new fy(this._api.info,this.environment);const i=new xy(Jv(this.environment));this._btcWallet=zr.fromPrivateKey(this._digestKey.digestKey,i)}static fromWallets(t){let r;if(typeof t.digestKey=="string"){const s=_.DigestKey.from(t.digestKey);if(!s.ok)throw new Error(s.error);r=s.val}else r=t.digestKey;const{api:n}=Jc(t.environment);if(!n)throw new Error("API not found, invalid environment "+t.environment);const i={evm:t.wallets.evm?new my(n.evmRelay,t.wallets.evm,_.Siwe.fromDigestKey(new _.Url(n.auth),r)):void 0,starknet:t.wallets.starknet?new Ey(n.starknetRelay,t.wallets.starknet,t.environment===_.Environment.MAINNET?_.Network.MAINNET:_.Network.TESTNET):void 0,solana:t.wallets.solana?new Hy(t.wallets.solana,new _.Url(n.solanaRelay),t.environment===_.Environment.MAINNET?Xc.mainnet:Xc.testnet,t.solanaProgramAddress?t.solanaProgramAddress:C0.mainnet):void 0};return new wf({htlc:i,...t})}get evmHTLC(){return this._evmHTLC}get starknetHTLC(){return this._starknetHTLC}get solanaHTLC(){return this._solanaHTLC}get quote(){return this._quote}get btcWallet(){return this._btcWallet}get orderbook(){return this._orderbook}get blockNumberFetcher(){return this._blockNumberFetcher}get secretManager(){return this._secretManager}get auth(){return this._auth}get digestKey(){return this._digestKey}async swap(t){const r=await this.validateAndFillParams(t);if(!r.ok)return _.Err(r.error);const{sendAddress:n,receiveAddress:i,timelock:s}=r.val,o=Date.now().toString(),a=await this._secretManager.generateSecret(o);if(!a.ok)return _.Err(a.error);const{strategyId:c,btcAddress:f}=t.additionalData,u={strategy_id:c,...f&&{bitcoin_optional_recipient:f}},d={source_chain:t.fromAsset.chain,destination_chain:t.toAsset.chain,source_asset:t.fromAsset.atomicSwapAddress,destination_asset:t.toAsset.atomicSwapAddress,initiator_source_address:n,initiator_destination_address:i,source_amount:t.sendAmount,destination_amount:t.receiveAmount,fee:"1",nonce:o,timelock:s,secret_hash:_.trim0x(a.val.secretHash),min_destination_confirmations:t.minDestinationConfirmations??0,additional_data:u,affiliate_fees:this.withDefaultAffiliateFees(t.affiliateFee)},y=await this._quote.getAttestedQuote(d);if(!y.ok)return _.Err(y.error);const p=await this._orderbook.createOrder(y.val,this._auth);if(!p.ok)return _.Err(p.error);const g=await this.pollOrder(p.val);return g.ok?_.Ok(g.val):_.Err(g.error)}withDefaultAffiliateFees(t){return(t??[]).map(r=>({fee:r.fee,address:r.address,chain:r.chain??gd.chain,asset:r.asset??gd.asset}))}async validateAndFillParams(t){if(!t.additionalData.strategyId)return _.Err("StrategyId is required");if(!t.fromAsset||!t.toAsset)return _.Err("Source and destination assets are required for swap");if(t.fromAsset.chain===t.toAsset.chain&&t.fromAsset.atomicSwapAddress===t.toAsset.atomicSwapAddress)return _.Err("Source and destination assets cannot be the same");if(de.isMainnet(t.fromAsset.chain)&&!de.isMainnet(t.toAsset.chain)||!de.isMainnet(t.fromAsset.chain)&&de.isMainnet(t.toAsset.chain))return _.Err("Both assets should be on the same network (either mainnet or testnet)");const r=this.validateAmount(t.sendAmount);if(!r.ok)return _.Err(r.error);const n=this.validateAmount(t.receiveAmount);if(!n.ok)return _.Err(n.error);if(r<n)return _.Err("Send amount should be greater than receive amount");const i=de.getTimeLock(t.fromAsset.chain);if(!i)return _.Err("Unsupported chain for timelock");if((de.isBitcoin(t.fromAsset.chain)||de.isBitcoin(t.toAsset.chain))&&!t.additionalData.btcAddress)return _.Err("btcAddress in additionalData is required if source or destination chain is bitcoin, it is used as refund or redeem address.");const s=await this.getAddresses(t.fromAsset.chain);if(!s.ok)return _.Err(s.error);const o=await this.getAddresses(t.toAsset.chain);return o.ok?_.Ok({sendAddress:s.val,receiveAddress:o.val,timelock:t.timelock??i}):_.Err(o.error)}async getAddresses(t){var n;switch(de.getBlockchainType(t)){case de.BlockchainType.EVM:return this._evmHTLC?_.Ok(this._evmHTLC.htlcActorAddress):_.Err("Please provide evmHTLC when initializing garden");case de.BlockchainType.Bitcoin:{const i=await((n=this._btcWallet)==null?void 0:n.getPublicKey());return!i||!Zv(i)?_.Err("Invalid btc public key"):_.Ok(Ar(i))}case de.BlockchainType.Solana:return this._solanaHTLC?_.Ok(this._solanaHTLC.htlcActorAddress):_.Err("Please provide solanaHTLC when initializing garden");case de.BlockchainType.Starknet:return this._starknetHTLC?_.Ok(this._starknetHTLC.htlcActorAddress):_.Err("Please provide starknetHTLC when initializing garden");default:return _.Err("Unsupported chain")}}validateAmount(t){if(t==null||t.includes("."))return _.Err("Invalid amount ",t);const r=new Dy(t);return!r.isInteger()||r.isNaN()||r.lt(0)||r.isLessThanOrEqualTo(0)?_.Err("Invalid amount ",t):_.Ok(r)}async pollOrder(t){let r=await this._orderbook.getOrder(t,!0),n=0;for(;n<this.getOrderThreshold;){if(await _.sleep(1e3),n++,r.ok){if(r.val&&r.val.create_order.create_id.toLowerCase()===t.toLowerCase())return _.Ok(r.val)}else if(!r.error.includes("result is undefined"))return _.Err(r.error);r=await this._orderbook.getOrder(t,!0)}return _.Err(`Order not found, createOrder id: ${t}`)}async execute(t=5e3){return await this._orderbook.subscribeOrders(this._digestKey.userId,!0,t,async r=>{const n=await this.filterExpiredAndAssignStatus(r.data);if(n.ok&&(this.emit("onPendingOrdersChanged",n.val),r.data.length!==0))for(let i=0;i<n.val.length;i++){const s=n.val[i],o=ef(s.status);if(de.isBitcoin(s.source_swap.chain)&&s.status===be.InitiateDetected){const a=this._btcWallet;if(!a){this.emit("error",s,"BTC wallet not found");continue}await this.postRefundSACP(s,a)}switch(o){case ve.Redeem:{const a=await this._secretManager.generateSecret(s.create_order.nonce);if(!a.ok){this.emit("error",s,a.error);return}switch(de.getBlockchainType(s.destination_swap.chain)){case de.BlockchainType.EVM:{await this.evmRedeem(s,a.val.secret);break}case de.BlockchainType.Bitcoin:{const c=this.btcWallet;if(!c){this.emit("error",s,"BTC wallet not found");return}await this.btcRedeem(c,s,a.val.secret);break}case de.BlockchainType.Starknet:{await this.starknetRedeem(s,a.val.secret);break}case de.BlockchainType.Solana:await this.solRedeem(s,a.val.secret);break;default:this.emit("error",s,"Unsupported chain: "+s.destination_swap.chain)}break}case ve.Refund:{switch(de.getBlockchainType(s.source_swap.chain)){case de.BlockchainType.Solana:{this.emit("error",s,"Solana refund is automatically done by relay service");break}case de.BlockchainType.EVM:{this.emit("error",s,"EVM refund is automatically done by relay service");break}case de.BlockchainType.Bitcoin:{const a=this.btcWallet;if(!a){this.emit("error",s,"BTC wallet not found");return}await this.btcRefund(a,s);break}case de.BlockchainType.Starknet:{this.emit("error",s,"Starknet refund is automatically done by relay service");break}default:this.emit("error",s,"Unsupported chain: "+s.source_swap.chain)}break}}}},"pending",{per_page:500})}async solRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing sol redeem"),this.orderExecutorCache.get(t,ve.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._solanaHTLC){this.emit("error",t,"Solana HTLC is required");return}const i=await this._solanaHTLC.redeem(t,r);if(i.error){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,ve.Redeem,t.destination_swap.redeem_tx_hash);return}i.val&&(this.orderExecutorCache.set(t,ve.Redeem,i.val),this.emit("success",t,ve.Redeem,i.val))}async evmRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing evm redeem"),this.orderExecutorCache.get(t,ve.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._evmHTLC){this.emit("error",t,"EVMHTLC is required");return}const i=await this._evmHTLC.redeem(t,r);if(!i.ok){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,ve.Redeem,t.destination_swap.redeem_tx_hash);return}this.orderExecutorCache.set(t,ve.Redeem,i.val),this.emit("success",t,ve.Redeem,i.val)}async starknetRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing starknet redeem"),this.orderExecutorCache.get(t,ve.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._starknetHTLC){this.emit("error",t,"StarknetHTLC is required");return}const i=await this._starknetHTLC.redeem(t,r);if(!i.ok){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,ve.Redeem,t.destination_swap.redeem_tx_hash);return}i.val&&(this.orderExecutorCache.set(t,ve.Redeem,i.val),this.emit("success",t,ve.Redeem,i.val))}async btcRedeem(t,r,n){var a,c;const i=this.bitcoinRedeemCache.get(r.create_order.create_id),s=(a=r.destination_swap.initiate_tx_hash.split(",").at(-1))==null?void 0:a.split(":").at(0);if(!s){this.emit("error",r,"Failed to get initiate_tx_hash");return}let o=!1;if(i)if(i.redeemedFromUTXO&&i.redeemedFromUTXO!==s)o=!0,this.emit("log",r.create_order.create_id,"rbf btc redeem");else if(i.redeemedAt&&Date.now()-i.redeemedAt>1e3*60*15)this.emit("log",r.create_order.create_id,"redeem not confirmed in last 15 minutes"),o=!0;else{this.emit("log",r.create_order.create_id,"btcRedeem: already redeemed");return}else if(r.destination_swap.redeem_tx_hash&&!Number(r.destination_swap.redeem_block_number))try{const f=await(await t.getProvider()).getTransaction(r.destination_swap.redeem_tx_hash);let u=!1;for(const d of f.vin)if(d.txid===s){u=!0;break}if(u){this.emit("log",r.create_order.create_id,"already a valid redeem");let d=0;try{const[y]=await(await t.getProvider()).getTransactionTimes([r.destination_swap.redeem_tx_hash]);y!==0&&(d=y)}catch{d=Date.now()}this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:s,redeemedAt:d,redeemTxHash:r.destination_swap.redeem_tx_hash});return}o=!0}catch(f){if(f.message.includes("Transaction not found"))o=!0;else{this.emit("error",r,"Failed to get redeem tx: "+f);return}}this.emit("log",r.create_order.create_id,"executing btc redeem");try{const u=await(await vi.from(t,Number(r.destination_swap.amount),r.create_order.secret_hash,Ar(r.destination_swap.initiator),Ar(r.destination_swap.redeemer),r.destination_swap.timelock,o?[s]:[])).getRedeemHex(_.trim0x(n),(c=r.create_order.additional_data)==null?void 0:c.bitcoin_optional_recipient),d=await this.broadcastRedeemTx(u,r.create_order.create_id);if(!d.ok){this.emit("error",r,d.error||"Failed to broadcast redeem tx");return}o?(this.emit("log",r.create_order.create_id,"rbf: btc redeem success"),this.emit("rbf",r,d.val)):this.emit("success",r,ve.Redeem,d.val),this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:s,redeemedAt:Date.now(),redeemTxHash:d.val})}catch(f){this.emit("error",r,"Failed btc redeem: "+f)}}async btcRefund(t,r){var n;if(!this.orderExecutorCache.get(r,ve.Refund)){this.emit("log",r.create_order.create_id,"executing btc refund");try{const s=await(await vi.from(t,Number(r.source_swap.amount),r.create_order.secret_hash,Ar(r.source_swap.initiator),Ar(r.source_swap.redeemer),r.source_swap.timelock)).refund((n=r.create_order.additional_data)==null?void 0:n.bitcoin_optional_recipient);this.orderExecutorCache.set(r,ve.Refund,s),this.emit("success",r,ve.Refund,s)}catch(i){this.emit("error",r,"Failed btc refund: "+i)}}}async postRefundSACP(t,r){const n=this.refundSacpCache.get(t.create_order.create_id);if((n==null?void 0:n.initTxHash)===t.source_swap.initiate_tx_hash)return;const i=await vi.from(r,Number(t.source_swap.amount),t.create_order.secret_hash,Ar(t.source_swap.initiator),Ar(t.source_swap.redeemer),t.source_swap.timelock),s=t.create_order.additional_data.bitcoin_optional_recipient;if(s)try{const o=await i.generateInstantRefundSACP(s);if(!this._api)return;const a=new _.Url(this._api.orderbook).endpoint("orders/bitcoin/"+t.create_order.create_id+"/instant-refund");(await _.Fetcher.post(a,{headers:{"Content-Type":"application/json"},body:JSON.stringify({instant_refund_tx_bytes:o})})).status==="Ok"&&this.refundSacpCache.set(t.create_order.create_id,{initTxHash:t.source_swap.initiate_tx_hash})}catch(o){this.emit("error",t,"Failed to generate and post SACP: "+o);return}}async filterExpiredAndAssignStatus(t){var i;if(t.length===0)return _.Ok([]);const r=await((i=this._blockNumberFetcher)==null?void 0:i.fetchBlockNumbers());if(!r.ok)return _.Err(r.error);const n=[];for(let s=0;s<t.length;s++){const o=t[s];if(R0(o))continue;const a=o.source_swap.chain,c=o.destination_swap.chain,f=r==null?void 0:r.val[a],u=r==null?void 0:r.val[c];if(!f||!u){this.emit("error",o,"Error while fetching CurrentBlockNumbers");continue}const d=Qu(o,f,u);n.push({...o,status:d})}return _.Ok(n)}async broadcastRedeemTx(t,r){try{if(!this._api)return _.Err("API not found");const n=new _.Url(this._api.evmRelay).endpoint("/bitcoin/redeem "),i=await this._auth.getAuthHeaders(),o=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...i.val},body:JSON.stringify({redeem_tx_bytes:t,order_id:r})})).json();return o.status==="Ok"&&o.result?_.Ok(o.result):_.Err(o.error)}catch(n){return _.Err("Failed to broadcast redeem tx: "+n)}}}class JA{constructor(t,r,n){this.callData=new $e.CallData(gy),this.account=t,this.starknetProvider=new $e.RpcProvider({nodeUrl:r||(n?Vi[n].nodeUrl:Vi.mainnet.nodeUrl)})}get htlcActorAddress(){return this.account.address}async getHTLCContract(t,r=!1){const n=r?t.destination_swap.asset:t.source_swap.asset;return new $e.Contract(vy,n,this.account)}async initiate(t){try{const n=await(await this.getHTLCContract(t)).token();if(!n)throw new Error("Token address retrieval failed");const i=$e.num.toHex(n),s=$e.cairo.uint256(BigInt(t.source_swap.amount));try{const a=await by(this.account,i,t.source_swap.asset,BigInt(t.source_swap.amount),this.starknetProvider);if(a.error)return _.Err(a.error)}catch(a){return _.Err(`Allowance check failed: ${a}`)}const o=await this.account.execute({contractAddress:t.source_swap.asset,entrypoint:"initiate",calldata:[t.source_swap.redeemer,BigInt(t.source_swap.timelock),s.low,s.high,..._.hexToU32Array(t.create_order.secret_hash)]});if(!o.transaction_hash)throw new Error("Failed to initiate HTLC transaction");return _.Ok(o.transaction_hash)}catch(r){return _.Err(`HTLC Initiation Error: ${r}`)}}async redeem(t,r){try{const n=await this.getHTLCContract(t,!0),i=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,s=await this.account.execute({contractAddress:n.address,entrypoint:"redeem",calldata:$e.CallData.compile({swap_id:i,secret:_.hexToU32Array(r)})});return s.transaction_hash?_.Ok(s.transaction_hash):_.Err("Failed to redeem HTLC transaction")}catch{return _.Err("HTLC Redeem Error")}}async refund(t){try{const r=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,n=await this.getHTLCContract(t),i=await this.account.execute({contractAddress:n.address,entrypoint:"refund",calldata:{orderId:r}});return i.transaction_hash?_.Ok(i.transaction_hash):_.Err("Failed to refund HTLC transaction")}catch{return _.Err("HTLC Refund Error")}}}class QA{constructor(t){if(this.provider=t,!t)throw new Error("Provider is required");this.provider=t,this.program=new Pt.Program(au,t)}get htlcActorAddress(){if(!this.program.programId)throw new Error("No program found");return this.provider.publicKey.toBase58()}async initiate(t){if(!t)return _.Err("Order is required");try{const{redeemer:r,secretHash:n,amount:i,expiresIn:s}=Pr.from(t),o=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(o,this.program.programId)[0];const a=await this.program.methods.initiate(i,s,r,n).accounts({initiator:this.provider.publicKey}).transaction(),c=await this.provider.sendAndConfirm(a);return c?_.Ok(c):_.Err("Failed to initiate HTLC transaction")}catch(r){return _.Err(`Error initiating swap: ${r instanceof Error?r.message:String(r)}`)}}async redeem(t,r){if(!t)return _.Err("Order is required");if(!r)return _.Err("Secret is required");const{secretHash:n}=Pr.from(t),i=[Buffer.from("swap_account"),this.provider.publicKey.toBuffer(),Buffer.from(n)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(i,this.program.programId)[0];try{const{redeemer:s}=Pr.from(t);if(!this.swapAccount)return _.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const o=await this.program.methods.redeem(Uy(r)).accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey,redeemer:s}).transaction(),a=await this.provider.sendAndConfirm(o);return a?_.Ok(a):_.Err("Failed to redeem HTLC transaction")}catch(s){return _.Err(`Error redeeming swap: ${s instanceof Error?s.message:String(s)}`)}}async refund(t){if(!t)return _.Err("Order is required");const{secretHash:r}=Pr.from(t),n=[Buffer.from("swap_account"),Buffer.from(r)];this.swapAccount=Pt.web3.PublicKey.findProgramAddressSync(n,this.program.programId)[0];try{if(console.log("Initiating refund for ::",t.source_swap.swap_id),!this.swapAccount)return _.Err("Swap account not initialized. Call initiate() first or provide swap ID.");const i=await this.program.methods.refund().accounts({swapAccount:this.swapAccount,initiator:this.provider.publicKey}).transaction(),s=await this.provider.sendAndConfirm(i);return s?_.Ok(s):_.Err("Failed to refund HTLC transaction")}catch(i){return _.Err(`Error refunding swap: ${i instanceof Error?i.message:String(i)}`)}}}exports.API=Us;exports.BaseError=D;exports.BitcoinNetwork=at;exports.BitcoinProvider=xy;exports.BitcoinWallet=zr;exports.BlockNumberFetcher=fy;exports.EvmRelay=my;exports.Garden=wf;exports.HttpRequestError=Tn;exports.OrderActions=ve;exports.OrderStatus=be;exports.ParseOrderStatus=Qu;exports.ParseSwapStatus=nu;exports.Quote=dy;exports.STARKNET_CONFIG=Vi;exports.SecretManager=Zi;exports.SolanaHTLC=QA;exports.SolanaRelay=Hy;exports.SolanaRelayerAddress=Xc;exports.StarknetHTLC=JA;exports.StarknetRelay=Ey;exports.SwapStatus=Ee;exports.botanixMainnet=ly;exports.call=ss;exports.checkAllowance=Ei;exports.checkAllowanceAndApprove=by;exports.concat=ct;exports.constructOrderPair=eu;exports.decodeErrorResult=$p;exports.encodeAbiParameters=pr;exports.evmToViemChainMap=hf;exports.filterDeadlineExpiredOrders=rE;exports.getUrl=so;exports.hyperliquid=hy;exports.hyperliquidTestnet=py;exports.isAddressEqual=is;exports.isAllowanceSufficient=wy;exports.isExpired=Wi;exports.isHex=It;exports.localBatchGatewayRequest=Lh;exports.localBatchGatewayUrl=vo;exports.parseAction=tE;exports.parseActionFromStatus=ef;exports.resolveApiConfig=Jc;exports.solanaProgramAddress=C0;exports.stringify=Oe;exports.switchOrAddNetwork=yy;exports.toXOnly=Ar;exports.validateBTCAddress=Xv;
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-K8fs0tKV.cjs");exports.API=e.API;exports.BitcoinNetwork=e.BitcoinNetwork;exports.BitcoinProvider=e.BitcoinProvider;exports.BitcoinWallet=e.BitcoinWallet;exports.BlockNumberFetcher=e.BlockNumberFetcher;exports.EvmRelay=e.EvmRelay;exports.Garden=e.Garden;exports.OrderActions=e.OrderActions;exports.OrderStatus=e.OrderStatus;exports.ParseOrderStatus=e.ParseOrderStatus;exports.ParseSwapStatus=e.ParseSwapStatus;exports.Quote=e.Quote;exports.STARKNET_CONFIG=e.STARKNET_CONFIG;exports.SecretManager=e.SecretManager;exports.SolanaHTLC=e.SolanaHTLC;exports.SolanaRelay=e.SolanaRelay;exports.SolanaRelayerAddress=e.SolanaRelayerAddress;exports.StarknetHTLC=e.StarknetHTLC;exports.StarknetRelay=e.StarknetRelay;exports.SwapStatus=e.SwapStatus;exports.botanix=e.botanixMainnet;exports.checkStarknetAlloance=e.checkAllowance;exports.checkStarknetAllowanceAndApprove=e.checkAllowanceAndApprove;exports.constructOrderPair=e.constructOrderPair;exports.evmToViemChainMap=e.evmToViemChainMap;exports.filterDeadlineExpiredOrders=e.filterDeadlineExpiredOrders;exports.hyperliquid=e.hyperliquid;exports.hyperliquidTestnet=e.hyperliquidTestnet;exports.isExpired=e.isExpired;exports.isStarknetAllowanceSufficient=e.isAllowanceSufficient;exports.parseAction=e.parseAction;exports.parseActionFromStatus=e.parseActionFromStatus;exports.resolveApiConfig=e.resolveApiConfig;exports.solanaProgramAddress=e.solanaProgramAddress;exports.switchOrAddNetwork=e.switchOrAddNetwork;exports.toXOnly=e.toXOnly;exports.validateBTCAddress=e.validateBTCAddress;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { T as e, M as r, N as t, R as i, m as n, E as o, G as l, O as d, n as c, P as S, q as A, Q as p, U as u, v as k, k as O, j as h, V as m, h as w, S as y, o as T, L as v, y as C, w as P, z as N, F as R, t as f, K as x, J as B, r as E, x as F, p as g, u as q, D as G, W as I, I as L, C as M, A as b } from "./index-
|
|
1
|
+
import { T as e, M as r, N as t, R as i, m as n, E as o, G as l, O as d, n as c, P as S, q as A, Q as p, U as u, v as k, k as O, j as h, V as m, h as w, S as y, o as T, L as v, y as C, w as P, z as N, F as R, t as f, K as x, J as B, r as E, x as F, p as g, u as q, D as G, W as I, I as L, C as M, A as b } from "./index-C4i5UzzH.js";
|
|
2
2
|
export {
|
|
3
3
|
e as API,
|
|
4
4
|
r as BitcoinNetwork,
|