@gardenfi/core 0.2.0-beta.77 → 0.2.0-beta.78
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 +1 -1
- package/dist/index.js +4 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
OP_CHECKSIGADD
|
|
21
21
|
OP_2
|
|
22
22
|
OP_NUMEQUAL
|
|
23
|
-
`.trim().replace(/\s+/g," "))}leaves(){return[{version:rr,output:this.redeemLeaf()},[{version:rr,output:this.refundLeaf()},{version:rr,output:this.instantRefundLeaf()}]]}generateMerkleProofFor(t){const r=this.leafHash(1),n=this.leafHash(2),i=this.leafHash(0);switch(t){case 1:{const a=Ca(i,n);return[le.crypto.taggedHash("TapBranch",Buffer.concat(a))]}case 0:return[n,r];case 2:return[i,r];default:throw new Error(me.invalidLeaf)}}}function Or(e,t){const r=[];for(let n=0;n<t;n++)r.push(e);return r}class Ga{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 Wa{constructor(t){if(this.eventListeners=new Map,this.getOrderThreshold=20,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 Ga,!t.wallets.evmWallet.account)throw new Error("Account not found in evmWallet");this.evmAddress=t.wallets.evmWallet.account.address,this.blockNumberFetcher=t.blockNumberFetcher}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:b,btcAddress:g}=t.additionalData,m={strategy_id:b,...g&&{bitcoin_optional_recipient:g}},v={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:m},A=await this.quote.getAttestedQuote(v);if(A.error)return P.Err(A.error);const B=await this.orderBook.createOrder(A.val);if(B.error)return P.Err(B.error);const k=await this.pollOrder(B.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||!La(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 $s(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 or.evm;case J.BlockchainType.Bitcoin:return or.btc;default:return}}async pollOrder(t){let r=await this.orderBook.getOrder(t,!0),n=0;for(;n<this.getOrderThreshold;){if(await we.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=>{const n=Wi(r.data),i=await this.assignOrderStatus(n);this.emit("onPendingOrdersChanged",i);for(let a=0;a<i.length;a++){const f=i[a];switch(mn(f.status)){case ue.Redeem:{const l=this.secretManager.generateSecret(Number(f.create_order.nonce));if(l.error){this.emit("error",f,l.error);return}switch(J.getBlockchainType(f.destination_swap.chain)){case J.BlockchainType.EVM:{await this.evmRedeem(f,l.val.secret);break}case J.BlockchainType.Bitcoin:{const b=this.getWallet(f.destination_swap.chain);if(b.error){this.emit("error",f,b.error);return}await this.btcRedeem(b.val,f,l.val.secret);break}default:this.emit("error",f,"Unsupported chain: "+f.destination_swap.chain)}break}case ue.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:{const l=this.getWallet(f.source_swap.chain);if(l.error){this.emit("error",f,l.error);return}await this.btcRefund(l.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,ue.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}const a=await new qi(t,this.orderbookUrl,this.auth).redeem(t.create_order.create_id,r);if(a.error){this.emit("error",t,a.error),a.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,ue.Redeem,t.destination_swap.redeem_tx_hash);return}this.emit("success",t,ue.Redeem,a.val),this.orderExecutorCache.set(t,ue.Redeem,a.val)}async btcRedeem(t,r,n){var u,l;const i=this.orderExecutorCache.get(r,ue.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}let f=!1;if(i)if(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}else if(r.destination_swap.redeem_tx_hash&&!Number(r.destination_swap.redeem_block_number))try{const b=await(await t.getProvider()).getTransaction(r.destination_swap.redeem_tx_hash);let g=!1;for(const m of b.vin)if(m.txid===a){g=!0;break}if(g){this.emit("log",r.create_order.create_id,"already a valid redeem"),this.orderExecutorCache.set(r,ue.Redeem,r.destination_swap.redeem_tx_hash,a);return}f=!0}catch(b){if(b.message.includes("Transaction not found"))f=!0;else{this.emit("error",r,"Failed to get redeem tx: "+b);return}}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);f?this.emit("log",r.create_order.create_id,"rbf: btc redeem success"):this.emit("success",r,ue.Redeem,g),this.orderExecutorCache.set(r,ue.Redeem,g,a)}catch(b){this.emit("error",r,"Failed btc redeem: "+b)}}async btcRefund(t,r){var n;if(!this.orderExecutorCache.get(r,ue.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,ue.Refund,a),this.orderExecutorCache.set(r,ue.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 we.fetchBitcoinBlockNumber(await r.source.getProvider()):await we.fetchEVMBlockNumber(r.source);if(n.error)return P.Err(n.error);const i=J.isBitcoin(t.destination_swap.chain)?await we.fetchBitcoinBlockNumber(await r.destination.getProvider()):await we.fetchEVMBlockNumber(r.destination);return i.error?P.Err(i.error):P.Ok({source:n.val,destination:i.val})}async assignOrderStatus(t){var i;const r=await((i=this.blockNumberFetcher)==null?void 0:i.fetchBlockNumbers()),n=[];for(let a=0;a<t.length;a++){const f=t[a],u=f.source_swap.chain,l=f.destination_swap.chain,b=this.getWallet(u),g=this.getWallet(l);if(b.error||g.error||!b.val||!g.val){this.emit("error",f,"Source or Destination Wallet not found while executing order");continue}let m=r==null?void 0:r.val[u],v=r==null?void 0:r.val[l];if(!m||!v){const B=await this.fetchCurrentBlockNumbers(f,{source:b.val,destination:g.val});if(B.error){this.emit("error",f,"Error while fetching CurrentBlockNumbers: "+B.error);continue}m=B.val.source,v=B.val.destination}const A=gn(f,m,v);n.push({...f,status:A})}return n}}class qa{constructor(t,r){this.url=new we.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)}}}var Qe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Va(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Ka(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 Vi={},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:rr,output:this.redeemLeaf()},[{version:rr,output:this.refundLeaf()},{version:rr,output:this.instantRefundLeaf()}]]}generateMerkleProofFor(t){const r=this.leafHash(1),n=this.leafHash(2),i=this.leafHash(0);switch(t){case 1:{const a=Ca(i,n);return[le.crypto.taggedHash("TapBranch",Buffer.concat(a))]}case 0:return[n,r];case 2:return[i,r];default:throw new Error(me.invalidLeaf)}}}function Or(e,t){const r=[];for(let n=0;n<t;n++)r.push(e);return r}class Ga{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 Wa{constructor(t){if(this.eventListeners=new Map,this.getOrderThreshold=20,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 Ga,!t.wallets.evmWallet.account)throw new Error("Account not found in evmWallet");this.evmAddress=t.wallets.evmWallet.account.address,this.blockNumberFetcher=t.blockNumberFetcher}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:b,btcAddress:g}=t.additionalData,m={strategy_id:b,...g&&{bitcoin_optional_recipient:g}},v={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:m},A=await this.quote.getAttestedQuote(v);if(A.error)return P.Err(A.error);const B=await this.orderBook.createOrder(A.val);if(B.error)return P.Err(B.error);const k=await this.pollOrder(B.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||!La(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 $s(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 or.evm;case J.BlockchainType.Bitcoin:return or.btc;default:return}}async pollOrder(t){let r=await this.orderBook.getOrder(t,!0),n=0;for(;n<this.getOrderThreshold;){if(await we.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=>{console.log("executing orders");const n=Wi(r.data),i=await this.assignOrderStatus(n);this.emit("onPendingOrdersChanged",i);for(let a=0;a<i.length;a++){const f=i[a];switch(mn(f.status)){case ue.Redeem:{const l=this.secretManager.generateSecret(Number(f.create_order.nonce));if(l.error){this.emit("error",f,l.error);return}switch(J.getBlockchainType(f.destination_swap.chain)){case J.BlockchainType.EVM:{await this.evmRedeem(f,l.val.secret);break}case J.BlockchainType.Bitcoin:{const b=this.getWallet(f.destination_swap.chain);if(b.error){this.emit("error",f,b.error);return}await this.btcRedeem(b.val,f,l.val.secret);break}default:this.emit("error",f,"Unsupported chain: "+f.destination_swap.chain)}break}case ue.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:{const l=this.getWallet(f.source_swap.chain);if(l.error){this.emit("error",f,l.error);return}await this.btcRefund(l.val,f);break}default:this.emit("error",f,"Unsupported chain: "+f.source_swap.chain)}break}}}},{per_page:500},!0)}async evmRedeem(t,r){this.emit("log",t.create_order.create_id,"executing evm redeem");const n=this.orderExecutorCache.get(t,ue.Redeem);if(console.log("cache inside evm redeem:",n),n){this.emit("log",t.create_order.create_id,"already redeemed");return}const a=await new qi(t,this.orderbookUrl,this.auth).redeem(t.create_order.create_id,r);if(a.error){this.emit("error",t,a.error),a.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,ue.Redeem,t.destination_swap.redeem_tx_hash);return}this.emit("success",t,ue.Redeem,a.val),this.orderExecutorCache.set(t,ue.Redeem,a.val)}async btcRedeem(t,r,n){var u,l;const i=this.orderExecutorCache.get(r,ue.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}let f=!1;if(i)if(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}else if(r.destination_swap.redeem_tx_hash&&!Number(r.destination_swap.redeem_block_number))try{const b=await(await t.getProvider()).getTransaction(r.destination_swap.redeem_tx_hash);let g=!1;for(const m of b.vin)if(m.txid===a){g=!0;break}if(g){this.emit("log",r.create_order.create_id,"already a valid redeem"),this.orderExecutorCache.set(r,ue.Redeem,r.destination_swap.redeem_tx_hash,a);return}f=!0}catch(b){if(b.message.includes("Transaction not found"))f=!0;else{this.emit("error",r,"Failed to get redeem tx: "+b);return}}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);f?this.emit("log",r.create_order.create_id,"rbf: btc redeem success"):this.emit("success",r,ue.Redeem,g),this.orderExecutorCache.set(r,ue.Redeem,g,a)}catch(b){this.emit("error",r,"Failed btc redeem: "+b)}}async btcRefund(t,r){var n;if(!this.orderExecutorCache.get(r,ue.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,ue.Refund,a),this.orderExecutorCache.set(r,ue.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 we.fetchBitcoinBlockNumber(await r.source.getProvider()):await we.fetchEVMBlockNumber(r.source);if(n.error)return P.Err(n.error);const i=J.isBitcoin(t.destination_swap.chain)?await we.fetchBitcoinBlockNumber(await r.destination.getProvider()):await we.fetchEVMBlockNumber(r.destination);return i.error?P.Err(i.error):P.Ok({source:n.val,destination:i.val})}async assignOrderStatus(t){var i;const r=await((i=this.blockNumberFetcher)==null?void 0:i.fetchBlockNumbers()),n=[];for(let a=0;a<t.length;a++){const f=t[a],u=f.source_swap.chain,l=f.destination_swap.chain,b=this.getWallet(u),g=this.getWallet(l);if(b.error||g.error||!b.val||!g.val){this.emit("error",f,"Source or Destination Wallet not found while executing order");continue}let m=r==null?void 0:r.val[u],v=r==null?void 0:r.val[l];if(!m||!v){const B=await this.fetchCurrentBlockNumbers(f,{source:b.val,destination:g.val});if(B.error){this.emit("error",f,"Error while fetching CurrentBlockNumbers: "+B.error);continue}m=B.val.source,v=B.val.destination}const A=gn(f,m,v);n.push({...f,status:A})}return n}}class qa{constructor(t,r){this.url=new we.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)}}}var Qe=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Va(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Ka(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 Vi={},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 Ki={},jt={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}};jt.Null=jt.Nil;for(var Hn in jt)jt[Hn].toJSON=(function(e){return e}).bind(null,Hn);var _n=jt,it=_n;function Yi(e){return e.name||e.toString().match(/function (.*?)\s*\(/)[1]}function wn(e){return it.Nil(e)?"":Yi(e.constructor)}function Ya(e){return it.Function(e)?"":it.String(e)?JSON.stringify(e):e&&it.Object(e)?"":e}function xn(e,t){Error.captureStackTrace&&Error.captureStackTrace(e,t)}function lr(e){return it.Function(e)?e.toJSON?e.toJSON():Yi(e):it.Array(e)?"Array":e&&it.Object(e)?"Object":e!==void 0?e:""}function Ji(e,t,r){var n=Ya(t);return"Expected "+lr(e)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function ze(e,t,r){r=r||wn(t),this.message=Ji(e,t,r),xn(this,ze),this.__type=e,this.__value=t,this.__valueTypeName=r}ze.prototype=Object.create(Error.prototype);ze.prototype.constructor=ze;function Ja(e,t,r,n,i){var a='" of type ';return t==="key"&&(a='" with key type '),Ji('property "'+lr(r)+a+lr(e),n,i)}function _t(e,t,r,n,i){e?(i=i||wn(n),this.message=Ja(e,r,t,n,i)):this.message='Unexpected property "'+t+'"',xn(this,ze),this.__label=r,this.__property=t,this.__type=e,this.__value=n,this.__valueTypeName=i}_t.prototype=Object.create(Error.prototype);_t.prototype.constructor=ze;function Xa(e,t){return new ze(e,{},t)}function Qa(e,t,r){return e instanceof _t?(t=t+"."+e.__property,e=new _t(e.__type,t,e.__label,e.__value,e.__valueTypeName)):e instanceof ze&&(e=new _t(e.__type,t,r,e.__value,e.__valueTypeName)),xn(e),e}var Xi={TfTypeError:ze,TfPropertyTypeError:_t,tfCustomError:Xa,tfSubError:Qa,tfJSON:lr,getValueTypeName:wn},Fr,zn;function Za(){if(zn)return Fr;zn=1;var e=_n,t=Xi;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 b(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 m(S){return typeof S=="number"&&isFinite(S)}function v(S){return S<<24>>24===S}function A(S){return S<<16>>16===S}function B(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:m,Hex:n,HexN:u,Int8:v,Int16:A,Int32:B,Int53:k,Range:b,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 Yt=Xi,he=_n,De=Yt.tfJSON,Qi=Yt.TfTypeError,Zi=Yt.TfPropertyTypeError,Ft=Yt.tfSubError,ef=Yt.getValueTypeName,$e={arrayOf:function(t,r){t=Fe(t),r=r||{};function n(i,a){return!he.Array(i)||he.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 he.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(!he.Object(i)||he.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(!he.Object(a)||he.Nil(a))return!1;var u;try{for(u in r){var l=r[u],b=a[u];xe(l,b,f)}}catch(g){throw Ft(g,u)}if(f){for(u in a)if(!r[u])throw new Zi(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===ef(n)}return r.toJSON=function(){return t},r},tuple:function(){var t=[].slice.call(arguments).map(Fe);function r(n,i){return he.Nil(n)||he.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(he.String(e))return e[0]==="?"?$e.maybe(e.slice(1)):he[e]||$e.quacksLike(e);if(e&&he.Object(e)){if(he.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(he.Function(e))return e;return $e.value(e)}function xe(e,t,r,n){if(he.Function(e)){if(e(t,r))return!0;throw new Qi(n||e,t)}return xe(Fe(e),t,r)}for(var Xe in he)xe[Xe]=he[Xe];for(Xe in $e)xe[Xe]=$e[Xe];var jn=Za();for(Xe in jn)xe[Xe]=jn[Xe];xe.compile=Fe;xe.TfTypeError=Qi;xe.TfPropertyTypeError=Zi;var tf=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=tf,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})(Ki);var Zr={exports:{}},en={exports:{}},It={},_r={};_r.byteLength=sf;_r.toByteArray=af;_r.fromByteArray=cf;var Ue=[],Re=[],rf=typeof Uint8Array<"u"?Uint8Array:Array,Ur="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var gt=0,nf=Ur.length;gt<nf;++gt)Ue[gt]=Ur[gt],Re[Ur.charCodeAt(gt)]=gt;Re[45]=62;Re[95]=63;function es(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 sf(e){var t=es(e),r=t[0],n=t[1];return(r+n)*3/4-n}function of(e,t,r){return(t+r)*3/4-r}function af(e){var t,r=es(e),n=r[0],i=r[1],a=new rf(of(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 ff(e){return Ue[e>>18&63]+Ue[e>>12&63]+Ue[e>>6&63]+Ue[e&63]}function uf(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(ff(n));return i.join("")}function cf(e){for(var t,r=e.length,n=r%3,i=[],a=16383,f=0,u=r-n;f<u;f+=a)i.push(uf(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 vn={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */vn.read=function(e,t,r,n,i){var a,f,u=i*8-n-1,l=(1<<u)-1,b=l>>1,g=-7,m=r?i-1:0,v=r?-1:1,A=e[t+m];for(m+=v,a=A&(1<<-g)-1,A>>=-g,g+=u;g>0;a=a*256+e[t+m],m+=v,g-=8);for(f=a&(1<<-g)-1,a>>=-g,g+=n;g>0;f=f*256+e[t+m],m+=v,g-=8);if(a===0)a=1-b;else{if(a===l)return f?NaN:(A?-1:1)*(1/0);f=f+Math.pow(2,n),a=a-b}return(A?-1:1)*f*Math.pow(2,a-n)};vn.write=function(e,t,r,n,i,a){var f,u,l,b=a*8-i-1,g=(1<<b)-1,m=g>>1,v=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,A=n?0:a-1,B=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+m>=1?t+=v/l:t+=v*Math.pow(2,1-m),t*l>=2&&(f++,l/=2),f+m>=g?(u=0,f=g):f+m>=1?(u=(t*l-1)*Math.pow(2,i),f=f+m):(u=t*Math.pow(2,m-1)*Math.pow(2,i),f=0));i>=8;e[r+A]=u&255,A+=B,u/=256,i-=8);for(f=f<<i|u,b+=i;b>0;e[r+A]=f&255,A+=B,f/=256,b-=8);e[r+A-B]|=k*128};/*!
|
|
26
26
|
* The buffer module from node.js, for the browser.
|
package/dist/index.js
CHANGED
|
@@ -2835,6 +2835,7 @@ class bl {
|
|
|
2835
2835
|
!0,
|
|
2836
2836
|
t,
|
|
2837
2837
|
async (r) => {
|
|
2838
|
+
console.log("executing orders");
|
|
2838
2839
|
const n = Ka(r.data), i = await this.assignOrderStatus(n);
|
|
2839
2840
|
this.emit("onPendingOrdersChanged", i);
|
|
2840
2841
|
for (let a = 0; a < i.length; a++) {
|
|
@@ -2918,7 +2919,9 @@ class bl {
|
|
|
2918
2919
|
);
|
|
2919
2920
|
}
|
|
2920
2921
|
async evmRedeem(t, r) {
|
|
2921
|
-
|
|
2922
|
+
this.emit("log", t.create_order.create_id, "executing evm redeem");
|
|
2923
|
+
const n = this.orderExecutorCache.get(t, le.Redeem);
|
|
2924
|
+
if (console.log("cache inside evm redeem:", n), n) {
|
|
2922
2925
|
this.emit("log", t.create_order.create_id, "already redeemed");
|
|
2923
2926
|
return;
|
|
2924
2927
|
}
|