@gardenfi/core 0.2.0-beta.55 → 0.2.0-beta.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";var Fs=Object.defineProperty;var Us=(e,t,r)=>t in e?Fs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var pt=(e,t,r)=>Us(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("@catalogfi/utils"),J=require("@gardenfi/orderbook"),ge=require("@gardenfi/utils"),He=require("viem"),Ms=require("varuint-bitcoin"),Ns=require("tiny-secp256k1"),Bn=require("@catalogfi/wallets"),bi=require("bitcoinjs-lib"),Ds=require("bignumber.js");function an(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const Sn=an(Ms),_t=an(Ns),ye=an(bi);var sr=(e=>(e[e.evm=14400]="evm",e[e.btc=288]="btc",e))(sr||{}),ce=(e=>(e.Idle="Idle",e.Initiate="Initiate",e.Redeem="Redeem",e.Refund="Refund",e))(ce||{});function Gt(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}const yi="2.21.30";let kt={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${yi}`};class Z extends Error{constructor(t,r={}){var u;const n=(()=>{var l;return r.cause instanceof Z?r.cause.details:(l=r.cause)!=null&&l.message?r.cause.message:r.details})(),i=r.cause instanceof Z&&r.cause.docsPath||r.docsPath,a=(u=kt.getDocsUrl)==null?void 0:u.call(kt,{...r,docsPath:i}),f=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...a?[`Docs: ${a}`]:[],...n?[`Details: ${n}`]:[],...kt.version?[`Version: ${kt.version}`]:[]].join(`
2
2
  `);super(f,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{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,"metaMessages",{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,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=yi}walk(t){return gi(this,t)}}function gi(e,t){return t!=null&&t(e)?e:e&&typeof e=="object"&&"cause"in e?gi(e.cause,t):t?null:e}class $s extends Z{constructor({max:t,min:r,signed:n,size:i,value:a}){super(`Number "${a}" is not in safe ${i?`${i*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${r} to ${t})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}}class Hs extends Z{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}}function qt(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}function xt(e){return qt(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}function or(e,{dir:t="left"}={}){let r=typeof e=="string"?e.replace("0x",""):e,n=0;for(let i=0;i<r.length-1&&r[t==="left"?i:r.length-i-1].toString()==="0";i++)n++;return r=t==="left"?r.slice(n):r.slice(0,r.length-n),typeof e=="string"?(r.length===1&&t==="right"&&(r=`${r}0`),`0x${r.length%2===1?`0${r}`:r}`):r}class zs extends Z{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${t}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}}class mi extends Z{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${t}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}}function St(e,{dir:t,size:r=32}={}){return typeof e=="string"?js(e,{dir:t,size:r}):Gs(e,{dir:t,size:r})}function js(e,{dir:t,size:r=32}={}){if(r===null)return e;const n=e.replace("0x","");if(n.length>r*2)throw new mi({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function Gs(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new mi({size:e.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let i=0;i<r;i++){const a=t==="right";n[a?i:r-i-1]=e[a?i:e.length-i-1]}return n}const qs=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function q(e,t={}){return typeof e=="number"||typeof e=="bigint"?wi(e,t):typeof e=="string"?Ks(e,t):typeof e=="boolean"?Ws(e,t):Ze(e,t)}function Ws(e,t={}){const r=`0x${Number(e)}`;return typeof t.size=="number"?(It(r,{size:t.size}),St(r,{size:t.size})):r}function Ze(e,t={}){let r="";for(let i=0;i<e.length;i++)r+=qs[e[i]];const n=`0x${r}`;return typeof t.size=="number"?(It(n,{size:t.size}),St(n,{dir:"right",size:t.size})):n}function wi(e,t={}){const{signed:r,size:n}=t,i=BigInt(e);let a;n?r?a=(1n<<BigInt(n)*8n-1n)-1n:a=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(a=BigInt(Number.MAX_SAFE_INTEGER));const f=typeof a=="bigint"&&r?-a-1n:0;if(a&&i>a||i<f){const l=typeof e=="bigint"?"n":"";throw new $s({max:a?`${a}${l}`:void 0,min:`${f}${l}`,signed:r,size:n,value:`${e}${l}`})}const u=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?St(u,{size:n}):u}const Vs=new TextEncoder;function Ks(e,t={}){const r=Vs.encode(e);return Ze(r,t)}const Ys=new TextEncoder;function _i(e,t={}){return typeof e=="number"||typeof e=="bigint"?Xs(e,t):typeof e=="boolean"?Js(e,t):qt(e)?st(e,t):xi(e,t)}function Js(e,t={}){const r=new Uint8Array(1);return r[0]=Number(e),typeof t.size=="number"?(It(r,{size:t.size}),St(r,{size:t.size})):r}const Ne={zero:48,nine:57,A:65,F:70,a:97,f:102};function In(e){if(e>=Ne.zero&&e<=Ne.nine)return e-Ne.zero;if(e>=Ne.A&&e<=Ne.F)return e-(Ne.A-10);if(e>=Ne.a&&e<=Ne.f)return e-(Ne.a-10)}function st(e,t={}){let r=e;t.size&&(It(r,{size:t.size}),r=St(r,{dir:"right",size:t.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const i=n.length/2,a=new Uint8Array(i);for(let f=0,u=0;f<i;f++){const l=In(n.charCodeAt(u++)),y=In(n.charCodeAt(u++));if(l===void 0||y===void 0)throw new Z(`Invalid byte sequence ("${n[u-2]}${n[u-1]}" in "${n}").`);a[f]=l*16+y}return a}function Xs(e,t){const r=wi(e,t);return st(r)}function xi(e,t={}){const r=Ys.encode(e);return typeof t.size=="number"?(It(r,{size:t.size}),St(r,{dir:"right",size:t.size})):r}function It(e,{size:t}){if(xt(e)>t)throw new Hs({givenSize:xt(e),maxSize:t})}function gt(e,t={}){const{signed:r}=t;t.size&&It(e,{size:t.size});const n=BigInt(e);if(!r)return n;const i=(e.length-2)/2,a=(1n<<BigInt(i)*8n-1n)-1n;return n<=a?n:n-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function ar(e,t={}){return Number(gt(e,t))}function fn(e,t){return({exclude:r,format:n})=>({exclude:r,format:i=>{const a=t(i);if(r)for(const f of r)delete a[f];return{...a,...n(i)}},type:e})}const vi={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function un(e){const t={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,chainId:e.chainId?ar(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?ar(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?vi[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=Zs(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 Qs=fn("transaction",un);function Zs(e){return e.map(t=>({contractAddress:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}function eo(e){var r;const t=(r=e.transactions)==null?void 0:r.map(n=>typeof n=="string"?n:un(n));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 to=fn("block",eo);function ro(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}:{}}}const no={"0x0":"reverted","0x1":"success"};function io(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=>ro(r)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?ar(e.transactionIndex):null,status:e.status?no[e.status]:null,type:e.type?vi[e.type]||e.type:null};return e.blobGasPrice&&(t.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(t.blobGasUsed=BigInt(e.blobGasUsed)),t}const so=fn("transactionReceipt",io),cn=2n**256n-1n;function Wt(e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}class An extends Z{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`,{name:"NegativeOffsetError"})}}class oo extends Z{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`,{name:"PositionOutOfBoundsError"})}}class ao extends Z{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`,{name:"RecursiveReadLimitExceededError"})}}const fo={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new ao({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new oo({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new An({offset:e});const t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new An({offset:e});const t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){const r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){const t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){const t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){const t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();const r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();const e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();const e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();const e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();const e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){const t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function Ei(e,{recursiveReadLimit:t=8192}={}){const r=Object.create(fo);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}function ot(e,t="hex"){const r=Bi(e),n=Ei(new Uint8Array(r.length));return r.encode(n),t==="hex"?Ze(n.bytes):n.bytes}function Bi(e){return Array.isArray(e)?uo(e.map(t=>Bi(t))):co(e)}function uo(e){const t=e.reduce((i,a)=>i+a.length,0),r=Si(t);return{length:t<=55?1+t:1+r+t,encode(i){t<=55?i.pushByte(192+t):(i.pushByte(247+r),r===1?i.pushUint8(t):r===2?i.pushUint16(t):r===3?i.pushUint24(t):i.pushUint32(t));for(const{encode:a}of e)a(i)}}}function co(e){const t=typeof e=="string"?st(e):e,r=Si(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(i){t.length===1&&t[0]<128?i.pushBytes(t):t.length<=55?(i.pushByte(128+t.length),i.pushBytes(t)):(i.pushByte(183+r),r===1?i.pushUint8(t.length):r===2?i.pushUint16(t.length):r===3?i.pushUint24(t.length):i.pushUint32(t.length),i.pushBytes(t))}}}function Si(e){if(e<2**8)return 1;if(e<2**16)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new Z("Length is too large.")}const lo={ether:-9,wei:9};function ho(e,t){let r=e.toString();const n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[i,a]=[r.slice(0,r.length-t),r.slice(r.length-t)];return a=a.replace(/(0+)$/,""),`${n?"-":""}${i||"0"}${a?`.${a}`:""}`}function Jr(e,t="wei"){return ho(e,lo[t])}function po(e){const t=Object.entries(e).map(([n,i])=>i===void 0||i===!1?null:[n,i]).filter(Boolean),r=t.reduce((n,[i])=>Math.max(n,i.length),0);return t.map(([n,i])=>` ${`${n}:`.padEnd(r+1)} ${i}`).join(`
3
3
  `)}class bo extends Z{constructor({v:t}){super(`Invalid \`v\` value "${t}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class yo extends Z{constructor({transaction:t}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",po(t),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class go extends Z{constructor({storageKey:t}){super(`Size for storage key "${t}" is invalid. Expected 32 bytes. Got ${Math.floor((t.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}function Ii(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(a=>st(a)):e.blobs,i=[];for(const a of n)i.push(Uint8Array.from(t.blobToKzgCommitment(a)));return r==="bytes"?i:i.map(a=>Ze(a))}function Ai(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(f=>st(f)):e.blobs,i=typeof e.commitments[0]=="string"?e.commitments.map(f=>st(f)):e.commitments,a=[];for(let f=0;f<n.length;f++){const u=n[f],l=i[f];a.push(Uint8Array.from(t.computeBlobKzgProof(u,l)))}return r==="bytes"?a:a.map(f=>Ze(f))}function Rn(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function mo(e){return e instanceof Uint8Array||e!=null&&typeof e=="object"&&e.constructor.name==="Uint8Array"}function ln(e,...t){if(!mo(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function fr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ri(e,t){ln(e);const r=t.outputLen;if(e.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const wo=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),kr=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),Oe=(e,t)=>e<<32-t|e>>>t,Tn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68,_o=e=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255;function Pn(e){for(let t=0;t<e.length;t++)e[t]=_o(e[t])}function xo(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}function hn(e){return typeof e=="string"&&(e=xo(e)),ln(e),e}let Ti=class{clone(){return this._cloneInto()}};function Pi(e){const t=n=>e().update(hn(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function vo(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const i=BigInt(32),a=BigInt(4294967295),f=Number(r>>i&a),u=Number(r&a),l=n?4:0,y=n?0:4;e.setUint32(t+l,f,n),e.setUint32(t+y,u,n)}const Eo=(e,t,r)=>e&t^~e&r,Bo=(e,t,r)=>e&t^e&r^t&r;class So extends Ti{constructor(t,r,n,i){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=kr(this.buffer)}update(t){fr(this);const{view:r,buffer:n,blockLen:i}=this;t=hn(t);const a=t.length;for(let f=0;f<a;){const u=Math.min(i-this.pos,a-f);if(u===i){const l=kr(t);for(;i<=a-f;f+=i)this.process(l,f);continue}n.set(t.subarray(f,f+u),this.pos),this.pos+=u,f+=u,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){fr(this),Ri(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:a}=this;let{pos:f}=this;r[f++]=128,this.buffer.subarray(f).fill(0),this.padOffset>i-f&&(this.process(n,0),f=0);for(let w=f;w<i;w++)r[w]=0;vo(n,i-8,BigInt(this.length*8),a),this.process(n,0);const u=kr(t),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const y=l/4,g=this.get();if(y>g.length)throw new Error("_sha2: outputLen bigger than state");for(let w=0;w<y;w++)u.setUint32(4*w,g[w],a)}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:a,destroyed:f,pos:u}=this;return t.length=i,t.pos=u,t.finished=a,t.destroyed=f,i%r&&t.buffer.set(n),t}}const Io=new Uint32Array([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]),Ye=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Je=new Uint32Array(64);class Ao extends So{constructor(){super(64,32,8,!1),this.A=Ye[0]|0,this.B=Ye[1]|0,this.C=Ye[2]|0,this.D=Ye[3]|0,this.E=Ye[4]|0,this.F=Ye[5]|0,this.G=Ye[6]|0,this.H=Ye[7]|0}get(){const{A:t,B:r,C:n,D:i,E:a,F:f,G:u,H:l}=this;return[t,r,n,i,a,f,u,l]}set(t,r,n,i,a,f,u,l){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=a|0,this.F=f|0,this.G=u|0,this.H=l|0}process(t,r){for(let w=0;w<16;w++,r+=4)Je[w]=t.getUint32(r,!1);for(let w=16;w<64;w++){const E=Je[w-15],I=Je[w-2],v=Oe(E,7)^Oe(E,18)^E>>>3,k=Oe(I,17)^Oe(I,19)^I>>>10;Je[w]=k+Je[w-7]+v+Je[w-16]|0}let{A:n,B:i,C:a,D:f,E:u,F:l,G:y,H:g}=this;for(let w=0;w<64;w++){const E=Oe(u,6)^Oe(u,11)^Oe(u,25),I=g+E+Eo(u,l,y)+Io[w]+Je[w]|0,k=(Oe(n,2)^Oe(n,13)^Oe(n,22))+Bo(n,i,a)|0;g=y,y=l,l=u,u=f+I|0,f=a,a=i,i=n,n=I+k|0}n=n+this.A|0,i=i+this.B|0,a=a+this.C|0,f=f+this.D|0,u=u+this.E|0,l=l+this.F|0,y=y+this.G|0,g=g+this.H|0,this.set(n,i,a,f,u,l,y,g)}roundClean(){Je.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Ro=Pi(()=>new Ao);function To(e,t){return Ro(qt(e,{strict:!1})?_i(e):e)}function Po(e){const{commitment:t,version:r=1}=e,n=e.to??(typeof t=="string"?"hex":"bytes"),i=To(t);return i.set([r],0),n==="bytes"?i:Ze(i)}function ko(e){const{commitments:t,version:r}=e,n=e.to??(typeof t[0]=="string"?"hex":"bytes"),i=[];for(const a of t)i.push(Po({commitment:a,to:n,version:r}));return i}const kn=6,ki=32,dn=4096,Ci=ki*dn,Cn=Ci*kn-1-1*dn*kn,Li=1;class Co extends Z{constructor({maxSize:t,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${t} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}}class Oi extends Z{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class Lo extends Z{constructor({hash:t,size:r}){super(`Versioned hash "${t}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}}class Oo extends Z{constructor({hash:t,version:r}){super(`Versioned hash "${t}" version is invalid.`,{metaMessages:[`Expected: ${Li}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}function Fo(e){const t=e.to??(typeof e.data=="string"?"hex":"bytes"),r=typeof e.data=="string"?st(e.data):e.data,n=xt(r);if(!n)throw new Oi;if(n>Cn)throw new Co({maxSize:Cn,size:n});const i=[];let a=!0,f=0;for(;a;){const u=Ei(new Uint8Array(Ci));let l=0;for(;l<dn;){const y=r.slice(f,f+(ki-1));if(u.pushByte(0),u.pushBytes(y),y.length<31){u.pushByte(128),a=!1;break}l++,f+=31}i.push(u)}return t==="bytes"?i.map(u=>u.bytes):i.map(u=>Ze(u.bytes))}function Uo(e){const{data:t,kzg:r,to:n}=e,i=e.blobs??Fo({data:t,to:n}),a=e.commitments??Ii({blobs:i,kzg:r,to:n}),f=e.proofs??Ai({blobs:i,commitments:a,kzg:r,to:n}),u=[];for(let l=0;l<i.length;l++)u.push({blob:i[l],commitment:a[l],proof:f[l]});return u}function Mo(e){if(!e||e.length===0)return[];const t=[];for(const r of e){const{contractAddress:n,chainId:i,nonce:a,...f}=r;t.push([q(i),n,a?q(a):"0x",...Vt({},f)])}return t}class at extends Z{constructor({address:t}){super(`Address "${t}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}class yr extends Z{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}class gr extends Z{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Jr(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:t,name:"FeeCapTooHighError"})}}Object.defineProperty(gr,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class Fi extends Z{constructor({cause:t,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${Jr(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${Jr(n)} gwei`:""}).`].join(`
4
- `),{cause:t,name:"TipAboveFeeCapError"})}}Object.defineProperty(Fi,"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 Ui 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 er=BigInt(2**32-1),Ln=BigInt(32);function No(e,t=!1){return t?{h:Number(e&er),l:Number(e>>Ln&er)}:{h:Number(e>>Ln&er)|0,l:Number(e&er)|0}}function Do(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:a,l:f}=No(e[i],t);[r[i],n[i]]=[a,f]}return[r,n]}const $o=(e,t,r)=>e<<r|t>>>32-r,Ho=(e,t,r)=>t<<r|e>>>32-r,zo=(e,t,r)=>t<<r-32|e>>>64-r,jo=(e,t,r)=>e<<r-32|t>>>64-r,Mi=[],Ni=[],Di=[],Go=BigInt(0),Ct=BigInt(1),qo=BigInt(2),Wo=BigInt(7),Vo=BigInt(256),Ko=BigInt(113);for(let e=0,t=Ct,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Mi.push(2*(5*n+r)),Ni.push((e+1)*(e+2)/2%64);let i=Go;for(let a=0;a<7;a++)t=(t<<Ct^(t>>Wo)*Ko)%Vo,t&qo&&(i^=Ct<<(Ct<<BigInt(a))-Ct);Di.push(i)}const[Yo,Jo]=Do(Di,!0),On=(e,t,r)=>r>32?zo(e,t,r):$o(e,t,r),Fn=(e,t,r)=>r>32?jo(e,t,r):Ho(e,t,r);function Xo(e,t=24){const r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let f=0;f<10;f++)r[f]=e[f]^e[f+10]^e[f+20]^e[f+30]^e[f+40];for(let f=0;f<10;f+=2){const u=(f+8)%10,l=(f+2)%10,y=r[l],g=r[l+1],w=On(y,g,1)^r[u],E=Fn(y,g,1)^r[u+1];for(let I=0;I<50;I+=10)e[f+I]^=w,e[f+I+1]^=E}let i=e[2],a=e[3];for(let f=0;f<24;f++){const u=Ni[f],l=On(i,a,u),y=Fn(i,a,u),g=Mi[f];i=e[g],a=e[g+1],e[g]=l,e[g+1]=y}for(let f=0;f<50;f+=10){for(let u=0;u<10;u++)r[u]=e[f+u];for(let u=0;u<10;u++)e[f+u]^=~r[(u+2)%10]&r[(u+4)%10]}e[0]^=Yo[n],e[1]^=Jo[n]}r.fill(0)}class pn extends Ti{constructor(t,r,n,i=!1,a=24){if(super(),this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=a,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Rn(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=wo(this.state)}keccak(){Tn||Pn(this.state32),Xo(this.state32,this.rounds),Tn||Pn(this.state32),this.posOut=0,this.pos=0}update(t){fr(this);const{blockLen:r,state:n}=this;t=hn(t);const i=t.length;for(let a=0;a<i;){const f=Math.min(r-this.pos,i-a);for(let u=0;u<f;u++)n[this.pos++]^=t[a++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:r,pos:n,blockLen:i}=this;t[n]^=r,r&128&&n===i-1&&this.keccak(),t[i-1]^=128,this.keccak()}writeInto(t){fr(this,!1),ln(t),this.finish();const r=this.state,{blockLen:n}=this;for(let i=0,a=t.length;i<a;){this.posOut>=n&&this.keccak();const f=Math.min(n-this.posOut,a-i);t.set(r.subarray(this.posOut,this.posOut+f),i),this.posOut+=f,i+=f}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return Rn(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(Ri(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(t){const{blockLen:r,suffix:n,outputLen:i,rounds:a,enableXOF:f}=this;return t||(t=new pn(r,n,i,f,a)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=a,t.suffix=n,t.outputLen=i,t.enableXOF=f,t.destroyed=this.destroyed,t}}const Qo=(e,t,r)=>Pi(()=>new pn(t,e,r)),Zo=Qo(1,136,256/8);function ea(e,t){return Zo(qt(e,{strict:!1})?_i(e):e)}const Cr=new Ui(8192);function ta(e,t){if(Cr.has(`${e}.${t}`))return Cr.get(`${e}.${t}`);const r=e.substring(2).toLowerCase(),n=ea(xi(r)),i=r.split("");for(let f=0;f<40;f+=2)n[f>>1]>>4>=8&&i[f]&&(i[f]=i[f].toUpperCase()),(n[f>>1]&15)>=8&&i[f+1]&&(i[f+1]=i[f+1].toUpperCase());const a=`0x${i.join("")}`;return Cr.set(`${e}.${t}`,a),a}const ra=/^0x[a-fA-F0-9]{40}$/,Lr=new Ui(8192);function ft(e,t){const{strict:r=!0}=t??{},n=`${e}.${r}`;if(Lr.has(n))return Lr.get(n);const i=ra.test(e)?e.toLowerCase()===e?!0:r?ta(e)===e:!0:!1;return Lr.set(n,i),i}function na(e,t,r,{strict:n}={}){return qt(e,{strict:!1})?sa(e,t,r,{strict:n}):ia(e,t,r,{strict:n})}function $i(e,t,r){if(xt(e)!==r-t)throw new zs({offset:r,position:"end",size:xt(e)})}function ia(e,t,r,{strict:n}={}){const i=e.slice(t,r);return n&&$i(i,t,r),i}function sa(e,t,r,{strict:n}={}){const i=`0x${e.replace("0x","").slice(t*2,r*2)}`;return n&&$i(i,t,r),i}function oa(e){const{authorizationList:t}=e;if(t)for(const r of t){const{contractAddress:n,chainId:i}=r;if(!ft(n))throw new at({address:n});if(i<=0)throw new yr({chainId:i})}bn(e)}function aa(e){const{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new Oi;for(const r of t){const n=xt(r),i=ar(na(r,0,1));if(n!==32)throw new Lo({hash:r,size:n});if(i!==Li)throw new Oo({hash:r,version:i})}}bn(e)}function bn(e){const{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:i}=e;if(t<=0)throw new yr({chainId:t});if(i&&!ft(i))throw new at({address:i});if(n&&n>cn)throw new gr({maxFeePerGas:n});if(r&&n&&r>n)throw new Fi({maxFeePerGas:n,maxPriorityFeePerGas:r})}function fa(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:a}=e;if(t<=0)throw new yr({chainId:t});if(a&&!ft(a))throw new at({address:a});if(r||i)throw new Z("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>cn)throw new gr({maxFeePerGas:n})}function ua(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:a}=e;if(a&&!ft(a))throw new at({address:a});if(typeof t<"u"&&t<=0)throw new yr({chainId:t});if(r||i)throw new Z("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>cn)throw new gr({maxFeePerGas:n})}function ca(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 yo({transaction:e})}function mr(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 a=0;a<i.length;a++)if(i[a].length-2!==64)throw new go({storageKey:i[a]});if(!ft(n,{strict:!1}))throw new at({address:n});t.push([n,i])}return t}function la(e,t){const r=ca(e);return r==="eip1559"?pa(e,t):r==="eip2930"?ba(e,t):r==="eip4844"?da(e,t):r==="eip7702"?ha(e,t):ya(e,t)}function ha(e,t){const{authorizationList:r,chainId:n,gas:i,nonce:a,to:f,value:u,maxFeePerGas:l,maxPriorityFeePerGas:y,accessList:g,data:w}=e;oa(e);const E=mr(g),I=Mo(r);return Wt(["0x04",ot([q(n),a?q(a):"0x",y?q(y):"0x",l?q(l):"0x",i?q(i):"0x",f??"0x",u?q(u):"0x",w??"0x",E,I,...Vt(e,t)])])}function da(e,t){const{chainId:r,gas:n,nonce:i,to:a,value:f,maxFeePerBlobGas:u,maxFeePerGas:l,maxPriorityFeePerGas:y,accessList:g,data:w}=e;aa(e);let E=e.blobVersionedHashes,I=e.sidecars;if(e.blobs&&(typeof E>"u"||typeof I>"u")){const O=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(S=>Ze(S)),L=e.kzg,U=Ii({blobs:O,kzg:L});if(typeof E>"u"&&(E=ko({commitments:U})),typeof I>"u"){const S=Ai({blobs:O,commitments:U,kzg:L});I=Uo({blobs:O,commitments:U,proofs:S})}}const v=mr(g),k=[q(r),i?q(i):"0x",y?q(y):"0x",l?q(l):"0x",n?q(n):"0x",a??"0x",f?q(f):"0x",w??"0x",v,u?q(u):"0x",E??[],...Vt(e,t)],T=[],C=[],F=[];if(I)for(let O=0;O<I.length;O++){const{blob:L,commitment:U,proof:S}=I[O];T.push(L),C.push(U),F.push(S)}return Wt(["0x03",ot(I?[k,T,C,F]:k)])}function pa(e,t){const{chainId:r,gas:n,nonce:i,to:a,value:f,maxFeePerGas:u,maxPriorityFeePerGas:l,accessList:y,data:g}=e;bn(e);const w=mr(y),E=[q(r),i?q(i):"0x",l?q(l):"0x",u?q(u):"0x",n?q(n):"0x",a??"0x",f?q(f):"0x",g??"0x",w,...Vt(e,t)];return Wt(["0x02",ot(E)])}function ba(e,t){const{chainId:r,gas:n,data:i,nonce:a,to:f,value:u,accessList:l,gasPrice:y}=e;fa(e);const g=mr(l),w=[q(r),a?q(a):"0x",y?q(y):"0x",n?q(n):"0x",f??"0x",u?q(u):"0x",i??"0x",g,...Vt(e,t)];return Wt(["0x01",ot(w)])}function ya(e,t){const{chainId:r=0,gas:n,data:i,nonce:a,to:f,value:u,gasPrice:l}=e;ua(e);let y=[a?q(a):"0x",l?q(l):"0x",n?q(n):"0x",f??"0x",u?q(u):"0x",i??"0x"];if(t){const g=(()=>{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 I=27n+(t.v===27n?0n:1n);if(t.v!==I)throw new bo({v:t.v});return I})(),w=or(t.r),E=or(t.s);y=[...y,q(g),w==="0x00"?"0x":w,E==="0x00"?"0x":E]}else r>0&&(y=[...y,q(r),"0x","0x"]);return ot(y)}function Vt(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 a=or(r.r),f=or(r.s);return[typeof i=="number"?i?q(1):"0x":n===0n?"0x":n===1n?q(1):n===27n?"0x":q(1),a==="0x00"?"0x":a,f==="0x00"?"0x":f]}const ga={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},ma={block:to({format(e){var r;return{transactions:(r=e.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const i=un(n);return i.typeHex==="0x7e"&&(i.isSystemTx=n.isSystemTx,i.mint=n.mint?gt(n.mint):void 0,i.sourceHash=n.sourceHash,i.type="deposit"),i}),stateRoot:e.stateRoot}}}),transaction:Qs({format(e){const t={};return e.type==="0x7e"&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?gt(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}}),transactionReceipt:so({format(e){return{l1GasPrice:e.l1GasPrice?gt(e.l1GasPrice):null,l1GasUsed:e.l1GasUsed?gt(e.l1GasUsed):null,l1Fee:e.l1Fee?gt(e.l1Fee):null,l1FeeScalar:e.l1FeeScalar?Number(e.l1FeeScalar):null}}})};function wa(e,t){return va(e)?xa(e):la(e,t)}const _a={transaction:wa};function xa(e){Ea(e);const{sourceHash:t,data:r,from:n,gas:i,isSystemTx:a,mint:f,to:u,value:l}=e,y=[t,n,u??"0x",f?q(f):"0x",l?q(l):"0x",i?q(i):"0x",a?"0x1":"0x",r??"0x"];return Wt(["0x7e",ot(y)])}function va(e){return e.type==="deposit"||typeof e.sourceHash<"u"}function Ea(e){const{from:t,to:r}=e;if(t&&!ft(t))throw new at({address:t});if(r&&!ft(r))throw new at({address:r})}const Un={contracts:ga,formatters:ma,serializers:_a},Ba=Gt({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io",apiUrl:"https://api.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:7654707}}}),Sa=Gt({id:421614,name:"Arbitrum Sepolia",nativeCurrency:{name:"Arbitrum Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://sepolia.arbiscan.io",apiUrl:"https://api-sepolia.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:81930}},testnet:!0}),Lt=11155111,Ia=Gt({...Un,id:84532,network:"base-sepolia",name:"Base Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://sepolia.basescan.org",apiUrl:"https://api-sepolia.basescan.org/api"}},contracts:{...Un.contracts,disputeGameFactory:{[Lt]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[Lt]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[Lt]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[Lt]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:Lt}),Aa=Gt({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://cloudflare-eth.com"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xce01f8eee7E479C928F8919abD53E553a36CeF67",blockCreated:19258213},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),Ra=Gt({id:11155111,name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc2.sepolia.org"]}},blockExplorers:{default:{name:"Etherscan",url:"https://sepolia.etherscan.io",apiUrl:"https://api-sepolia.etherscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:751532},ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xc8Af999e38273D658BE1b921b88A9Ddf005769cC",blockCreated:5317080}},testnet:!0});function Xr(e){return typeof e=="string"&&(e=Buffer.from(e,"hex")),e.length===32?e:e.subarray(1,33)}function bt(e,t){if(!e)throw new Error(t)}function Ta(e){return Buffer.concat([Uint8Array.from([192]),Pa(e)])}function Pa(e){const t=Sn.encodingLength(e.length),r=Buffer.allocUnsafe(t);return Sn.encode(e.length,r),Buffer.concat([r,e])}function ka(e,t){if(e.compare(t)>0){const r=e;e=t,t=r}return[e,t]}const Ot=e=>e.length===64?e:e.slice(2),Ca=e=>{if(!e)return!1;try{const t=Buffer.from(e,"hex");return _t.isPoint(t)}catch{return!1}},La={ethereum:Aa,ethereum_arbitrum:Ba,ethereum_sepolia:Ra,arbitrum_sepolia:Sa,ethereum_localnet:J.EthereumLocalnet,arbitrum_localnet:J.ArbitrumLocalnet,base_sepolia:Ia},Oa=async(e,t)=>{var n;const r=La[e];if(r)try{if(r.id===((n=t.chain)==null?void 0:n.id))return P.Ok({message:"Already on the network",walletClient:t});await t.switchChain({id:r.id});const i=He.createWalletClient({account:t.account,chain:r,transport:He.custom(window.ethereum)});return P.Ok({message:"Switched chain",walletClient:i})}catch(i){if(Fa(i))try{await t.addChain({chain:r});const a=He.createWalletClient({account:t.account,chain:r,transport:He.custom(window.ethereum)});return P.Ok({message:"Added network",walletClient:a})}catch{return P.Err("Failed to add network")}else return P.Err("Failed to switch network")}else return P.Err("Chain not supported")},Fa=e=>typeof e=="object"&&e!==null&&"code"in e&&e.code===4902,Hi=(e,t,r,n)=>e+":"+t.toLowerCase()+"::"+r+":"+n.toLowerCase();var ne=(e=>(e.Created="Created",e.Matched="Matched",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.CounterPartyInitiateDetected="CounterPartyInitiateDetected",e.CounterPartyInitiated="CounterPartyInitiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.CounterPartyRedeemDetected="CounterPartyRedeemDetected",e.CounterPartyRedeemed="CounterPartyRedeemed",e.Completed="Completed",e.CounterPartySwapExpired="CounterPartySwapExpired",e.Expired="Expired",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.CounterPartyRefundDetected="CounterPartyRefundDetected",e.CounterPartyRefunded="CounterPartyRefunded",e.Cancelled="Cancelled",e.DeadLineExceeded="DeadLineExceeded",e))(ne||{}),Q=(e=>(e.Idle="Idle",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.Expired="Expired",e))(Q||{});const zi=(e,t,r)=>{const n=ur(e.source_swap,t),i=ur(e.destination_swap,r);if(n===Q.Redeemed)return ne.CounterPartyRedeemed;if(n===Q.RedeemDetected)return ne.CounterPartyRedeemDetected;if(i===Q.Redeemed)return ne.Redeemed;if(i===Q.RedeemDetected)return ne.RedeemDetected;if(n===Q.Refunded)return ne.Refunded;if(n===Q.RefundDetected)return ne.RefundDetected;if(i===Q.Refunded)return ne.CounterPartyRefunded;if(i===Q.RefundDetected)return ne.CounterPartyRefundDetected;if(i===Q.Expired)return ne.CounterPartySwapExpired;if(n===Q.Expired)return ne.Expired;const a=Number(e.create_order.additional_data.deadline);return i===Q.Initiated?ne.CounterPartyInitiated:i===Q.InitiateDetected?ne.CounterPartyInitiateDetected:Mn(a,12)?ne.DeadLineExceeded:n===Q.Initiated?ne.Initiated:Mn(a,1)?ne.DeadLineExceeded:n===Q.InitiateDetected?ne.InitiateDetected:ne.Matched},ur=(e,t)=>{if(e.redeem_tx_hash)return Number(e.redeem_block_number)?Q.Redeemed:Q.RedeemDetected;if(e.refund_tx_hash)return Number(e.refund_block_number)?Q.Refunded:Q.RefundDetected;if(Number(e.initiate_block_number)){const r=Number(e.initiate_block_number)+e.timelock;if(t>r)return Q.Expired}return e.initiate_tx_hash?Number(e.initiate_block_number)?Q.Initiated:Q.InitiateDetected:Q.Idle},ji=(e,t,r)=>{switch(zi(e,t,r)){case ne.Matched:return ce.Initiate;case ne.CounterPartyInitiated:case ne.CounterPartyInitiateDetected:return ce.Redeem;case ne.Expired:return ce.Refund;default:return ce.Idle}},Mn=(e,t=0)=>{const r=Date.now(),n=e*1e3+t*36e5;return r>=n},Ua=[{inputs:[{internalType:"address",name:"token_",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InvalidShortString",type:"error"},{inputs:[{internalType:"string",name:"str",type:"string"}],name:"StringTooLong",type:"error"},{anonymous:!1,inputs:[],name:"EIP712DomainChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Initiated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"secret",type:"bytes"}],name:"Redeemed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"Refunded",type:"event"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"}],name:"initiate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"initiateWithSignature",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"instantRefund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"expiry",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],internalType:"struct HTLC.InitWithSig[]",name:"inits",type:"tuple[]"},{components:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],internalType:"struct HTLC.Redeem[]",name:"redeems",type:"tuple[]"},{components:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],internalType:"struct HTLC.Refund[]",name:"refunds",type:"tuple[]"}],name:"multicall",outputs:[{internalType:"bool[]",name:"results",type:"bool[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"orders",outputs:[{internalType:"bool",name:"isFulfilled",type:"bool"},{internalType:"address",name:"initiator",type:"address"},{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"initiatedAt",type:"uint256"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],name:"redeem",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"refund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"token",outputs:[{internalType:"contract IERC20",name:"",type:"address"}],stateMutability:"view",type:"function"}];class Gi{constructor(t,r,n){this.url=new ge.Url("/relayer",r),this.auth=n,this.order=t}async init(t,r){if(!t.account)return P.Err("No account found");if(t.account.address.toLowerCase()!==this.order.source_swap.initiator.toLowerCase())return P.Err("Account address and order initiator mismatch");if(!r){const g=await ge.fetchEVMBlockNumber(t);if(g.error)return P.Err(g.error);r=g.val}if(ur(this.order.source_swap,r)!==Q.Idle)return P.Err("Invalid swap status");const{create_order:i,source_swap:a}=this.order;if(!a.amount||!a.redeemer||!i.timelock||!i.secret_hash)return P.Err("Invalid order");const f=ge.with0x(i.secret_hash),u=BigInt(i.timelock),l=ge.with0x(a.redeemer),y=BigInt(a.amount);try{const g=await this.auth.getToken();if(g.error)return P.Err(g.error);const w=He.getContract({address:ge.with0x(this.order.source_swap.asset),abi:Ua,client:t}),E=await w.read.token(),I=await ge.checkAllowanceAndApprove(Number(y),E,this.order.source_swap.asset,t);if(I.error)return P.Err(I.error);const v=await w.read.eip712Domain(),k=await t.signTypedData({account:t.account,domain:{name:v[1],version:v[2],chainId:Number(v[3]),verifyingContract:v[4]},types:{Initiate:[{name:"redeemer",type:"address"},{name:"timelock",type:"uint256"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"}]},primaryType:"Initiate",message:{redeemer:l,timelock:u,amount:y,secretHash:f}}),T=await P.Fetcher.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:i.create_id,signature:k,perform_on:"Source"}),headers:{Authorization:ge.Authorization(g.val),"Content-Type":"application/json"}});return T.error?P.Err(T.error):T.result?P.Ok(T.result):P.Err("Init: No result found")}catch(g){return console.log("init error :",g),P.Err(String(g))}}async redeem(t,r){try{const n=await this.auth.getToken();if(n.error)return P.Err(n.error);const i=await P.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t,secret:P.trim0x(r),perform_on:"Destination"}),headers:{Authorization:ge.Authorization(n.val),"Content-Type":"application/json"}});return i.error?P.Err(i.error):i.result?P.Ok(i.result):P.Err("Redeem: No result found")}catch(n){return P.Err(String(n))}}}const Ma=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),Na=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),Da=Buffer.concat([Ma,Na]),$a=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),Nn={failedToCreateInternalPubkey:"failed to create internal pubkey",failedToTweakPubkey:"failed to tweak pubkey"};function Ha(){const e=bi.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),t=_t.pointMultiply(Buffer.concat([Buffer.from("04","hex"),Da]),e);if(!t)throw new Error(Nn.failedToCreateInternalPubkey);const r=_t.pointAdd($a,t);if(!r)throw new Error(Nn.failedToCreateInternalPubkey);return Xr(Buffer.from(r))}const we={secretMismatch:"invalid secret",secretHashLenMismatch:"secret hash should be 32 bytes",pubkeyLenMismatch:"pubkey should be 32 bytes",zeroOrNegativeExpiry:"expiry should be greater than 0",htlcAddressGenerationFailed:"failed to generate htlc address",notFunded:"address not funded",noCounterpartySigs:"counterparty signatures are required",counterPartySigNotFound:e=>"counterparty signature not found for utxo "+e,invalidCounterpartySigForUTXO:e=>"invalid counterparty signature for utxo "+e,htlcNotExpired:e=>`HTLC not expired, need more ${e} blocks`,controlBlockGenerationFailed:"failed to generate control block",invalidLeaf:"invalid leaf"},tr=192;ye.initEccLib(_t);class cr{constructor(t,r,n,i,a,f,u,l){this.secretHash=n,this.redeemerPubkey=i,this.initiatorPubkey=a,this.expiry=f,this.signer=t,this.network=u,this.internalPubkey=Ha(),this.initiateAmount=r,this.utxoHashes=l}static async from(t,r,n,i,a,f,u){n=n.startsWith("0x")?n.slice(2):n,bt(n.length===64,we.secretHashLenMismatch),bt(i.length===64||i.length===66,`initiator ${we.pubkeyLenMismatch}`),bt(a.length===64||a.length===66,`redeemer ${we.pubkeyLenMismatch}`),bt(f>0,we.zeroOrNegativeExpiry);const l=await t.getNetwork();return new cr(t,r,n,Xr(a).toString("hex"),Xr(i).toString("hex"),f,l,u)}address(){const{address:t}=ye.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves()});if(!t)throw new Error(we.htlcAddressGenerationFailed);return t}id(){return this.address()}async _buildRawTx(t,r){const n=new ye.Transaction;n.version=2;const i=this.address(),a=await this.signer.getProvider();let f=[];if(this.utxoHashes&&this.utxoHashes.length>0)for(const l of this.utxoHashes){const y=await a.getTransaction(l);for(let g=0;g<y.vout.length;g++){const w=y.vout[g];w.scriptpubkey_address===i&&f.push({txid:y.txid,vout:g,value:w.value,status:{confirmed:!1}})}}else f=await a.getUTXOs(i);const u=f.reduce((l,y)=>l+y.value,0);if(u===0)throw new Error(`${i} ${we.notFunded}`);for(let l=0;l<f.length;l++)n.addInput(Buffer.from(f[l].txid,"hex").reverse(),f[l].vout);return r??(r=await a.suggestFee(i,u,Bn.Urgency.MEDIUM)),n.addOutput(ye.address.toOutputScript(t,this.network),u-r),{tx:n,usedUtxos:f}}async buildRawTx(t){return await this._buildRawTx(await this.signer.getAddress(),t)}getOutputScript(){return ye.address.toOutputScript(this.address(),this.network)}async init(t){return t??(t=await(await this.signer.getProvider()).suggestFee(await this.signer.getAddress(),this.initiateAmount,Bn.Urgency.MEDIUM)),await this.signer.send(this.address(),this.initiateAmount,t)}async instantRefund(t,r){bt(t.length>0,we.noCounterpartySigs);const{tx:n,usedUtxos:i}=await this.buildRawTx(r);for(const w of i)if(!t.find(E=>E.utxo===w.txid))throw new Error(we.counterPartySigNotFound(w.txid));const a=this.getOutputScript(),f=ye.Transaction.SIGHASH_DEFAULT,u=this.leafHash(2),l=i.map(w=>w.value),y=Or(a,i.length);for(let w=0;w<n.ins.length;w++){const E=n.hashForWitnessV1(w,y,l,f,u);if(!_t.verifySchnorr(E,Buffer.from(this.redeemerPubkey,"hex"),Buffer.from(t[w].sig,"hex")))throw new Error(we.invalidCounterpartySigForUTXO(t[w].utxo));const I=await this.signer.signSchnorr(E),v=Buffer.from(n.ins[w].hash).reverse().toString("hex"),k=t.find(T=>T.utxo===v);if(!k)throw new Error(we.counterPartySigNotFound(v));n.setWitness(w,[Buffer.from(k.sig,"hex"),I,this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async redeem(t,r,n){bt(ye.crypto.sha256(Buffer.from(t,"hex")).toString("hex")===this.secretHash,we.secretMismatch);const{tx:i,usedUtxos:a}=await this._buildRawTx(r??await this.signer.getAddress(),n),f=this.leafHash(1),u=a.map(w=>w.value),l=Or(this.getOutputScript(),a.length),y=ye.Transaction.SIGHASH_DEFAULT;for(let w=0;w<i.ins.length;w++){const E=i.hashForWitnessV1(w,l,u,y,f),I=await this.signer.signSchnorr(E);i.setWitness(w,[I,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return await(await this.signer.getProvider()).broadcast(i.toHex())}async refund(t,r){const{tx:n,usedUtxos:i}=await this._buildRawTx(t??await this.signer.getAddress(),r),[a,f]=await this.canRefund(i);if(!a)throw new Error(we.htlcNotExpired(f));const u=this.leafHash(0),l=i.map(E=>E.value),y=Or(this.getOutputScript(),i.length),g=ye.Transaction.SIGHASH_DEFAULT;for(let E=0;E<n.ins.length;E++){n.ins[E].sequence=this.expiry;const I=n.hashForWitnessV1(E,y,l,g,u),v=await this.signer.signSchnorr(I);n.setWitness(E,[v,this.refundLeaf(),this.generateControlBlockFor(0)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async canRefund(t){const n=await(await this.signer.getProvider()).getLatestTip();for(const i of t){let a=0;if(i.status.confirmed&&i.status.block_height+this.expiry>n?a=i.status.block_height+this.expiry-n+1:i.status.confirmed||(a=this.expiry+1),a>0)return[!1,a]}return[!0,0]}generateControlBlockFor(t){let r;switch(t){case 1:r=this.redeemLeaf();break;case 0:r=this.refundLeaf();break;case 2:r=this.instantRefundLeaf();break;default:throw new Error(we.invalidLeaf)}const n=ye.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves(),redeem:{output:r,redeemVersion:tr}});if(!n.witness)throw new Error(we.controlBlockGenerationFailed);return n.witness[n.witness.length-1]}leafHash(t){let r=this.redeemLeaf();return t===0&&(r=this.refundLeaf()),t===2&&(r=this.instantRefundLeaf()),ye.crypto.taggedHash("TapLeaf",Ta(r))}refundLeaf(){return ye.script.fromASM(`
4
+ `),{cause:t,name:"TipAboveFeeCapError"})}}Object.defineProperty(Fi,"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 Ui 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 er=BigInt(2**32-1),Ln=BigInt(32);function No(e,t=!1){return t?{h:Number(e&er),l:Number(e>>Ln&er)}:{h:Number(e>>Ln&er)|0,l:Number(e&er)|0}}function Do(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:a,l:f}=No(e[i],t);[r[i],n[i]]=[a,f]}return[r,n]}const $o=(e,t,r)=>e<<r|t>>>32-r,Ho=(e,t,r)=>t<<r|e>>>32-r,zo=(e,t,r)=>t<<r-32|e>>>64-r,jo=(e,t,r)=>e<<r-32|t>>>64-r,Mi=[],Ni=[],Di=[],Go=BigInt(0),Ct=BigInt(1),qo=BigInt(2),Wo=BigInt(7),Vo=BigInt(256),Ko=BigInt(113);for(let e=0,t=Ct,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Mi.push(2*(5*n+r)),Ni.push((e+1)*(e+2)/2%64);let i=Go;for(let a=0;a<7;a++)t=(t<<Ct^(t>>Wo)*Ko)%Vo,t&qo&&(i^=Ct<<(Ct<<BigInt(a))-Ct);Di.push(i)}const[Yo,Jo]=Do(Di,!0),On=(e,t,r)=>r>32?zo(e,t,r):$o(e,t,r),Fn=(e,t,r)=>r>32?jo(e,t,r):Ho(e,t,r);function Xo(e,t=24){const r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let f=0;f<10;f++)r[f]=e[f]^e[f+10]^e[f+20]^e[f+30]^e[f+40];for(let f=0;f<10;f+=2){const u=(f+8)%10,l=(f+2)%10,y=r[l],g=r[l+1],w=On(y,g,1)^r[u],E=Fn(y,g,1)^r[u+1];for(let I=0;I<50;I+=10)e[f+I]^=w,e[f+I+1]^=E}let i=e[2],a=e[3];for(let f=0;f<24;f++){const u=Ni[f],l=On(i,a,u),y=Fn(i,a,u),g=Mi[f];i=e[g],a=e[g+1],e[g]=l,e[g+1]=y}for(let f=0;f<50;f+=10){for(let u=0;u<10;u++)r[u]=e[f+u];for(let u=0;u<10;u++)e[f+u]^=~r[(u+2)%10]&r[(u+4)%10]}e[0]^=Yo[n],e[1]^=Jo[n]}r.fill(0)}class pn extends Ti{constructor(t,r,n,i=!1,a=24){if(super(),this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=a,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Rn(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=wo(this.state)}keccak(){Tn||Pn(this.state32),Xo(this.state32,this.rounds),Tn||Pn(this.state32),this.posOut=0,this.pos=0}update(t){fr(this);const{blockLen:r,state:n}=this;t=hn(t);const i=t.length;for(let a=0;a<i;){const f=Math.min(r-this.pos,i-a);for(let u=0;u<f;u++)n[this.pos++]^=t[a++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:r,pos:n,blockLen:i}=this;t[n]^=r,r&128&&n===i-1&&this.keccak(),t[i-1]^=128,this.keccak()}writeInto(t){fr(this,!1),ln(t),this.finish();const r=this.state,{blockLen:n}=this;for(let i=0,a=t.length;i<a;){this.posOut>=n&&this.keccak();const f=Math.min(n-this.posOut,a-i);t.set(r.subarray(this.posOut,this.posOut+f),i),this.posOut+=f,i+=f}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return Rn(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(Ri(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(t){const{blockLen:r,suffix:n,outputLen:i,rounds:a,enableXOF:f}=this;return t||(t=new pn(r,n,i,f,a)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=a,t.suffix=n,t.outputLen=i,t.enableXOF=f,t.destroyed=this.destroyed,t}}const Qo=(e,t,r)=>Pi(()=>new pn(t,e,r)),Zo=Qo(1,136,256/8);function ea(e,t){return Zo(qt(e,{strict:!1})?_i(e):e)}const Cr=new Ui(8192);function ta(e,t){if(Cr.has(`${e}.${t}`))return Cr.get(`${e}.${t}`);const r=e.substring(2).toLowerCase(),n=ea(xi(r)),i=r.split("");for(let f=0;f<40;f+=2)n[f>>1]>>4>=8&&i[f]&&(i[f]=i[f].toUpperCase()),(n[f>>1]&15)>=8&&i[f+1]&&(i[f+1]=i[f+1].toUpperCase());const a=`0x${i.join("")}`;return Cr.set(`${e}.${t}`,a),a}const ra=/^0x[a-fA-F0-9]{40}$/,Lr=new Ui(8192);function ft(e,t){const{strict:r=!0}=t??{},n=`${e}.${r}`;if(Lr.has(n))return Lr.get(n);const i=ra.test(e)?e.toLowerCase()===e?!0:r?ta(e)===e:!0:!1;return Lr.set(n,i),i}function na(e,t,r,{strict:n}={}){return qt(e,{strict:!1})?sa(e,t,r,{strict:n}):ia(e,t,r,{strict:n})}function $i(e,t,r){if(xt(e)!==r-t)throw new zs({offset:r,position:"end",size:xt(e)})}function ia(e,t,r,{strict:n}={}){const i=e.slice(t,r);return n&&$i(i,t,r),i}function sa(e,t,r,{strict:n}={}){const i=`0x${e.replace("0x","").slice(t*2,r*2)}`;return n&&$i(i,t,r),i}function oa(e){const{authorizationList:t}=e;if(t)for(const r of t){const{contractAddress:n,chainId:i}=r;if(!ft(n))throw new at({address:n});if(i<=0)throw new yr({chainId:i})}bn(e)}function aa(e){const{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new Oi;for(const r of t){const n=xt(r),i=ar(na(r,0,1));if(n!==32)throw new Lo({hash:r,size:n});if(i!==Li)throw new Oo({hash:r,version:i})}}bn(e)}function bn(e){const{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:i}=e;if(t<=0)throw new yr({chainId:t});if(i&&!ft(i))throw new at({address:i});if(n&&n>cn)throw new gr({maxFeePerGas:n});if(r&&n&&r>n)throw new Fi({maxFeePerGas:n,maxPriorityFeePerGas:r})}function fa(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:a}=e;if(t<=0)throw new yr({chainId:t});if(a&&!ft(a))throw new at({address:a});if(r||i)throw new Z("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>cn)throw new gr({maxFeePerGas:n})}function ua(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:a}=e;if(a&&!ft(a))throw new at({address:a});if(typeof t<"u"&&t<=0)throw new yr({chainId:t});if(r||i)throw new Z("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>cn)throw new gr({maxFeePerGas:n})}function ca(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 yo({transaction:e})}function mr(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 a=0;a<i.length;a++)if(i[a].length-2!==64)throw new go({storageKey:i[a]});if(!ft(n,{strict:!1}))throw new at({address:n});t.push([n,i])}return t}function la(e,t){const r=ca(e);return r==="eip1559"?pa(e,t):r==="eip2930"?ba(e,t):r==="eip4844"?da(e,t):r==="eip7702"?ha(e,t):ya(e,t)}function ha(e,t){const{authorizationList:r,chainId:n,gas:i,nonce:a,to:f,value:u,maxFeePerGas:l,maxPriorityFeePerGas:y,accessList:g,data:w}=e;oa(e);const E=mr(g),I=Mo(r);return Wt(["0x04",ot([q(n),a?q(a):"0x",y?q(y):"0x",l?q(l):"0x",i?q(i):"0x",f??"0x",u?q(u):"0x",w??"0x",E,I,...Vt(e,t)])])}function da(e,t){const{chainId:r,gas:n,nonce:i,to:a,value:f,maxFeePerBlobGas:u,maxFeePerGas:l,maxPriorityFeePerGas:y,accessList:g,data:w}=e;aa(e);let E=e.blobVersionedHashes,I=e.sidecars;if(e.blobs&&(typeof E>"u"||typeof I>"u")){const O=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(S=>Ze(S)),L=e.kzg,U=Ii({blobs:O,kzg:L});if(typeof E>"u"&&(E=ko({commitments:U})),typeof I>"u"){const S=Ai({blobs:O,commitments:U,kzg:L});I=Uo({blobs:O,commitments:U,proofs:S})}}const v=mr(g),k=[q(r),i?q(i):"0x",y?q(y):"0x",l?q(l):"0x",n?q(n):"0x",a??"0x",f?q(f):"0x",w??"0x",v,u?q(u):"0x",E??[],...Vt(e,t)],T=[],C=[],F=[];if(I)for(let O=0;O<I.length;O++){const{blob:L,commitment:U,proof:S}=I[O];T.push(L),C.push(U),F.push(S)}return Wt(["0x03",ot(I?[k,T,C,F]:k)])}function pa(e,t){const{chainId:r,gas:n,nonce:i,to:a,value:f,maxFeePerGas:u,maxPriorityFeePerGas:l,accessList:y,data:g}=e;bn(e);const w=mr(y),E=[q(r),i?q(i):"0x",l?q(l):"0x",u?q(u):"0x",n?q(n):"0x",a??"0x",f?q(f):"0x",g??"0x",w,...Vt(e,t)];return Wt(["0x02",ot(E)])}function ba(e,t){const{chainId:r,gas:n,data:i,nonce:a,to:f,value:u,accessList:l,gasPrice:y}=e;fa(e);const g=mr(l),w=[q(r),a?q(a):"0x",y?q(y):"0x",n?q(n):"0x",f??"0x",u?q(u):"0x",i??"0x",g,...Vt(e,t)];return Wt(["0x01",ot(w)])}function ya(e,t){const{chainId:r=0,gas:n,data:i,nonce:a,to:f,value:u,gasPrice:l}=e;ua(e);let y=[a?q(a):"0x",l?q(l):"0x",n?q(n):"0x",f??"0x",u?q(u):"0x",i??"0x"];if(t){const g=(()=>{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 I=27n+(t.v===27n?0n:1n);if(t.v!==I)throw new bo({v:t.v});return I})(),w=or(t.r),E=or(t.s);y=[...y,q(g),w==="0x00"?"0x":w,E==="0x00"?"0x":E]}else r>0&&(y=[...y,q(r),"0x","0x"]);return ot(y)}function Vt(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 a=or(r.r),f=or(r.s);return[typeof i=="number"?i?q(1):"0x":n===0n?"0x":n===1n?q(1):n===27n?"0x":q(1),a==="0x00"?"0x":a,f==="0x00"?"0x":f]}const ga={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},ma={block:to({format(e){var r;return{transactions:(r=e.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const i=un(n);return i.typeHex==="0x7e"&&(i.isSystemTx=n.isSystemTx,i.mint=n.mint?gt(n.mint):void 0,i.sourceHash=n.sourceHash,i.type="deposit"),i}),stateRoot:e.stateRoot}}}),transaction:Qs({format(e){const t={};return e.type==="0x7e"&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?gt(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}}),transactionReceipt:so({format(e){return{l1GasPrice:e.l1GasPrice?gt(e.l1GasPrice):null,l1GasUsed:e.l1GasUsed?gt(e.l1GasUsed):null,l1Fee:e.l1Fee?gt(e.l1Fee):null,l1FeeScalar:e.l1FeeScalar?Number(e.l1FeeScalar):null}}})};function wa(e,t){return va(e)?xa(e):la(e,t)}const _a={transaction:wa};function xa(e){Ea(e);const{sourceHash:t,data:r,from:n,gas:i,isSystemTx:a,mint:f,to:u,value:l}=e,y=[t,n,u??"0x",f?q(f):"0x",l?q(l):"0x",i?q(i):"0x",a?"0x1":"0x",r??"0x"];return Wt(["0x7e",ot(y)])}function va(e){return e.type==="deposit"||typeof e.sourceHash<"u"}function Ea(e){const{from:t,to:r}=e;if(t&&!ft(t))throw new at({address:t});if(r&&!ft(r))throw new at({address:r})}const Un={contracts:ga,formatters:ma,serializers:_a},Ba=Gt({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io",apiUrl:"https://api.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:7654707}}}),Sa=Gt({id:421614,name:"Arbitrum Sepolia",nativeCurrency:{name:"Arbitrum Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://sepolia.arbiscan.io",apiUrl:"https://api-sepolia.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:81930}},testnet:!0}),Lt=11155111,Ia=Gt({...Un,id:84532,network:"base-sepolia",name:"Base Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://sepolia.basescan.org",apiUrl:"https://api-sepolia.basescan.org/api"}},contracts:{...Un.contracts,disputeGameFactory:{[Lt]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[Lt]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[Lt]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[Lt]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:Lt}),Aa=Gt({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://cloudflare-eth.com"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xce01f8eee7E479C928F8919abD53E553a36CeF67",blockCreated:19258213},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),Ra=Gt({id:11155111,name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc2.sepolia.org"]}},blockExplorers:{default:{name:"Etherscan",url:"https://sepolia.etherscan.io",apiUrl:"https://api-sepolia.etherscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:751532},ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xc8Af999e38273D658BE1b921b88A9Ddf005769cC",blockCreated:5317080}},testnet:!0});function Xr(e){return typeof e=="string"&&(e=Buffer.from(e,"hex")),e.length===32?e:e.subarray(1,33)}function bt(e,t){if(!e)throw new Error(t)}function Ta(e){return Buffer.concat([Uint8Array.from([192]),Pa(e)])}function Pa(e){const t=Sn.encodingLength(e.length),r=Buffer.allocUnsafe(t);return Sn.encode(e.length,r),Buffer.concat([r,e])}function ka(e,t){if(e.compare(t)>0){const r=e;e=t,t=r}return[e,t]}const Ot=e=>e.length===64?e:e.slice(2),Ca=e=>{if(!e)return!1;try{const t=Buffer.from(e,"hex");return _t.isPoint(t)}catch{return!1}},La={ethereum:Aa,ethereum_arbitrum:Ba,ethereum_sepolia:Ra,arbitrum_sepolia:Sa,ethereum_localnet:J.EthereumLocalnet,arbitrum_localnet:J.ArbitrumLocalnet,base_sepolia:Ia},Oa=async(e,t)=>{var n;const r=La[e];if(r)try{if(r.id===((n=t.chain)==null?void 0:n.id))return P.Ok({message:"Already on the network",walletClient:t});await t.switchChain({id:r.id});const i=He.createWalletClient({account:t.account,chain:r,transport:He.custom(window.ethereum)});return P.Ok({message:"Switched chain",walletClient:i})}catch(i){if(Fa(i))try{await t.addChain({chain:r});const a=He.createWalletClient({account:t.account,chain:r,transport:He.custom(window.ethereum)});return P.Ok({message:"Added network",walletClient:a})}catch{return P.Err("Failed to add network")}else return P.Err("Failed to switch network")}else return P.Err("Chain not supported")},Fa=e=>typeof e=="object"&&e!==null&&"code"in e&&e.code===4902,Hi=(e,t,r,n)=>e+":"+t.toLowerCase()+"::"+r+":"+n.toLowerCase();var ne=(e=>(e.Created="Created",e.Matched="Matched",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.CounterPartyInitiateDetected="CounterPartyInitiateDetected",e.CounterPartyInitiated="CounterPartyInitiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.CounterPartyRedeemDetected="CounterPartyRedeemDetected",e.CounterPartyRedeemed="CounterPartyRedeemed",e.Completed="Completed",e.CounterPartySwapExpired="CounterPartySwapExpired",e.Expired="Expired",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.CounterPartyRefundDetected="CounterPartyRefundDetected",e.CounterPartyRefunded="CounterPartyRefunded",e.Cancelled="Cancelled",e.DeadLineExceeded="DeadLineExceeded",e))(ne||{}),Q=(e=>(e.Idle="Idle",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.Expired="Expired",e))(Q||{});const zi=(e,t,r)=>{const n=ur(e.source_swap,t),i=ur(e.destination_swap,r);if(n===Q.Redeemed)return ne.CounterPartyRedeemed;if(n===Q.RedeemDetected)return ne.CounterPartyRedeemDetected;if(i===Q.Redeemed)return ne.Redeemed;if(i===Q.RedeemDetected)return ne.RedeemDetected;if(n===Q.Refunded)return ne.Refunded;if(n===Q.RefundDetected)return ne.RefundDetected;if(i===Q.Refunded)return ne.CounterPartyRefunded;if(i===Q.RefundDetected)return ne.CounterPartyRefundDetected;if(i===Q.Expired)return ne.CounterPartySwapExpired;if(n===Q.Expired)return ne.Expired;const a=Number(e.create_order.additional_data.deadline);return i===Q.Initiated?ne.CounterPartyInitiated:i===Q.InitiateDetected?ne.CounterPartyInitiateDetected:Mn(a,12)?ne.DeadLineExceeded:n===Q.Initiated?ne.Initiated:Mn(a,1)?ne.DeadLineExceeded:n===Q.InitiateDetected?ne.InitiateDetected:ne.Matched},ur=(e,t)=>{if(e.redeem_tx_hash)return Number(e.redeem_block_number)?Q.Redeemed:Q.RedeemDetected;if(e.refund_tx_hash)return Number(e.refund_block_number)?Q.Refunded:Q.RefundDetected;if(Number(e.initiate_block_number)){const r=Number(e.initiate_block_number)+e.timelock;if(t>r)return Q.Expired}return e.initiate_tx_hash?Number(e.initiate_block_number)?Q.Initiated:Q.InitiateDetected:Q.Idle},ji=(e,t,r)=>{switch(zi(e,t,r)){case ne.Matched:return ce.Initiate;case ne.CounterPartyInitiated:case ne.CounterPartyInitiateDetected:case ne.RedeemDetected:return ce.Redeem;case ne.Expired:return ce.Refund;default:return ce.Idle}},Mn=(e,t=0)=>{const r=Date.now(),n=e*1e3+t*36e5;return r>=n},Ua=[{inputs:[{internalType:"address",name:"token_",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InvalidShortString",type:"error"},{inputs:[{internalType:"string",name:"str",type:"string"}],name:"StringTooLong",type:"error"},{anonymous:!1,inputs:[],name:"EIP712DomainChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Initiated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"secret",type:"bytes"}],name:"Redeemed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"Refunded",type:"event"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"}],name:"initiate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"initiateWithSignature",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"instantRefund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"expiry",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],internalType:"struct HTLC.InitWithSig[]",name:"inits",type:"tuple[]"},{components:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],internalType:"struct HTLC.Redeem[]",name:"redeems",type:"tuple[]"},{components:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],internalType:"struct HTLC.Refund[]",name:"refunds",type:"tuple[]"}],name:"multicall",outputs:[{internalType:"bool[]",name:"results",type:"bool[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"orders",outputs:[{internalType:"bool",name:"isFulfilled",type:"bool"},{internalType:"address",name:"initiator",type:"address"},{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"initiatedAt",type:"uint256"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],name:"redeem",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"refund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"token",outputs:[{internalType:"contract IERC20",name:"",type:"address"}],stateMutability:"view",type:"function"}];class Gi{constructor(t,r,n){this.url=new ge.Url("/relayer",r),this.auth=n,this.order=t}async init(t,r){if(!t.account)return P.Err("No account found");if(t.account.address.toLowerCase()!==this.order.source_swap.initiator.toLowerCase())return P.Err("Account address and order initiator mismatch");if(!r){const g=await ge.fetchEVMBlockNumber(t);if(g.error)return P.Err(g.error);r=g.val}if(ur(this.order.source_swap,r)!==Q.Idle)return P.Err("Invalid swap status");const{create_order:i,source_swap:a}=this.order;if(!a.amount||!a.redeemer||!i.timelock||!i.secret_hash)return P.Err("Invalid order");const f=ge.with0x(i.secret_hash),u=BigInt(i.timelock),l=ge.with0x(a.redeemer),y=BigInt(a.amount);try{const g=await this.auth.getToken();if(g.error)return P.Err(g.error);const w=He.getContract({address:ge.with0x(this.order.source_swap.asset),abi:Ua,client:t}),E=await w.read.token(),I=await ge.checkAllowanceAndApprove(Number(y),E,this.order.source_swap.asset,t);if(I.error)return P.Err(I.error);const v=await w.read.eip712Domain(),k=await t.signTypedData({account:t.account,domain:{name:v[1],version:v[2],chainId:Number(v[3]),verifyingContract:v[4]},types:{Initiate:[{name:"redeemer",type:"address"},{name:"timelock",type:"uint256"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"}]},primaryType:"Initiate",message:{redeemer:l,timelock:u,amount:y,secretHash:f}}),T=await P.Fetcher.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:i.create_id,signature:k,perform_on:"Source"}),headers:{Authorization:ge.Authorization(g.val),"Content-Type":"application/json"}});return T.error?P.Err(T.error):T.result?P.Ok(T.result):P.Err("Init: No result found")}catch(g){return console.log("init error :",g),P.Err(String(g))}}async redeem(t,r){try{const n=await this.auth.getToken();if(n.error)return P.Err(n.error);const i=await P.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t,secret:P.trim0x(r),perform_on:"Destination"}),headers:{Authorization:ge.Authorization(n.val),"Content-Type":"application/json"}});return i.error?P.Err(i.error):i.result?P.Ok(i.result):P.Err("Redeem: No result found")}catch(n){return P.Err(String(n))}}}const Ma=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),Na=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),Da=Buffer.concat([Ma,Na]),$a=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),Nn={failedToCreateInternalPubkey:"failed to create internal pubkey",failedToTweakPubkey:"failed to tweak pubkey"};function Ha(){const e=bi.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),t=_t.pointMultiply(Buffer.concat([Buffer.from("04","hex"),Da]),e);if(!t)throw new Error(Nn.failedToCreateInternalPubkey);const r=_t.pointAdd($a,t);if(!r)throw new Error(Nn.failedToCreateInternalPubkey);return Xr(Buffer.from(r))}const we={secretMismatch:"invalid secret",secretHashLenMismatch:"secret hash should be 32 bytes",pubkeyLenMismatch:"pubkey should be 32 bytes",zeroOrNegativeExpiry:"expiry should be greater than 0",htlcAddressGenerationFailed:"failed to generate htlc address",notFunded:"address not funded",noCounterpartySigs:"counterparty signatures are required",counterPartySigNotFound:e=>"counterparty signature not found for utxo "+e,invalidCounterpartySigForUTXO:e=>"invalid counterparty signature for utxo "+e,htlcNotExpired:e=>`HTLC not expired, need more ${e} blocks`,controlBlockGenerationFailed:"failed to generate control block",invalidLeaf:"invalid leaf"},tr=192;ye.initEccLib(_t);class cr{constructor(t,r,n,i,a,f,u,l){this.secretHash=n,this.redeemerPubkey=i,this.initiatorPubkey=a,this.expiry=f,this.signer=t,this.network=u,this.internalPubkey=Ha(),this.initiateAmount=r,this.utxoHashes=l}static async from(t,r,n,i,a,f,u){n=n.startsWith("0x")?n.slice(2):n,bt(n.length===64,we.secretHashLenMismatch),bt(i.length===64||i.length===66,`initiator ${we.pubkeyLenMismatch}`),bt(a.length===64||a.length===66,`redeemer ${we.pubkeyLenMismatch}`),bt(f>0,we.zeroOrNegativeExpiry);const l=await t.getNetwork();return new cr(t,r,n,Xr(a).toString("hex"),Xr(i).toString("hex"),f,l,u)}address(){const{address:t}=ye.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves()});if(!t)throw new Error(we.htlcAddressGenerationFailed);return t}id(){return this.address()}async _buildRawTx(t,r){const n=new ye.Transaction;n.version=2;const i=this.address(),a=await this.signer.getProvider();let f=[];if(this.utxoHashes&&this.utxoHashes.length>0)for(const l of this.utxoHashes){const y=await a.getTransaction(l);for(let g=0;g<y.vout.length;g++){const w=y.vout[g];w.scriptpubkey_address===i&&f.push({txid:y.txid,vout:g,value:w.value,status:{confirmed:!1}})}}else f=await a.getUTXOs(i);const u=f.reduce((l,y)=>l+y.value,0);if(u===0)throw new Error(`${i} ${we.notFunded}`);for(let l=0;l<f.length;l++)n.addInput(Buffer.from(f[l].txid,"hex").reverse(),f[l].vout);return r??(r=await a.suggestFee(i,u,Bn.Urgency.MEDIUM)),n.addOutput(ye.address.toOutputScript(t,this.network),u-r),{tx:n,usedUtxos:f}}async buildRawTx(t){return await this._buildRawTx(await this.signer.getAddress(),t)}getOutputScript(){return ye.address.toOutputScript(this.address(),this.network)}async init(t){return t??(t=await(await this.signer.getProvider()).suggestFee(await this.signer.getAddress(),this.initiateAmount,Bn.Urgency.MEDIUM)),await this.signer.send(this.address(),this.initiateAmount,t)}async instantRefund(t,r){bt(t.length>0,we.noCounterpartySigs);const{tx:n,usedUtxos:i}=await this.buildRawTx(r);for(const w of i)if(!t.find(E=>E.utxo===w.txid))throw new Error(we.counterPartySigNotFound(w.txid));const a=this.getOutputScript(),f=ye.Transaction.SIGHASH_DEFAULT,u=this.leafHash(2),l=i.map(w=>w.value),y=Or(a,i.length);for(let w=0;w<n.ins.length;w++){const E=n.hashForWitnessV1(w,y,l,f,u);if(!_t.verifySchnorr(E,Buffer.from(this.redeemerPubkey,"hex"),Buffer.from(t[w].sig,"hex")))throw new Error(we.invalidCounterpartySigForUTXO(t[w].utxo));const I=await this.signer.signSchnorr(E),v=Buffer.from(n.ins[w].hash).reverse().toString("hex"),k=t.find(T=>T.utxo===v);if(!k)throw new Error(we.counterPartySigNotFound(v));n.setWitness(w,[Buffer.from(k.sig,"hex"),I,this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async redeem(t,r,n){bt(ye.crypto.sha256(Buffer.from(t,"hex")).toString("hex")===this.secretHash,we.secretMismatch);const{tx:i,usedUtxos:a}=await this._buildRawTx(r??await this.signer.getAddress(),n),f=this.leafHash(1),u=a.map(w=>w.value),l=Or(this.getOutputScript(),a.length),y=ye.Transaction.SIGHASH_DEFAULT;for(let w=0;w<i.ins.length;w++){const E=i.hashForWitnessV1(w,l,u,y,f),I=await this.signer.signSchnorr(E);i.setWitness(w,[I,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return await(await this.signer.getProvider()).broadcast(i.toHex())}async refund(t,r){const{tx:n,usedUtxos:i}=await this._buildRawTx(t??await this.signer.getAddress(),r),[a,f]=await this.canRefund(i);if(!a)throw new Error(we.htlcNotExpired(f));const u=this.leafHash(0),l=i.map(E=>E.value),y=Or(this.getOutputScript(),i.length),g=ye.Transaction.SIGHASH_DEFAULT;for(let E=0;E<n.ins.length;E++){n.ins[E].sequence=this.expiry;const I=n.hashForWitnessV1(E,y,l,g,u),v=await this.signer.signSchnorr(I);n.setWitness(E,[v,this.refundLeaf(),this.generateControlBlockFor(0)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async canRefund(t){const n=await(await this.signer.getProvider()).getLatestTip();for(const i of t){let a=0;if(i.status.confirmed&&i.status.block_height+this.expiry>n?a=i.status.block_height+this.expiry-n+1:i.status.confirmed||(a=this.expiry+1),a>0)return[!1,a]}return[!0,0]}generateControlBlockFor(t){let r;switch(t){case 1:r=this.redeemLeaf();break;case 0:r=this.refundLeaf();break;case 2:r=this.instantRefundLeaf();break;default:throw new Error(we.invalidLeaf)}const n=ye.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves(),redeem:{output:r,redeemVersion:tr}});if(!n.witness)throw new Error(we.controlBlockGenerationFailed);return n.witness[n.witness.length-1]}leafHash(t){let r=this.redeemLeaf();return t===0&&(r=this.refundLeaf()),t===2&&(r=this.instantRefundLeaf()),ye.crypto.taggedHash("TapLeaf",Ta(r))}refundLeaf(){return ye.script.fromASM(`
5
5
  ${ye.script.number.encode(this.expiry).toString("hex")}
6
6
  OP_CHECKSEQUENCEVERIFY
7
7
  OP_DROP
@@ -20,7 +20,7 @@
20
20
  OP_CHECKSIGADD
21
21
  OP_2
22
22
  OP_NUMEQUAL
23
- `.trim().replace(/\s+/g," "))}leaves(){return[{version:tr,output:this.redeemLeaf()},[{version:tr,output:this.refundLeaf()},{version:tr,output:this.instantRefundLeaf()}]]}generateMerkleProofFor(t){const r=this.leafHash(1),n=this.leafHash(2),i=this.leafHash(0);switch(t){case 1:{const a=ka(i,n);return[ye.crypto.taggedHash("TapBranch",Buffer.concat(a))]}case 0:return[n,r];case 2:return[i,r];default:throw new Error(we.invalidLeaf)}}}function Or(e,t){const r=[];for(let n=0;n<t;n++)r.push(e);return r}class za{constructor(){this.cache={}}set(t,r,n,i){const a={txHash:n,timeStamp:Date.now(),btcRedeemUTXO:i};this.cache[`${r}_${t.create_order.create_id}`]=a}get(t,r){return this.cache[`${r}_${t.create_order.create_id}`]||null}remove(t,r){delete this.cache[`${r}_${t.create_order.create_id}`]}}class qi{constructor(t,r){this.url=new ge.Url("/blocknumber/"+r,t)}async fetchBlockNumbers(){try{const t=await P.Fetcher.get(this.url);return P.Ok(t)}catch(t){return P.Err("Failed to fetch block numbers",t)}}}class ja{constructor(t){if(this.eventListeners=new Map,this.getOrderThreshold=20,this.pendingOrdersCount=0,this.useRelay=!0,this.orderBook=new J.Orderbook({url:t.orderbookURl,walletClient:t.wallets.evmWallet,auth:t.auth}),this.quote=t.quote,this.secretManager=t.secretManager,this.wallets=t.wallets,this.orderbookUrl=t.orderbookURl,this.auth=t.auth,this.orderExecutorCache=new za,!t.wallets.evmWallet.account)throw new Error("Account not found in evmWallet");this.evmAddress=t.wallets.evmWallet.account.address,this.blockNumberFetcher=t.blockNumberFetcher&&new qi(t.blockNumberFetcher.url,t.blockNumberFetcher.network)}getPendingOrderCount(){return this.pendingOrdersCount}setUseRelay(t){this.useRelay=t}async swap(t){const r=await this.validateAndFillParams(t);if(r.error)return P.Err(r.error);const{sendAddress:n,receiveAddress:i,timelock:a}=r.val,f=await this.orderBook.getOrdersCount(this.evmAddress);if(f.error)return P.Err(f.error);const u=f.val+1,l=this.secretManager.generateSecret(u);if(l.error)return P.Err(l.error);const{strategyId:y,btcAddress:g}=t.additionalData,w={strategy_id:y,...g&&{bitcoin_optional_recipient:g}},E={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:u.toString(),timelock:a,secret_hash:P.trim0x(l.val.secretHash),min_destination_confirmations:t.minDestinationConfirmations??0,additional_data:w},I=await this.quote.getAttestedQuote(E);if(I.error)return P.Err(I.error);const v=await this.orderBook.createOrder(I.val);if(v.error)return P.Err(v.error);const k=await this.pollOrder(v.val);return k.error?P.Err(k.error):P.Ok(k.val)}async validateAndFillParams(t){if(t.fromAsset.chain===t.toAsset.chain&&t.fromAsset.atomicSwapAddress===t.toAsset.atomicSwapAddress)return P.Err("Source and destination assets cannot be the same");if(J.isMainnet(t.fromAsset.chain)&&!J.isMainnet(t.toAsset.chain)||!J.isMainnet(t.fromAsset.chain)&&J.isMainnet(t.toAsset.chain))return P.Err("Both assets should be on the same network (either mainnet or testnet)");if(J.isBitcoin(t.fromAsset.chain)||J.isBitcoin(t.toAsset.chain)){if(!this.wallets.btcWallet)return P.Err("btcWallet is required for bitcoin chain. Please provide btcWallet in the constructor");if(!t.additionalData.btcAddress)return P.Err("btcAddress in additionalData is required for bitcoin chain")}const r=await this.getAddresses(t.fromAsset.chain);if(r.error)return P.Err(r.error);const n=await this.getAddresses(t.toAsset.chain);if(n.error)return P.Err(n.error);const i=this.validateAmount(t.sendAmount);if(i.error)return P.Err(i.error);const a=this.validateAmount(t.receiveAmount);if(a.error)return P.Err(a.error);if(i<a)return P.Err("Send amount should be greater than receive amount");const f=this.getTimelock(t.fromAsset.chain);return f?P.Ok({sendAddress:r.val,receiveAddress:n.val,timelock:t.timelock??f}):P.Err("Unsupported chain for timelock")}async getAddresses(t){var n;switch(J.getBlockchainType(t)){case J.BlockchainType.EVM:return this.wallets.evmWallet.account?P.Ok(this.wallets.evmWallet.account.address):P.Err("EVM Wallet not found");case J.BlockchainType.Bitcoin:{const i=await((n=this.wallets.btcWallet)==null?void 0:n.getPublicKey());return!i||!Ca(i)?P.Err("Invalid btc public key"):P.Ok(Ot(i))}default:return P.Err("Unsupported chain")}}validateAmount(t){if(t==null||t.includes("."))return P.Err("Invalid amount ",t);const r=new Ds(t);return!r.isInteger()||r.isNaN()||r.lt(0)||r.isLessThanOrEqualTo(0)?P.Err("Invalid amount ",t):P.Ok(r)}getTimelock(t){switch(J.getBlockchainType(t)){case J.BlockchainType.EVM:return sr.evm;case J.BlockchainType.Bitcoin:return sr.btc;default:return}}async pollOrder(t){let r=await this.orderBook.getOrder(t,!0),n=0;for(;n<this.getOrderThreshold;){if(await ge.sleep(1e3),n++,r.error){if(!r.error.includes("result is undefined"))return P.Err(r.error)}else if(r.val&&r.val.create_order.create_id.toLowerCase()===t.toLowerCase())return P.Ok(r.val);r=await this.orderBook.getOrder(t,!0)}return P.Err(`Order not found, createOrder id: ${t}`)}emit(t,...r){(this.eventListeners.get(t)??[]).forEach(i=>{i(...r)})}async execute(t=5e3){return await this.orderBook.subscribeToOrders(!0,t,async r=>{var i;this.pendingOrdersCount=r.data.length,this.emit("onPendingOrdersChanged",r.data);const n=await((i=this.blockNumberFetcher)==null?void 0:i.fetchBlockNumbers());for(let a=0;a<r.data.length;a++){const f=r.data[a],u=f.source_swap.chain,l=f.destination_swap.chain,y=this.getWallet(u),g=this.getWallet(l);if(y.error||g.error||!y.val||!g.val){this.emit("error",f,"Source or Destination Wallet not found while executing order");return}let w=n==null?void 0:n.val[u],E=n==null?void 0:n.val[l];if(!w||!E){const v=await this.fetchCurrentBlockNumbers(f,{source:y.val,destination:g.val});if(v.error){this.emit("error",f,"Error while fetching CurrentBlockNumbers: "+v.error);return}w=v.val.source,E=v.val.destination}switch(ji(f,w,E)){case ce.Redeem:{const v=this.secretManager.generateSecret(Number(f.create_order.nonce));if(v.error){this.emit("error",f,v.error);return}switch(J.getBlockchainType(f.destination_swap.chain)){case J.BlockchainType.EVM:{await this.evmRedeem(f,v.val.secret);break}case J.BlockchainType.Bitcoin:{await this.btcRedeem(g.val,f,v.val.secret);break}default:this.emit("error",f,"Unsupported chain: "+f.destination_swap.chain)}break}case ce.Refund:{switch(J.getBlockchainType(f.source_swap.chain)){case J.BlockchainType.EVM:{this.emit("error",f,"EVM refund is automatically done by relay service");break}case J.BlockchainType.Bitcoin:{await this.btcRefund(y.val,f);break}default:this.emit("error",f,"Unsupported chain: "+f.source_swap.chain)}break}}}},{per_page:500},!0)}async evmRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing evm redeem"),this.orderExecutorCache.get(t,ce.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}const a=await new Gi(t,this.orderbookUrl,this.auth).redeem(t.create_order.create_id,r);if(a.error){this.emit("error",t,a.error);return}this.emit("success",t,ce.Redeem,a.val),this.orderExecutorCache.set(t,ce.Redeem,a.val)}async btcRedeem(t,r,n){var f;const i=this.orderExecutorCache.get(r,ce.Redeem);let a=!1;if(i)if(i.btcRedeemUTXO&&i.btcRedeemUTXO!==r.destination_swap.initiate_tx_hash)a=!0,this.emit("log",r.create_order.create_id,"rbf btc redeem");else{this.emit("log",r.create_order.create_id,"btcRedeem: already redeemed");return}this.emit("log",r.create_order.create_id,"executing btc redeem");try{const l=await(await cr.from(t,Number(r.destination_swap.amount),r.create_order.secret_hash,Ot(r.destination_swap.initiator),Ot(r.destination_swap.redeemer),r.destination_swap.timelock,a?[r.destination_swap.initiate_tx_hash]:[])).redeem(P.trim0x(n),(f=r.create_order.additional_data)==null?void 0:f.bitcoin_optional_recipient);this.emit("success",r,ce.Redeem,l),this.orderExecutorCache.set(r,ce.Redeem,l,r.destination_swap.initiate_tx_hash)}catch(u){this.emit("error",r,"Failed btc redeem: "+u)}}async btcRefund(t,r){var n;if(!this.orderExecutorCache.get(r,ce.Refund)){this.emit("log",r.create_order.create_id,"executing btc refund");try{const a=await(await cr.from(t,Number(r.source_swap.amount),r.create_order.secret_hash,Ot(r.source_swap.initiator),Ot(r.source_swap.redeemer),r.source_swap.timelock)).refund((n=r.create_order.additional_data)==null?void 0:n.bitcoin_optional_recipient);this.emit("success",r,ce.Refund,a),this.orderExecutorCache.set(r,ce.Refund,a)}catch(i){this.emit("error",r,"Failed btc refund: "+i)}}}getWallet(t){switch(J.getBlockchainType(t)){case J.BlockchainType.EVM:return P.Ok(this.wallets.evmWallet);case J.BlockchainType.Bitcoin:return P.Ok(this.wallets.btcWallet);default:return P.Err("Unsupported chain for wallet")}}on(t,r){const n=this.eventListeners.get(t)??[];n.push(r),this.eventListeners.set(t,n)}off(t,r){const n=this.eventListeners.get(t)??[],i=n.indexOf(r);i!==-1&&n.splice(i,1)}async fetchCurrentBlockNumbers(t,r){if(!r||!r.source||!r.destination)return P.Err("Provide wallets to fetch the current block number");const n=J.isBitcoin(t.source_swap.chain)?await ge.fetchBitcoinBlockNumber(await r.source.getProvider()):await ge.fetchEVMBlockNumber(r.source);if(n.error)return P.Err(n.error);const i=J.isBitcoin(t.destination_swap.chain)?await ge.fetchBitcoinBlockNumber(await r.destination.getProvider()):await ge.fetchEVMBlockNumber(r.destination);return i.error?P.Err(i.error):P.Ok({source:n.val,destination:i.val})}}var Qe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ga(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}),r}var Wi={},vt={},Et={};Object.defineProperty(Et,"__esModule",{value:!0});Et.testnet=Et.bitcoin=void 0;Et.bitcoin={messagePrefix:`Bitcoin Signed Message:
23
+ `.trim().replace(/\s+/g," "))}leaves(){return[{version:tr,output:this.redeemLeaf()},[{version:tr,output:this.refundLeaf()},{version:tr,output:this.instantRefundLeaf()}]]}generateMerkleProofFor(t){const r=this.leafHash(1),n=this.leafHash(2),i=this.leafHash(0);switch(t){case 1:{const a=ka(i,n);return[ye.crypto.taggedHash("TapBranch",Buffer.concat(a))]}case 0:return[n,r];case 2:return[i,r];default:throw new Error(we.invalidLeaf)}}}function Or(e,t){const r=[];for(let n=0;n<t;n++)r.push(e);return r}class za{constructor(){this.cache={}}set(t,r,n,i){const a={txHash:n,timeStamp:Date.now(),btcRedeemUTXO:i};this.cache[`${r}_${t.create_order.create_id}`]=a}get(t,r){return this.cache[`${r}_${t.create_order.create_id}`]||null}remove(t,r){delete this.cache[`${r}_${t.create_order.create_id}`]}}class qi{constructor(t,r){this.url=new ge.Url("/blocknumber/"+r,t)}async fetchBlockNumbers(){try{const t=await P.Fetcher.get(this.url);return P.Ok(t)}catch(t){return P.Err("Failed to fetch block numbers",t)}}}class ja{constructor(t){if(this.eventListeners=new Map,this.getOrderThreshold=20,this.pendingOrdersCount=0,this.useRelay=!0,this.orderBook=new J.Orderbook({url:t.orderbookURl,walletClient:t.wallets.evmWallet,auth:t.auth}),this.quote=t.quote,this.secretManager=t.secretManager,this.wallets=t.wallets,this.orderbookUrl=t.orderbookURl,this.auth=t.auth,this.orderExecutorCache=new za,!t.wallets.evmWallet.account)throw new Error("Account not found in evmWallet");this.evmAddress=t.wallets.evmWallet.account.address,this.blockNumberFetcher=t.blockNumberFetcher&&new qi(t.blockNumberFetcher.url,t.blockNumberFetcher.network)}getPendingOrderCount(){return this.pendingOrdersCount}setUseRelay(t){this.useRelay=t}async swap(t){const r=await this.validateAndFillParams(t);if(r.error)return P.Err(r.error);const{sendAddress:n,receiveAddress:i,timelock:a}=r.val,f=await this.orderBook.getOrdersCount(this.evmAddress);if(f.error)return P.Err(f.error);const u=f.val+1,l=this.secretManager.generateSecret(u);if(l.error)return P.Err(l.error);const{strategyId:y,btcAddress:g}=t.additionalData,w={strategy_id:y,...g&&{bitcoin_optional_recipient:g}},E={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:u.toString(),timelock:a,secret_hash:P.trim0x(l.val.secretHash),min_destination_confirmations:t.minDestinationConfirmations??0,additional_data:w},I=await this.quote.getAttestedQuote(E);if(I.error)return P.Err(I.error);const v=await this.orderBook.createOrder(I.val);if(v.error)return P.Err(v.error);const k=await this.pollOrder(v.val);return k.error?P.Err(k.error):P.Ok(k.val)}async validateAndFillParams(t){if(t.fromAsset.chain===t.toAsset.chain&&t.fromAsset.atomicSwapAddress===t.toAsset.atomicSwapAddress)return P.Err("Source and destination assets cannot be the same");if(J.isMainnet(t.fromAsset.chain)&&!J.isMainnet(t.toAsset.chain)||!J.isMainnet(t.fromAsset.chain)&&J.isMainnet(t.toAsset.chain))return P.Err("Both assets should be on the same network (either mainnet or testnet)");if(J.isBitcoin(t.fromAsset.chain)||J.isBitcoin(t.toAsset.chain)){if(!this.wallets.btcWallet)return P.Err("btcWallet is required for bitcoin chain. Please provide btcWallet in the constructor");if(!t.additionalData.btcAddress)return P.Err("btcAddress in additionalData is required for bitcoin chain")}const r=await this.getAddresses(t.fromAsset.chain);if(r.error)return P.Err(r.error);const n=await this.getAddresses(t.toAsset.chain);if(n.error)return P.Err(n.error);const i=this.validateAmount(t.sendAmount);if(i.error)return P.Err(i.error);const a=this.validateAmount(t.receiveAmount);if(a.error)return P.Err(a.error);if(i<a)return P.Err("Send amount should be greater than receive amount");const f=this.getTimelock(t.fromAsset.chain);return f?P.Ok({sendAddress:r.val,receiveAddress:n.val,timelock:t.timelock??f}):P.Err("Unsupported chain for timelock")}async getAddresses(t){var n;switch(J.getBlockchainType(t)){case J.BlockchainType.EVM:return this.wallets.evmWallet.account?P.Ok(this.wallets.evmWallet.account.address):P.Err("EVM Wallet not found");case J.BlockchainType.Bitcoin:{const i=await((n=this.wallets.btcWallet)==null?void 0:n.getPublicKey());return!i||!Ca(i)?P.Err("Invalid btc public key"):P.Ok(Ot(i))}default:return P.Err("Unsupported chain")}}validateAmount(t){if(t==null||t.includes("."))return P.Err("Invalid amount ",t);const r=new Ds(t);return!r.isInteger()||r.isNaN()||r.lt(0)||r.isLessThanOrEqualTo(0)?P.Err("Invalid amount ",t):P.Ok(r)}getTimelock(t){switch(J.getBlockchainType(t)){case J.BlockchainType.EVM:return sr.evm;case J.BlockchainType.Bitcoin:return sr.btc;default:return}}async pollOrder(t){let r=await this.orderBook.getOrder(t,!0),n=0;for(;n<this.getOrderThreshold;){if(await ge.sleep(1e3),n++,r.error){if(!r.error.includes("result is undefined"))return P.Err(r.error)}else if(r.val&&r.val.create_order.create_id.toLowerCase()===t.toLowerCase())return P.Ok(r.val);r=await this.orderBook.getOrder(t,!0)}return P.Err(`Order not found, createOrder id: ${t}`)}emit(t,...r){(this.eventListeners.get(t)??[]).forEach(i=>{i(...r)})}async execute(t=5e3){return await this.orderBook.subscribeToOrders(!0,t,async r=>{var i;this.pendingOrdersCount=r.data.length,this.emit("onPendingOrdersChanged",r.data);const n=await((i=this.blockNumberFetcher)==null?void 0:i.fetchBlockNumbers());for(let a=0;a<r.data.length;a++){const f=r.data[a],u=f.source_swap.chain,l=f.destination_swap.chain,y=this.getWallet(u),g=this.getWallet(l);if(y.error||g.error||!y.val||!g.val){this.emit("error",f,"Source or Destination Wallet not found while executing order");return}let w=n==null?void 0:n.val[u],E=n==null?void 0:n.val[l];if(!w||!E){const v=await this.fetchCurrentBlockNumbers(f,{source:y.val,destination:g.val});if(v.error){this.emit("error",f,"Error while fetching CurrentBlockNumbers: "+v.error);return}w=v.val.source,E=v.val.destination}switch(ji(f,w,E)){case ce.Redeem:{const v=this.secretManager.generateSecret(Number(f.create_order.nonce));if(v.error){this.emit("error",f,v.error);return}switch(J.getBlockchainType(f.destination_swap.chain)){case J.BlockchainType.EVM:{await this.evmRedeem(f,v.val.secret);break}case J.BlockchainType.Bitcoin:{await this.btcRedeem(g.val,f,v.val.secret);break}default:this.emit("error",f,"Unsupported chain: "+f.destination_swap.chain)}break}case ce.Refund:{switch(J.getBlockchainType(f.source_swap.chain)){case J.BlockchainType.EVM:{this.emit("error",f,"EVM refund is automatically done by relay service");break}case J.BlockchainType.Bitcoin:{await this.btcRefund(y.val,f);break}default:this.emit("error",f,"Unsupported chain: "+f.source_swap.chain)}break}}}},{per_page:500},!0)}async evmRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing evm redeem"),this.orderExecutorCache.get(t,ce.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}const a=await new Gi(t,this.orderbookUrl,this.auth).redeem(t.create_order.create_id,r);if(a.error){this.emit("error",t,a.error);return}this.emit("success",t,ce.Redeem,a.val),this.orderExecutorCache.set(t,ce.Redeem,a.val)}async btcRedeem(t,r,n){var u,l;const i=this.orderExecutorCache.get(r,ce.Redeem),a=(u=r.destination_swap.initiate_tx_hash.split(",").at(-1))==null?void 0:u.split(":").at(0);if(!a){this.emit("error",r,"Failed to get initiate_tx_hash");return}console.log("initTx :",a);let f=!1;if(i)if(console.log("cache inside bitcoin redeem: ",i),i.btcRedeemUTXO&&i.btcRedeemUTXO!==a)f=!0,this.emit("log",r.create_order.create_id,"rbf btc redeem");else{this.emit("log",r.create_order.create_id,"btcRedeem: already redeemed");return}console.log("rbf :",f),this.emit("log",r.create_order.create_id,"executing btc redeem");try{const g=await(await cr.from(t,Number(r.destination_swap.amount),r.create_order.secret_hash,Ot(r.destination_swap.initiator),Ot(r.destination_swap.redeemer),r.destination_swap.timelock,f?[a]:[])).redeem(P.trim0x(n),(l=r.create_order.additional_data)==null?void 0:l.bitcoin_optional_recipient);this.emit("success",r,ce.Redeem,g),this.orderExecutorCache.set(r,ce.Redeem,g,a)}catch(y){this.emit("error",r,"Failed btc redeem: "+y)}}async btcRefund(t,r){var n;if(!this.orderExecutorCache.get(r,ce.Refund)){this.emit("log",r.create_order.create_id,"executing btc refund");try{const a=await(await cr.from(t,Number(r.source_swap.amount),r.create_order.secret_hash,Ot(r.source_swap.initiator),Ot(r.source_swap.redeemer),r.source_swap.timelock)).refund((n=r.create_order.additional_data)==null?void 0:n.bitcoin_optional_recipient);this.emit("success",r,ce.Refund,a),this.orderExecutorCache.set(r,ce.Refund,a)}catch(i){this.emit("error",r,"Failed btc refund: "+i)}}}getWallet(t){switch(J.getBlockchainType(t)){case J.BlockchainType.EVM:return P.Ok(this.wallets.evmWallet);case J.BlockchainType.Bitcoin:return P.Ok(this.wallets.btcWallet);default:return P.Err("Unsupported chain for wallet")}}on(t,r){const n=this.eventListeners.get(t)??[];n.push(r),this.eventListeners.set(t,n)}off(t,r){const n=this.eventListeners.get(t)??[],i=n.indexOf(r);i!==-1&&n.splice(i,1)}async fetchCurrentBlockNumbers(t,r){if(!r||!r.source||!r.destination)return P.Err("Provide wallets to fetch the current block number");const n=J.isBitcoin(t.source_swap.chain)?await ge.fetchBitcoinBlockNumber(await r.source.getProvider()):await ge.fetchEVMBlockNumber(r.source);if(n.error)return P.Err(n.error);const i=J.isBitcoin(t.destination_swap.chain)?await ge.fetchBitcoinBlockNumber(await r.destination.getProvider()):await ge.fetchEVMBlockNumber(r.destination);return i.error?P.Err(i.error):P.Ok({source:n.val,destination:i.val})}}var Qe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ga(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}),r}var Wi={},vt={},Et={};Object.defineProperty(Et,"__esModule",{value:!0});Et.testnet=Et.bitcoin=void 0;Et.bitcoin={messagePrefix:`Bitcoin Signed Message:
24
24
  `,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128};Et.testnet={messagePrefix:`Bitcoin Signed Message:
25
25
  `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var Vi={},zt={Array:function(e){return e!=null&&e.constructor===Array},Boolean:function(e){return typeof e=="boolean"},Function:function(e){return typeof e=="function"},Nil:function(e){return e==null},Number:function(e){return typeof e=="number"},Object:function(e){return typeof e=="object"},String:function(e){return typeof e=="string"},"":function(){return!0}};zt.Null=zt.Nil;for(var Dn in zt)zt[Dn].toJSON=(function(e){return e}).bind(null,Dn);var yn=zt,it=yn;function Ki(e){return e.name||e.toString().match(/function (.*?)\s*\(/)[1]}function gn(e){return it.Nil(e)?"":Ki(e.constructor)}function qa(e){return it.Function(e)?"":it.String(e)?JSON.stringify(e):e&&it.Object(e)?"":e}function mn(e,t){Error.captureStackTrace&&Error.captureStackTrace(e,t)}function lr(e){return it.Function(e)?e.toJSON?e.toJSON():Ki(e):it.Array(e)?"Array":e&&it.Object(e)?"Object":e!==void 0?e:""}function Yi(e,t,r){var n=qa(t);return"Expected "+lr(e)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function ze(e,t,r){r=r||gn(t),this.message=Yi(e,t,r),mn(this,ze),this.__type=e,this.__value=t,this.__valueTypeName=r}ze.prototype=Object.create(Error.prototype);ze.prototype.constructor=ze;function Wa(e,t,r,n,i){var a='" of type ';return t==="key"&&(a='" with key type '),Yi('property "'+lr(r)+a+lr(e),n,i)}function mt(e,t,r,n,i){e?(i=i||gn(n),this.message=Wa(e,r,t,n,i)):this.message='Unexpected property "'+t+'"',mn(this,ze),this.__label=r,this.__property=t,this.__type=e,this.__value=n,this.__valueTypeName=i}mt.prototype=Object.create(Error.prototype);mt.prototype.constructor=ze;function Va(e,t){return new ze(e,{},t)}function Ka(e,t,r){return e instanceof mt?(t=t+"."+e.__property,e=new mt(e.__type,t,e.__label,e.__value,e.__valueTypeName)):e instanceof ze&&(e=new mt(e.__type,t,r,e.__value,e.__valueTypeName)),mn(e),e}var Ji={TfTypeError:ze,TfPropertyTypeError:mt,tfCustomError:Va,tfSubError:Ka,tfJSON:lr,getValueTypeName:gn},Fr,$n;function Ya(){if($n)return Fr;$n=1;var e=yn,t=Ji;function r(S){return Buffer.isBuffer(S)}function n(S){return typeof S=="string"&&/^([0-9a-f]{2})+$/i.test(S)}function i(S,z){var N=S.toJSON();function $(oe){if(!S(oe))return!1;if(oe.length===z)return!0;throw t.tfCustomError(N+"(Length: "+z+")",N+"(Length: "+oe.length+")")}return $.toJSON=function(){return N},$}var a=i.bind(null,e.Array),f=i.bind(null,r),u=i.bind(null,n),l=i.bind(null,e.String);function y(S,z,N){N=N||e.Number;function $(oe,Pe){return N(oe,Pe)&&oe>S&&oe<z}return $.toJSON=function(){return`${N.toJSON()} between [${S}, ${z}]`},$}var g=Math.pow(2,53)-1;function w(S){return typeof S=="number"&&isFinite(S)}function E(S){return S<<24>>24===S}function I(S){return S<<16>>16===S}function v(S){return(S|0)===S}function k(S){return typeof S=="number"&&S>=-g&&S<=g&&Math.floor(S)===S}function T(S){return(S&255)===S}function C(S){return(S&65535)===S}function F(S){return S>>>0===S}function O(S){return typeof S=="number"&&S>=0&&S<=g&&Math.floor(S)===S}var L={ArrayN:a,Buffer:r,BufferN:f,Finite:w,Hex:n,HexN:u,Int8:E,Int16:I,Int32:v,Int53:k,Range:y,StringN:l,UInt8:T,UInt16:C,UInt32:F,UInt53:O};for(var U in L)L[U].toJSON=(function(S){return S}).bind(null,U);return Fr=L,Fr}var Kt=Ji,le=yn,De=Kt.tfJSON,Xi=Kt.TfTypeError,Qi=Kt.TfPropertyTypeError,Ft=Kt.tfSubError,Ja=Kt.getValueTypeName,$e={arrayOf:function(t,r){t=Fe(t),r=r||{};function n(i,a){return!le.Array(i)||le.Nil(i)||r.minLength!==void 0&&i.length<r.minLength||r.maxLength!==void 0&&i.length>r.maxLength||r.length!==void 0&&i.length!==r.length?!1:i.every(function(f,u){try{return xe(t,f,a)}catch(l){throw Ft(l,u)}})}return n.toJSON=function(){var i="["+De(t)+"]";return r.length!==void 0?i+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(i+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),i},n},maybe:function e(t){t=Fe(t);function r(n,i){return le.Nil(n)||t(n,i,e)}return r.toJSON=function(){return"?"+De(t)},r},map:function(t,r){t=Fe(t),r&&(r=Fe(r));function n(i,a){if(!le.Object(i)||le.Nil(i))return!1;for(var f in i){try{r&&xe(r,f,a)}catch(l){throw Ft(l,f,"key")}try{var u=i[f];xe(t,u,a)}catch(l){throw Ft(l,f)}}return!0}return r?n.toJSON=function(){return"{"+De(r)+": "+De(t)+"}"}:n.toJSON=function(){return"{"+De(t)+"}"},n},object:function(t){var r={};for(var n in t)r[n]=Fe(t[n]);function i(a,f){if(!le.Object(a)||le.Nil(a))return!1;var u;try{for(u in r){var l=r[u],y=a[u];xe(l,y,f)}}catch(g){throw Ft(g,u)}if(f){for(u in a)if(!r[u])throw new Qi(void 0,u)}return!0}return i.toJSON=function(){return De(r)},i},anyOf:function(){var t=[].slice.call(arguments).map(Fe);function r(n,i){return t.some(function(a){try{return xe(a,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(De).join("|")},r},allOf:function(){var t=[].slice.call(arguments).map(Fe);function r(n,i){return t.every(function(a){try{return xe(a,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(De).join(" & ")},r},quacksLike:function(t){function r(n){return t===Ja(n)}return r.toJSON=function(){return t},r},tuple:function(){var t=[].slice.call(arguments).map(Fe);function r(n,i){return le.Nil(n)||le.Nil(n.length)||i&&n.length!==t.length?!1:t.every(function(a,f){try{return xe(a,n[f],i)}catch(u){throw Ft(u,f)}})}return r.toJSON=function(){return"("+t.map(De).join(", ")+")"},r},value:function(t){function r(n){return n===t}return r.toJSON=function(){return t},r}};$e.oneOf=$e.anyOf;function Fe(e){if(le.String(e))return e[0]==="?"?$e.maybe(e.slice(1)):le[e]||$e.quacksLike(e);if(e&&le.Object(e)){if(le.Array(e)){if(e.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return $e.arrayOf(e[0])}return $e.object(e)}else if(le.Function(e))return e;return $e.value(e)}function xe(e,t,r,n){if(le.Function(e)){if(e(t,r))return!0;throw new Xi(n||e,t)}return xe(Fe(e),t,r)}for(var Xe in le)xe[Xe]=le[Xe];for(Xe in $e)xe[Xe]=$e[Xe];var Hn=Ya();for(Xe in Hn)xe[Xe]=Hn[Xe];xe.compile=Fe;xe.TfTypeError=Xi;xe.TfPropertyTypeError=Qi;var Xa=xe;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.maybe=e.Boolean=e.Array=e.Buffer256bit=e.Network=e.typeforce=void 0,e.typeforce=Xa,e.Network=e.typeforce.compile({messagePrefix:e.typeforce.oneOf(e.typeforce.Buffer,e.typeforce.String),bip32:{public:e.typeforce.UInt32,private:e.typeforce.UInt32},pubKeyHash:e.typeforce.UInt8,scriptHash:e.typeforce.UInt8,wif:e.typeforce.UInt8}),e.Buffer256bit=e.typeforce.BufferN(32),e.Array=e.typeforce.Array,e.Boolean=e.typeforce.Boolean,e.maybe=e.typeforce.maybe})(Vi);var Qr={exports:{}},Zr={exports:{}},At={},wr={};wr.byteLength=ef;wr.toByteArray=rf;wr.fromByteArray=of;var Ue=[],Re=[],Qa=typeof Uint8Array<"u"?Uint8Array:Array,Ur="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var yt=0,Za=Ur.length;yt<Za;++yt)Ue[yt]=Ur[yt],Re[Ur.charCodeAt(yt)]=yt;Re[45]=62;Re[95]=63;function Zi(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function ef(e){var t=Zi(e),r=t[0],n=t[1];return(r+n)*3/4-n}function tf(e,t,r){return(t+r)*3/4-r}function rf(e){var t,r=Zi(e),n=r[0],i=r[1],a=new Qa(tf(e,n,i)),f=0,u=i>0?n-4:n,l;for(l=0;l<u;l+=4)t=Re[e.charCodeAt(l)]<<18|Re[e.charCodeAt(l+1)]<<12|Re[e.charCodeAt(l+2)]<<6|Re[e.charCodeAt(l+3)],a[f++]=t>>16&255,a[f++]=t>>8&255,a[f++]=t&255;return i===2&&(t=Re[e.charCodeAt(l)]<<2|Re[e.charCodeAt(l+1)]>>4,a[f++]=t&255),i===1&&(t=Re[e.charCodeAt(l)]<<10|Re[e.charCodeAt(l+1)]<<4|Re[e.charCodeAt(l+2)]>>2,a[f++]=t>>8&255,a[f++]=t&255),a}function nf(e){return Ue[e>>18&63]+Ue[e>>12&63]+Ue[e>>6&63]+Ue[e&63]}function sf(e,t,r){for(var n,i=[],a=t;a<r;a+=3)n=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(nf(n));return i.join("")}function of(e){for(var t,r=e.length,n=r%3,i=[],a=16383,f=0,u=r-n;f<u;f+=a)i.push(sf(e,f,f+a>u?u:f+a));return n===1?(t=e[r-1],i.push(Ue[t>>2]+Ue[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],i.push(Ue[t>>10]+Ue[t>>4&63]+Ue[t<<2&63]+"=")),i.join("")}var wn={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */wn.read=function(e,t,r,n,i){var a,f,u=i*8-n-1,l=(1<<u)-1,y=l>>1,g=-7,w=r?i-1:0,E=r?-1:1,I=e[t+w];for(w+=E,a=I&(1<<-g)-1,I>>=-g,g+=u;g>0;a=a*256+e[t+w],w+=E,g-=8);for(f=a&(1<<-g)-1,a>>=-g,g+=n;g>0;f=f*256+e[t+w],w+=E,g-=8);if(a===0)a=1-y;else{if(a===l)return f?NaN:(I?-1:1)*(1/0);f=f+Math.pow(2,n),a=a-y}return(I?-1:1)*f*Math.pow(2,a-n)};wn.write=function(e,t,r,n,i,a){var f,u,l,y=a*8-i-1,g=(1<<y)-1,w=g>>1,E=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,I=n?0:a-1,v=n?1:-1,k=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(u=isNaN(t)?1:0,f=g):(f=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-f))<1&&(f--,l*=2),f+w>=1?t+=E/l:t+=E*Math.pow(2,1-w),t*l>=2&&(f++,l/=2),f+w>=g?(u=0,f=g):f+w>=1?(u=(t*l-1)*Math.pow(2,i),f=f+w):(u=t*Math.pow(2,w-1)*Math.pow(2,i),f=0));i>=8;e[r+I]=u&255,I+=v,u/=256,i-=8);for(f=f<<i|u,y+=i;y>0;e[r+I]=f&255,I+=v,f/=256,y-=8);e[r+I-v]|=k*128};/*!
26
26
  * The buffer module from node.js, for the browser.
package/dist/index.js CHANGED
@@ -1677,7 +1677,7 @@ const Ot = (e) => e.length === 64 ? e : e.slice(2), za = (e) => {
1677
1677
  ethereum_localnet: zs,
1678
1678
  arbitrum_localnet: Gs,
1679
1679
  base_sepolia: Oa
1680
- }, c0 = async (e, t) => {
1680
+ }, cl = async (e, t) => {
1681
1681
  var n;
1682
1682
  const r = Ga[e];
1683
1683
  if (r)
@@ -1716,7 +1716,7 @@ const Ot = (e) => e.length === 64 ? e : e.slice(2), za = (e) => {
1716
1716
  else
1717
1717
  return M("Chain not supported");
1718
1718
  }, ja = (e) => typeof e == "object" && e !== null && "code" in e && e.code === 4902, Wa = (e, t, r, n) => e + ":" + t.toLowerCase() + "::" + r + ":" + n.toLowerCase();
1719
- var ie = /* @__PURE__ */ ((e) => (e.Created = "Created", e.Matched = "Matched", e.InitiateDetected = "InitiateDetected", e.Initiated = "Initiated", e.CounterPartyInitiateDetected = "CounterPartyInitiateDetected", e.CounterPartyInitiated = "CounterPartyInitiated", e.RedeemDetected = "RedeemDetected", e.Redeemed = "Redeemed", e.CounterPartyRedeemDetected = "CounterPartyRedeemDetected", e.CounterPartyRedeemed = "CounterPartyRedeemed", e.Completed = "Completed", e.CounterPartySwapExpired = "CounterPartySwapExpired", e.Expired = "Expired", e.RefundDetected = "RefundDetected", e.Refunded = "Refunded", e.CounterPartyRefundDetected = "CounterPartyRefundDetected", e.CounterPartyRefunded = "CounterPartyRefunded", e.Cancelled = "Cancelled", e.DeadLineExceeded = "DeadLineExceeded", e))(ie || {}), te = /* @__PURE__ */ ((e) => (e.Idle = "Idle", e.InitiateDetected = "InitiateDetected", e.Initiated = "Initiated", e.RedeemDetected = "RedeemDetected", e.Redeemed = "Redeemed", e.RefundDetected = "RefundDetected", e.Refunded = "Refunded", e.Expired = "Expired", e))(te || {});
1719
+ var re = /* @__PURE__ */ ((e) => (e.Created = "Created", e.Matched = "Matched", e.InitiateDetected = "InitiateDetected", e.Initiated = "Initiated", e.CounterPartyInitiateDetected = "CounterPartyInitiateDetected", e.CounterPartyInitiated = "CounterPartyInitiated", e.RedeemDetected = "RedeemDetected", e.Redeemed = "Redeemed", e.CounterPartyRedeemDetected = "CounterPartyRedeemDetected", e.CounterPartyRedeemed = "CounterPartyRedeemed", e.Completed = "Completed", e.CounterPartySwapExpired = "CounterPartySwapExpired", e.Expired = "Expired", e.RefundDetected = "RefundDetected", e.Refunded = "Refunded", e.CounterPartyRefundDetected = "CounterPartyRefundDetected", e.CounterPartyRefunded = "CounterPartyRefunded", e.Cancelled = "Cancelled", e.DeadLineExceeded = "DeadLineExceeded", e))(re || {}), te = /* @__PURE__ */ ((e) => (e.Idle = "Idle", e.InitiateDetected = "InitiateDetected", e.Initiated = "Initiated", e.RedeemDetected = "RedeemDetected", e.Redeemed = "Redeemed", e.RefundDetected = "RefundDetected", e.Refunded = "Refunded", e.Expired = "Expired", e))(te || {});
1720
1720
  const qa = (e, t, r) => {
1721
1721
  const n = nn(
1722
1722
  e.source_swap,
@@ -1726,26 +1726,26 @@ const qa = (e, t, r) => {
1726
1726
  r
1727
1727
  );
1728
1728
  if (n === te.Redeemed)
1729
- return ie.CounterPartyRedeemed;
1729
+ return re.CounterPartyRedeemed;
1730
1730
  if (n === te.RedeemDetected)
1731
- return ie.CounterPartyRedeemDetected;
1732
- if (i === te.Redeemed) return ie.Redeemed;
1731
+ return re.CounterPartyRedeemDetected;
1732
+ if (i === te.Redeemed) return re.Redeemed;
1733
1733
  if (i === te.RedeemDetected)
1734
- return ie.RedeemDetected;
1735
- if (n === te.Refunded) return ie.Refunded;
1734
+ return re.RedeemDetected;
1735
+ if (n === te.Refunded) return re.Refunded;
1736
1736
  if (n === te.RefundDetected)
1737
- return ie.RefundDetected;
1737
+ return re.RefundDetected;
1738
1738
  if (i === te.Refunded)
1739
- return ie.CounterPartyRefunded;
1739
+ return re.CounterPartyRefunded;
1740
1740
  if (i === te.RefundDetected)
1741
- return ie.CounterPartyRefundDetected;
1741
+ return re.CounterPartyRefundDetected;
1742
1742
  if (i === te.Expired)
1743
- return ie.CounterPartySwapExpired;
1744
- if (n === te.Expired) return ie.Expired;
1743
+ return re.CounterPartySwapExpired;
1744
+ if (n === te.Expired) return re.Expired;
1745
1745
  const a = Number(
1746
1746
  e.create_order.additional_data.deadline
1747
1747
  );
1748
- return i === te.Initiated ? ie.CounterPartyInitiated : i === te.InitiateDetected ? ie.CounterPartyInitiateDetected : Kn(a, 12) ? ie.DeadLineExceeded : n === te.Initiated ? ie.Initiated : Kn(a, 1) ? ie.DeadLineExceeded : n === te.InitiateDetected ? ie.InitiateDetected : ie.Matched;
1748
+ return i === te.Initiated ? re.CounterPartyInitiated : i === te.InitiateDetected ? re.CounterPartyInitiateDetected : Kn(a, 12) ? re.DeadLineExceeded : n === te.Initiated ? re.Initiated : Kn(a, 1) ? re.DeadLineExceeded : n === te.InitiateDetected ? re.InitiateDetected : re.Matched;
1749
1749
  }, nn = (e, t) => {
1750
1750
  if (e.redeem_tx_hash)
1751
1751
  return Number(e.redeem_block_number) ? te.Redeemed : te.RedeemDetected;
@@ -1762,12 +1762,13 @@ const qa = (e, t, r) => {
1762
1762
  t,
1763
1763
  r
1764
1764
  )) {
1765
- case ie.Matched:
1765
+ case re.Matched:
1766
1766
  return ye.Initiate;
1767
- case ie.CounterPartyInitiated:
1768
- case ie.CounterPartyInitiateDetected:
1767
+ case re.CounterPartyInitiated:
1768
+ case re.CounterPartyInitiateDetected:
1769
+ case re.RedeemDetected:
1769
1770
  return ye.Redeem;
1770
- case ie.Expired:
1771
+ case re.Expired:
1771
1772
  return ye.Refund;
1772
1773
  default:
1773
1774
  return ye.Idle;
@@ -2709,7 +2710,7 @@ class rf {
2709
2710
  }
2710
2711
  }
2711
2712
  }
2712
- class l0 {
2713
+ class ll {
2713
2714
  constructor(t) {
2714
2715
  if (this.eventListeners = /* @__PURE__ */ new Map(), this.getOrderThreshold = 20, this.pendingOrdersCount = 0, this.useRelay = !0, this.orderBook = new js({
2715
2716
  url: t.orderbookURl,
@@ -2959,12 +2960,17 @@ class l0 {
2959
2960
  this.emit("success", t, ye.Redeem, a.val), this.orderExecutorCache.set(t, ye.Redeem, a.val);
2960
2961
  }
2961
2962
  async btcRedeem(t, r, n) {
2962
- var f;
2963
- const i = this.orderExecutorCache.get(r, ye.Redeem);
2964
- let a = !1;
2963
+ var u, l;
2964
+ const i = this.orderExecutorCache.get(r, ye.Redeem), a = (u = r.destination_swap.initiate_tx_hash.split(",").at(-1)) == null ? void 0 : u.split(":").at(0);
2965
+ if (!a) {
2966
+ this.emit("error", r, "Failed to get initiate_tx_hash");
2967
+ return;
2968
+ }
2969
+ console.log("initTx :", a);
2970
+ let f = !1;
2965
2971
  if (i)
2966
- if (i.btcRedeemUTXO && i.btcRedeemUTXO !== r.destination_swap.initiate_tx_hash)
2967
- a = !0, this.emit("log", r.create_order.create_id, "rbf btc redeem");
2972
+ if (console.log("cache inside bitcoin redeem: ", i), i.btcRedeemUTXO && i.btcRedeemUTXO !== a)
2973
+ f = !0, this.emit("log", r.create_order.create_id, "rbf btc redeem");
2968
2974
  else {
2969
2975
  this.emit(
2970
2976
  "log",
@@ -2973,28 +2979,23 @@ class l0 {
2973
2979
  );
2974
2980
  return;
2975
2981
  }
2976
- this.emit("log", r.create_order.create_id, "executing btc redeem");
2982
+ console.log("rbf :", f), this.emit("log", r.create_order.create_id, "executing btc redeem");
2977
2983
  try {
2978
- const l = await (await pr.from(
2984
+ const g = await (await pr.from(
2979
2985
  t,
2980
2986
  Number(r.destination_swap.amount),
2981
2987
  r.create_order.secret_hash,
2982
2988
  Ot(r.destination_swap.initiator),
2983
2989
  Ot(r.destination_swap.redeemer),
2984
2990
  r.destination_swap.timelock,
2985
- a ? [r.destination_swap.initiate_tx_hash] : []
2991
+ f ? [a] : []
2986
2992
  )).redeem(
2987
2993
  nt(n),
2988
- (f = r.create_order.additional_data) == null ? void 0 : f.bitcoin_optional_recipient
2989
- );
2990
- this.emit("success", r, ye.Redeem, l), this.orderExecutorCache.set(
2991
- r,
2992
- ye.Redeem,
2993
- l,
2994
- r.destination_swap.initiate_tx_hash
2994
+ (l = r.create_order.additional_data) == null ? void 0 : l.bitcoin_optional_recipient
2995
2995
  );
2996
- } catch (u) {
2997
- this.emit("error", r, "Failed btc redeem: " + u);
2996
+ this.emit("success", r, ye.Redeem, g), this.orderExecutorCache.set(r, ye.Redeem, g, a);
2997
+ } catch (y) {
2998
+ this.emit("error", r, "Failed btc redeem: " + y);
2998
2999
  }
2999
3000
  }
3000
3001
  async btcRefund(t, r) {
@@ -3856,10 +3857,10 @@ In.write = function(e, t, r, n, i, a) {
3856
3857
  return 1;
3857
3858
  if (o >>>= 0, h >>>= 0, b >>>= 0, x >>>= 0, this === s) return 0;
3858
3859
  let B = x - b, q = h - o;
3859
- const re = Math.min(B, q), ee = this.slice(b, x), ne = s.slice(o, h);
3860
- for (let Y = 0; Y < re; ++Y)
3861
- if (ee[Y] !== ne[Y]) {
3862
- B = ee[Y], q = ne[Y];
3860
+ const ne = Math.min(B, q), ee = this.slice(b, x), ie = s.slice(o, h);
3861
+ for (let Y = 0; Y < ne; ++Y)
3862
+ if (ee[Y] !== ie[Y]) {
3863
+ B = ee[Y], q = ie[Y];
3863
3864
  break;
3864
3865
  }
3865
3866
  return B < q ? -1 : q < B ? 1 : 0;
@@ -3885,26 +3886,26 @@ In.write = function(e, t, r, n, i, a) {
3885
3886
  return -1;
3886
3887
  x = 2, B /= 2, q /= 2, o /= 2;
3887
3888
  }
3888
- function re(ne, Y) {
3889
- return x === 1 ? ne[Y] : ne.readUInt16BE(Y * x);
3889
+ function ne(ie, Y) {
3890
+ return x === 1 ? ie[Y] : ie.readUInt16BE(Y * x);
3890
3891
  }
3891
3892
  let ee;
3892
3893
  if (b) {
3893
- let ne = -1;
3894
+ let ie = -1;
3894
3895
  for (ee = o; ee < B; ee++)
3895
- if (re(c, ee) === re(s, ne === -1 ? 0 : ee - ne)) {
3896
- if (ne === -1 && (ne = ee), ee - ne + 1 === q) return ne * x;
3896
+ if (ne(c, ee) === ne(s, ie === -1 ? 0 : ee - ie)) {
3897
+ if (ie === -1 && (ie = ee), ee - ie + 1 === q) return ie * x;
3897
3898
  } else
3898
- ne !== -1 && (ee -= ee - ne), ne = -1;
3899
+ ie !== -1 && (ee -= ee - ie), ie = -1;
3899
3900
  } else
3900
3901
  for (o + q > B && (o = B - q), ee = o; ee >= 0; ee--) {
3901
- let ne = !0;
3902
+ let ie = !0;
3902
3903
  for (let Y = 0; Y < q; Y++)
3903
- if (re(c, ee + Y) !== re(s, Y)) {
3904
- ne = !1;
3904
+ if (ne(c, ee + Y) !== ne(s, Y)) {
3905
+ ie = !1;
3905
3906
  break;
3906
3907
  }
3907
- if (ne) return ee;
3908
+ if (ie) return ee;
3908
3909
  }
3909
3910
  return -1;
3910
3911
  }
@@ -3996,19 +3997,19 @@ In.write = function(e, t, r, n, i, a) {
3996
3997
  const x = c[b];
3997
3998
  let B = null, q = x > 239 ? 4 : x > 223 ? 3 : x > 191 ? 2 : 1;
3998
3999
  if (b + q <= o) {
3999
- let re, ee, ne, Y;
4000
+ let ne, ee, ie, Y;
4000
4001
  switch (q) {
4001
4002
  case 1:
4002
4003
  x < 128 && (B = x);
4003
4004
  break;
4004
4005
  case 2:
4005
- re = c[b + 1], (re & 192) === 128 && (Y = (x & 31) << 6 | re & 63, Y > 127 && (B = Y));
4006
+ ne = c[b + 1], (ne & 192) === 128 && (Y = (x & 31) << 6 | ne & 63, Y > 127 && (B = Y));
4006
4007
  break;
4007
4008
  case 3:
4008
- re = c[b + 1], ee = c[b + 2], (re & 192) === 128 && (ee & 192) === 128 && (Y = (x & 15) << 12 | (re & 63) << 6 | ee & 63, Y > 2047 && (Y < 55296 || Y > 57343) && (B = Y));
4009
+ ne = c[b + 1], ee = c[b + 2], (ne & 192) === 128 && (ee & 192) === 128 && (Y = (x & 15) << 12 | (ne & 63) << 6 | ee & 63, Y > 2047 && (Y < 55296 || Y > 57343) && (B = Y));
4009
4010
  break;
4010
4011
  case 4:
4011
- re = c[b + 1], ee = c[b + 2], ne = c[b + 3], (re & 192) === 128 && (ee & 192) === 128 && (ne & 192) === 128 && (Y = (x & 15) << 18 | (re & 63) << 12 | (ee & 63) << 6 | ne & 63, Y > 65535 && Y < 1114112 && (B = Y));
4012
+ ne = c[b + 1], ee = c[b + 2], ie = c[b + 3], (ne & 192) === 128 && (ee & 192) === 128 && (ie & 192) === 128 && (Y = (x & 15) << 18 | (ne & 63) << 12 | (ee & 63) << 6 | ie & 63, Y > 65535 && Y < 1114112 && (B = Y));
4012
4013
  }
4013
4014
  }
4014
4015
  B === null ? (B = 65533, q = 1) : B > 65535 && (B -= 65536, h.push(B >>> 10 & 1023 | 55296), B = 56320 | B & 1023), h.push(B), b += q;
@@ -4203,8 +4204,8 @@ In.write = function(e, t, r, n, i, a) {
4203
4204
  return qe(this, s, o, BigInt(0), BigInt("0xffffffffffffffff"));
4204
4205
  }), u.prototype.writeIntLE = function(s, o, h, b) {
4205
4206
  if (s = +s, o = o >>> 0, !b) {
4206
- const re = Math.pow(2, 8 * h - 1);
4207
- oe(this, s, o, h, re - 1, -re);
4207
+ const ne = Math.pow(2, 8 * h - 1);
4208
+ oe(this, s, o, h, ne - 1, -ne);
4208
4209
  }
4209
4210
  let x = 0, B = 1, q = 0;
4210
4211
  for (this[o] = s & 255; ++x < h && (B *= 256); )
@@ -4212,8 +4213,8 @@ In.write = function(e, t, r, n, i, a) {
4212
4213
  return o + h;
4213
4214
  }, u.prototype.writeIntBE = function(s, o, h, b) {
4214
4215
  if (s = +s, o = o >>> 0, !b) {
4215
- const re = Math.pow(2, 8 * h - 1);
4216
- oe(this, s, o, h, re - 1, -re);
4216
+ const ne = Math.pow(2, 8 * h - 1);
4217
+ oe(this, s, o, h, ne - 1, -ne);
4217
4218
  }
4218
4219
  let x = h - 1, B = 1, q = 0;
4219
4220
  for (this[o + x] = s & 255; --x >= 0 && (B *= 256); )
@@ -7480,7 +7481,7 @@ const we = Qi, Xc = Bf, Si = Yc, Qc = kr, Qr = we.typeforce.maybe(
7480
7481
  network: we.maybe(we.Network)
7481
7482
  })
7482
7483
  ), Zc = (e) => e.length === 32 ? e : e.slice(1, 33);
7483
- function e0(e) {
7484
+ function el(e) {
7484
7485
  (0, Qc.testEcc)(e);
7485
7486
  function t(u) {
7486
7487
  return e.isPoint(u);
@@ -7594,7 +7595,7 @@ function e0(e) {
7594
7595
  makeRandom: a
7595
7596
  };
7596
7597
  }
7597
- Et.ECPairFactory = e0;
7598
+ Et.ECPairFactory = el;
7598
7599
  (function(e) {
7599
7600
  Object.defineProperty(e, "__esModule", { value: !0 }), e.networks = e.ECPairFactory = e.default = void 0;
7600
7601
  var t = Et;
@@ -7668,7 +7669,7 @@ class dn {
7668
7669
  return r.fromPrivateKey(f).sign(Buffer.from(nt(a), "hex")).toString("hex");
7669
7670
  }
7670
7671
  }
7671
- class d0 {
7672
+ class dl {
7672
7673
  constructor(t) {
7673
7674
  this.quoteUrl = new pn("/quote", t);
7674
7675
  }
@@ -7728,16 +7729,16 @@ class d0 {
7728
7729
  export {
7729
7730
  rf as BlockNumberFetcher,
7730
7731
  Ya as EvmRelay,
7731
- l0 as Garden,
7732
+ ll as Garden,
7732
7733
  ye as OrderActions,
7733
- ie as OrderStatus,
7734
+ re as OrderStatus,
7734
7735
  qa as ParseOrderStatus,
7735
7736
  nn as ParseSwapStatus,
7736
- d0 as Quote,
7737
+ dl as Quote,
7737
7738
  dn as SecretManager,
7738
7739
  te as SwapStatus,
7739
7740
  en as TimeLocks,
7740
7741
  Wa as constructOrderPair,
7741
7742
  Va as parseAction,
7742
- c0 as switchOrAddNetwork
7743
+ cl as switchOrAddNetwork
7743
7744
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gardenfi/core",
3
- "version": "0.2.0-beta.55",
3
+ "version": "0.2.0-beta.56",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist"