@gardenfi/core 0.2.0-beta.33 → 0.2.0-beta.35
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 +2 -2
- package/dist/index.js +19 -8
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var li=Object.defineProperty;var hi=(e,t,r)=>t in e?li(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var nt=(e,t,r)=>hi(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("@catalogfi/utils"),J=require("@gardenfi/orderbook"),ge=require("@gardenfi/utils"),Ne=require("viem"),di=require("varuint-bitcoin"),pi=require("tiny-secp256k1"),Nr=require("@catalogfi/wallets"),gn=require("bitcoinjs-lib"),bi=require("bignumber.js");function Tr(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const Ur=Tr(di),ft=Tr(pi),de=Tr(gn);var gr=(e=>(e[e.evm=14400]="evm",e[e.btc=288]="btc",e))(gr||{}),pe=(e=>(e.Idle="Idle",e.Initiate="Initiate",e.Redeem="Redeem",e.Refund="Refund",e))(pe||{});function qt(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}const yi=qt({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}}}),_i=qt({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}),gi=qt({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}}}),wi=qt({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 wr(e){return typeof e=="string"&&(e=Buffer.from(e,"hex")),e.length===32?e:e.subarray(1,33)}function it(e,t){if(!e)throw new Error(t)}function mi(e){return Buffer.concat([Uint8Array.from([192]),vi(e)])}function vi(e){const t=Ur.encodingLength(e.length),r=Buffer.allocUnsafe(t);return Ur.encode(e.length,r),Buffer.concat([r,e])}function xi(e,t){if(e.compare(t)>0){const r=e;e=t,t=r}return[e,t]}const yt=e=>e.length===64?e:e.slice(2),Ei=e=>{if(!e)return!1;try{const t=Buffer.from(e,"hex");return ft.isPoint(t)}catch{return!1}},Bi={ethereum:gi,ethereum_arbitrum:yi,ethereum_sepolia:wi,arbitrum_sepolia:_i,ethereum_localnet:J.EthereumLocalnet,arbitrum_localnet:J.ArbitrumLocalnet},Ri=async(e,t)=>{var a;const r=Bi[e];if(r)try{if(r.id===((a=t.chain)==null?void 0:a.id))return C.Ok({message:"Already on the network",walletClient:t});await t.switchChain({id:r.id});const o=Ne.createWalletClient({account:t.account,chain:r,transport:Ne.custom(window.ethereum)});return C.Ok({message:"Switched chain",walletClient:o})}catch(o){if(Si(o))try{await t.addChain({chain:r});const s=Ne.createWalletClient({account:t.account,chain:r,transport:Ne.custom(window.ethereum)});return C.Ok({message:"Added network",walletClient:s})}catch{return C.Err("Failed to add network")}else return C.Err("Failed to switch network")}else return C.Err("Chain not supported")},Si=e=>typeof e=="object"&&e!==null&&"code"in e&&e.code===4902;var ae=(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))(ae||{}),ee=(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))(ee||{});const wn=(e,t,r)=>{const a=Ft(e.source_swap,t),o=Ft(e.destination_swap,r);if(a===ee.RedeemDetected)return ae.CounterPartyRedeemDetected;if(a===ee.Redeemed)return ae.CounterPartyRedeemed;if(o===ee.RedeemDetected)return ae.RedeemDetected;if(o===ee.Redeemed)return ae.Redeemed;if(o===ee.RefundDetected)return ae.CounterPartyRefundDetected;if(o===ee.Refunded)return ae.CounterPartyRefunded;if(a===ee.RefundDetected)return ae.RefundDetected;if(a===ee.Refunded)return ae.Refunded;if(o===ee.Expired)return ae.CounterPartySwapExpired;if(a===ee.Expired)return ae.Expired;const s=Number(e.create_order.additional_data.deadline)*1e3;return o===ee.InitiateDetected?ae.CounterPartyInitiateDetected:o===ee.Initiated?ae.CounterPartyInitiated:Dr(s,1)?ae.Expired:a===ee.InitiateDetected?ae.InitiateDetected:Dr(s,12)?ae.Expired:a===ee.Initiated?ae.Initiated:ae.Matched},Ft=(e,t)=>{if(e.redeem_tx_hash)return e.redeem_block_number?ee.Redeemed:ee.RedeemDetected;if(e.refund_tx_hash)return e.refund_block_number?ee.Refunded:ee.RefundDetected;if(Number(e.initiate_block_number)){const r=Number(e.initiate_block_number)+e.timelock;if(t>r)return ee.Expired}return e.initiate_tx_hash?e.initiate_block_number?ee.Initiated:ee.InitiateDetected:ee.Idle},mn=(e,t,r)=>{switch(wn(e,t,r)){case ae.Matched:return pe.Initiate;case ae.CounterPartyInitiated:return pe.Redeem;case ae.Expired:return pe.Refund;default:return pe.Idle}},Dr=(e,t=0)=>{const r=Date.now(),a=e*1e3+t*36e5;return r>=a},Ai=[{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 vn{constructor(t,r,a){this.url=new ge.Url("/relayer",r),this.auth=a,this.order=t}async init(t,r){if(!t.account)return C.Err("No account found");if(t.account.address.toLowerCase()!==this.order.source_swap.initiator.toLowerCase())return C.Err("Account address and order initiator mismatch");if(!r){const m=await ge.fetchEVMBlockNumber(t);if(m.error)return C.Err(m.error);r=m.val}if(Ft(this.order.source_swap,r)!==ee.Idle)return C.Err("Invalid swap status");const{create_order:o,source_swap:s}=this.order;if(!s.amount||!s.redeemer||!o.timelock||!o.secret_hash)return C.Err("Invalid order");const c=ge.with0x(o.secret_hash),u=BigInt(o.timelock),p=ge.with0x(s.redeemer),w=BigInt(s.amount);try{const m=await this.auth.getToken();if(m.error)return C.Err(m.error);const v=Ne.getContract({address:ge.with0x(this.order.source_swap.asset),abi:Ai,client:t}),T=await v.read.token(),O=await ge.checkAllowanceAndApprove(Number(w),T,this.order.source_swap.asset,t);if(O.error)return C.Err(O.error);const R=await v.read.eip712Domain(),k=await t.signTypedData({account:t.account,domain:{name:R[1],version:R[2],chainId:Number(R[3]),verifyingContract:R[4]},types:{Initiate:[{name:"redeemer",type:"address"},{name:"timelock",type:"uint256"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"}]},primaryType:"Initiate",message:{redeemer:p,timelock:u,amount:w,secretHash:c}}),A=await C.Fetcher.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:o.create_id,signature:k,perform_on:"Source"}),headers:{Authorization:ge.Authorization(m.val),"Content-Type":"application/json"}});return A.error?C.Err(A.error):A.result?C.Ok(A.result):C.Err("Init: No result found")}catch(m){return console.log("init error :",m),C.Err(String(m))}}async redeem(t,r){try{const a=await this.auth.getToken();if(a.error)return C.Err(a.error);const o=await C.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t,secret:C.trim0x(r),perform_on:"Destination"}),headers:{Authorization:ge.Authorization(a.val),"Content-Type":"application/json"}});return o.error?C.Err(o.error):o.result?C.Ok(o.result):C.Err("Redeem: No result found")}catch(a){return C.Err(String(a))}}}const Ti=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),Ii=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),ki=Buffer.concat([Ti,Ii]),Ci=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),$r={failedToCreateInternalPubkey:"failed to create internal pubkey",failedToTweakPubkey:"failed to tweak pubkey"};function Oi(){const e=gn.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),t=ft.pointMultiply(Buffer.concat([Buffer.from("04","hex"),ki]),e);if(!t)throw new Error($r.failedToCreateInternalPubkey);const r=ft.pointAdd(Ci,t);if(!r)throw new Error($r.failedToCreateInternalPubkey);return wr(Buffer.from(r))}const ye={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"},Ot=192;de.initEccLib(ft);class Nt{constructor(t,r,a,o,s,c,u,p){this.secretHash=a,this.redeemerPubkey=o,this.initiatorPubkey=s,this.expiry=c,this.signer=t,this.network=u,this.internalPubkey=Oi(),this.initiateAmount=r,this.utxoHashes=p}static async from(t,r,a,o,s,c,u){a=a.startsWith("0x")?a.slice(2):a,it(a.length===64,ye.secretHashLenMismatch),it(o.length===64||o.length===66,`initiator ${ye.pubkeyLenMismatch}`),it(s.length===64||s.length===66,`redeemer ${ye.pubkeyLenMismatch}`),it(c>0,ye.zeroOrNegativeExpiry);const p=await t.getNetwork();return new Nt(t,r,a,wr(s).toString("hex"),wr(o).toString("hex"),c,p,u)}address(){const{address:t}=de.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves()});if(!t)throw new Error(ye.htlcAddressGenerationFailed);return t}id(){return this.address()}async _buildRawTx(t,r){const a=new de.Transaction;a.version=2;const o=this.address(),s=await this.signer.getProvider();let c=[];if(this.utxoHashes&&this.utxoHashes.length>0)for(const p of this.utxoHashes){const w=await s.getTransaction(p);for(let m=0;m<w.vout.length;m++){const v=w.vout[m];v.scriptpubkey_address===o&&c.push({txid:w.txid,vout:m,value:v.value,status:{confirmed:!1}})}}else c=await s.getUTXOs(o);const u=c.reduce((p,w)=>p+w.value,0);if(u===0)throw new Error(`${o} ${ye.notFunded}`);for(let p=0;p<c.length;p++)a.addInput(Buffer.from(c[p].txid,"hex").reverse(),c[p].vout);return r??(r=await s.suggestFee(o,u,Nr.Urgency.MEDIUM)),a.addOutput(de.address.toOutputScript(t,this.network),u-r),{tx:a,usedUtxos:c}}async buildRawTx(t){return await this._buildRawTx(await this.signer.getAddress(),t)}getOutputScript(){return de.address.toOutputScript(this.address(),this.network)}async init(t){return t??(t=await(await this.signer.getProvider()).suggestFee(await this.signer.getAddress(),this.initiateAmount,Nr.Urgency.MEDIUM)),await this.signer.send(this.address(),this.initiateAmount,t)}async instantRefund(t,r){it(t.length>0,ye.noCounterpartySigs);const{tx:a,usedUtxos:o}=await this.buildRawTx(r);for(const v of o)if(!t.find(T=>T.utxo===v.txid))throw new Error(ye.counterPartySigNotFound(v.txid));const s=this.getOutputScript(),c=de.Transaction.SIGHASH_DEFAULT,u=this.leafHash(2),p=o.map(v=>v.value),w=rr(s,o.length);for(let v=0;v<a.ins.length;v++){const T=a.hashForWitnessV1(v,w,p,c,u);if(!ft.verifySchnorr(T,Buffer.from(this.redeemerPubkey,"hex"),Buffer.from(t[v].sig,"hex")))throw new Error(ye.invalidCounterpartySigForUTXO(t[v].utxo));const O=await this.signer.signSchnorr(T),R=Buffer.from(a.ins[v].hash).reverse().toString("hex"),k=t.find(A=>A.utxo===R);if(!k)throw new Error(ye.counterPartySigNotFound(R));a.setWitness(v,[Buffer.from(k.sig,"hex"),O,this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return await(await this.signer.getProvider()).broadcast(a.toHex())}async redeem(t,r,a){it(de.crypto.sha256(Buffer.from(t,"hex")).toString("hex")===this.secretHash,ye.secretMismatch);const{tx:o,usedUtxos:s}=await this._buildRawTx(r??await this.signer.getAddress(),a),c=this.leafHash(1),u=s.map(v=>v.value),p=rr(this.getOutputScript(),s.length),w=de.Transaction.SIGHASH_DEFAULT;for(let v=0;v<o.ins.length;v++){const T=o.hashForWitnessV1(v,p,u,w,c),O=await this.signer.signSchnorr(T);o.setWitness(v,[O,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return await(await this.signer.getProvider()).broadcast(o.toHex())}async refund(t,r){const{tx:a,usedUtxos:o}=await this._buildRawTx(t??await this.signer.getAddress(),r),[s,c]=await this.canRefund(o);if(!s)throw new Error(ye.htlcNotExpired(c));const u=this.leafHash(0),p=o.map(T=>T.value),w=rr(this.getOutputScript(),o.length),m=de.Transaction.SIGHASH_DEFAULT;for(let T=0;T<a.ins.length;T++){a.ins[T].sequence=this.expiry;const O=a.hashForWitnessV1(T,w,p,m,u),R=await this.signer.signSchnorr(O);a.setWitness(T,[R,this.refundLeaf(),this.generateControlBlockFor(0)])}return await(await this.signer.getProvider()).broadcast(a.toHex())}async canRefund(t){const a=await(await this.signer.getProvider()).getLatestTip();for(const o of t){let s=0;if(o.status.confirmed&&o.status.block_height+this.expiry>a?s=o.status.block_height+this.expiry-a+1:o.status.confirmed||(s=this.expiry+1),s>0)return[!1,s]}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(ye.invalidLeaf)}const a=de.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves(),redeem:{output:r,redeemVersion:Ot}});if(!a.witness)throw new Error(ye.controlBlockGenerationFailed);return a.witness[a.witness.length-1]}leafHash(t){let r=this.redeemLeaf();return t===0&&(r=this.refundLeaf()),t===2&&(r=this.instantRefundLeaf()),de.crypto.taggedHash("TapLeaf",mi(r))}refundLeaf(){return de.script.fromASM(`
|
|
1
|
+
"use strict";var li=Object.defineProperty;var hi=(e,t,r)=>t in e?li(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var nt=(e,t,r)=>hi(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("@catalogfi/utils"),J=require("@gardenfi/orderbook"),ge=require("@gardenfi/utils"),Ne=require("viem"),di=require("varuint-bitcoin"),pi=require("tiny-secp256k1"),Nr=require("@catalogfi/wallets"),gn=require("bitcoinjs-lib"),bi=require("bignumber.js");function Tr(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const Ur=Tr(di),ft=Tr(pi),de=Tr(gn);var gr=(e=>(e[e.evm=14400]="evm",e[e.btc=288]="btc",e))(gr||{}),pe=(e=>(e.Idle="Idle",e.Initiate="Initiate",e.Redeem="Redeem",e.Refund="Refund",e))(pe||{});function qt(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}const yi=qt({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}}}),_i=qt({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}),gi=qt({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}}}),wi=qt({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 wr(e){return typeof e=="string"&&(e=Buffer.from(e,"hex")),e.length===32?e:e.subarray(1,33)}function it(e,t){if(!e)throw new Error(t)}function mi(e){return Buffer.concat([Uint8Array.from([192]),vi(e)])}function vi(e){const t=Ur.encodingLength(e.length),r=Buffer.allocUnsafe(t);return Ur.encode(e.length,r),Buffer.concat([r,e])}function xi(e,t){if(e.compare(t)>0){const r=e;e=t,t=r}return[e,t]}const yt=e=>e.length===64?e:e.slice(2),Ei=e=>{if(!e)return!1;try{const t=Buffer.from(e,"hex");return ft.isPoint(t)}catch{return!1}},Bi={ethereum:gi,ethereum_arbitrum:yi,ethereum_sepolia:wi,arbitrum_sepolia:_i,ethereum_localnet:J.EthereumLocalnet,arbitrum_localnet:J.ArbitrumLocalnet},Ri=async(e,t)=>{var a;const r=Bi[e];if(r)try{if(r.id===((a=t.chain)==null?void 0:a.id))return C.Ok({message:"Already on the network",walletClient:t});await t.switchChain({id:r.id});const o=Ne.createWalletClient({account:t.account,chain:r,transport:Ne.custom(window.ethereum)});return C.Ok({message:"Switched chain",walletClient:o})}catch(o){if(Si(o))try{await t.addChain({chain:r});const s=Ne.createWalletClient({account:t.account,chain:r,transport:Ne.custom(window.ethereum)});return C.Ok({message:"Added network",walletClient:s})}catch{return C.Err("Failed to add network")}else return C.Err("Failed to switch network")}else return C.Err("Chain not supported")},Si=e=>typeof e=="object"&&e!==null&&"code"in e&&e.code===4902;var ae=(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))(ae||{}),ee=(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))(ee||{});const wn=(e,t,r)=>{const a=Ft(e.source_swap,t),o=Ft(e.destination_swap,r);if(a===ee.RedeemDetected)return ae.CounterPartyRedeemDetected;if(a===ee.Redeemed)return ae.CounterPartyRedeemed;if(o===ee.RedeemDetected)return ae.RedeemDetected;if(o===ee.Redeemed)return ae.Redeemed;if(o===ee.RefundDetected)return ae.CounterPartyRefundDetected;if(o===ee.Refunded)return ae.CounterPartyRefunded;if(a===ee.RefundDetected)return ae.RefundDetected;if(a===ee.Refunded)return ae.Refunded;if(o===ee.Expired)return ae.CounterPartySwapExpired;if(a===ee.Expired)return ae.Expired;const s=Number(e.create_order.additional_data.deadline);return o===ee.InitiateDetected?ae.CounterPartyInitiateDetected:o===ee.Initiated?ae.CounterPartyInitiated:Dr(s,1)?ae.Expired:a===ee.InitiateDetected?ae.InitiateDetected:Dr(s,12)?ae.Expired:a===ee.Initiated?ae.Initiated:ae.Matched},Ft=(e,t)=>{if(e.redeem_tx_hash)return e.redeem_block_number?ee.Redeemed:ee.RedeemDetected;if(e.refund_tx_hash)return e.refund_block_number?ee.Refunded:ee.RefundDetected;if(Number(e.initiate_block_number)){const r=Number(e.initiate_block_number)+e.timelock;if(t>r)return ee.Expired}return e.initiate_tx_hash?e.initiate_block_number?ee.Initiated:ee.InitiateDetected:ee.Idle},mn=(e,t,r)=>{const a=wn(e,t,r);switch(console.log("orderId: ",e.create_order.create_id," orderStatus :",a),a){case ae.Matched:return pe.Initiate;case ae.CounterPartyInitiated:return pe.Redeem;case ae.Expired:return pe.Refund;default:return pe.Idle}},Dr=(e,t=0)=>{const r=Date.now(),a=e*1e3+t*36e5;return r>=a},Ai=[{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 vn{constructor(t,r,a){this.url=new ge.Url("/relayer",r),this.auth=a,this.order=t}async init(t,r){if(!t.account)return C.Err("No account found");if(t.account.address.toLowerCase()!==this.order.source_swap.initiator.toLowerCase())return C.Err("Account address and order initiator mismatch");if(!r){const m=await ge.fetchEVMBlockNumber(t);if(m.error)return C.Err(m.error);r=m.val}if(Ft(this.order.source_swap,r)!==ee.Idle)return C.Err("Invalid swap status");const{create_order:o,source_swap:s}=this.order;if(!s.amount||!s.redeemer||!o.timelock||!o.secret_hash)return C.Err("Invalid order");const c=ge.with0x(o.secret_hash),u=BigInt(o.timelock),p=ge.with0x(s.redeemer),w=BigInt(s.amount);try{const m=await this.auth.getToken();if(m.error)return C.Err(m.error);const v=Ne.getContract({address:ge.with0x(this.order.source_swap.asset),abi:Ai,client:t}),T=await v.read.token(),O=await ge.checkAllowanceAndApprove(Number(w),T,this.order.source_swap.asset,t);if(O.error)return C.Err(O.error);const R=await v.read.eip712Domain(),k=await t.signTypedData({account:t.account,domain:{name:R[1],version:R[2],chainId:Number(R[3]),verifyingContract:R[4]},types:{Initiate:[{name:"redeemer",type:"address"},{name:"timelock",type:"uint256"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"}]},primaryType:"Initiate",message:{redeemer:p,timelock:u,amount:w,secretHash:c}}),A=await C.Fetcher.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:o.create_id,signature:k,perform_on:"Source"}),headers:{Authorization:ge.Authorization(m.val),"Content-Type":"application/json"}});return A.error?C.Err(A.error):A.result?C.Ok(A.result):C.Err("Init: No result found")}catch(m){return console.log("init error :",m),C.Err(String(m))}}async redeem(t,r){try{const a=await this.auth.getToken();if(a.error)return C.Err(a.error);const o=await C.Fetcher.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t,secret:C.trim0x(r),perform_on:"Destination"}),headers:{Authorization:ge.Authorization(a.val),"Content-Type":"application/json"}});return o.error?C.Err(o.error):o.result?C.Ok(o.result):C.Err("Redeem: No result found")}catch(a){return C.Err(String(a))}}}const Ti=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),Ii=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),ki=Buffer.concat([Ti,Ii]),Ci=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),$r={failedToCreateInternalPubkey:"failed to create internal pubkey",failedToTweakPubkey:"failed to tweak pubkey"};function Oi(){const e=gn.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),t=ft.pointMultiply(Buffer.concat([Buffer.from("04","hex"),ki]),e);if(!t)throw new Error($r.failedToCreateInternalPubkey);const r=ft.pointAdd(Ci,t);if(!r)throw new Error($r.failedToCreateInternalPubkey);return wr(Buffer.from(r))}const ye={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"},Ot=192;de.initEccLib(ft);class Nt{constructor(t,r,a,o,s,c,u,p){this.secretHash=a,this.redeemerPubkey=o,this.initiatorPubkey=s,this.expiry=c,this.signer=t,this.network=u,this.internalPubkey=Oi(),this.initiateAmount=r,this.utxoHashes=p}static async from(t,r,a,o,s,c,u){a=a.startsWith("0x")?a.slice(2):a,it(a.length===64,ye.secretHashLenMismatch),it(o.length===64||o.length===66,`initiator ${ye.pubkeyLenMismatch}`),it(s.length===64||s.length===66,`redeemer ${ye.pubkeyLenMismatch}`),it(c>0,ye.zeroOrNegativeExpiry);const p=await t.getNetwork();return new Nt(t,r,a,wr(s).toString("hex"),wr(o).toString("hex"),c,p,u)}address(){const{address:t}=de.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves()});if(!t)throw new Error(ye.htlcAddressGenerationFailed);return t}id(){return this.address()}async _buildRawTx(t,r){const a=new de.Transaction;a.version=2;const o=this.address(),s=await this.signer.getProvider();let c=[];if(this.utxoHashes&&this.utxoHashes.length>0)for(const p of this.utxoHashes){const w=await s.getTransaction(p);for(let m=0;m<w.vout.length;m++){const v=w.vout[m];v.scriptpubkey_address===o&&c.push({txid:w.txid,vout:m,value:v.value,status:{confirmed:!1}})}}else c=await s.getUTXOs(o);const u=c.reduce((p,w)=>p+w.value,0);if(u===0)throw new Error(`${o} ${ye.notFunded}`);for(let p=0;p<c.length;p++)a.addInput(Buffer.from(c[p].txid,"hex").reverse(),c[p].vout);return r??(r=await s.suggestFee(o,u,Nr.Urgency.MEDIUM)),a.addOutput(de.address.toOutputScript(t,this.network),u-r),{tx:a,usedUtxos:c}}async buildRawTx(t){return await this._buildRawTx(await this.signer.getAddress(),t)}getOutputScript(){return de.address.toOutputScript(this.address(),this.network)}async init(t){return t??(t=await(await this.signer.getProvider()).suggestFee(await this.signer.getAddress(),this.initiateAmount,Nr.Urgency.MEDIUM)),await this.signer.send(this.address(),this.initiateAmount,t)}async instantRefund(t,r){it(t.length>0,ye.noCounterpartySigs);const{tx:a,usedUtxos:o}=await this.buildRawTx(r);for(const v of o)if(!t.find(T=>T.utxo===v.txid))throw new Error(ye.counterPartySigNotFound(v.txid));const s=this.getOutputScript(),c=de.Transaction.SIGHASH_DEFAULT,u=this.leafHash(2),p=o.map(v=>v.value),w=rr(s,o.length);for(let v=0;v<a.ins.length;v++){const T=a.hashForWitnessV1(v,w,p,c,u);if(!ft.verifySchnorr(T,Buffer.from(this.redeemerPubkey,"hex"),Buffer.from(t[v].sig,"hex")))throw new Error(ye.invalidCounterpartySigForUTXO(t[v].utxo));const O=await this.signer.signSchnorr(T),R=Buffer.from(a.ins[v].hash).reverse().toString("hex"),k=t.find(A=>A.utxo===R);if(!k)throw new Error(ye.counterPartySigNotFound(R));a.setWitness(v,[Buffer.from(k.sig,"hex"),O,this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return await(await this.signer.getProvider()).broadcast(a.toHex())}async redeem(t,r,a){it(de.crypto.sha256(Buffer.from(t,"hex")).toString("hex")===this.secretHash,ye.secretMismatch);const{tx:o,usedUtxos:s}=await this._buildRawTx(r??await this.signer.getAddress(),a),c=this.leafHash(1),u=s.map(v=>v.value),p=rr(this.getOutputScript(),s.length),w=de.Transaction.SIGHASH_DEFAULT;for(let v=0;v<o.ins.length;v++){const T=o.hashForWitnessV1(v,p,u,w,c),O=await this.signer.signSchnorr(T);o.setWitness(v,[O,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return await(await this.signer.getProvider()).broadcast(o.toHex())}async refund(t,r){const{tx:a,usedUtxos:o}=await this._buildRawTx(t??await this.signer.getAddress(),r),[s,c]=await this.canRefund(o);if(!s)throw new Error(ye.htlcNotExpired(c));const u=this.leafHash(0),p=o.map(T=>T.value),w=rr(this.getOutputScript(),o.length),m=de.Transaction.SIGHASH_DEFAULT;for(let T=0;T<a.ins.length;T++){a.ins[T].sequence=this.expiry;const O=a.hashForWitnessV1(T,w,p,m,u),R=await this.signer.signSchnorr(O);a.setWitness(T,[R,this.refundLeaf(),this.generateControlBlockFor(0)])}return await(await this.signer.getProvider()).broadcast(a.toHex())}async canRefund(t){const a=await(await this.signer.getProvider()).getLatestTip();for(const o of t){let s=0;if(o.status.confirmed&&o.status.block_height+this.expiry>a?s=o.status.block_height+this.expiry-a+1:o.status.confirmed||(s=this.expiry+1),s>0)return[!1,s]}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(ye.invalidLeaf)}const a=de.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves(),redeem:{output:r,redeemVersion:Ot}});if(!a.witness)throw new Error(ye.controlBlockGenerationFailed);return a.witness[a.witness.length-1]}leafHash(t){let r=this.redeemLeaf();return t===0&&(r=this.refundLeaf()),t===2&&(r=this.instantRefundLeaf()),de.crypto.taggedHash("TapLeaf",mi(r))}refundLeaf(){return de.script.fromASM(`
|
|
2
2
|
${de.script.number.encode(this.expiry).toString("hex")}
|
|
3
3
|
OP_CHECKSEQUENCEVERIFY
|
|
4
4
|
OP_DROP
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
OP_CHECKSIGADD
|
|
18
18
|
OP_2
|
|
19
19
|
OP_NUMEQUAL
|
|
20
|
-
`.trim().replace(/\s+/g," "))}leaves(){return[{version:Ot,output:this.redeemLeaf()},[{version:Ot,output:this.refundLeaf()},{version:Ot,output:this.instantRefundLeaf()}]]}generateMerkleProofFor(t){const r=this.leafHash(1),a=this.leafHash(2),o=this.leafHash(0);switch(t){case 1:{const s=xi(o,a);return[de.crypto.taggedHash("TapBranch",Buffer.concat(s))]}case 0:return[a,r];case 2:return[o,r];default:throw new Error(ye.invalidLeaf)}}}function rr(e,t){const r=[];for(let a=0;a<t;a++)r.push(e);return r}class Li{constructor(){this.cache={}}set(t,r,a,o){const s={txHash:a,timeStamp:Date.now(),btcRedeemUTXO:o};this.cache[`${r}_${t.create_order.create_id}`]=s}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 Mi{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 Li,!t.wallets.evmWallet.account)throw new Error("Account not found in evmWallet");this.evmAddress=t.wallets.evmWallet.account.address}getPendingOrderCount(){return this.pendingOrdersCount}setUseRelay(t){this.useRelay=t}async swap(t){const r=await this.validateAndFillParams(t);if(r.error)return C.Err(r.error);const{sendAddress:a,receiveAddress:o,timelock:s}=r.val,c=await this.orderBook.getOrdersCount(this.evmAddress);if(c.error)return C.Err(c.error);const u=c.val+1,p=this.secretManager.generateSecret(u);if(p.error)return C.Err(p.error);const{strategyId:w,btcAddress:m}=t.additionalData,v={strategy_id:w,...m&&{bitcoin_optional_recipient:m}},T={source_chain:t.fromAsset.chain,destination_chain:t.toAsset.chain,source_asset:t.fromAsset.atomicSwapAddress,destination_asset:t.toAsset.atomicSwapAddress,initiator_source_address:a,initiator_destination_address:o,source_amount:t.sendAmount,destination_amount:t.receiveAmount,fee:"1",nonce:u.toString(),timelock:s,secret_hash:C.trim0x(p.val.secretHash),min_destination_confirmations:t.minDestinationConfirmations??0,additional_data:v},O=await this.quote.getAttestedQuote(T);if(O.error)return C.Err(O.error);const R=await this.orderBook.createOrder(O.val);if(R.error)return C.Err(R.error);const k=await this.pollOrder(R.val);return k.error?C.Err(k.error):C.Ok(k.val)}async validateAndFillParams(t){if(t.fromAsset.chain===t.toAsset.chain&&t.fromAsset.atomicSwapAddress===t.toAsset.atomicSwapAddress)return C.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 C.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 C.Err("btcWallet is required for bitcoin chain. Please provide btcWallet in the constructor");if(!t.additionalData.btcAddress)return C.Err("btcAddress in additionalData is required for bitcoin chain")}const r=await this.getAddresses(t.fromAsset.chain);if(r.error)return C.Err(r.error);const a=await this.getAddresses(t.toAsset.chain);if(a.error)return C.Err(a.error);const o=this.validateAmount(t.sendAmount);if(o.error)return C.Err(o.error);const s=this.validateAmount(t.receiveAmount);if(s.error)return C.Err(s.error);if(o<s)return C.Err("Send amount should be greater than receive amount");const c=this.getTimelock(t.fromAsset.chain);return c?C.Ok({sendAddress:r.val,receiveAddress:a.val,timelock:t.timelock??c}):C.Err("Unsupported chain for timelock")}async getAddresses(t){var a;switch(J.getBlockchainType(t)){case J.BlockchainType.EVM:return this.wallets.evmWallet.account?C.Ok(this.wallets.evmWallet.account.address):C.Err("EVM Wallet not found");case J.BlockchainType.Bitcoin:{const o=await((a=this.wallets.btcWallet)==null?void 0:a.getPublicKey());return!o||!Ei(o)?C.Err("Invalid btc public key"):C.Ok(yt(o))}default:return C.Err("Unsupported chain")}}validateAmount(t){if(t==null||t.includes("."))return C.Err("Invalid amount ",t);const r=new bi(t);return!r.isInteger()||r.isNaN()||r.lt(0)||r.isLessThanOrEqualTo(0)?C.Err("Invalid amount ",t):C.Ok(r)}getTimelock(t){switch(J.getBlockchainType(t)){case J.BlockchainType.EVM:return gr.evm;case J.BlockchainType.Bitcoin:return gr.btc;default:return}}async pollOrder(t){let r=await this.orderBook.getOrder(t,!0),a=0;for(;a<this.getOrderThreshold;){if(await ge.sleep(1e3),a++,r.error){if(!r.error.includes("result is undefined"))return C.Err(r.error)}else if(r.val&&r.val.create_order.create_id.toLowerCase()===t.toLowerCase())return C.Ok(r.val);r=await this.orderBook.getOrder(t,!0)}return C.Err(`Order not found, createOrder id: ${t}`)}emit(t,...r){(this.eventListeners.get(t)??[]).forEach(o=>{o(...r)})}async execute(t=5e3){return await this.orderBook.subscribeToOrders(!0,t,async r=>{this.pendingOrdersCount=r.data.length,this.emit("onPendingOrdersChanged",r.data);for(let a=0;a<r.data.length;a++){const o=r.data[a],s=o.source_swap.chain,c=o.destination_swap.chain;this.emit("log",o.create_order.create_id,"executing order");const u=this.getWallet(s),p=this.getWallet(c);if(u.error||p.error||!u.val||!p.val){this.emit("error",o,"Source or Destination Wallet not found while executing order");return}const w=await this.fetchCurrentBlockNumbers(o,{source:u.val,destination:p.val});if(w.error){this.emit("error",o,"Error while fetching CurrentBlockNumbers: "+w.error);return}switch(mn(o,w.val.source,w.val.destination)){case pe.Redeem:{const v=this.secretManager.generateSecret(Number(o.create_order.nonce));if(v.error){this.emit("error",o,v.error);return}switch(J.getBlockchainType(o.destination_swap.chain)){case J.BlockchainType.EVM:{await this.evmRedeem(o,v.val.secret);break}case J.BlockchainType.Bitcoin:{await this.btcRedeem(p.val,o,v.val.secret);break}default:this.emit("error",o,"Unsupported chain: "+o.destination_swap.chain)}break}case pe.Refund:{switch(J.getBlockchainType(o.source_swap.chain)){case J.BlockchainType.EVM:{this.emit("error",o,"EVM refund is automatically done by relay service");break}case J.BlockchainType.Bitcoin:{await this.btcRefund(u.val,o);break}default:this.emit("error",o,"Unsupported chain: "+o.source_swap.chain)}break}}}},{per_page:500},!0)}async evmRedeem(t,r){this.emit("log",t.create_order.create_id,"executing evm redeem");const a=this.orderExecutorCache.get(t,pe.Redeem);if(console.log("cache inside evm redeem :",a),a){this.emit("log",t.create_order.create_id,"already redeemed");return}const s=await new vn(t,this.orderbookUrl,this.auth).redeem(t.create_order.create_id,r);if(s.error){this.emit("error",t,s.error);return}this.emit("success",t,pe.Redeem,s.val),this.orderExecutorCache.set(t,pe.Redeem,s.val)}async btcRedeem(t,r,a){var c;const o=this.orderExecutorCache.get(r,pe.Redeem);console.log("cache inside btc redeem :",o);let s=!1;if(o)if(o.btcRedeemUTXO&&o.btcRedeemUTXO!==r.destination_swap.initiate_tx_hash)s=!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 p=await(await Nt.from(t,Number(r.destination_swap.amount),r.create_order.secret_hash,yt(r.destination_swap.initiator),yt(r.destination_swap.redeemer),r.destination_swap.timelock,s?[r.destination_swap.initiate_tx_hash]:[])).redeem(C.trim0x(a),(c=r.create_order.additional_data)==null?void 0:c.bitcoin_optional_recipient);this.emit("success",r,pe.Redeem,p),this.orderExecutorCache.set(r,pe.Redeem,p,r.destination_swap.initiate_tx_hash)}catch(u){this.emit("error",r,"Failed btc redeem: "+u)}}async btcRefund(t,r){var a;if(!this.orderExecutorCache.get(r,pe.Refund)){this.emit("log",r.create_order.create_id,"executing btc refund");try{const s=await(await Nt.from(t,Number(r.source_swap.amount),r.create_order.secret_hash,yt(r.source_swap.initiator),yt(r.source_swap.redeemer),r.source_swap.timelock)).refund((a=r.create_order.additional_data)==null?void 0:a.bitcoin_optional_recipient);this.emit("success",r,pe.Refund,s),this.orderExecutorCache.set(r,pe.Refund,s)}catch(o){this.emit("error",r,"Failed btc refund: "+o)}}}getWallet(t){switch(J.getBlockchainType(t)){case J.BlockchainType.EVM:return C.Ok(this.wallets.evmWallet);case J.BlockchainType.Bitcoin:return C.Ok(this.wallets.btcWallet);default:return C.Err("Unsupported chain for wallet")}}on(t,r){const a=this.eventListeners.get(t)??[];a.push(r),this.eventListeners.set(t,a)}off(t,r){const a=this.eventListeners.get(t)??[],o=a.indexOf(r);o!==-1&&a.splice(o,1)}async fetchCurrentBlockNumbers(t,r){if(!r||!r.source||!r.destination)return C.Err("Provide wallets to fetch the current block number");const a=J.isBitcoin(t.source_swap.chain)?await ge.fetchBitcoinBlockNumber(await r.source.getProvider()):await ge.fetchEVMBlockNumber(r.source);if(a.error)return C.Err(a.error);const o=J.isBitcoin(t.destination_swap.chain)?await ge.fetchBitcoinBlockNumber(await r.destination.getProvider()):await ge.fetchEVMBlockNumber(r.destination);return o.error?C.Err(o.error):C.Ok({source:a.val,destination:o.val})}}var Ge=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Pi(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function a(){return this instanceof a?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(a){var o=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(r,a,o.get?o:{enumerable:!0,get:function(){return e[a]}})}),r}var xn={},ut={},ct={};Object.defineProperty(ct,"__esModule",{value:!0});ct.testnet=ct.bitcoin=void 0;ct.bitcoin={messagePrefix:`Bitcoin Signed Message:
|
|
20
|
+
`.trim().replace(/\s+/g," "))}leaves(){return[{version:Ot,output:this.redeemLeaf()},[{version:Ot,output:this.refundLeaf()},{version:Ot,output:this.instantRefundLeaf()}]]}generateMerkleProofFor(t){const r=this.leafHash(1),a=this.leafHash(2),o=this.leafHash(0);switch(t){case 1:{const s=xi(o,a);return[de.crypto.taggedHash("TapBranch",Buffer.concat(s))]}case 0:return[a,r];case 2:return[o,r];default:throw new Error(ye.invalidLeaf)}}}function rr(e,t){const r=[];for(let a=0;a<t;a++)r.push(e);return r}class Li{constructor(){this.cache={}}set(t,r,a,o){const s={txHash:a,timeStamp:Date.now(),btcRedeemUTXO:o};this.cache[`${r}_${t.create_order.create_id}`]=s}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 Mi{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 Li,!t.wallets.evmWallet.account)throw new Error("Account not found in evmWallet");this.evmAddress=t.wallets.evmWallet.account.address}getPendingOrderCount(){return this.pendingOrdersCount}setUseRelay(t){this.useRelay=t}async swap(t){const r=await this.validateAndFillParams(t);if(r.error)return C.Err(r.error);const{sendAddress:a,receiveAddress:o,timelock:s}=r.val,c=await this.orderBook.getOrdersCount(this.evmAddress);if(c.error)return C.Err(c.error);const u=c.val+1,p=this.secretManager.generateSecret(u);if(p.error)return C.Err(p.error);const{strategyId:w,btcAddress:m}=t.additionalData,v={strategy_id:w,...m&&{bitcoin_optional_recipient:m}},T={source_chain:t.fromAsset.chain,destination_chain:t.toAsset.chain,source_asset:t.fromAsset.atomicSwapAddress,destination_asset:t.toAsset.atomicSwapAddress,initiator_source_address:a,initiator_destination_address:o,source_amount:t.sendAmount,destination_amount:t.receiveAmount,fee:"1",nonce:u.toString(),timelock:s,secret_hash:C.trim0x(p.val.secretHash),min_destination_confirmations:t.minDestinationConfirmations??0,additional_data:v},O=await this.quote.getAttestedQuote(T);if(O.error)return C.Err(O.error);const R=await this.orderBook.createOrder(O.val);if(R.error)return C.Err(R.error);const k=await this.pollOrder(R.val);return k.error?C.Err(k.error):C.Ok(k.val)}async validateAndFillParams(t){if(t.fromAsset.chain===t.toAsset.chain&&t.fromAsset.atomicSwapAddress===t.toAsset.atomicSwapAddress)return C.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 C.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 C.Err("btcWallet is required for bitcoin chain. Please provide btcWallet in the constructor");if(!t.additionalData.btcAddress)return C.Err("btcAddress in additionalData is required for bitcoin chain")}const r=await this.getAddresses(t.fromAsset.chain);if(r.error)return C.Err(r.error);const a=await this.getAddresses(t.toAsset.chain);if(a.error)return C.Err(a.error);const o=this.validateAmount(t.sendAmount);if(o.error)return C.Err(o.error);const s=this.validateAmount(t.receiveAmount);if(s.error)return C.Err(s.error);if(o<s)return C.Err("Send amount should be greater than receive amount");const c=this.getTimelock(t.fromAsset.chain);return c?C.Ok({sendAddress:r.val,receiveAddress:a.val,timelock:t.timelock??c}):C.Err("Unsupported chain for timelock")}async getAddresses(t){var a;switch(J.getBlockchainType(t)){case J.BlockchainType.EVM:return this.wallets.evmWallet.account?C.Ok(this.wallets.evmWallet.account.address):C.Err("EVM Wallet not found");case J.BlockchainType.Bitcoin:{const o=await((a=this.wallets.btcWallet)==null?void 0:a.getPublicKey());return!o||!Ei(o)?C.Err("Invalid btc public key"):C.Ok(yt(o))}default:return C.Err("Unsupported chain")}}validateAmount(t){if(t==null||t.includes("."))return C.Err("Invalid amount ",t);const r=new bi(t);return!r.isInteger()||r.isNaN()||r.lt(0)||r.isLessThanOrEqualTo(0)?C.Err("Invalid amount ",t):C.Ok(r)}getTimelock(t){switch(J.getBlockchainType(t)){case J.BlockchainType.EVM:return gr.evm;case J.BlockchainType.Bitcoin:return gr.btc;default:return}}async pollOrder(t){let r=await this.orderBook.getOrder(t,!0),a=0;for(;a<this.getOrderThreshold;){if(await ge.sleep(1e3),a++,r.error){if(!r.error.includes("result is undefined"))return C.Err(r.error)}else if(r.val&&r.val.create_order.create_id.toLowerCase()===t.toLowerCase())return C.Ok(r.val);r=await this.orderBook.getOrder(t,!0)}return C.Err(`Order not found, createOrder id: ${t}`)}emit(t,...r){(this.eventListeners.get(t)??[]).forEach(o=>{o(...r)})}async execute(t=5e3){return await this.orderBook.subscribeToOrders(!0,t,async r=>{this.pendingOrdersCount=r.data.length,this.emit("onPendingOrdersChanged",r.data);for(let a=0;a<r.data.length;a++){const o=r.data[a],s=o.source_swap.chain,c=o.destination_swap.chain,u=this.getWallet(s),p=this.getWallet(c);if(u.error||p.error||!u.val||!p.val){this.emit("error",o,"Source or Destination Wallet not found while executing order");return}const w=await this.fetchCurrentBlockNumbers(o,{source:u.val,destination:p.val});if(w.error){this.emit("error",o,"Error while fetching CurrentBlockNumbers: "+w.error);return}const m=mn(o,w.val.source,w.val.destination);switch(this.emit("log",o.create_order.create_id,`executing order, action: ${m}`),m){case pe.Redeem:{const v=this.secretManager.generateSecret(Number(o.create_order.nonce));if(v.error){this.emit("error",o,v.error);return}switch(J.getBlockchainType(o.destination_swap.chain)){case J.BlockchainType.EVM:{await this.evmRedeem(o,v.val.secret);break}case J.BlockchainType.Bitcoin:{await this.btcRedeem(p.val,o,v.val.secret);break}default:this.emit("error",o,"Unsupported chain: "+o.destination_swap.chain)}break}case pe.Refund:{switch(J.getBlockchainType(o.source_swap.chain)){case J.BlockchainType.EVM:{this.emit("error",o,"EVM refund is automatically done by relay service");break}case J.BlockchainType.Bitcoin:{await this.btcRefund(u.val,o);break}default:this.emit("error",o,"Unsupported chain: "+o.source_swap.chain)}break}}}},{per_page:500},!0)}async evmRedeem(t,r){this.emit("log",t.create_order.create_id,"executing evm redeem");const a=this.orderExecutorCache.get(t,pe.Redeem);if(console.log("cache inside evm redeem :",a),a){this.emit("log",t.create_order.create_id,"already redeemed");return}const s=await new vn(t,this.orderbookUrl,this.auth).redeem(t.create_order.create_id,r);if(s.error){this.emit("error",t,s.error);return}this.emit("success",t,pe.Redeem,s.val),this.orderExecutorCache.set(t,pe.Redeem,s.val)}async btcRedeem(t,r,a){var c;const o=this.orderExecutorCache.get(r,pe.Redeem);console.log("cache inside btc redeem :",o);let s=!1;if(o)if(o.btcRedeemUTXO&&o.btcRedeemUTXO!==r.destination_swap.initiate_tx_hash)s=!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 p=await(await Nt.from(t,Number(r.destination_swap.amount),r.create_order.secret_hash,yt(r.destination_swap.initiator),yt(r.destination_swap.redeemer),r.destination_swap.timelock,s?[r.destination_swap.initiate_tx_hash]:[])).redeem(C.trim0x(a),(c=r.create_order.additional_data)==null?void 0:c.bitcoin_optional_recipient);this.emit("success",r,pe.Redeem,p),this.orderExecutorCache.set(r,pe.Redeem,p,r.destination_swap.initiate_tx_hash)}catch(u){this.emit("error",r,"Failed btc redeem: "+u)}}async btcRefund(t,r){var a;if(!this.orderExecutorCache.get(r,pe.Refund)){this.emit("log",r.create_order.create_id,"executing btc refund");try{const s=await(await Nt.from(t,Number(r.source_swap.amount),r.create_order.secret_hash,yt(r.source_swap.initiator),yt(r.source_swap.redeemer),r.source_swap.timelock)).refund((a=r.create_order.additional_data)==null?void 0:a.bitcoin_optional_recipient);this.emit("success",r,pe.Refund,s),this.orderExecutorCache.set(r,pe.Refund,s)}catch(o){this.emit("error",r,"Failed btc refund: "+o)}}}getWallet(t){switch(J.getBlockchainType(t)){case J.BlockchainType.EVM:return C.Ok(this.wallets.evmWallet);case J.BlockchainType.Bitcoin:return C.Ok(this.wallets.btcWallet);default:return C.Err("Unsupported chain for wallet")}}on(t,r){const a=this.eventListeners.get(t)??[];a.push(r),this.eventListeners.set(t,a)}off(t,r){const a=this.eventListeners.get(t)??[],o=a.indexOf(r);o!==-1&&a.splice(o,1)}async fetchCurrentBlockNumbers(t,r){if(!r||!r.source||!r.destination)return C.Err("Provide wallets to fetch the current block number");const a=J.isBitcoin(t.source_swap.chain)?await ge.fetchBitcoinBlockNumber(await r.source.getProvider()):await ge.fetchEVMBlockNumber(r.source);if(a.error)return C.Err(a.error);const o=J.isBitcoin(t.destination_swap.chain)?await ge.fetchBitcoinBlockNumber(await r.destination.getProvider()):await ge.fetchEVMBlockNumber(r.destination);return o.error?C.Err(o.error):C.Ok({source:a.val,destination:o.val})}}var Ge=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Pi(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function a(){return this instanceof a?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(a){var o=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(r,a,o.get?o:{enumerable:!0,get:function(){return e[a]}})}),r}var xn={},ut={},ct={};Object.defineProperty(ct,"__esModule",{value:!0});ct.testnet=ct.bitcoin=void 0;ct.bitcoin={messagePrefix:`Bitcoin Signed Message:
|
|
21
21
|
`,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128};ct.testnet={messagePrefix:`Bitcoin Signed Message:
|
|
22
22
|
`,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var En={},Bt={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}};Bt.Null=Bt.Nil;for(var Hr in Bt)Bt[Hr].toJSON=(function(e){return e}).bind(null,Hr);var Ir=Bt,Xe=Ir;function Bn(e){return e.name||e.toString().match(/function (.*?)\s*\(/)[1]}function kr(e){return Xe.Nil(e)?"":Bn(e.constructor)}function Fi(e){return Xe.Function(e)?"":Xe.String(e)?JSON.stringify(e):e&&Xe.Object(e)?"":e}function Cr(e,t){Error.captureStackTrace&&Error.captureStackTrace(e,t)}function Ut(e){return Xe.Function(e)?e.toJSON?e.toJSON():Bn(e):Xe.Array(e)?"Array":e&&Xe.Object(e)?"Object":e!==void 0?e:""}function Rn(e,t,r){var a=Fi(t);return"Expected "+Ut(e)+", got"+(r!==""?" "+r:"")+(a!==""?" "+a:"")}function Ue(e,t,r){r=r||kr(t),this.message=Rn(e,t,r),Cr(this,Ue),this.__type=e,this.__value=t,this.__valueTypeName=r}Ue.prototype=Object.create(Error.prototype);Ue.prototype.constructor=Ue;function Ni(e,t,r,a,o){var s='" of type ';return t==="key"&&(s='" with key type '),Rn('property "'+Ut(r)+s+Ut(e),a,o)}function ot(e,t,r,a,o){e?(o=o||kr(a),this.message=Ni(e,r,t,a,o)):this.message='Unexpected property "'+t+'"',Cr(this,Ue),this.__label=r,this.__property=t,this.__type=e,this.__value=a,this.__valueTypeName=o}ot.prototype=Object.create(Error.prototype);ot.prototype.constructor=Ue;function Ui(e,t){return new Ue(e,{},t)}function Di(e,t,r){return e instanceof ot?(t=t+"."+e.__property,e=new ot(e.__type,t,e.__label,e.__value,e.__valueTypeName)):e instanceof Ue&&(e=new ot(e.__type,t,r,e.__value,e.__valueTypeName)),Cr(e),e}var Sn={TfTypeError:Ue,TfPropertyTypeError:ot,tfCustomError:Ui,tfSubError:Di,tfJSON:Ut,getValueTypeName:kr},nr,jr;function $i(){if(jr)return nr;jr=1;var e=Ir,t=Sn;function r(E){return Buffer.isBuffer(E)}function a(E){return typeof E=="string"&&/^([0-9a-f]{2})+$/i.test(E)}function o(E,j){var U=E.toJSON();function $(ne){if(!E(ne))return!1;if(ne.length===j)return!0;throw t.tfCustomError(U+"(Length: "+j+")",U+"(Length: "+ne.length+")")}return $.toJSON=function(){return U},$}var s=o.bind(null,e.Array),c=o.bind(null,r),u=o.bind(null,a),p=o.bind(null,e.String);function w(E,j,U){U=U||e.Number;function $(ne,Te){return U(ne,Te)&&ne>E&&ne<j}return $.toJSON=function(){return`${U.toJSON()} between [${E}, ${j}]`},$}var m=Math.pow(2,53)-1;function v(E){return typeof E=="number"&&isFinite(E)}function T(E){return E<<24>>24===E}function O(E){return E<<16>>16===E}function R(E){return(E|0)===E}function k(E){return typeof E=="number"&&E>=-m&&E<=m&&Math.floor(E)===E}function A(E){return(E&255)===E}function I(E){return(E&65535)===E}function M(E){return E>>>0===E}function P(E){return typeof E=="number"&&E>=0&&E<=m&&Math.floor(E)===E}var L={ArrayN:s,Buffer:r,BufferN:c,Finite:v,Hex:a,HexN:u,Int8:T,Int16:O,Int32:R,Int53:k,Range:w,StringN:p,UInt8:A,UInt16:I,UInt32:M,UInt53:P};for(var N in L)L[N].toJSON=(function(E){return E}).bind(null,N);return nr=L,nr}var St=Sn,fe=Ir,Pe=St.tfJSON,An=St.TfTypeError,Tn=St.TfPropertyTypeError,_t=St.tfSubError,Hi=St.getValueTypeName,Fe={arrayOf:function(t,r){t=Oe(t),r=r||{};function a(o,s){return!fe.Array(o)||fe.Nil(o)||r.minLength!==void 0&&o.length<r.minLength||r.maxLength!==void 0&&o.length>r.maxLength||r.length!==void 0&&o.length!==r.length?!1:o.every(function(c,u){try{return we(t,c,s)}catch(p){throw _t(p,u)}})}return a.toJSON=function(){var o="["+Pe(t)+"]";return r.length!==void 0?o+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(o+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),o},a},maybe:function e(t){t=Oe(t);function r(a,o){return fe.Nil(a)||t(a,o,e)}return r.toJSON=function(){return"?"+Pe(t)},r},map:function(t,r){t=Oe(t),r&&(r=Oe(r));function a(o,s){if(!fe.Object(o)||fe.Nil(o))return!1;for(var c in o){try{r&&we(r,c,s)}catch(p){throw _t(p,c,"key")}try{var u=o[c];we(t,u,s)}catch(p){throw _t(p,c)}}return!0}return r?a.toJSON=function(){return"{"+Pe(r)+": "+Pe(t)+"}"}:a.toJSON=function(){return"{"+Pe(t)+"}"},a},object:function(t){var r={};for(var a in t)r[a]=Oe(t[a]);function o(s,c){if(!fe.Object(s)||fe.Nil(s))return!1;var u;try{for(u in r){var p=r[u],w=s[u];we(p,w,c)}}catch(m){throw _t(m,u)}if(c){for(u in s)if(!r[u])throw new Tn(void 0,u)}return!0}return o.toJSON=function(){return Pe(r)},o},anyOf:function(){var t=[].slice.call(arguments).map(Oe);function r(a,o){return t.some(function(s){try{return we(s,a,o)}catch{return!1}})}return r.toJSON=function(){return t.map(Pe).join("|")},r},allOf:function(){var t=[].slice.call(arguments).map(Oe);function r(a,o){return t.every(function(s){try{return we(s,a,o)}catch{return!1}})}return r.toJSON=function(){return t.map(Pe).join(" & ")},r},quacksLike:function(t){function r(a){return t===Hi(a)}return r.toJSON=function(){return t},r},tuple:function(){var t=[].slice.call(arguments).map(Oe);function r(a,o){return fe.Nil(a)||fe.Nil(a.length)||o&&a.length!==t.length?!1:t.every(function(s,c){try{return we(s,a[c],o)}catch(u){throw _t(u,c)}})}return r.toJSON=function(){return"("+t.map(Pe).join(", ")+")"},r},value:function(t){function r(a){return a===t}return r.toJSON=function(){return t},r}};Fe.oneOf=Fe.anyOf;function Oe(e){if(fe.String(e))return e[0]==="?"?Fe.maybe(e.slice(1)):fe[e]||Fe.quacksLike(e);if(e&&fe.Object(e)){if(fe.Array(e)){if(e.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return Fe.arrayOf(e[0])}return Fe.object(e)}else if(fe.Function(e))return e;return Fe.value(e)}function we(e,t,r,a){if(fe.Function(e)){if(e(t,r))return!0;throw new An(a||e,t)}return we(Oe(e),t,r)}for(var Ke in fe)we[Ke]=fe[Ke];for(Ke in Fe)we[Ke]=Fe[Ke];var qr=$i();for(Ke in qr)we[Ke]=qr[Ke];we.compile=Oe;we.TfTypeError=An;we.TfPropertyTypeError=Tn;var ji=we;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.maybe=e.Boolean=e.Array=e.Buffer256bit=e.Network=e.typeforce=void 0,e.typeforce=ji,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})(En);var mr={exports:{}},vr={exports:{}},ht={},Wt={};Wt.byteLength=Ki;Wt.toByteArray=Vi;Wt.fromByteArray=Yi;var Le=[],Se=[],qi=typeof Uint8Array<"u"?Uint8Array:Array,ir="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var at=0,Wi=ir.length;at<Wi;++at)Le[at]=ir[at],Se[ir.charCodeAt(at)]=at;Se[45]=62;Se[95]=63;function In(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 a=r===t?0:4-r%4;return[r,a]}function Ki(e){var t=In(e),r=t[0],a=t[1];return(r+a)*3/4-a}function Gi(e,t,r){return(t+r)*3/4-r}function Vi(e){var t,r=In(e),a=r[0],o=r[1],s=new qi(Gi(e,a,o)),c=0,u=o>0?a-4:a,p;for(p=0;p<u;p+=4)t=Se[e.charCodeAt(p)]<<18|Se[e.charCodeAt(p+1)]<<12|Se[e.charCodeAt(p+2)]<<6|Se[e.charCodeAt(p+3)],s[c++]=t>>16&255,s[c++]=t>>8&255,s[c++]=t&255;return o===2&&(t=Se[e.charCodeAt(p)]<<2|Se[e.charCodeAt(p+1)]>>4,s[c++]=t&255),o===1&&(t=Se[e.charCodeAt(p)]<<10|Se[e.charCodeAt(p+1)]<<4|Se[e.charCodeAt(p+2)]>>2,s[c++]=t>>8&255,s[c++]=t&255),s}function zi(e){return Le[e>>18&63]+Le[e>>12&63]+Le[e>>6&63]+Le[e&63]}function Ji(e,t,r){for(var a,o=[],s=t;s<r;s+=3)a=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),o.push(zi(a));return o.join("")}function Yi(e){for(var t,r=e.length,a=r%3,o=[],s=16383,c=0,u=r-a;c<u;c+=s)o.push(Ji(e,c,c+s>u?u:c+s));return a===1?(t=e[r-1],o.push(Le[t>>2]+Le[t<<4&63]+"==")):a===2&&(t=(e[r-2]<<8)+e[r-1],o.push(Le[t>>10]+Le[t>>4&63]+Le[t<<2&63]+"=")),o.join("")}var Or={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Or.read=function(e,t,r,a,o){var s,c,u=o*8-a-1,p=(1<<u)-1,w=p>>1,m=-7,v=r?o-1:0,T=r?-1:1,O=e[t+v];for(v+=T,s=O&(1<<-m)-1,O>>=-m,m+=u;m>0;s=s*256+e[t+v],v+=T,m-=8);for(c=s&(1<<-m)-1,s>>=-m,m+=a;m>0;c=c*256+e[t+v],v+=T,m-=8);if(s===0)s=1-w;else{if(s===p)return c?NaN:(O?-1:1)*(1/0);c=c+Math.pow(2,a),s=s-w}return(O?-1:1)*c*Math.pow(2,s-a)};Or.write=function(e,t,r,a,o,s){var c,u,p,w=s*8-o-1,m=(1<<w)-1,v=m>>1,T=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,O=a?0:s-1,R=a?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,c=m):(c=Math.floor(Math.log(t)/Math.LN2),t*(p=Math.pow(2,-c))<1&&(c--,p*=2),c+v>=1?t+=T/p:t+=T*Math.pow(2,1-v),t*p>=2&&(c++,p/=2),c+v>=m?(u=0,c=m):c+v>=1?(u=(t*p-1)*Math.pow(2,o),c=c+v):(u=t*Math.pow(2,v-1)*Math.pow(2,o),c=0));o>=8;e[r+O]=u&255,O+=R,u/=256,o-=8);for(c=c<<o|u,w+=o;w>0;e[r+O]=c&255,O+=R,c/=256,w-=8);e[r+O-R]|=k*128};/*!
|
|
23
23
|
* The buffer module from node.js, for the browser.
|
package/dist/index.js
CHANGED
|
@@ -230,7 +230,9 @@ const Ui = (e, t, r) => {
|
|
|
230
230
|
if (o === Z.Expired)
|
|
231
231
|
return ie.CounterPartySwapExpired;
|
|
232
232
|
if (a === Z.Expired) return ie.Expired;
|
|
233
|
-
const s = Number(
|
|
233
|
+
const s = Number(
|
|
234
|
+
e.create_order.additional_data.deadline
|
|
235
|
+
);
|
|
234
236
|
return o === Z.InitiateDetected ? ie.CounterPartyInitiateDetected : o === Z.Initiated ? ie.CounterPartyInitiated : Yr(s, 1) ? ie.Expired : a === Z.InitiateDetected ? ie.InitiateDetected : Yr(s, 12) ? ie.Expired : a === Z.Initiated ? ie.Initiated : ie.Matched;
|
|
235
237
|
}, Br = (e, t) => {
|
|
236
238
|
if (e.redeem_tx_hash)
|
|
@@ -243,11 +245,17 @@ const Ui = (e, t, r) => {
|
|
|
243
245
|
}
|
|
244
246
|
return e.initiate_tx_hash ? e.initiate_block_number ? Z.Initiated : Z.InitiateDetected : Z.Idle;
|
|
245
247
|
}, Di = (e, t, r) => {
|
|
246
|
-
|
|
248
|
+
const a = Ui(
|
|
247
249
|
e,
|
|
248
250
|
t,
|
|
249
251
|
r
|
|
250
|
-
)
|
|
252
|
+
);
|
|
253
|
+
switch (console.log(
|
|
254
|
+
"orderId: ",
|
|
255
|
+
e.create_order.create_id,
|
|
256
|
+
" orderStatus :",
|
|
257
|
+
a
|
|
258
|
+
), a) {
|
|
251
259
|
case ie.Matched:
|
|
252
260
|
return pe.Initiate;
|
|
253
261
|
case ie.CounterPartyInitiated:
|
|
@@ -1318,9 +1326,7 @@ class tf {
|
|
|
1318
1326
|
async (r) => {
|
|
1319
1327
|
this.pendingOrdersCount = r.data.length, this.emit("onPendingOrdersChanged", r.data);
|
|
1320
1328
|
for (let a = 0; a < r.data.length; a++) {
|
|
1321
|
-
const o = r.data[a], s = o.source_swap.chain, c = o.destination_swap.chain;
|
|
1322
|
-
this.emit("log", o.create_order.create_id, "executing order");
|
|
1323
|
-
const u = this.getWallet(s), p = this.getWallet(c);
|
|
1329
|
+
const o = r.data[a], s = o.source_swap.chain, c = o.destination_swap.chain, u = this.getWallet(s), p = this.getWallet(c);
|
|
1324
1330
|
if (u.error || p.error || !u.val || !p.val) {
|
|
1325
1331
|
this.emit(
|
|
1326
1332
|
"error",
|
|
@@ -1341,11 +1347,16 @@ class tf {
|
|
|
1341
1347
|
);
|
|
1342
1348
|
return;
|
|
1343
1349
|
}
|
|
1344
|
-
|
|
1350
|
+
const m = Di(
|
|
1345
1351
|
o,
|
|
1346
1352
|
w.val.source,
|
|
1347
1353
|
w.val.destination
|
|
1348
|
-
)
|
|
1354
|
+
);
|
|
1355
|
+
switch (this.emit(
|
|
1356
|
+
"log",
|
|
1357
|
+
o.create_order.create_id,
|
|
1358
|
+
`executing order, action: ${m}`
|
|
1359
|
+
), m) {
|
|
1349
1360
|
case pe.Redeem: {
|
|
1350
1361
|
const v = this.secretManager.generateSecret(
|
|
1351
1362
|
Number(o.create_order.nonce)
|