@swapkit/toolboxes 1.0.0-beta.2 → 1.0.0-beta.20

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.
Files changed (124) hide show
  1. package/dist/chunk-12xtvbsp.js +4 -0
  2. package/dist/{chunk-0h4xdrwz.js.map → chunk-12xtvbsp.js.map} +2 -2
  3. package/dist/{chunk-fjfxga2v.js → chunk-5yxc1e69.js} +1 -1
  4. package/dist/{chunk-fjfxga2v.js.map → chunk-5yxc1e69.js.map} +1 -1
  5. package/dist/{chunk-0f0249b1.js → chunk-9bqegm61.js} +1 -1
  6. package/dist/chunk-kbnwrc5b.js +4 -0
  7. package/dist/chunk-kbnwrc5b.js.map +10 -0
  8. package/dist/{chunk-p1kdg37m.js → chunk-s47y8512.js} +2 -2
  9. package/dist/{chunk-p1kdg37m.js.map → chunk-s47y8512.js.map} +1 -1
  10. package/dist/chunk-vtd17cje.js +3 -0
  11. package/dist/chunk-vtd17cje.js.map +10 -0
  12. package/dist/src/cosmos/index.cjs +3 -0
  13. package/dist/src/cosmos/index.cjs.map +16 -0
  14. package/dist/src/cosmos/index.js +3 -0
  15. package/dist/src/cosmos/index.js.map +16 -0
  16. package/dist/src/evm/index.cjs +3 -0
  17. package/dist/src/evm/index.cjs.map +18 -0
  18. package/dist/src/evm/index.js +3 -0
  19. package/dist/src/evm/index.js.map +18 -0
  20. package/dist/src/index.cjs +3 -0
  21. package/dist/src/index.cjs.map +10 -0
  22. package/dist/src/index.js +3 -0
  23. package/dist/src/index.js.map +10 -0
  24. package/dist/src/near/index.cjs +3 -0
  25. package/dist/src/near/index.cjs.map +13 -0
  26. package/dist/src/near/index.js +3 -0
  27. package/dist/src/near/index.js.map +13 -0
  28. package/dist/{radix → src/radix}/index.cjs +2 -2
  29. package/dist/src/radix/index.cjs.map +10 -0
  30. package/dist/src/radix/index.js +3 -0
  31. package/dist/src/radix/index.js.map +10 -0
  32. package/dist/src/ripple/index.cjs +3 -0
  33. package/dist/src/ripple/index.cjs.map +10 -0
  34. package/dist/src/ripple/index.js +3 -0
  35. package/dist/src/ripple/index.js.map +10 -0
  36. package/dist/src/solana/index.cjs +3 -0
  37. package/dist/src/solana/index.cjs.map +10 -0
  38. package/dist/src/solana/index.js +3 -0
  39. package/dist/src/solana/index.js.map +10 -0
  40. package/dist/src/substrate/index.cjs +3 -0
  41. package/dist/src/substrate/index.cjs.map +11 -0
  42. package/dist/src/substrate/index.js +3 -0
  43. package/dist/src/substrate/index.js.map +11 -0
  44. package/dist/src/tron/index.cjs +3 -0
  45. package/dist/src/tron/index.cjs.map +11 -0
  46. package/dist/src/tron/index.js +3 -0
  47. package/dist/src/tron/index.js.map +11 -0
  48. package/dist/src/utxo/index.cjs +3 -0
  49. package/dist/src/utxo/index.cjs.map +16 -0
  50. package/dist/src/utxo/index.js +3 -0
  51. package/dist/src/utxo/index.js.map +16 -0
  52. package/package.json +49 -37
  53. package/src/cosmos/thorchainUtils/addressFormat.ts +4 -1
  54. package/src/cosmos/thorchainUtils/messages.ts +2 -2
  55. package/src/cosmos/thorchainUtils/registry.ts +3 -3
  56. package/src/cosmos/toolbox/cosmos.ts +16 -11
  57. package/src/cosmos/toolbox/index.ts +2 -2
  58. package/src/cosmos/toolbox/thorchain.ts +11 -9
  59. package/src/cosmos/util.ts +13 -6
  60. package/src/evm/__tests__/ethereum.test.ts +1 -1
  61. package/src/evm/helpers.ts +4 -3
  62. package/src/evm/toolbox/baseEVMToolbox.ts +37 -25
  63. package/src/evm/toolbox/index.ts +2 -2
  64. package/src/evm/toolbox/op.ts +21 -7
  65. package/src/index.ts +117 -100
  66. package/src/near/helpers/contractFactory.ts +22 -0
  67. package/src/near/helpers/core.ts +86 -0
  68. package/src/near/helpers/gasEstimation.ts +110 -0
  69. package/src/near/helpers/index.ts +5 -0
  70. package/src/near/helpers/nep141.ts +110 -0
  71. package/src/near/index.ts +24 -0
  72. package/src/near/toolbox.ts +497 -0
  73. package/src/near/types/contract.ts +48 -0
  74. package/src/near/types/nep141.ts +66 -0
  75. package/src/near/types.ts +58 -0
  76. package/src/radix/index.ts +8 -2
  77. package/src/ripple/index.ts +15 -26
  78. package/src/solana/toolbox.ts +75 -2
  79. package/src/substrate/substrate.ts +1 -1
  80. package/src/tron/helpers/trc20.abi.ts +40 -0
  81. package/src/tron/index.ts +16 -0
  82. package/src/tron/toolbox.ts +328 -0
  83. package/src/tron/types.ts +22 -0
  84. package/src/utxo/helpers/api.ts +30 -16
  85. package/src/utxo/helpers/bchaddrjs.ts +8 -8
  86. package/src/utxo/helpers/coinselect.ts +2 -2
  87. package/src/utxo/helpers/txSize.ts +4 -3
  88. package/src/utxo/toolbox/bitcoinCash.ts +22 -14
  89. package/src/utxo/toolbox/index.ts +2 -1
  90. package/src/utxo/toolbox/utxo.ts +35 -27
  91. package/src/utxo/types.ts +2 -0
  92. package/dist/chunk-0h4xdrwz.js +0 -4
  93. package/dist/cosmos/index.cjs +0 -3
  94. package/dist/cosmos/index.cjs.map +0 -16
  95. package/dist/cosmos/index.js +0 -3
  96. package/dist/cosmos/index.js.map +0 -16
  97. package/dist/evm/index.cjs +0 -3
  98. package/dist/evm/index.cjs.map +0 -18
  99. package/dist/evm/index.js +0 -3
  100. package/dist/evm/index.js.map +0 -18
  101. package/dist/index.cjs +0 -3
  102. package/dist/index.cjs.map +0 -10
  103. package/dist/index.js +0 -3
  104. package/dist/index.js.map +0 -10
  105. package/dist/radix/index.cjs.map +0 -10
  106. package/dist/radix/index.js +0 -3
  107. package/dist/radix/index.js.map +0 -10
  108. package/dist/ripple/index.cjs +0 -3
  109. package/dist/ripple/index.cjs.map +0 -10
  110. package/dist/ripple/index.js +0 -3
  111. package/dist/ripple/index.js.map +0 -10
  112. package/dist/solana/index.cjs +0 -3
  113. package/dist/solana/index.cjs.map +0 -10
  114. package/dist/solana/index.js +0 -3
  115. package/dist/solana/index.js.map +0 -10
  116. package/dist/substrate/index.cjs +0 -3
  117. package/dist/substrate/index.cjs.map +0 -11
  118. package/dist/substrate/index.js +0 -3
  119. package/dist/substrate/index.js.map +0 -11
  120. package/dist/utxo/index.cjs +0 -3
  121. package/dist/utxo/index.cjs.map +0 -16
  122. package/dist/utxo/index.js +0 -3
  123. package/dist/utxo/index.js.map +0 -16
  124. /package/dist/{chunk-0f0249b1.js.map → chunk-9bqegm61.js.map} +0 -0
@@ -0,0 +1,3 @@
1
+ var $G={};ZG($G,{toLegacyAddress:()=>f,toCashAddress:()=>m,stripToCashAddress:()=>K,stripPrefix:()=>S,nonSegwitChains:()=>u,isValidAddress:()=>jX,getUtxoToolbox:()=>JG,getUtxoNetwork:()=>P,getUtxoApi:()=>Y,getUTXOAddressValidator:()=>OX,getScriptTypeForAddress:()=>h,getOutputSize:()=>l,getInputSize:()=>N,getDustThreshold:()=>r,getCreateKeysForPath:()=>o,detectAddressNetwork:()=>LX,createUTXOToolbox:()=>p,createCustomUtxoApi:()=>mX,createBCHToolbox:()=>DX,compileMemo:()=>O,calculateTxSize:()=>E,bchValidateAddress:()=>A,addressFromKeysGetter:()=>qX,accumulative:()=>k,UtxoNetwork:()=>$X,UTXOScriptType:()=>i,TX_OVERHEAD:()=>d,OutputSizes:()=>c,OP_RETURN_OVERHEAD:()=>PX,MIN_TX_FEE:()=>pX,InputSizes:()=>a});module.exports=QG($G);var b=require("@swapkit/helpers");var g=require("@psf/bitcoincashjs-lib"),H=require("@swapkit/helpers"),AX=require("bitcoinjs-lib");var B=require("@swapkit/helpers"),TX=require("bitcoinjs-lib");var w=x(require("coininfo"));async function RX({chain:X,txHash:G}){let J=B.SKConfig.get("rpcUrls")[X],Q=JSON.stringify({jsonrpc:"2.0",method:"sendrawtransaction",params:[G],id:zX()}),$=await B.RequestClient.post(J,{headers:{"Content-Type":"application/json"},body:Q});if($.error)throw new B.SwapKitError("toolbox_utxo_broadcast_failed",{error:$.error?.message});if($.result.includes('"code":-26'))throw new B.SwapKitError("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return $.result}function GX(X){return`https://api.blockchair.com/${wX(X)}`}function MX(X){switch(X){case B.Chain.Bitcoin:return 5;case B.Chain.Dogecoin:return 1e4;case B.Chain.Litecoin:return 1;default:return 2}}function wX(X){switch(X){case B.Chain.BitcoinCash:return"bitcoin-cash";case B.Chain.Litecoin:return"litecoin";case B.Chain.Dash:return"dash";case B.Chain.Dogecoin:return"dogecoin";case B.Chain.Polkadot:return"polkadot";default:return"bitcoin"}}async function fX(X){try{let{feePerKb:G}=await B.RequestClient.get(`https://app.bitgo.com/api/v2/${X.toLowerCase()}/tx/fee`),J=G/1000;return Math.max(J,MX(X))}catch(G){return MX(X)}}async function JX(X,G){try{let J=await B.RequestClient.get(X);if(!J||J.context.code!==200)throw new B.SwapKitError("toolbox_utxo_api_error",{error:`Failed to query ${X}`});return J.data}catch(J){if(!G)throw J;let Q=await B.RequestClient.get(`${X}${G?`&key=${G}`:""}`);if(!Q||Q.context.code!==200)throw new B.SwapKitError("toolbox_utxo_api_error",{error:`Failed to query ${X}`});return Q.data}}async function CX({address:X,chain:G,apiKey:J}){if(!X)throw new B.SwapKitError("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await JX(`${GX(G)}/dashboards/address/${X}?transaction_details=true`,J))[X]}catch(Q){return{utxo:[],address:{balance:0,transaction_count:0}}}}async function EX({address:X,chain:G,apiKey:J}){return(await CX({address:X,chain:G,apiKey:J}))?.address.balance||0}async function HX({chain:X,apiKey:G,txHash:J}){if(!J)throw new B.SwapKitError("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await JX(`${GX(X)}/raw/transaction/${J}`,G))?.[J]?.raw_transaction||""}catch(Q){return console.error("Failed to fetch raw transaction:",Q),""}}async function SX({chain:X,address:G,apiKey:J,offset:Q=0,limit:$=100}){return(await JX(`${GX(X)}/outputs?q=is_spent(false),recipient(${G})&limit=${$}&offset=${Q}`,J)).filter(({is_spent:q})=>!q).map(({script_hex:q,block_id:W,transaction_hash:D,index:U,value:M,spending_signature_hex:v})=>({hash:D,index:U,value:M,txHex:v,script_hex:q,is_confirmed:W!==-1}))}async function YX({chain:X,address:G,apiKey:J,offset:Q=0,limit:$=100}){if(!G)throw new B.SwapKitError("toolbox_utxo_invalid_params",{error:"Address is required"});try{let j=await SX({chain:X,address:G,apiKey:J,offset:Q,limit:$});if(j.length<=$)return j;let Z=await YX({chain:X,address:G,apiKey:J,offset:Q+$,limit:$});return[...j,...Z]}catch(j){return console.error("Failed to fetch unspent UTXOs:",j),[]}}async function gX({address:X,chain:G,apiKey:J,fetchTxHex:Q=!0}){let $=await YX({chain:G,address:X,apiKey:J}),j=[];for(let{hash:Z,index:q,script_hex:W,value:D}of $){let U;if(Q)U=await HX({txHash:Z,chain:G,apiKey:J});j.push({address:X,hash:Z,index:q,txHex:U,value:D,witnessUtxo:{value:D,script:Buffer.from(W,"hex")}})}return j}function xX(X){let G=B.SKConfig.get("apiKeys").blockchair||"";return B.warnOnce(!G,"No Blockchair API key found. Functionality will be limited."),{broadcastTx:(J)=>RX({txHash:J,chain:X}),getRawTx:(J)=>HX({txHash:J,chain:X,apiKey:G}),getSuggestedTxFee:()=>fX(X),getBalance:(J)=>EX({address:J,chain:X,apiKey:G}),getAddressData:(J)=>CX({address:J,chain:X,apiKey:G}),scanUTXOs:(J)=>gX({...J,chain:X,apiKey:G})}}function mX(X){return X}function Y(X){let G=B.SKConfig.get("apis")[X];if(G)return B.warnOnce(!0,"Using custom UTXO API. Be sure to implement all methods to avoid issues."),G;return xX(X)}function P(){return function X(G){switch(G){case B.Chain.Bitcoin:return TX.networks.bitcoin;case B.Chain.BitcoinCash:return w.default.bitcoincash.main.toBitcoinJS();case B.Chain.Dash:return w.default.dash.main.toBitcoinJS();case B.Chain.Litecoin:return w.default.litecoin.main.toBitcoinJS();case B.Chain.Dogecoin:{let J={private:70615956,public:70617039},Q=w.default.dogecoin.test;return Q.versions.bip32=J,w.default.dogecoin.main.toBitcoinJS()}default:throw new B.SwapKitError("toolbox_utxo_not_supported",{chain:G})}}}var V=require("@swapkit/helpers"),QX=x(require("bs58check")),ZX=x(require("cashaddrjs"));var $X;((J)=>{J.Mainnet="mainnet";J.Testnet="testnet"})($X||={});var z={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}};function jX(X){try{return n(X),!0}catch(G){return!1}}function LX(X){return n(X)?.network}function f(X){let G=n(X);if(G?.format==="legacy")return X;return cX(G)}function m(X){let G=n(X);return uX(G)}function n(X){try{return lX(X)}catch(G){}try{return hX(X)}catch(G){}throw new V.SwapKitError("toolbox_utxo_invalid_address",{address:X})}function lX(X){try{let G=QX.default.decode(X);if(G.length!==21)throw new V.SwapKitError("toolbox_utxo_invalid_address",{address:X});let J=G[0],Q=Array.prototype.slice.call(G,1);switch(J){case z.legacy.mainnet.p2pkh:return{hash:Q,format:"legacy",network:"mainnet",type:"p2pkh"};case z.legacy.mainnet.p2sh:return{hash:Q,format:"legacy",network:"mainnet",type:"p2sh"};case z.legacy.testnet.p2pkh:return{hash:Q,format:"legacy",network:"testnet",type:"p2pkh"};case z.legacy.testnet.p2sh:return{hash:Q,format:"legacy",network:"testnet",type:"p2sh"};case z.bitpay.mainnet.p2pkh:return{hash:Q,format:"bitpay",network:"mainnet",type:"p2pkh"};case z.bitpay.mainnet.p2sh:return{hash:Q,format:"bitpay",network:"mainnet",type:"p2sh"};default:throw new V.SwapKitError("toolbox_utxo_invalid_address",{address:X})}}catch(G){throw new V.SwapKitError("toolbox_utxo_invalid_address",{address:X})}}function hX(X){if(X.indexOf(":")!==-1)try{return IX(X)}catch(G){}else{let G=["bitcoincash","bchtest","bchreg"];for(let J of G)try{return IX(`${J}:${X}`)}catch(Q){}}throw new V.SwapKitError("toolbox_utxo_invalid_address",{address:X})}function IX(X){try{let{hash:G,prefix:J,type:Q}=ZX.default.decode(X);return{format:"cashaddr",hash:Array.prototype.slice.call(G,0),network:J==="bitcoincash"?"mainnet":"testnet",type:Q==="P2PKH"?"p2pkh":"p2sh"}}catch(G){throw new V.SwapKitError("toolbox_utxo_invalid_address",{address:X})}}function cX(X){let G=z.legacy[X.network][X.type],J=Buffer.alloc(1+X.hash.length);return J[0]=G,J.set(X.hash,1),QX.default.encode(J)}function uX(X){let G=X.network==="mainnet"?"bitcoincash":"bchtest",J=X.type==="p2pkh"?"P2PKH":"P2SH",Q=new Uint8Array(X.hash);return ZX.default.encode(G,J,Q)}var y=require("@swapkit/helpers");var r=(X)=>{switch(X){case y.Chain.Bitcoin:case y.Chain.BitcoinCash:return 550;case y.Chain.Dash:case y.Chain.Litecoin:return 5500;case y.Chain.Dogecoin:return 1e5;default:throw new y.SwapKitError("toolbox_utxo_not_supported",{chain:X})}},k=({inputs:X,outputs:G,feeRate:J=1,chain:Q=y.Chain.Bitcoin})=>{let $=Math.ceil(J),j=X[0]&&"address"in X[0]&&X[0].address?h(X[0].address):"P2PKH",Z=X.filter((v)=>N(v)*$<=v.value),q=d+G.reduce((v,C)=>v+l(C,j),0),W=G.reduce((v,C)=>v+C.value,0),D=q*$,U=0,M=[];for(let v of Z){let C=N(v),T=$*C;D+=T,U+=v.value,M.push(v);let _=D+W;if(U<_)continue;let R=U-_,BX=$*l({address:"",value:0},j);if(R>BX){let UX=BX+D,vX=U-(W+UX);if(vX>Math.max(N({})*$,r(Q)))return{inputs:M,outputs:G.concat({value:vX,address:""}),fee:UX}}return{inputs:M,outputs:G,fee:D}}return{fee:$*E({inputs:X,outputs:G,feeRate:$})}};var _X=require("@swapkit/helpers"),s=require("bitcoinjs-lib"),pX=1000,d=10,PX=10,oX=41,nX=107;function O(X){let G=Buffer.from(X,"utf8");return s.script.compile([s.opcodes.OP_RETURN,G])}var i;((J)=>{J.P2PKH="P2PKH";J.P2WPKH="P2WPKH"})(i||={});var a={["P2PKH"]:148,["P2WPKH"]:68},c={["P2PKH"]:34,["P2WPKH"]:31},h=(X)=>{if(X.startsWith("bc1")||X.startsWith("ltc1"))return"P2WPKH";if(X.startsWith("1")||X.startsWith("3")||X.startsWith("L")||X.startsWith("M")||X.startsWith("X")||X.startsWith("D")||X.startsWith("bitcoincash:q")||X.startsWith("q"))return"P2PKH";throw new _X.SwapKitError("toolbox_utxo_invalid_address",{address:X})},E=({inputs:X,outputs:G,feeRate:J})=>{let Q=X[0]&&"address"in X[0]&&X[0].address?h(X[0].address):"P2PKH",$=X.filter((Z)=>Z.value>=a["type"in Z?Z.type:"P2PKH"]*Math.ceil(J)).reduce((Z,q)=>Z+N(q),0),j=G?.reduce((Z,q)=>Z+l(q),0)||c[Q];return d+$+j},N=(X)=>{if("type"in X)return a[X.type];if("address"in X&&X.address)return a[h(X.address)];return oX+nX},l=(X,G)=>{if(X?.script)return PX+X.script.length+(X.script.length>=74?2:1);if(G)return c[G];return c.P2PKH};var L=require("@swapkit/helpers"),F=require("bitcoinjs-lib"),yX=x(require("ecpair"));var t=x(require("@bitcoinerlab/secp256k1")),e=require("@psf/bitcoincashjs-lib"),NX=require("@scure/bip32"),WX=require("@scure/bip39"),u=[L.Chain.Dash,L.Chain.Dogecoin];function rX({inputs:X,outputs:G,chain:J,psbt:Q,sender:$,compiledMemo:j}){for(let Z of X){let q=!!Z.witnessUtxo&&!u.includes(J)&&{witnessUtxo:Z.witnessUtxo},W=u.includes(J)&&{nonWitnessUtxo:Z.txHex?Buffer.from(Z.txHex,"hex"):void 0};Q.addInput({hash:Z.hash,index:Z.index,...q,...W})}for(let Z of G){let q="address"in Z&&Z.address?Z.address:$,W=Z.script;if(W&&!j)continue;let D=W?{script:j,value:0}:{address:q,value:Z.value};F.initEccLib(t.default),Q.addOutput(D)}return{psbt:Q,inputs:X}}async function kX({assetValue:X,recipient:G,memo:J,feeRate:Q,sender:$,fetchTxHex:j=!1}){let Z=X.chain,q=J?await O(J):null,W=await VX({assetValue:X,recipient:G,memo:J,sender:$,fetchTxHex:j}),{inputs:D,outputs:U}=k({...W,feeRate:Q,chain:Z});if(!(D&&U))throw new L.SwapKitError("toolbox_utxo_insufficient_balance",{sender:$,assetValue:X});let M=await P(),v=new F.Psbt({network:M(Z)});if(Z===L.Chain.Dogecoin)v.setMaximumFeeRate(650000000);let{psbt:C,inputs:T}=await rX({inputs:D,outputs:U,chain:Z,psbt:v,sender:$,compiledMemo:q});return{psbt:C,utxos:W.inputs,inputs:T}}async function OX(){let X=await P();return function G({address:J,chain:Q}){if(Q===L.Chain.BitcoinCash)return A(J);try{return F.initEccLib(t.default),F.address.toOutputScript(J,X(Q)),!0}catch($){return!1}}}async function dX({chain:X,phrase:G,derivationPath:J}){let Q=(await o(X))({phrase:G,derivationPath:J});async function $(Z){return await Z.signAllInputs(Q),Z}async function j(){return(await qX(X))(Q)}return{getAddress:j,signTransaction:$}}async function p({chain:X,...G}){let J="phrase"in G?G.phrase:void 0,Q="index"in G?G.index||0:0,$=L.derivationPathToString("derivationPath"in G&&G.derivationPath?G.derivationPath:L.updateDerivationPath(L.NetworkDerivationPath[X],{index:Q})),j=J?await dX({chain:X,phrase:J,derivationPath:$}):("signer"in G)?G.signer:void 0;function Z(){return Promise.resolve(j?.getAddress())}let q=await qX(X),W=await OX(),D=await o(X);return{accumulative:k,calculateTxSize:E,getAddressFromKeys:q,getAddress:Z,validateAddress:(U)=>W({address:U,chain:X}),broadcastTx:(U)=>Y(X).broadcastTx(U),createTransaction:kX,createKeysForPath:D,getFeeRates:()=>XX(X),getInputsOutputsFee:bX,transfer:sX(j),getPrivateKeyFromMnemonic:(U)=>{return D(U).toWIF()},getBalance:FX(X),estimateTransactionFee:aX(X),estimateMaxSendableAmount:iX(X)}}async function bX({assetValue:X,feeOptionKey:G=L.FeeOption.Fast,feeRate:J,memo:Q,sender:$,recipient:j}){let Z=X.chain,q=await VX({assetValue:X,sender:$,memo:Q,recipient:j}),W=J?Math.floor(J):(await XX(Z))[G];return k({...q,feeRate:W,chain:Z})}function iX(X){return async function G({from:J,memo:Q,feeRate:$,feeOptionKey:j=L.FeeOption.Fast,recipients:Z=1}){let q=await Y(X).getAddressData(J),W=$?Math.ceil($):(await XX(X))[j],D=q?.utxo.map((T)=>({...T,type:"P2PKH",hash:""})).filter((T)=>T.value>Math.max(r(X),N(T)*W));if(!D?.length)return L.AssetValue.from({chain:X});let U=L.AssetValue.from({chain:X,value:D.reduce((T,_)=>T+_.value,0)}),M=typeof Z==="number"?Array.from({length:Z},()=>({address:J,value:0})):Z;if(Q){let T=await O(Q);M.push({address:J,script:T,value:0})}let C=E({inputs:D,outputs:M,feeRate:W})*W;return U.sub(C)}}function aX(X){return async(G)=>{let J=await bX(G);return L.AssetValue.from({chain:X,value:L.SwapKitNumber.fromBigInt(BigInt(J.fee),8).getValue("string")})}}async function o(X){let G=await P();switch(X){case L.Chain.BitcoinCash:return function J({phrase:Q,derivationPath:$=`${L.DerivationPath.BCH}/0`,wif:j}){let Z=G(X);if(j)return e.ECPair.fromWIF(j,Z);if(!Q)throw new L.SwapKitError("toolbox_utxo_invalid_params",{error:"No phrase provided"});return e.HDNode.fromSeedBuffer(Buffer.from(WX.mnemonicToSeedSync(Q)),Z).derivePath($).keyPair};case L.Chain.Bitcoin:case L.Chain.Dogecoin:case L.Chain.Litecoin:case L.Chain.Dash:return function J({phrase:Q,wif:$,derivationPath:j}){if(!($||Q))throw new L.SwapKitError("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let Z=yX.default(t.default),q=G(X);if($)return Z.fromWIF($,q);let W=WX.mnemonicToSeedSync(Q),D=NX.HDKey.fromMasterSeed(W,q).derive(j);if(!D.privateKey)throw new L.SwapKitError("toolbox_utxo_invalid_params",{error:"Could not get private key from phrase"});return Z.fromPrivateKey(Buffer.from(D.privateKey),{network:q})};default:throw new L.SwapKitError("toolbox_utxo_not_supported",{chain:X})}}async function qX(X){let G=await P();return function J(Q){if(!Q)throw new L.SwapKitError("toolbox_utxo_invalid_params",{error:"Keys must be provided"});let $=u.includes(X)?F.payments.p2pkh:F.payments.p2wpkh,{address:j}=$({pubkey:Q.publicKey,network:G(X)});if(!j)throw new L.SwapKitError("toolbox_utxo_invalid_address",{error:"Address not defined"});return j}}function sX(X){return async function G({memo:J,recipient:Q,feeOptionKey:$,feeRate:j,assetValue:Z}){let q=await X?.getAddress(),W=Z.chain;if(!(X&&q))throw new L.SwapKitError("toolbox_utxo_no_signer");if(!Q)throw new L.SwapKitError("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let D=j||(await XX(W))[$||L.FeeOption.Fast],{psbt:U}=await kX({recipient:Q,feeRate:D,sender:q,assetValue:Z,memo:J}),M=await X.signTransaction(U);return M.finalizeAllInputs(),Y(W).broadcastTx(M.extractTransaction().toHex())}}async function XX(X){let G=await Y(X).getSuggestedTxFee();return{[L.FeeOption.Average]:G,[L.FeeOption.Fast]:L.applyFeeMultiplier(G,L.FeeOption.Fast),[L.FeeOption.Fastest]:L.applyFeeMultiplier(G,L.FeeOption.Fastest)}}async function VX({assetValue:X,recipient:G,memo:J,sender:Q,fetchTxHex:$=!1}){let j=X.chain,Z=$||u.includes(j);return{inputs:await Y(j).scanUTXOs({address:Q,fetchTxHex:Z}),outputs:[{address:G,value:Number(X.bigIntValue)},...J?[{address:"",script:await O(J),value:0}]:[]]}}var I=H.Chain.BitcoinCash;function S(X){return X.replace(/(bchtest:|bitcoincash:)/,"")}function A(X){let G=S(X);return jX(G)&&LX(G)==="mainnet"}function K(X){return S(m(X))}async function tX(X){async function G({builder:Q,utxos:$}){return $.forEach((j,Z)=>{Q.sign(Z,X,void 0,65,j.witnessUtxo?.value)}),Q.build()}return{getAddress:()=>{let Q=X.getAddress(0);return Promise.resolve(K(Q))},signTransaction:G}}async function DX(X){let G="phrase"in X?X.phrase:void 0,J="index"in X?X.index||0:0,Q=H.derivationPathToString("derivationPath"in X&&X.derivationPath?X.derivationPath:H.updateDerivationPath(H.NetworkDerivationPath[I],{index:J})),$=(await o(I))({phrase:G,derivationPath:Q}),j=$?await tX($):("signer"in X)?X.signer:void 0;function Z(){return Promise.resolve(j?.getAddress())}let{getBalance:q,getFeeRates:W,broadcastTx:D,...U}=await p({chain:I});function M(v,C=!0){return q(S(m(v)))}return{...U,getAddress:Z,broadcastTx:D,createTransaction:KX,buildTx:XG,getAddressFromKeys:GG,getBalance:M,getFeeRates:W,stripPrefix:S,stripToCashAddress:K,validateAddress:A,transfer:eX({getFeeRates:W,broadcastTx:D,signer:j})}}async function KX({assetValue:X,recipient:G,memo:J,feeRate:Q,sender:$}){if(!A(G))throw new H.SwapKitError("toolbox_utxo_invalid_address",{address:G});let j=await Y(I).scanUTXOs({address:K($),fetchTxHex:!0}),Z=J?await O(J):null,q=[];q.push({address:G,value:X.getBaseValue("number")});let{inputs:W,outputs:D}=k({inputs:j,outputs:q,feeRate:Q,chain:I});if(!(W&&D))throw new H.SwapKitError("toolbox_utxo_insufficient_balance",{sender:$,assetValue:X});let U=await P(),M=new g.TransactionBuilder(U(I));await Promise.all(W.map(async(v)=>{let C=await Y(I).getRawTx(v.hash);M.addInput(g.Transaction.fromBuffer(Buffer.from(C,"hex")),v.index)}));for(let v of D){let C="address"in v&&v.address?v.address:f($),T=await P(),_=g.address.toOutputScript(f(C),T(I));M.addOutput(_,v.value)}if(Z)M.addOutput(Z,0);return{builder:M,utxos:W}}function eX({broadcastTx:X,getFeeRates:G,signer:J}){return async function Q({recipient:$,assetValue:j,feeOptionKey:Z=H.FeeOption.Fast,...q}){let W=await J?.getAddress();if(!(J&&W))throw new H.SwapKitError("toolbox_utxo_no_signer");if(!$)throw new H.SwapKitError("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let D=q.feeRate||(await G())[Z],{builder:U,utxos:M}=await KX({...q,assetValue:j,feeRate:D,recipient:$,sender:W}),C=(await J.signTransaction({builder:U,utxos:M})).toHex();return X(C)}}async function XG({assetValue:X,recipient:G,memo:J,feeRate:Q,sender:$}){let j=m(G);if(!A(j))throw new H.SwapKitError("toolbox_utxo_invalid_address",{address:j});let Z=await Y(I).scanUTXOs({address:K($),fetchTxHex:!0}),q=Number(Q.toFixed(0)),W=J?await O(J):null,D=[];if(D.push({address:f(G),value:X.getBaseValue("number")}),W)D.push({script:W,value:0});let{inputs:U,outputs:M}=k({inputs:Z,outputs:D,feeRate:q,chain:I});if(!(U&&M))throw new H.SwapKitError("toolbox_utxo_insufficient_balance",{sender:$,assetValue:X});let v=await P(),C=new AX.Psbt({network:v(I)});for(let{hash:T,index:_,witnessUtxo:R}of U)C.addInput({hash:T,index:_,witnessUtxo:R});for(let T of M){let _="address"in T&&T.address?T.address:f($),R=T.script?W?{script:W,value:0}:void 0:{address:_,value:T.value};if(R)C.addOutput(R)}return{psbt:C,utxos:Z,inputs:U}}function GG(X){let G=X.getAddress(0);return K(G)}async function JG(X,G){switch(X){case b.Chain.BitcoinCash:return await DX(G);case b.Chain.Bitcoin:case b.Chain.Dogecoin:case b.Chain.Litecoin:case b.Chain.Dash:return await p({chain:X,...G});default:throw new b.SwapKitError("toolbox_utxo_not_supported",{chain:X})}}
2
+
3
+ //# debugId=3121718C7D34F25A64756E2164756E21
@@ -0,0 +1,16 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/utxo/toolbox/index.ts", "../src/utxo/toolbox/bitcoinCash.ts", "../src/utxo/helpers/api.ts", "../src/utxo/helpers/bchaddrjs.ts", "../src/utxo/helpers/coinselect.ts", "../src/utxo/helpers/txSize.ts", "../src/utxo/toolbox/utxo.ts"],
4
+ "sourcesContent": [
5
+ "import {\n Chain,\n type ChainSigner,\n type DerivationPathArray,\n SwapKitError,\n type UTXOChain,\n} from \"@swapkit/helpers\";\nimport type { Psbt } from \"bitcoinjs-lib\";\n\nimport type { TransactionBuilderType, TransactionType, UTXOType } from \"../types\";\nimport { createBCHToolbox } from \"./bitcoinCash\";\nimport { createUTXOToolbox } from \"./utxo\";\n\ntype BCHToolbox = Awaited<ReturnType<typeof createBCHToolbox>>;\ntype CommonUTXOToolbox = Awaited<\n ReturnType<typeof createUTXOToolbox<Exclude<UTXOChain, Chain.BitcoinCash>>>\n>;\n\nexport type UTXOToolboxes = {\n [Chain.BitcoinCash]: BCHToolbox;\n [Chain.Bitcoin]: CommonUTXOToolbox;\n [Chain.Dogecoin]: CommonUTXOToolbox;\n [Chain.Litecoin]: CommonUTXOToolbox;\n [Chain.Dash]: CommonUTXOToolbox;\n};\n\nexport type UTXOWallets = {\n [key in keyof UTXOToolboxes]: UTXOToolboxes[key];\n};\n\nexport type UtxoToolboxParams = {\n [Chain.BitcoinCash]: {\n signer: ChainSigner<{ builder: TransactionBuilderType; utxos: UTXOType[] }, TransactionType>;\n };\n [Chain.Bitcoin]: { signer: ChainSigner<Psbt, Psbt> };\n [Chain.Dogecoin]: { signer: ChainSigner<Psbt, Psbt> };\n [Chain.Litecoin]: { signer: ChainSigner<Psbt, Psbt> };\n [Chain.Dash]: { signer: ChainSigner<Psbt, Psbt> };\n};\n\nexport async function getUtxoToolbox<T extends keyof UTXOToolboxes>(\n chain: T,\n params?:\n | UtxoToolboxParams[T]\n | {\n phrase?: string;\n derivationPath?: DerivationPathArray;\n index?: number;\n },\n): Promise<UTXOToolboxes[T]> {\n switch (chain) {\n case Chain.BitcoinCash: {\n const toolbox = await createBCHToolbox(params as UtxoToolboxParams[Chain.BitcoinCash]);\n return toolbox as UTXOToolboxes[T];\n }\n\n case Chain.Bitcoin:\n case Chain.Dogecoin:\n case Chain.Litecoin:\n case Chain.Dash: {\n const toolbox = await createUTXOToolbox({\n chain,\n ...(params as UtxoToolboxParams[Exclude<T, Chain.BitcoinCash>]),\n });\n return toolbox as UTXOToolboxes[Exclude<T, Chain.BitcoinCash>];\n }\n\n default:\n throw new SwapKitError(\"toolbox_utxo_not_supported\", { chain });\n }\n}\n\nexport {\n stripToCashAddress,\n stripPrefix,\n bchValidateAddress,\n} from \"./bitcoinCash\";\n",
6
+ "import {\n Transaction,\n TransactionBuilder,\n address as bchAddress,\n // @ts-ignore\n} from \"@psf/bitcoincashjs-lib\";\nimport {\n Chain,\n type ChainSigner,\n type DerivationPathArray,\n FeeOption,\n NetworkDerivationPath,\n SwapKitError,\n derivationPathToString,\n updateDerivationPath,\n} from \"@swapkit/helpers\";\nimport { Psbt } from \"bitcoinjs-lib\";\nimport type { UtxoToolboxParams } from \".\";\nimport {\n accumulative,\n UtxoNetwork as bchNetwork,\n compileMemo,\n detectAddressNetwork,\n getUtxoApi,\n getUtxoNetwork,\n isValidAddress,\n toCashAddress,\n toLegacyAddress,\n} from \"../helpers\";\nimport type {\n BchECPair,\n TargetOutput,\n TransactionBuilderType,\n TransactionType,\n UTXOBuildTxParams,\n UTXOTransferParams,\n UTXOType,\n} from \"../types\";\nimport { createUTXOToolbox, getCreateKeysForPath } from \"./utxo\";\n\nconst chain = Chain.BitcoinCash;\n\nexport function stripPrefix(address: string) {\n return address.replace(/(bchtest:|bitcoincash:)/, \"\");\n}\n\nexport function bchValidateAddress(address: string) {\n const strippedAddress = stripPrefix(address);\n return (\n isValidAddress(strippedAddress) && detectAddressNetwork(strippedAddress) === bchNetwork.Mainnet\n );\n}\n\nexport function stripToCashAddress(address: string) {\n return stripPrefix(toCashAddress(address));\n}\n\nasync function createSignerWithKeys(keys: BchECPair) {\n async function signTransaction({\n builder,\n utxos,\n }: { builder: TransactionBuilderType; utxos: UTXOType[] }) {\n utxos.forEach((utxo, index) => {\n builder.sign(index, keys, undefined, 0x41, utxo.witnessUtxo?.value);\n });\n\n return builder.build();\n }\n\n const getAddress = () => {\n const address = keys.getAddress(0);\n return Promise.resolve(stripToCashAddress(address));\n };\n\n return {\n getAddress,\n signTransaction,\n };\n}\n\nexport async function createBCHToolbox<T extends Chain.BitcoinCash>(\n toolboxParams:\n | UtxoToolboxParams[T]\n | {\n phrase?: string;\n derivationPath?: DerivationPathArray;\n index?: number;\n },\n) {\n const phrase = \"phrase\" in toolboxParams ? toolboxParams.phrase : undefined;\n\n const index = \"index\" in toolboxParams ? toolboxParams.index || 0 : 0;\n\n const derivationPath = derivationPathToString(\n \"derivationPath\" in toolboxParams && toolboxParams.derivationPath\n ? toolboxParams.derivationPath\n : updateDerivationPath(NetworkDerivationPath[chain], { index }),\n );\n\n const keys = (await getCreateKeysForPath(chain))({ phrase, derivationPath });\n\n const signer = keys\n ? await createSignerWithKeys(keys)\n : \"signer\" in toolboxParams\n ? toolboxParams.signer\n : undefined;\n\n function getAddress() {\n return Promise.resolve(signer?.getAddress());\n }\n\n const { getBalance, getFeeRates, broadcastTx, ...toolbox } = await createUTXOToolbox({ chain });\n\n function handleGetBalance(address: string, _scamFilter = true) {\n return getBalance(stripPrefix(toCashAddress(address)));\n }\n\n return {\n ...toolbox,\n getAddress,\n broadcastTx,\n createTransaction,\n buildTx,\n getAddressFromKeys,\n getBalance: handleGetBalance,\n getFeeRates,\n stripPrefix,\n stripToCashAddress,\n validateAddress: bchValidateAddress,\n transfer: transfer({ getFeeRates, broadcastTx, signer }),\n };\n}\n\nasync function createTransaction({\n assetValue,\n recipient,\n memo,\n feeRate,\n sender,\n}: UTXOBuildTxParams) {\n if (!bchValidateAddress(recipient))\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address: recipient });\n const utxos = await getUtxoApi(chain).scanUTXOs({\n address: stripToCashAddress(sender),\n fetchTxHex: true,\n });\n\n const compiledMemo = memo ? await compileMemo(memo) : null;\n\n const targetOutputs: TargetOutput[] = [];\n // output to recipient\n targetOutputs.push({\n address: recipient,\n value: assetValue.getBaseValue(\"number\"),\n });\n const { inputs, outputs } = accumulative({\n inputs: utxos,\n outputs: targetOutputs,\n feeRate,\n chain,\n });\n\n // .inputs and .outputs will be undefined if no solution was found\n if (!(inputs && outputs))\n throw new SwapKitError(\"toolbox_utxo_insufficient_balance\", { sender, assetValue });\n const getNetwork = await getUtxoNetwork();\n const builder = new TransactionBuilder(getNetwork(chain)) as TransactionBuilderType;\n\n await Promise.all(\n inputs.map(async (utxo: UTXOType) => {\n const txHex = await getUtxoApi(chain).getRawTx(utxo.hash);\n\n builder.addInput(Transaction.fromBuffer(Buffer.from(txHex, \"hex\")), utxo.index);\n }),\n );\n\n for (const output of outputs) {\n const address =\n \"address\" in output && output.address ? output.address : toLegacyAddress(sender);\n const getNetwork = await getUtxoNetwork();\n const outputScript = bchAddress.toOutputScript(toLegacyAddress(address), getNetwork(chain));\n\n builder.addOutput(outputScript, output.value);\n }\n\n // add output for memo\n if (compiledMemo) {\n builder.addOutput(compiledMemo, 0); // Add OP_RETURN {script, value}\n }\n\n return { builder, utxos: inputs };\n}\n\nfunction transfer({\n broadcastTx,\n getFeeRates,\n signer,\n}: {\n broadcastTx: (txHash: string) => Promise<string>;\n getFeeRates: () => Promise<Record<FeeOption, number>>;\n signer?: ChainSigner<{ builder: TransactionBuilderType; utxos: UTXOType[] }, TransactionType>;\n}) {\n return async function transfer({\n recipient,\n assetValue,\n feeOptionKey = FeeOption.Fast,\n ...rest\n }: UTXOTransferParams) {\n const from = await signer?.getAddress();\n if (!(signer && from)) throw new SwapKitError(\"toolbox_utxo_no_signer\");\n if (!recipient)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", {\n error: \"Recipient address must be provided\",\n });\n\n const feeRate = rest.feeRate || (await getFeeRates())[feeOptionKey];\n\n // try out if psbt tx is faster/better/nicer\n const { builder, utxos } = await createTransaction({\n ...rest,\n assetValue,\n feeRate,\n recipient,\n sender: from,\n });\n\n const tx = await signer.signTransaction({ builder, utxos });\n const txHex = tx.toHex();\n\n return broadcastTx(txHex);\n };\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO: refactor\nasync function buildTx({ assetValue, recipient, memo, feeRate, sender }: UTXOBuildTxParams) {\n const recipientCashAddress = toCashAddress(recipient);\n if (!bchValidateAddress(recipientCashAddress))\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address: recipientCashAddress });\n\n const utxos = await getUtxoApi(chain).scanUTXOs({\n address: stripToCashAddress(sender),\n fetchTxHex: true,\n });\n\n const feeRateWhole = Number(feeRate.toFixed(0));\n const compiledMemo = memo ? await compileMemo(memo) : null;\n\n const targetOutputs = [] as TargetOutput[];\n\n // output to recipient\n targetOutputs.push({\n address: toLegacyAddress(recipient),\n value: assetValue.getBaseValue(\"number\"),\n });\n\n //2. add output memo to targets (optional)\n if (compiledMemo) {\n targetOutputs.push({ script: compiledMemo, value: 0 });\n }\n\n const { inputs, outputs } = accumulative({\n inputs: utxos,\n outputs: targetOutputs,\n feeRate: feeRateWhole,\n chain,\n });\n\n // .inputs and .outputs will be undefined if no solution was found\n if (!(inputs && outputs))\n throw new SwapKitError(\"toolbox_utxo_insufficient_balance\", { sender, assetValue });\n const getNetwork = await getUtxoNetwork();\n const psbt = new Psbt({ network: getNetwork(chain) }); // Network-specific\n\n for (const { hash, index, witnessUtxo } of inputs) {\n psbt.addInput({ hash, index, witnessUtxo });\n }\n\n // Outputs\n for (const output of outputs) {\n const address =\n \"address\" in output && output.address ? output.address : toLegacyAddress(sender);\n const params = output.script\n ? compiledMemo\n ? { script: compiledMemo, value: 0 }\n : undefined\n : { address, value: output.value };\n\n if (params) {\n psbt.addOutput(params);\n }\n }\n\n return { psbt, utxos, inputs: inputs as UTXOType[] };\n}\n\nfunction getAddressFromKeys(keys: { getAddress: (index?: number) => string }) {\n const address = keys.getAddress(0);\n return stripToCashAddress(address);\n}\n",
7
+ "import {\n Chain,\n RequestClient,\n SKConfig,\n SwapKitError,\n type UTXOChain,\n warnOnce,\n} from \"@swapkit/helpers\";\nimport { networks } from \"bitcoinjs-lib\";\nimport { uniqid } from \"../../utils\";\n\n// @ts-ignore\nimport coininfo from \"coininfo\";\n\ntype BlockchairParams<T> = T & { chain: Chain; apiKey?: string };\ntype BlockchairFetchUnspentUtxoParams = BlockchairParams<{\n offset?: number;\n limit?: number;\n address: string;\n}>;\n\nasync function broadcastUTXOTx({ chain, txHash }: { chain: Chain; txHash: string }) {\n const rpcUrl = SKConfig.get(\"rpcUrls\")[chain];\n const body = JSON.stringify({\n jsonrpc: \"2.0\",\n method: \"sendrawtransaction\",\n params: [txHash],\n id: uniqid(),\n });\n\n const response = await RequestClient.post<{\n id: string;\n result: string;\n error: { message: string; code?: number } | null;\n }>(rpcUrl, { headers: { \"Content-Type\": \"application/json\" }, body });\n\n if (response.error) {\n throw new SwapKitError(\"toolbox_utxo_broadcast_failed\", { error: response.error?.message });\n }\n\n if (response.result.includes('\"code\":-26')) {\n throw new SwapKitError(\"toolbox_utxo_invalid_transaction\", {\n error: \"Transaction amount was too low\",\n });\n }\n\n return response.result;\n}\n\nfunction baseUrl(chain: Chain) {\n return `https://api.blockchair.com/${mapChainToBlockchairChain(chain)}`;\n}\n\nfunction getDefaultTxFeeByChain(chain: Chain) {\n switch (chain) {\n case Chain.Bitcoin:\n return 5;\n case Chain.Dogecoin:\n return 10000;\n case Chain.Litecoin:\n return 1;\n default:\n return 2;\n }\n}\n\nfunction mapChainToBlockchairChain(chain: Chain) {\n switch (chain) {\n case Chain.BitcoinCash:\n return \"bitcoin-cash\";\n case Chain.Litecoin:\n return \"litecoin\";\n case Chain.Dash:\n return \"dash\";\n case Chain.Dogecoin:\n return \"dogecoin\";\n case Chain.Polkadot:\n return \"polkadot\";\n default:\n return \"bitcoin\";\n }\n}\n\nasync function getSuggestedTxFee(chain: Chain) {\n try {\n //Use Bitgo API for fee estimation\n //Refer: https://app.bitgo.com/docs/#operation/v2.tx.getfeeestimate\n const { feePerKb } = await RequestClient.get<{\n feePerKb: number;\n cpfpFeePerKb: number;\n numBlocks: number;\n feeByBlockTarget: { 1: number; 3: number };\n }>(`https://app.bitgo.com/api/v2/${chain.toLowerCase()}/tx/fee`);\n const suggestedFee = feePerKb / 1000;\n\n return Math.max(suggestedFee, getDefaultTxFeeByChain(chain));\n } catch (_error) {\n return getDefaultTxFeeByChain(chain);\n }\n}\n\nasync function blockchairRequest<T>(url: string, apiKey?: string): Promise<T> {\n try {\n const response = await RequestClient.get<BlockchairResponse<T>>(url);\n if (!response || response.context.code !== 200)\n throw new SwapKitError(\"toolbox_utxo_api_error\", { error: `Failed to query ${url}` });\n\n return response.data as T;\n } catch (error) {\n if (!apiKey) throw error;\n const response = await RequestClient.get<BlockchairResponse<T>>(\n `${url}${apiKey ? `&key=${apiKey}` : \"\"}`,\n );\n\n if (!response || response.context.code !== 200)\n throw new SwapKitError(\"toolbox_utxo_api_error\", { error: `Failed to query ${url}` });\n\n return response.data as T;\n }\n}\n\nasync function getAddressData({ address, chain, apiKey }: BlockchairParams<{ address?: string }>) {\n if (!address)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"Address is required\" });\n\n try {\n const response = await blockchairRequest<BlockchairAddressResponse>(\n `${baseUrl(chain)}/dashboards/address/${address}?transaction_details=true`,\n apiKey,\n );\n\n return response[address];\n } catch (_error) {\n return { utxo: [], address: { balance: 0, transaction_count: 0 } };\n }\n}\n\nasync function getUnconfirmedBalance({\n address,\n chain,\n apiKey,\n}: BlockchairParams<{ address?: string }>) {\n const response = await getAddressData({ address, chain, apiKey });\n\n return response?.address.balance || 0;\n}\n\nasync function getRawTx({ chain, apiKey, txHash }: BlockchairParams<{ txHash?: string }>) {\n if (!txHash)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"TxHash is required\" });\n\n try {\n const rawTxResponse = await blockchairRequest<BlockchairRawTransactionResponse>(\n `${baseUrl(chain)}/raw/transaction/${txHash}`,\n apiKey,\n );\n return rawTxResponse?.[txHash]?.raw_transaction || \"\";\n } catch (error) {\n console.error(\"Failed to fetch raw transaction:\", error);\n return \"\";\n }\n}\n\nasync function fetchUnspentUtxoBatch({\n chain,\n address,\n apiKey,\n offset = 0,\n limit = 100,\n}: BlockchairFetchUnspentUtxoParams) {\n const response = await blockchairRequest<BlockchairOutputsResponse[]>(\n `${baseUrl(chain)}/outputs?q=is_spent(false),recipient(${address})&limit=${limit}&offset=${offset}`,\n apiKey,\n );\n\n const txs = response\n .filter(({ is_spent }) => !is_spent)\n .map(({ script_hex, block_id, transaction_hash, index, value, spending_signature_hex }) => ({\n hash: transaction_hash,\n index,\n value,\n txHex: spending_signature_hex,\n script_hex,\n is_confirmed: block_id !== -1,\n }));\n\n return txs;\n}\n\nasync function getUnspentUtxos({\n chain,\n address,\n apiKey,\n offset = 0,\n limit = 100,\n}: BlockchairFetchUnspentUtxoParams): Promise<Awaited<ReturnType<typeof fetchUnspentUtxoBatch>>> {\n if (!address)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"Address is required\" });\n\n try {\n const txs = await fetchUnspentUtxoBatch({ chain, address, apiKey, offset, limit });\n\n if (txs.length <= limit) return txs;\n\n const nextBatch = await getUnspentUtxos({\n chain,\n address,\n apiKey,\n offset: offset + limit,\n limit,\n });\n\n return [...txs, ...nextBatch];\n } catch (error) {\n console.error(\"Failed to fetch unspent UTXOs:\", error);\n return [];\n }\n}\n\nasync function scanUTXOs({\n address,\n chain,\n apiKey,\n fetchTxHex = true,\n}: BlockchairParams<{ address: string; fetchTxHex?: boolean }>) {\n const utxos = await getUnspentUtxos({ chain, address, apiKey });\n const results = [];\n\n for (const { hash, index, script_hex, value } of utxos) {\n let txHex: string | undefined;\n if (fetchTxHex) {\n txHex = await getRawTx({ txHash: hash, chain, apiKey });\n }\n results.push({\n address,\n hash,\n index,\n txHex,\n value,\n witnessUtxo: { value, script: Buffer.from(script_hex, \"hex\") },\n });\n }\n return results;\n}\n\nfunction utxoApi(chain: UTXOChain) {\n const apiKey = SKConfig.get(\"apiKeys\").blockchair || \"\";\n\n warnOnce(!apiKey, \"No Blockchair API key found. Functionality will be limited.\");\n\n return {\n broadcastTx: (txHash: string) => broadcastUTXOTx({ txHash, chain }),\n getRawTx: (txHash: string) => getRawTx({ txHash, chain, apiKey }),\n getSuggestedTxFee: () => getSuggestedTxFee(chain),\n getBalance: (address: string) => getUnconfirmedBalance({ address, chain, apiKey }),\n getAddressData: (address: string) => getAddressData({ address, chain, apiKey }),\n scanUTXOs: (params: { address: string; fetchTxHex?: boolean }) =>\n scanUTXOs({ ...params, chain, apiKey }),\n };\n}\n\n/**\n * \"Factory\" to ensure typing for custom UTXO APIs\n */\nexport function createCustomUtxoApi(methods: ReturnType<typeof utxoApi>) {\n return methods;\n}\n\nexport function getUtxoApi(chain: UTXOChain) {\n const customUtxoApi = SKConfig.get(\"apis\")[chain];\n\n if (customUtxoApi) {\n warnOnce(true, \"Using custom UTXO API. Be sure to implement all methods to avoid issues.\");\n return customUtxoApi as ReturnType<typeof utxoApi>;\n }\n\n return utxoApi(chain);\n}\n\nexport function getUtxoNetwork() {\n return function getNetwork(chain: Chain) {\n switch (chain) {\n case Chain.Bitcoin:\n return networks.bitcoin;\n case Chain.BitcoinCash:\n return coininfo.bitcoincash.main.toBitcoinJS();\n case Chain.Dash:\n return coininfo.dash.main.toBitcoinJS();\n case Chain.Litecoin:\n return coininfo.litecoin.main.toBitcoinJS();\n\n case Chain.Dogecoin: {\n const bip32 = { private: 0x04358394, public: 0x043587cf };\n const test = coininfo.dogecoin.test;\n test.versions.bip32 = bip32;\n return coininfo.dogecoin.main.toBitcoinJS();\n }\n default:\n throw new SwapKitError(\"toolbox_utxo_not_supported\", { chain });\n }\n };\n}\n\ninterface BlockchairVin {\n txid: string;\n vout: number;\n scriptSig: {\n asm: string;\n hex: string;\n };\n sequence: number;\n}\n\ninterface BlockchairVout {\n value: number;\n n: number;\n scriptPubKey: {\n asm: string;\n hex: string;\n address: string;\n type: string;\n addresses: string[];\n reqSigs: number;\n };\n}\n\ninterface BlockchairTransaction {\n block_id: number;\n hash: string;\n time: string;\n balance_change: number;\n}\n\ninterface BlockchairUtxo {\n block_id: number;\n transaction_hash: string;\n index: number;\n value: number;\n}\n\ninterface BlockchairAddressCoreData {\n type: string;\n script_hex: string;\n balance: number;\n balance_usd: number;\n received: number;\n received_usd: number;\n spent: number;\n spent_usd: number;\n output_count: number;\n unspent_output_count: number;\n first_seen_receiving: string;\n last_seen_receiving: string;\n first_seen_spending: null | string;\n last_seen_spending: null | string;\n transaction_count: number;\n scripthash_type: null | string;\n}\n\ninterface BlockchairInputOutputCommonData {\n block_id: number;\n transaction_id: number;\n index: number;\n transaction_hash: string;\n date: string;\n time: string;\n value: number;\n value_usd: number;\n recipient: string;\n type: string;\n script_hex: string;\n is_from_coinbase: boolean;\n is_spendable: boolean | null;\n is_spent: boolean;\n lifespan: number | null;\n cdd: number | null;\n}\n\ninterface BlockchairSpendingBlockData {\n spending_block_id: number | null;\n spending_transaction_id: number | null;\n spending_index: number | null;\n spending_transaction_hash: string | null;\n spending_date: string | null;\n spending_time: string | null;\n spending_value_usd: number | null;\n spending_sequence: number | null;\n spending_signature_hex: string | null;\n spending_witness: string | null;\n}\n\ninterface BlockchairAddressResponse {\n [key: string]: {\n address: BlockchairAddressCoreData;\n transactions: BlockchairTransaction[];\n utxo: BlockchairUtxo[];\n };\n}\n\ninterface BlockchairOutputsResponse\n extends BlockchairSpendingBlockData,\n BlockchairInputOutputCommonData {}\n\ninterface BlockchairRawTransactionResponse {\n [key: string]: {\n raw_transaction: string;\n decoded_raw_transaction: {\n txid: string;\n hash: string;\n version: number;\n size: number;\n vsize: number;\n weight: number;\n locktime: number;\n vin: BlockchairVin[];\n vout: BlockchairVout[];\n };\n };\n}\n\ninterface BlockchairResponse<T> {\n data: T;\n context: {\n code: number;\n source: string;\n results: number;\n state: number;\n market_price_usd: number;\n cache: {\n live: boolean;\n duration: number;\n since: string;\n until: string;\n time: any;\n };\n api: {\n version: string;\n last_major_update: string;\n next_major_update: null | string;\n documentation: string;\n notice: string;\n };\n servers: string;\n time: number;\n render_time: number;\n full_time: number;\n request_cost: number;\n };\n}\n",
8
+ "import { SwapKitError } from \"@swapkit/helpers\";\nimport base58check from \"bs58check\";\n// @ts-ignore\nimport cashaddr from \"cashaddrjs\";\n\nenum Format {\n Legacy = \"legacy\",\n Bitpay = \"bitpay\",\n Cashaddr = \"cashaddr\",\n}\nenum UtxoNetwork {\n Mainnet = \"mainnet\",\n Testnet = \"testnet\",\n}\nenum Type {\n P2PKH = \"p2pkh\",\n P2SH = \"p2sh\",\n}\n\nconst VERSION_BYTE = {\n [Format.Legacy]: {\n [UtxoNetwork.Mainnet]: {\n [Type.P2PKH]: 0,\n [Type.P2SH]: 5,\n },\n [UtxoNetwork.Testnet]: {\n [Type.P2PKH]: 111,\n [Type.P2SH]: 196,\n },\n },\n [Format.Bitpay]: {\n [UtxoNetwork.Mainnet]: {\n [Type.P2PKH]: 28,\n [Type.P2SH]: 40,\n },\n [UtxoNetwork.Testnet]: {\n [Type.P2PKH]: 111,\n [Type.P2SH]: 196,\n },\n },\n};\n\ntype DecodedType = {\n format: Format;\n network: UtxoNetwork;\n type: Type;\n hash: any;\n};\n\nfunction isValidAddress(input: any) {\n try {\n decodeAddress(input);\n return true;\n } catch (_error) {\n return false;\n }\n}\n\nfunction detectAddressNetwork(address: string) {\n return decodeAddress(address)?.network;\n}\n\nfunction toLegacyAddress(address: string): string {\n const decoded = decodeAddress(address);\n if (decoded?.format === Format.Legacy) {\n return address;\n }\n return encodeAsLegacy(decoded);\n}\n\nfunction toCashAddress(address: string): string {\n const decoded = decodeAddress(address);\n return encodeAsCashaddr(decoded);\n}\n\nfunction decodeAddress(address: string) {\n try {\n return decodeBase58Address(address);\n } catch (_error) {\n // Try to decode as cashaddr if base58 decoding fails.\n }\n try {\n return decodeCashAddress(address);\n } catch (_error) {\n // Try to decode as bitpay if cashaddr decoding fails.\n }\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n}\n\nfunction decodeBase58Address(address: string) {\n try {\n const payload = base58check.decode(address);\n\n // BASE_58_CHECK_PAYLOAD_LENGTH\n if (payload.length !== 21) throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n const versionByte = payload[0];\n const hash = Array.prototype.slice.call(payload, 1);\n\n switch (versionByte) {\n case VERSION_BYTE[Format.Legacy][UtxoNetwork.Mainnet][Type.P2PKH]:\n return { hash, format: Format.Legacy, network: UtxoNetwork.Mainnet, type: Type.P2PKH };\n\n case VERSION_BYTE[Format.Legacy][UtxoNetwork.Mainnet][Type.P2SH]:\n return { hash, format: Format.Legacy, network: UtxoNetwork.Mainnet, type: Type.P2SH };\n\n case VERSION_BYTE[Format.Legacy][UtxoNetwork.Testnet][Type.P2PKH]:\n return { hash, format: Format.Legacy, network: UtxoNetwork.Testnet, type: Type.P2PKH };\n\n case VERSION_BYTE[Format.Legacy][UtxoNetwork.Testnet][Type.P2SH]:\n return { hash, format: Format.Legacy, network: UtxoNetwork.Testnet, type: Type.P2SH };\n\n case VERSION_BYTE[Format.Bitpay][UtxoNetwork.Mainnet][Type.P2PKH]:\n return { hash, format: Format.Bitpay, network: UtxoNetwork.Mainnet, type: Type.P2PKH };\n\n case VERSION_BYTE[Format.Bitpay][UtxoNetwork.Mainnet][Type.P2SH]:\n return { hash, format: Format.Bitpay, network: UtxoNetwork.Mainnet, type: Type.P2SH };\n\n default:\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n }\n } catch (_error) {\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n }\n}\n\nfunction decodeCashAddress(address: string) {\n if (address.indexOf(\":\") !== -1) {\n try {\n return decodeCashAddressWithPrefix(address);\n } catch (_error) {\n // Try to decode as legacy if cashaddr decoding fails.\n }\n } else {\n const prefixes = [\"bitcoincash\", \"bchtest\", \"bchreg\"];\n for (const prefix of prefixes) {\n try {\n return decodeCashAddressWithPrefix(`${prefix}:${address}`);\n } catch (_error) {\n // Try next prefix if decoding fails.\n }\n }\n }\n\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n}\n\nfunction decodeCashAddressWithPrefix(address: string): DecodedType {\n try {\n const { hash, prefix, type } = cashaddr.decode(address);\n\n return {\n format: Format.Cashaddr,\n hash: Array.prototype.slice.call(hash, 0),\n network: prefix === \"bitcoincash\" ? UtxoNetwork.Mainnet : UtxoNetwork.Testnet,\n type: type === \"P2PKH\" ? Type.P2PKH : Type.P2SH,\n };\n } catch (_error) {\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n }\n}\n\nfunction encodeAsLegacy(decoded: DecodedType) {\n const versionByte = VERSION_BYTE[Format.Legacy][decoded.network][decoded.type];\n const buffer = Buffer.alloc(1 + decoded.hash.length);\n buffer[0] = versionByte;\n buffer.set(decoded.hash, 1);\n return base58check.encode(buffer);\n}\n\nfunction encodeAsCashaddr(decoded: DecodedType) {\n const prefix = decoded.network === UtxoNetwork.Mainnet ? \"bitcoincash\" : \"bchtest\";\n const type = decoded.type === Type.P2PKH ? \"P2PKH\" : \"P2SH\";\n const hash = new Uint8Array(decoded.hash);\n return cashaddr.encode(prefix, type, hash);\n}\n\nexport { detectAddressNetwork, isValidAddress, UtxoNetwork, toCashAddress, toLegacyAddress };\n",
9
+ "import { Chain, SwapKitError, type UTXOChain } from \"@swapkit/helpers\";\n\nimport {\n TX_OVERHEAD,\n UTXOScriptType,\n calculateTxSize,\n getInputSize,\n getOutputSize,\n getScriptTypeForAddress,\n} from \"../helpers\";\nimport type { TargetOutput, UTXOCalculateTxSizeParams, UTXOType } from \"../types\";\n\nexport const getDustThreshold = (chain: UTXOChain) => {\n switch (chain) {\n case Chain.Bitcoin:\n case Chain.BitcoinCash:\n return 550;\n case Chain.Dash:\n case Chain.Litecoin:\n return 5500;\n case Chain.Dogecoin:\n return 100000;\n default:\n throw new SwapKitError(\"toolbox_utxo_not_supported\", { chain });\n }\n};\n\nexport const accumulative = ({\n inputs,\n outputs,\n feeRate: initialFeeRate = 1,\n chain = Chain.Bitcoin,\n}: UTXOCalculateTxSizeParams & { outputs: TargetOutput[]; chain: UTXOChain }) => {\n const feeRate = Math.ceil(initialFeeRate);\n\n const newTxType =\n inputs[0] && \"address\" in inputs[0] && inputs[0].address\n ? getScriptTypeForAddress(inputs[0].address)\n : UTXOScriptType.P2PKH;\n // skip input if adding it would cost more than input is worth\n const filteredInputs = inputs.filter((input) => getInputSize(input) * feeRate <= input.value);\n\n const txSizeWithoutInputs =\n TX_OVERHEAD + outputs.reduce((total, output) => total + getOutputSize(output, newTxType), 0);\n\n const amountToSend = outputs.reduce((total, output) => total + output.value, 0);\n\n let fees = txSizeWithoutInputs * feeRate;\n let inputsValue = 0;\n const inputsToUse: typeof inputs = [];\n\n for (const input of filteredInputs) {\n const inputSize = getInputSize(input);\n const inputFee = feeRate * inputSize;\n\n fees += inputFee;\n inputsValue += input.value;\n\n inputsToUse.push(input);\n\n const totalCost = fees + amountToSend;\n\n // we need more inputs\n if (inputsValue < totalCost) continue;\n\n const remainder = inputsValue - totalCost;\n\n const feeForExtraOutput = feeRate * getOutputSize({ address: \"\", value: 0 }, newTxType);\n\n // potential change address\n if (remainder > feeForExtraOutput) {\n const feeAfterExtraOutput = feeForExtraOutput + fees;\n const remainderAfterExtraOutput = inputsValue - (amountToSend + feeAfterExtraOutput);\n\n // is it worth a change output aka can we send it in the future?\n if (\n remainderAfterExtraOutput >\n Math.max(getInputSize({} as UTXOType) * feeRate, getDustThreshold(chain))\n ) {\n return {\n inputs: inputsToUse,\n outputs: outputs.concat({ value: remainderAfterExtraOutput, address: \"\" }),\n fee: feeAfterExtraOutput,\n };\n }\n }\n return {\n inputs: inputsToUse,\n outputs,\n fee: fees,\n };\n }\n\n // We don't have enough inputs, let's calculate transaction fee accrude to the last input\n return { fee: feeRate * calculateTxSize({ inputs, outputs, feeRate }) };\n};\n",
10
+ "import { SwapKitError } from \"@swapkit/helpers\";\nimport { opcodes, script } from \"bitcoinjs-lib\";\nimport type {\n TargetOutput,\n UTXOCalculateTxSizeParams,\n UTXOInputWithScriptType,\n UTXOType,\n} from \"../types\";\n\n/**\n * Minimum transaction fee\n * 1000 satoshi/kB (similar to current `minrelaytxfee`)\n * @see https://github.com/bitcoin/bitcoin/blob/db88db47278d2e7208c50d16ab10cb355067d071/src/validation.h#L56\n */\nexport const MIN_TX_FEE = 1000;\nexport const TX_OVERHEAD = 4 + 1 + 1 + 4; //10\nexport const OP_RETURN_OVERHEAD = 1 + 8 + 1; //10\nconst TX_INPUT_BASE = 32 + 4 + 1 + 4; // 41\nconst TX_INPUT_PUBKEYHASH = 107;\n\nexport function compileMemo(memo: string) {\n const data = Buffer.from(memo, \"utf8\"); // converts MEMO to buffer\n return script.compile([opcodes.OP_RETURN as number, data]); // Compile OP_RETURN script\n}\n\nexport enum UTXOScriptType {\n P2PKH = \"P2PKH\", // legacy\n // P2SH = 'P2SH', // multisig\n P2WPKH = \"P2WPKH\", // bech32 - native segwit\n // P2TR = \"P2TR\", // taproot\n}\n\nexport const InputSizes: Record<UTXOScriptType, number> = {\n [UTXOScriptType.P2PKH]: 148,\n // [UTXOScriptType.P2SH]: 91,\n [UTXOScriptType.P2WPKH]: 68,\n};\n\nexport const OutputSizes: Record<UTXOScriptType, number> = {\n [UTXOScriptType.P2PKH]: 34,\n // [UTXOScriptType.P2SH]: 91,\n [UTXOScriptType.P2WPKH]: 31,\n};\n\nexport const getScriptTypeForAddress = (address: string) => {\n if (address.startsWith(\"bc1\") || address.startsWith(\"ltc1\")) {\n return UTXOScriptType.P2WPKH;\n }\n // if (address.startsWith('3') || address.startsWith('M')) {\n // return UTXOScriptType.P2SH;\n // }\n if (\n address.startsWith(\"1\") ||\n address.startsWith(\"3\") ||\n address.startsWith(\"L\") ||\n address.startsWith(\"M\") ||\n address.startsWith(\"X\") ||\n address.startsWith(\"D\") ||\n address.startsWith(\"bitcoincash:q\") ||\n address.startsWith(\"q\")\n ) {\n return UTXOScriptType.P2PKH;\n }\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n};\n\nexport const calculateTxSize = ({ inputs, outputs, feeRate }: UTXOCalculateTxSizeParams) => {\n const newTxType =\n inputs[0] && \"address\" in inputs[0] && inputs[0].address\n ? getScriptTypeForAddress(inputs[0].address)\n : UTXOScriptType.P2PKH;\n const inputSize = inputs\n .filter(\n (utxo) =>\n utxo.value >=\n InputSizes[\"type\" in utxo ? utxo.type : UTXOScriptType.P2PKH] * Math.ceil(feeRate),\n )\n .reduce((total, utxo) => total + getInputSize(utxo), 0);\n\n const outputSize =\n outputs?.reduce((total, output) => total + getOutputSize(output), 0) || OutputSizes[newTxType];\n\n return TX_OVERHEAD + inputSize + outputSize;\n};\n\nexport const getInputSize = (input: UTXOInputWithScriptType | UTXOType) => {\n if (\"type\" in input) {\n return InputSizes[input.type];\n }\n if (\"address\" in input && input.address) {\n return InputSizes[getScriptTypeForAddress(input.address as string)];\n }\n return TX_INPUT_BASE + TX_INPUT_PUBKEYHASH;\n};\n\nexport const getOutputSize = (output: TargetOutput, scriptType?: UTXOScriptType) => {\n if (output?.script) {\n return OP_RETURN_OVERHEAD + output.script.length + (output.script.length >= 74 ? 2 : 1);\n }\n if (scriptType) {\n return OutputSizes[scriptType];\n }\n return OutputSizes[UTXOScriptType.P2PKH];\n};\n",
11
+ "import {\n AssetValue,\n Chain,\n type ChainSigner,\n DerivationPath,\n type DerivationPathArray,\n FeeOption,\n NetworkDerivationPath,\n SwapKitError,\n SwapKitNumber,\n type UTXOChain,\n applyFeeMultiplier,\n derivationPathToString,\n updateDerivationPath,\n} from \"@swapkit/helpers\";\nimport { Psbt, address as btcLibAddress, initEccLib, payments } from \"bitcoinjs-lib\";\nimport type { ECPairInterface } from \"ecpair\";\nimport ECPairFactory from \"ecpair\";\nimport type { UtxoToolboxParams } from \".\";\nimport { getBalance } from \"../../utils\";\nimport {\n UTXOScriptType,\n accumulative,\n calculateTxSize,\n compileMemo,\n getDustThreshold,\n getInputSize,\n getUtxoApi,\n getUtxoNetwork,\n} from \"../helpers\";\nimport type {\n BchECPair,\n TargetOutput,\n UTXOBuildTxParams,\n UTXOTransferParams,\n UTXOType,\n} from \"../types\";\nimport { bchValidateAddress } from \"./bitcoinCash\";\n\nimport secp256k1 from \"@bitcoinerlab/secp256k1\";\n// @ts-ignore\nimport { ECPair, HDNode } from \"@psf/bitcoincashjs-lib\";\nimport { HDKey } from \"@scure/bip32\";\nimport { mnemonicToSeedSync } from \"@scure/bip39\";\n\nexport const nonSegwitChains = [Chain.Dash, Chain.Dogecoin];\n\nfunction addInputsAndOutputs({\n inputs,\n outputs,\n chain,\n psbt,\n sender,\n compiledMemo,\n}: {\n inputs: UTXOType[];\n outputs: TargetOutput[];\n chain: UTXOChain;\n psbt: Psbt;\n sender: string;\n compiledMemo: Buffer<ArrayBufferLike> | null;\n}) {\n for (const utxo of inputs) {\n const witnessInfo = !!utxo.witnessUtxo &&\n !nonSegwitChains.includes(chain) && { witnessUtxo: utxo.witnessUtxo };\n\n const nonWitnessInfo = nonSegwitChains.includes(chain) && {\n nonWitnessUtxo: utxo.txHex ? Buffer.from(utxo.txHex, \"hex\") : undefined,\n };\n\n psbt.addInput({ hash: utxo.hash, index: utxo.index, ...witnessInfo, ...nonWitnessInfo });\n }\n\n for (const output of outputs) {\n const address = \"address\" in output && output.address ? output.address : sender;\n const hasOutputScript = output.script;\n\n if (hasOutputScript && !compiledMemo) {\n continue;\n }\n\n const mappedOutput = hasOutputScript\n ? {\n script: compiledMemo as Buffer<ArrayBufferLike>,\n value: 0,\n }\n : {\n address,\n value: output.value,\n };\n\n initEccLib(secp256k1);\n psbt.addOutput(mappedOutput);\n }\n\n return { psbt, inputs };\n}\n\nasync function createTransaction({\n assetValue,\n recipient,\n memo,\n feeRate,\n sender,\n fetchTxHex = false,\n}: UTXOBuildTxParams): Promise<{\n psbt: Psbt;\n utxos: UTXOType[];\n inputs: UTXOType[];\n}> {\n const chain = assetValue.chain as UTXOChain;\n const compiledMemo = memo ? await compileMemo(memo) : null;\n\n const inputsAndOutputs = await getInputsAndTargetOutputs({\n assetValue,\n recipient,\n memo,\n sender,\n fetchTxHex,\n });\n\n const { inputs, outputs } = accumulative({ ...inputsAndOutputs, feeRate, chain });\n\n // .inputs and .outputs will be undefined if no solution was found\n if (!(inputs && outputs))\n throw new SwapKitError(\"toolbox_utxo_insufficient_balance\", { sender, assetValue });\n const getNetwork = await getUtxoNetwork();\n const psbt = new Psbt({ network: getNetwork(chain) });\n\n if (chain === Chain.Dogecoin) psbt.setMaximumFeeRate(650000000);\n\n const { psbt: mappedPsbt, inputs: mappedInputs } = await addInputsAndOutputs({\n inputs,\n outputs,\n chain,\n psbt,\n sender,\n compiledMemo,\n });\n\n return {\n psbt: mappedPsbt,\n utxos: inputsAndOutputs.inputs,\n inputs: mappedInputs,\n };\n}\n\nexport async function getUTXOAddressValidator() {\n const getNetwork = await getUtxoNetwork();\n\n return function validateAddress({ address, chain }: { address: string; chain: UTXOChain }) {\n if (chain === Chain.BitcoinCash) {\n return bchValidateAddress(address);\n }\n\n try {\n initEccLib(secp256k1);\n btcLibAddress.toOutputScript(address, getNetwork(chain));\n return true;\n } catch (_error) {\n return false;\n }\n };\n}\n\nasync function createSignerWithKeys({\n chain,\n phrase,\n derivationPath,\n}: { chain: UTXOChain; phrase: string; derivationPath: string }) {\n const keyPair = (await getCreateKeysForPath(chain as Chain.Bitcoin))({ phrase, derivationPath });\n\n async function signTransaction(psbt: Psbt) {\n await psbt.signAllInputs(keyPair);\n return psbt;\n }\n\n async function getAddress() {\n const addressGetter = await addressFromKeysGetter(chain);\n return addressGetter(keyPair);\n }\n\n return {\n getAddress,\n signTransaction,\n };\n}\n\nexport async function createUTXOToolbox<T extends UTXOChain>({\n chain,\n ...toolboxParams\n}: (\n | UtxoToolboxParams[T]\n | {\n phrase?: string;\n derivationPath?: DerivationPathArray;\n index?: number;\n }\n) & { chain: T }) {\n const phrase = \"phrase\" in toolboxParams ? toolboxParams.phrase : undefined;\n\n const index = \"index\" in toolboxParams ? toolboxParams.index || 0 : 0;\n\n const derivationPath = derivationPathToString(\n \"derivationPath\" in toolboxParams && toolboxParams.derivationPath\n ? toolboxParams.derivationPath\n : updateDerivationPath(NetworkDerivationPath[chain], { index }),\n );\n\n const signer = phrase\n ? await createSignerWithKeys({ chain, phrase, derivationPath })\n : \"signer\" in toolboxParams\n ? toolboxParams.signer\n : undefined;\n\n function getAddress() {\n return Promise.resolve(signer?.getAddress());\n }\n\n // const { signer } = params || {};\n const getAddressFromKeys = await addressFromKeysGetter(chain);\n const validateAddress = await getUTXOAddressValidator();\n const createKeysForPath = await getCreateKeysForPath(chain);\n\n return {\n accumulative,\n calculateTxSize,\n getAddressFromKeys,\n getAddress,\n validateAddress: (address: string) => validateAddress({ address, chain }),\n broadcastTx: (txHash: string) => getUtxoApi(chain).broadcastTx(txHash),\n createTransaction,\n createKeysForPath,\n getFeeRates: () => getFeeRates(chain),\n getInputsOutputsFee,\n transfer: transfer(signer as UtxoToolboxParams[\"BTC\"][\"signer\"]),\n getPrivateKeyFromMnemonic: (params: { phrase: string; derivationPath: string }) => {\n const keys = createKeysForPath(params);\n return keys.toWIF();\n },\n\n getBalance: getBalance(chain),\n estimateTransactionFee: estimateTransactionFee(chain),\n estimateMaxSendableAmount: estimateMaxSendableAmount(chain),\n };\n}\n\nasync function getInputsOutputsFee({\n assetValue,\n feeOptionKey = FeeOption.Fast,\n feeRate,\n memo,\n sender,\n recipient,\n}: Omit<UTXOBuildTxParams, \"feeRate\"> & {\n feeOptionKey?: FeeOption;\n feeRate?: number;\n}) {\n const chain = assetValue.chain as UTXOChain;\n\n const inputsAndOutputs = await getInputsAndTargetOutputs({\n assetValue,\n sender,\n memo,\n recipient,\n });\n\n const feeRateWhole = feeRate ? Math.floor(feeRate) : (await getFeeRates(chain))[feeOptionKey];\n\n return accumulative({ ...inputsAndOutputs, feeRate: feeRateWhole, chain });\n}\n\nfunction estimateMaxSendableAmount(chain: UTXOChain) {\n return async function estimateMaxSendableAmount({\n from,\n memo,\n feeRate,\n feeOptionKey = FeeOption.Fast,\n recipients = 1,\n }: {\n from: string;\n memo?: string;\n feeRate?: number;\n feeOptionKey?: FeeOption;\n recipients?: number | TargetOutput[];\n }) {\n const addressData = await getUtxoApi(chain).getAddressData(from);\n const feeRateWhole = feeRate ? Math.ceil(feeRate) : (await getFeeRates(chain))[feeOptionKey];\n\n const inputs = addressData?.utxo\n .map((utxo) => ({\n ...utxo,\n // type: utxo.witnessUtxo ? UTXOScriptType.P2WPKH : UTXOScriptType.P2PKH,\n type: UTXOScriptType.P2PKH,\n hash: \"\",\n }))\n .filter(\n (utxo) => utxo.value > Math.max(getDustThreshold(chain), getInputSize(utxo) * feeRateWhole),\n );\n\n if (!inputs?.length) return AssetValue.from({ chain });\n\n const balance = AssetValue.from({\n chain,\n value: inputs.reduce((sum, utxo) => sum + utxo.value, 0),\n });\n\n const outputs =\n typeof recipients === \"number\"\n ? (Array.from({ length: recipients }, () => ({\n address: from,\n value: 0,\n })) as TargetOutput[])\n : recipients;\n\n if (memo) {\n const script = await compileMemo(memo);\n outputs.push({ address: from, script, value: 0 });\n }\n\n const txSize = calculateTxSize({ inputs, outputs, feeRate: feeRateWhole });\n\n const fee = txSize * feeRateWhole;\n\n return balance.sub(fee);\n };\n}\n\nfunction estimateTransactionFee(chain: UTXOChain) {\n return async (params: {\n assetValue: AssetValue;\n recipient: string;\n sender: string;\n memo?: string;\n feeOptionKey?: FeeOption;\n feeRate?: number;\n fetchTxHex?: boolean;\n }) => {\n const inputFees = await getInputsOutputsFee(params);\n\n return AssetValue.from({\n chain,\n value: SwapKitNumber.fromBigInt(BigInt(inputFees.fee), 8).getValue(\"string\"),\n });\n };\n}\n\ntype CreateKeysForPathReturnType = {\n [Chain.BitcoinCash]: BchECPair;\n [Chain.Bitcoin]: ECPairInterface;\n [Chain.Dash]: ECPairInterface;\n [Chain.Dogecoin]: ECPairInterface;\n [Chain.Litecoin]: ECPairInterface;\n};\n\nexport async function getCreateKeysForPath<T extends keyof CreateKeysForPathReturnType>(\n chain: T,\n): Promise<\n (params: {\n wif?: string;\n phrase?: string;\n derivationPath?: string;\n }) => CreateKeysForPathReturnType[T]\n> {\n const getNetwork = await getUtxoNetwork();\n\n switch (chain) {\n case Chain.BitcoinCash: {\n return function createKeysForPath({\n phrase,\n derivationPath = `${DerivationPath.BCH}/0`,\n wif,\n }: { wif?: string; phrase?: string; derivationPath?: string }) {\n const network = getNetwork(chain);\n\n if (wif) {\n return ECPair.fromWIF(wif, network) as BchECPair;\n }\n if (!phrase)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"No phrase provided\" });\n\n const masterHDNode = HDNode.fromSeedBuffer(\n Buffer.from(mnemonicToSeedSync(phrase)),\n network,\n );\n const keyPair = masterHDNode.derivePath(derivationPath).keyPair;\n\n return keyPair as BchECPair;\n } as (params: {\n wif?: string;\n phrase?: string;\n derivationPath?: string;\n }) => CreateKeysForPathReturnType[T];\n }\n case Chain.Bitcoin:\n case Chain.Dogecoin:\n case Chain.Litecoin:\n case Chain.Dash: {\n return function createKeysForPath({\n phrase,\n wif,\n derivationPath,\n }: { phrase?: string; wif?: string; derivationPath: string }) {\n if (!(wif || phrase))\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", {\n error: \"Either phrase or wif must be provided\",\n });\n\n const factory = ECPairFactory(secp256k1);\n const network = getNetwork(chain);\n\n if (wif) return factory.fromWIF(wif, network);\n\n const seed = mnemonicToSeedSync(phrase as string);\n const master = HDKey.fromMasterSeed(seed, network).derive(derivationPath);\n if (!master.privateKey)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", {\n error: \"Could not get private key from phrase\",\n });\n\n return factory.fromPrivateKey(Buffer.from(master.privateKey), { network });\n } as (params: {\n wif?: string;\n phrase?: string;\n derivationPath?: string;\n }) => CreateKeysForPathReturnType[T];\n }\n default:\n throw new SwapKitError(\"toolbox_utxo_not_supported\", { chain });\n }\n}\n\nexport async function addressFromKeysGetter(chain: UTXOChain) {\n const getNetwork = await getUtxoNetwork();\n\n return function getAddressFromKeys(keys: ECPairInterface | BchECPair) {\n if (!keys)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"Keys must be provided\" });\n\n const method = nonSegwitChains.includes(chain) ? payments.p2pkh : payments.p2wpkh;\n const { address } = method({ pubkey: keys.publicKey as Buffer, network: getNetwork(chain) });\n if (!address)\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { error: \"Address not defined\" });\n\n return address;\n };\n}\n\nfunction transfer(signer?: ChainSigner<Psbt, Psbt>) {\n return async function transfer({\n memo,\n recipient,\n feeOptionKey,\n feeRate,\n assetValue,\n }: UTXOTransferParams) {\n const from = await signer?.getAddress();\n\n const chain = assetValue.chain as UTXOChain;\n\n if (!(signer && from)) throw new SwapKitError(\"toolbox_utxo_no_signer\");\n if (!recipient)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", {\n error: \"Recipient address must be provided\",\n });\n const txFeeRate = feeRate || (await getFeeRates(chain))[feeOptionKey || FeeOption.Fast];\n\n const { psbt } = await createTransaction({\n recipient,\n feeRate: txFeeRate,\n sender: from,\n assetValue,\n memo,\n });\n const signedPsbt = await signer.signTransaction(psbt);\n signedPsbt.finalizeAllInputs(); // Finalise inputs\n // TX extracted and formatted to hex\n return getUtxoApi(chain).broadcastTx(signedPsbt.extractTransaction().toHex());\n };\n}\n\nasync function getFeeRates(chain: UTXOChain) {\n const suggestedFeeRate = await getUtxoApi(chain).getSuggestedTxFee();\n\n return {\n [FeeOption.Average]: suggestedFeeRate,\n [FeeOption.Fast]: applyFeeMultiplier(suggestedFeeRate, FeeOption.Fast),\n [FeeOption.Fastest]: applyFeeMultiplier(suggestedFeeRate, FeeOption.Fastest),\n };\n}\n\nasync function getInputsAndTargetOutputs({\n assetValue,\n recipient,\n memo,\n sender,\n fetchTxHex: fetchTxOverwrite = false,\n}: Omit<UTXOBuildTxParams, \"feeRate\">) {\n const chain = assetValue.chain as UTXOChain;\n\n const fetchTxHex = fetchTxOverwrite || nonSegwitChains.includes(chain);\n\n const inputs = await getUtxoApi(chain).scanUTXOs({ address: sender, fetchTxHex });\n\n //1. add output amount and recipient to targets\n //2. add output memo to targets (optional)\n\n return {\n inputs,\n outputs: [\n { address: recipient, value: Number(assetValue.bigIntValue) },\n ...(memo ? [{ address: \"\", script: await compileMemo(memo), value: 0 }] : []),\n ],\n };\n}\n"
12
+ ],
13
+ "mappings": "6tBAMO,IANP,8BCKO,IALP,oCAMA,8BAUA,4BCTO,IAPP,8BAQA,4BAIqB,IAArB,yBASA,eAAe,EAAe,EAAG,QAAO,UAA4C,CAClF,IAAM,EAAS,WAAS,IAAI,SAAS,EAAE,GACjC,EAAO,KAAK,UAAU,CA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,OADgB,MAAM,GAAiB,CAA8C,OAIlF,QAAM,aACN,QAAM,cACN,QAAM,cACN,QAAM,KAKT,OAJgB,MAAM,EAAkB,CACtC,WACI,CACN,CAAC,UAKD,MAAM,IAAI,eAAa,6BAA8B,CAAE,OAAM,CAAC",
14
+ "debugId": "3121718C7D34F25A64756E2164756E21",
15
+ "names": []
16
+ }
@@ -0,0 +1,3 @@
1
+ import{b as WX,c as PX}from"../../chunk-12xtvbsp.js";import"../../chunk-s47y8512.js";import{Chain as x,SwapKitError as NG}from"@swapkit/helpers";import{Transaction as UG,TransactionBuilder as vG,address as MG}from"@psf/bitcoincashjs-lib";import{Chain as zG,FeeOption as TG,NetworkDerivationPath as CG,SwapKitError as R,derivationPathToString as HG,updateDerivationPath as YG}from"@swapkit/helpers";import{Psbt as IG}from"bitcoinjs-lib";import{Chain as T,RequestClient as m,SKConfig as i,SwapKitError as F,warnOnce as qX}from"@swapkit/helpers";import{networks as AX}from"bitcoinjs-lib";import f from"coininfo";async function KX({chain:X,txHash:G}){let J=i.get("rpcUrls")[X],Q=JSON.stringify({jsonrpc:"2.0",method:"sendrawtransaction",params:[G],id:WX()}),$=await m.post(J,{headers:{"Content-Type":"application/json"},body:Q});if($.error)throw new F("toolbox_utxo_broadcast_failed",{error:$.error?.message});if($.result.includes('"code":-26'))throw new F("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return $.result}function a(X){return`https://api.blockchair.com/${RX(X)}`}function LX(X){switch(X){case T.Bitcoin:return 5;case T.Dogecoin:return 1e4;case T.Litecoin:return 1;default:return 2}}function RX(X){switch(X){case T.BitcoinCash:return"bitcoin-cash";case T.Litecoin:return"litecoin";case T.Dash:return"dash";case T.Dogecoin:return"dogecoin";case T.Polkadot:return"polkadot";default:return"bitcoin"}}async function wX(X){try{let{feePerKb:G}=await m.get(`https://app.bitgo.com/api/v2/${X.toLowerCase()}/tx/fee`),J=G/1000;return Math.max(J,LX(X))}catch(G){return LX(X)}}async function s(X,G){try{let J=await m.get(X);if(!J||J.context.code!==200)throw new F("toolbox_utxo_api_error",{error:`Failed to query ${X}`});return J.data}catch(J){if(!G)throw J;let Q=await m.get(`${X}${G?`&key=${G}`:""}`);if(!Q||Q.context.code!==200)throw new F("toolbox_utxo_api_error",{error:`Failed to query ${X}`});return Q.data}}async function DX({address:X,chain:G,apiKey:J}){if(!X)throw new F("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await s(`${a(G)}/dashboards/address/${X}?transaction_details=true`,J))[X]}catch(Q){return{utxo:[],address:{balance:0,transaction_count:0}}}}async function fX({address:X,chain:G,apiKey:J}){return(await DX({address:X,chain:G,apiKey:J}))?.address.balance||0}async function BX({chain:X,apiKey:G,txHash:J}){if(!J)throw new F("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await s(`${a(X)}/raw/transaction/${J}`,G))?.[J]?.raw_transaction||""}catch(Q){return console.error("Failed to fetch raw transaction:",Q),""}}async function EX({chain:X,address:G,apiKey:J,offset:Q=0,limit:$=100}){return(await s(`${a(X)}/outputs?q=is_spent(false),recipient(${G})&limit=${$}&offset=${Q}`,J)).filter(({is_spent:W})=>!W).map(({script_hex:W,block_id:L,transaction_hash:q,index:D,value:U,spending_signature_hex:B})=>({hash:q,index:D,value:U,txHex:B,script_hex:W,is_confirmed:L!==-1}))}async function UX({chain:X,address:G,apiKey:J,offset:Q=0,limit:$=100}){if(!G)throw new F("toolbox_utxo_invalid_params",{error:"Address is required"});try{let j=await EX({chain:X,address:G,apiKey:J,offset:Q,limit:$});if(j.length<=$)return j;let Z=await UX({chain:X,address:G,apiKey:J,offset:Q+$,limit:$});return[...j,...Z]}catch(j){return console.error("Failed to fetch unspent UTXOs:",j),[]}}async function SX({address:X,chain:G,apiKey:J,fetchTxHex:Q=!0}){let $=await UX({chain:G,address:X,apiKey:J}),j=[];for(let{hash:Z,index:W,script_hex:L,value:q}of $){let D;if(Q)D=await BX({txHash:Z,chain:G,apiKey:J});j.push({address:X,hash:Z,index:W,txHex:D,value:q,witnessUtxo:{value:q,script:Buffer.from(L,"hex")}})}return j}function gX(X){let G=i.get("apiKeys").blockchair||"";return qX(!G,"No Blockchair API key found. Functionality will be limited."),{broadcastTx:(J)=>KX({txHash:J,chain:X}),getRawTx:(J)=>BX({txHash:J,chain:X,apiKey:G}),getSuggestedTxFee:()=>wX(X),getBalance:(J)=>fX({address:J,chain:X,apiKey:G}),getAddressData:(J)=>DX({address:J,chain:X,apiKey:G}),scanUTXOs:(J)=>SX({...J,chain:X,apiKey:G})}}function AG(X){return X}function Y(X){let G=i.get("apis")[X];if(G)return qX(!0,"Using custom UTXO API. Be sure to implement all methods to avoid issues."),G;return gX(X)}function I(){return function X(G){switch(G){case T.Bitcoin:return AX.bitcoin;case T.BitcoinCash:return f.bitcoincash.main.toBitcoinJS();case T.Dash:return f.dash.main.toBitcoinJS();case T.Litecoin:return f.litecoin.main.toBitcoinJS();case T.Dogecoin:{let J={private:70615956,public:70617039},Q=f.dogecoin.test;return Q.versions.bip32=J,f.dogecoin.main.toBitcoinJS()}default:throw new F("toolbox_utxo_not_supported",{chain:G})}}}import{SwapKitError as V}from"@swapkit/helpers";import MX from"bs58check";import zX from"cashaddrjs";var TX;((J)=>{J.Mainnet="mainnet";J.Testnet="testnet"})(TX||={});var v={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}};function CX(X){try{return h(X),!0}catch(G){return!1}}function HX(X){return h(X)?.network}function E(X){let G=h(X);if(G?.format==="legacy")return X;return lX(G)}function l(X){let G=h(X);return hX(G)}function h(X){try{return xX(X)}catch(G){}try{return mX(X)}catch(G){}throw new V("toolbox_utxo_invalid_address",{address:X})}function xX(X){try{let G=MX.decode(X);if(G.length!==21)throw new V("toolbox_utxo_invalid_address",{address:X});let J=G[0],Q=Array.prototype.slice.call(G,1);switch(J){case v.legacy.mainnet.p2pkh:return{hash:Q,format:"legacy",network:"mainnet",type:"p2pkh"};case v.legacy.mainnet.p2sh:return{hash:Q,format:"legacy",network:"mainnet",type:"p2sh"};case v.legacy.testnet.p2pkh:return{hash:Q,format:"legacy",network:"testnet",type:"p2pkh"};case v.legacy.testnet.p2sh:return{hash:Q,format:"legacy",network:"testnet",type:"p2sh"};case v.bitpay.mainnet.p2pkh:return{hash:Q,format:"bitpay",network:"mainnet",type:"p2pkh"};case v.bitpay.mainnet.p2sh:return{hash:Q,format:"bitpay",network:"mainnet",type:"p2sh"};default:throw new V("toolbox_utxo_invalid_address",{address:X})}}catch(G){throw new V("toolbox_utxo_invalid_address",{address:X})}}function mX(X){if(X.indexOf(":")!==-1)try{return vX(X)}catch(G){}else{let G=["bitcoincash","bchtest","bchreg"];for(let J of G)try{return vX(`${J}:${X}`)}catch(Q){}}throw new V("toolbox_utxo_invalid_address",{address:X})}function vX(X){try{let{hash:G,prefix:J,type:Q}=zX.decode(X);return{format:"cashaddr",hash:Array.prototype.slice.call(G,0),network:J==="bitcoincash"?"mainnet":"testnet",type:Q==="P2PKH"?"p2pkh":"p2sh"}}catch(G){throw new V("toolbox_utxo_invalid_address",{address:X})}}function lX(X){let G=v.legacy[X.network][X.type],J=Buffer.alloc(1+X.hash.length);return J[0]=G,J.set(X.hash,1),MX.encode(J)}function hX(X){let G=X.network==="mainnet"?"bitcoincash":"bchtest",J=X.type==="p2pkh"?"P2PKH":"P2SH",Q=new Uint8Array(X.hash);return zX.encode(G,J,Q)}import{Chain as A,SwapKitError as cX}from"@swapkit/helpers";var t=(X)=>{switch(X){case A.Bitcoin:case A.BitcoinCash:return 550;case A.Dash:case A.Litecoin:return 5500;case A.Dogecoin:return 1e5;default:throw new cX("toolbox_utxo_not_supported",{chain:X})}},k=({inputs:X,outputs:G,feeRate:J=1,chain:Q=A.Bitcoin})=>{let $=Math.ceil(J),j=X[0]&&"address"in X[0]&&X[0].address?u(X[0].address):"P2PKH",Z=X.filter((B)=>N(B)*$<=B.value),W=e+G.reduce((B,z)=>B+c(z,j),0),L=G.reduce((B,z)=>B+z.value,0),q=W*$,D=0,U=[];for(let B of Z){let z=N(B),M=$*z;q+=M,D+=B.value,U.push(B);let H=q+L;if(D<H)continue;let b=D-H,ZX=$*c({address:"",value:0},j);if(b>ZX){let $X=ZX+q,jX=D-(L+$X);if(jX>Math.max(N({})*$,t(Q)))return{inputs:U,outputs:G.concat({value:jX,address:""}),fee:$X}}return{inputs:U,outputs:G,fee:q}}return{fee:$*S({inputs:X,outputs:G,feeRate:$})}};import{SwapKitError as uX}from"@swapkit/helpers";import{opcodes as pX,script as oX}from"bitcoinjs-lib";var hG=1000,e=10,nX=10,rX=41,dX=107;function O(X){let G=Buffer.from(X,"utf8");return oX.compile([pX.OP_RETURN,G])}var XX;((J)=>{J.P2PKH="P2PKH";J.P2WPKH="P2WPKH"})(XX||={});var GX={["P2PKH"]:148,["P2WPKH"]:68},p={["P2PKH"]:34,["P2WPKH"]:31},u=(X)=>{if(X.startsWith("bc1")||X.startsWith("ltc1"))return"P2WPKH";if(X.startsWith("1")||X.startsWith("3")||X.startsWith("L")||X.startsWith("M")||X.startsWith("X")||X.startsWith("D")||X.startsWith("bitcoincash:q")||X.startsWith("q"))return"P2PKH";throw new uX("toolbox_utxo_invalid_address",{address:X})},S=({inputs:X,outputs:G,feeRate:J})=>{let Q=X[0]&&"address"in X[0]&&X[0].address?u(X[0].address):"P2PKH",$=X.filter((Z)=>Z.value>=GX["type"in Z?Z.type:"P2PKH"]*Math.ceil(J)).reduce((Z,W)=>Z+N(W),0),j=G?.reduce((Z,W)=>Z+c(W),0)||p[Q];return e+$+j},N=(X)=>{if("type"in X)return GX[X.type];if("address"in X&&X.address)return GX[u(X.address)];return rX+dX},c=(X,G)=>{if(X?.script)return nX+X.script.length+(X.script.length>=74?2:1);if(G)return p[G];return p.P2PKH};import{AssetValue as JX,Chain as _,DerivationPath as iX,FeeOption as y,NetworkDerivationPath as aX,SwapKitError as P,SwapKitNumber as sX,applyFeeMultiplier as YX,derivationPathToString as tX,updateDerivationPath as eX}from"@swapkit/helpers";import{Psbt as XG,address as GG,initEccLib as FX,payments as IX}from"bitcoinjs-lib";import JG from"ecpair";import QX from"@bitcoinerlab/secp256k1";import{ECPair as QG,HDNode as ZG}from"@psf/bitcoincashjs-lib";import{HDKey as $G}from"@scure/bip32";import{mnemonicToSeedSync as _X}from"@scure/bip39";var o=[_.Dash,_.Dogecoin];function jG({inputs:X,outputs:G,chain:J,psbt:Q,sender:$,compiledMemo:j}){for(let Z of X){let W=!!Z.witnessUtxo&&!o.includes(J)&&{witnessUtxo:Z.witnessUtxo},L=o.includes(J)&&{nonWitnessUtxo:Z.txHex?Buffer.from(Z.txHex,"hex"):void 0};Q.addInput({hash:Z.hash,index:Z.index,...W,...L})}for(let Z of G){let W="address"in Z&&Z.address?Z.address:$,L=Z.script;if(L&&!j)continue;let q=L?{script:j,value:0}:{address:W,value:Z.value};FX(QX),Q.addOutput(q)}return{psbt:Q,inputs:X}}async function yX({assetValue:X,recipient:G,memo:J,feeRate:Q,sender:$,fetchTxHex:j=!1}){let Z=X.chain,W=J?await O(J):null,L=await OX({assetValue:X,recipient:G,memo:J,sender:$,fetchTxHex:j}),{inputs:q,outputs:D}=k({...L,feeRate:Q,chain:Z});if(!(q&&D))throw new P("toolbox_utxo_insufficient_balance",{sender:$,assetValue:X});let U=await I(),B=new XG({network:U(Z)});if(Z===_.Dogecoin)B.setMaximumFeeRate(650000000);let{psbt:z,inputs:M}=await jG({inputs:q,outputs:D,chain:Z,psbt:B,sender:$,compiledMemo:W});return{psbt:z,utxos:L.inputs,inputs:M}}async function LG(){let X=await I();return function G({address:J,chain:Q}){if(Q===_.BitcoinCash)return K(J);try{return FX(QX),GG.toOutputScript(J,X(Q)),!0}catch($){return!1}}}async function WG({chain:X,phrase:G,derivationPath:J}){let Q=(await r(X))({phrase:G,derivationPath:J});async function $(Z){return await Z.signAllInputs(Q),Z}async function j(){return(await kX(X))(Q)}return{getAddress:j,signTransaction:$}}async function n({chain:X,...G}){let J="phrase"in G?G.phrase:void 0,Q="index"in G?G.index||0:0,$=tX("derivationPath"in G&&G.derivationPath?G.derivationPath:eX(aX[X],{index:Q})),j=J?await WG({chain:X,phrase:J,derivationPath:$}):("signer"in G)?G.signer:void 0;function Z(){return Promise.resolve(j?.getAddress())}let W=await kX(X),L=await LG(),q=await r(X);return{accumulative:k,calculateTxSize:S,getAddressFromKeys:W,getAddress:Z,validateAddress:(D)=>L({address:D,chain:X}),broadcastTx:(D)=>Y(X).broadcastTx(D),createTransaction:yX,createKeysForPath:q,getFeeRates:()=>d(X),getInputsOutputsFee:NX,transfer:BG(j),getPrivateKeyFromMnemonic:(D)=>{return q(D).toWIF()},getBalance:PX(X),estimateTransactionFee:DG(X),estimateMaxSendableAmount:qG(X)}}async function NX({assetValue:X,feeOptionKey:G=y.Fast,feeRate:J,memo:Q,sender:$,recipient:j}){let Z=X.chain,W=await OX({assetValue:X,sender:$,memo:Q,recipient:j}),L=J?Math.floor(J):(await d(Z))[G];return k({...W,feeRate:L,chain:Z})}function qG(X){return async function G({from:J,memo:Q,feeRate:$,feeOptionKey:j=y.Fast,recipients:Z=1}){let W=await Y(X).getAddressData(J),L=$?Math.ceil($):(await d(X))[j],q=W?.utxo.map((M)=>({...M,type:"P2PKH",hash:""})).filter((M)=>M.value>Math.max(t(X),N(M)*L));if(!q?.length)return JX.from({chain:X});let D=JX.from({chain:X,value:q.reduce((M,H)=>M+H.value,0)}),U=typeof Z==="number"?Array.from({length:Z},()=>({address:J,value:0})):Z;if(Q){let M=await O(Q);U.push({address:J,script:M,value:0})}let z=S({inputs:q,outputs:U,feeRate:L})*L;return D.sub(z)}}function DG(X){return async(G)=>{let J=await NX(G);return JX.from({chain:X,value:sX.fromBigInt(BigInt(J.fee),8).getValue("string")})}}async function r(X){let G=await I();switch(X){case _.BitcoinCash:return function J({phrase:Q,derivationPath:$=`${iX.BCH}/0`,wif:j}){let Z=G(X);if(j)return QG.fromWIF(j,Z);if(!Q)throw new P("toolbox_utxo_invalid_params",{error:"No phrase provided"});return ZG.fromSeedBuffer(Buffer.from(_X(Q)),Z).derivePath($).keyPair};case _.Bitcoin:case _.Dogecoin:case _.Litecoin:case _.Dash:return function J({phrase:Q,wif:$,derivationPath:j}){if(!($||Q))throw new P("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let Z=JG(QX),W=G(X);if($)return Z.fromWIF($,W);let L=_X(Q),q=$G.fromMasterSeed(L,W).derive(j);if(!q.privateKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not get private key from phrase"});return Z.fromPrivateKey(Buffer.from(q.privateKey),{network:W})};default:throw new P("toolbox_utxo_not_supported",{chain:X})}}async function kX(X){let G=await I();return function J(Q){if(!Q)throw new P("toolbox_utxo_invalid_params",{error:"Keys must be provided"});let $=o.includes(X)?IX.p2pkh:IX.p2wpkh,{address:j}=$({pubkey:Q.publicKey,network:G(X)});if(!j)throw new P("toolbox_utxo_invalid_address",{error:"Address not defined"});return j}}function BG(X){return async function G({memo:J,recipient:Q,feeOptionKey:$,feeRate:j,assetValue:Z}){let W=await X?.getAddress(),L=Z.chain;if(!(X&&W))throw new P("toolbox_utxo_no_signer");if(!Q)throw new P("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let q=j||(await d(L))[$||y.Fast],{psbt:D}=await yX({recipient:Q,feeRate:q,sender:W,assetValue:Z,memo:J}),U=await X.signTransaction(D);return U.finalizeAllInputs(),Y(L).broadcastTx(U.extractTransaction().toHex())}}async function d(X){let G=await Y(X).getSuggestedTxFee();return{[y.Average]:G,[y.Fast]:YX(G,y.Fast),[y.Fastest]:YX(G,y.Fastest)}}async function OX({assetValue:X,recipient:G,memo:J,sender:Q,fetchTxHex:$=!1}){let j=X.chain,Z=$||o.includes(j);return{inputs:await Y(j).scanUTXOs({address:Q,fetchTxHex:Z}),outputs:[{address:G,value:Number(X.bigIntValue)},...J?[{address:"",script:await O(J),value:0}]:[]]}}var C=zG.BitcoinCash;function g(X){return X.replace(/(bchtest:|bitcoincash:)/,"")}function K(X){let G=g(X);return CX(G)&&HX(G)==="mainnet"}function w(X){return g(l(X))}async function _G(X){async function G({builder:Q,utxos:$}){return $.forEach((j,Z)=>{Q.sign(Z,X,void 0,65,j.witnessUtxo?.value)}),Q.build()}return{getAddress:()=>{let Q=X.getAddress(0);return Promise.resolve(w(Q))},signTransaction:G}}async function bX(X){let G="phrase"in X?X.phrase:void 0,J="index"in X?X.index||0:0,Q=HG("derivationPath"in X&&X.derivationPath?X.derivationPath:YG(CG[C],{index:J})),$=(await r(C))({phrase:G,derivationPath:Q}),j=$?await _G($):("signer"in X)?X.signer:void 0;function Z(){return Promise.resolve(j?.getAddress())}let{getBalance:W,getFeeRates:L,broadcastTx:q,...D}=await n({chain:C});function U(B,z=!0){return W(g(l(B)))}return{...D,getAddress:Z,broadcastTx:q,createTransaction:VX,buildTx:FG,getAddressFromKeys:yG,getBalance:U,getFeeRates:L,stripPrefix:g,stripToCashAddress:w,validateAddress:K,transfer:PG({getFeeRates:L,broadcastTx:q,signer:j})}}async function VX({assetValue:X,recipient:G,memo:J,feeRate:Q,sender:$}){if(!K(G))throw new R("toolbox_utxo_invalid_address",{address:G});let j=await Y(C).scanUTXOs({address:w($),fetchTxHex:!0}),Z=J?await O(J):null,W=[];W.push({address:G,value:X.getBaseValue("number")});let{inputs:L,outputs:q}=k({inputs:j,outputs:W,feeRate:Q,chain:C});if(!(L&&q))throw new R("toolbox_utxo_insufficient_balance",{sender:$,assetValue:X});let D=await I(),U=new vG(D(C));await Promise.all(L.map(async(B)=>{let z=await Y(C).getRawTx(B.hash);U.addInput(UG.fromBuffer(Buffer.from(z,"hex")),B.index)}));for(let B of q){let z="address"in B&&B.address?B.address:E($),M=await I(),H=MG.toOutputScript(E(z),M(C));U.addOutput(H,B.value)}if(Z)U.addOutput(Z,0);return{builder:U,utxos:L}}function PG({broadcastTx:X,getFeeRates:G,signer:J}){return async function Q({recipient:$,assetValue:j,feeOptionKey:Z=TG.Fast,...W}){let L=await J?.getAddress();if(!(J&&L))throw new R("toolbox_utxo_no_signer");if(!$)throw new R("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let q=W.feeRate||(await G())[Z],{builder:D,utxos:U}=await VX({...W,assetValue:j,feeRate:q,recipient:$,sender:L}),z=(await J.signTransaction({builder:D,utxos:U})).toHex();return X(z)}}async function FG({assetValue:X,recipient:G,memo:J,feeRate:Q,sender:$}){let j=l(G);if(!K(j))throw new R("toolbox_utxo_invalid_address",{address:j});let Z=await Y(C).scanUTXOs({address:w($),fetchTxHex:!0}),W=Number(Q.toFixed(0)),L=J?await O(J):null,q=[];if(q.push({address:E(G),value:X.getBaseValue("number")}),L)q.push({script:L,value:0});let{inputs:D,outputs:U}=k({inputs:Z,outputs:q,feeRate:W,chain:C});if(!(D&&U))throw new R("toolbox_utxo_insufficient_balance",{sender:$,assetValue:X});let B=await I(),z=new IG({network:B(C)});for(let{hash:M,index:H,witnessUtxo:b}of D)z.addInput({hash:M,index:H,witnessUtxo:b});for(let M of U){let H="address"in M&&M.address?M.address:E($),b=M.script?L?{script:L,value:0}:void 0:{address:H,value:M.value};if(b)z.addOutput(b)}return{psbt:z,utxos:Z,inputs:D}}function yG(X){let G=X.getAddress(0);return w(G)}async function MJ(X,G){switch(X){case x.BitcoinCash:return await bX(G);case x.Bitcoin:case x.Dogecoin:case x.Litecoin:case x.Dash:return await n({chain:X,...G});default:throw new NG("toolbox_utxo_not_supported",{chain:X})}}export{E as toLegacyAddress,l as toCashAddress,w as stripToCashAddress,g as stripPrefix,o as nonSegwitChains,CX as isValidAddress,MJ as getUtxoToolbox,I as getUtxoNetwork,Y as getUtxoApi,LG as getUTXOAddressValidator,u as getScriptTypeForAddress,c as getOutputSize,N as getInputSize,t as getDustThreshold,r as getCreateKeysForPath,HX as detectAddressNetwork,n as createUTXOToolbox,AG as createCustomUtxoApi,bX as createBCHToolbox,O as compileMemo,S as calculateTxSize,K as bchValidateAddress,kX as addressFromKeysGetter,k as accumulative,TX as UtxoNetwork,XX as UTXOScriptType,e as TX_OVERHEAD,p as OutputSizes,nX as OP_RETURN_OVERHEAD,hG as MIN_TX_FEE,GX as InputSizes};
2
+
3
+ //# debugId=6BEC65B4771F1DD464756E2164756E21
@@ -0,0 +1,16 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/utxo/toolbox/index.ts", "../src/utxo/toolbox/bitcoinCash.ts", "../src/utxo/helpers/api.ts", "../src/utxo/helpers/bchaddrjs.ts", "../src/utxo/helpers/coinselect.ts", "../src/utxo/helpers/txSize.ts", "../src/utxo/toolbox/utxo.ts"],
4
+ "sourcesContent": [
5
+ "import {\n Chain,\n type ChainSigner,\n type DerivationPathArray,\n SwapKitError,\n type UTXOChain,\n} from \"@swapkit/helpers\";\nimport type { Psbt } from \"bitcoinjs-lib\";\n\nimport type { TransactionBuilderType, TransactionType, UTXOType } from \"../types\";\nimport { createBCHToolbox } from \"./bitcoinCash\";\nimport { createUTXOToolbox } from \"./utxo\";\n\ntype BCHToolbox = Awaited<ReturnType<typeof createBCHToolbox>>;\ntype CommonUTXOToolbox = Awaited<\n ReturnType<typeof createUTXOToolbox<Exclude<UTXOChain, Chain.BitcoinCash>>>\n>;\n\nexport type UTXOToolboxes = {\n [Chain.BitcoinCash]: BCHToolbox;\n [Chain.Bitcoin]: CommonUTXOToolbox;\n [Chain.Dogecoin]: CommonUTXOToolbox;\n [Chain.Litecoin]: CommonUTXOToolbox;\n [Chain.Dash]: CommonUTXOToolbox;\n};\n\nexport type UTXOWallets = {\n [key in keyof UTXOToolboxes]: UTXOToolboxes[key];\n};\n\nexport type UtxoToolboxParams = {\n [Chain.BitcoinCash]: {\n signer: ChainSigner<{ builder: TransactionBuilderType; utxos: UTXOType[] }, TransactionType>;\n };\n [Chain.Bitcoin]: { signer: ChainSigner<Psbt, Psbt> };\n [Chain.Dogecoin]: { signer: ChainSigner<Psbt, Psbt> };\n [Chain.Litecoin]: { signer: ChainSigner<Psbt, Psbt> };\n [Chain.Dash]: { signer: ChainSigner<Psbt, Psbt> };\n};\n\nexport async function getUtxoToolbox<T extends keyof UTXOToolboxes>(\n chain: T,\n params?:\n | UtxoToolboxParams[T]\n | {\n phrase?: string;\n derivationPath?: DerivationPathArray;\n index?: number;\n },\n): Promise<UTXOToolboxes[T]> {\n switch (chain) {\n case Chain.BitcoinCash: {\n const toolbox = await createBCHToolbox(params as UtxoToolboxParams[Chain.BitcoinCash]);\n return toolbox as UTXOToolboxes[T];\n }\n\n case Chain.Bitcoin:\n case Chain.Dogecoin:\n case Chain.Litecoin:\n case Chain.Dash: {\n const toolbox = await createUTXOToolbox({\n chain,\n ...(params as UtxoToolboxParams[Exclude<T, Chain.BitcoinCash>]),\n });\n return toolbox as UTXOToolboxes[Exclude<T, Chain.BitcoinCash>];\n }\n\n default:\n throw new SwapKitError(\"toolbox_utxo_not_supported\", { chain });\n }\n}\n\nexport {\n stripToCashAddress,\n stripPrefix,\n bchValidateAddress,\n} from \"./bitcoinCash\";\n",
6
+ "import {\n Transaction,\n TransactionBuilder,\n address as bchAddress,\n // @ts-ignore\n} from \"@psf/bitcoincashjs-lib\";\nimport {\n Chain,\n type ChainSigner,\n type DerivationPathArray,\n FeeOption,\n NetworkDerivationPath,\n SwapKitError,\n derivationPathToString,\n updateDerivationPath,\n} from \"@swapkit/helpers\";\nimport { Psbt } from \"bitcoinjs-lib\";\nimport type { UtxoToolboxParams } from \".\";\nimport {\n accumulative,\n UtxoNetwork as bchNetwork,\n compileMemo,\n detectAddressNetwork,\n getUtxoApi,\n getUtxoNetwork,\n isValidAddress,\n toCashAddress,\n toLegacyAddress,\n} from \"../helpers\";\nimport type {\n BchECPair,\n TargetOutput,\n TransactionBuilderType,\n TransactionType,\n UTXOBuildTxParams,\n UTXOTransferParams,\n UTXOType,\n} from \"../types\";\nimport { createUTXOToolbox, getCreateKeysForPath } from \"./utxo\";\n\nconst chain = Chain.BitcoinCash;\n\nexport function stripPrefix(address: string) {\n return address.replace(/(bchtest:|bitcoincash:)/, \"\");\n}\n\nexport function bchValidateAddress(address: string) {\n const strippedAddress = stripPrefix(address);\n return (\n isValidAddress(strippedAddress) && detectAddressNetwork(strippedAddress) === bchNetwork.Mainnet\n );\n}\n\nexport function stripToCashAddress(address: string) {\n return stripPrefix(toCashAddress(address));\n}\n\nasync function createSignerWithKeys(keys: BchECPair) {\n async function signTransaction({\n builder,\n utxos,\n }: { builder: TransactionBuilderType; utxos: UTXOType[] }) {\n utxos.forEach((utxo, index) => {\n builder.sign(index, keys, undefined, 0x41, utxo.witnessUtxo?.value);\n });\n\n return builder.build();\n }\n\n const getAddress = () => {\n const address = keys.getAddress(0);\n return Promise.resolve(stripToCashAddress(address));\n };\n\n return {\n getAddress,\n signTransaction,\n };\n}\n\nexport async function createBCHToolbox<T extends Chain.BitcoinCash>(\n toolboxParams:\n | UtxoToolboxParams[T]\n | {\n phrase?: string;\n derivationPath?: DerivationPathArray;\n index?: number;\n },\n) {\n const phrase = \"phrase\" in toolboxParams ? toolboxParams.phrase : undefined;\n\n const index = \"index\" in toolboxParams ? toolboxParams.index || 0 : 0;\n\n const derivationPath = derivationPathToString(\n \"derivationPath\" in toolboxParams && toolboxParams.derivationPath\n ? toolboxParams.derivationPath\n : updateDerivationPath(NetworkDerivationPath[chain], { index }),\n );\n\n const keys = (await getCreateKeysForPath(chain))({ phrase, derivationPath });\n\n const signer = keys\n ? await createSignerWithKeys(keys)\n : \"signer\" in toolboxParams\n ? toolboxParams.signer\n : undefined;\n\n function getAddress() {\n return Promise.resolve(signer?.getAddress());\n }\n\n const { getBalance, getFeeRates, broadcastTx, ...toolbox } = await createUTXOToolbox({ chain });\n\n function handleGetBalance(address: string, _scamFilter = true) {\n return getBalance(stripPrefix(toCashAddress(address)));\n }\n\n return {\n ...toolbox,\n getAddress,\n broadcastTx,\n createTransaction,\n buildTx,\n getAddressFromKeys,\n getBalance: handleGetBalance,\n getFeeRates,\n stripPrefix,\n stripToCashAddress,\n validateAddress: bchValidateAddress,\n transfer: transfer({ getFeeRates, broadcastTx, signer }),\n };\n}\n\nasync function createTransaction({\n assetValue,\n recipient,\n memo,\n feeRate,\n sender,\n}: UTXOBuildTxParams) {\n if (!bchValidateAddress(recipient))\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address: recipient });\n const utxos = await getUtxoApi(chain).scanUTXOs({\n address: stripToCashAddress(sender),\n fetchTxHex: true,\n });\n\n const compiledMemo = memo ? await compileMemo(memo) : null;\n\n const targetOutputs: TargetOutput[] = [];\n // output to recipient\n targetOutputs.push({\n address: recipient,\n value: assetValue.getBaseValue(\"number\"),\n });\n const { inputs, outputs } = accumulative({\n inputs: utxos,\n outputs: targetOutputs,\n feeRate,\n chain,\n });\n\n // .inputs and .outputs will be undefined if no solution was found\n if (!(inputs && outputs))\n throw new SwapKitError(\"toolbox_utxo_insufficient_balance\", { sender, assetValue });\n const getNetwork = await getUtxoNetwork();\n const builder = new TransactionBuilder(getNetwork(chain)) as TransactionBuilderType;\n\n await Promise.all(\n inputs.map(async (utxo: UTXOType) => {\n const txHex = await getUtxoApi(chain).getRawTx(utxo.hash);\n\n builder.addInput(Transaction.fromBuffer(Buffer.from(txHex, \"hex\")), utxo.index);\n }),\n );\n\n for (const output of outputs) {\n const address =\n \"address\" in output && output.address ? output.address : toLegacyAddress(sender);\n const getNetwork = await getUtxoNetwork();\n const outputScript = bchAddress.toOutputScript(toLegacyAddress(address), getNetwork(chain));\n\n builder.addOutput(outputScript, output.value);\n }\n\n // add output for memo\n if (compiledMemo) {\n builder.addOutput(compiledMemo, 0); // Add OP_RETURN {script, value}\n }\n\n return { builder, utxos: inputs };\n}\n\nfunction transfer({\n broadcastTx,\n getFeeRates,\n signer,\n}: {\n broadcastTx: (txHash: string) => Promise<string>;\n getFeeRates: () => Promise<Record<FeeOption, number>>;\n signer?: ChainSigner<{ builder: TransactionBuilderType; utxos: UTXOType[] }, TransactionType>;\n}) {\n return async function transfer({\n recipient,\n assetValue,\n feeOptionKey = FeeOption.Fast,\n ...rest\n }: UTXOTransferParams) {\n const from = await signer?.getAddress();\n if (!(signer && from)) throw new SwapKitError(\"toolbox_utxo_no_signer\");\n if (!recipient)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", {\n error: \"Recipient address must be provided\",\n });\n\n const feeRate = rest.feeRate || (await getFeeRates())[feeOptionKey];\n\n // try out if psbt tx is faster/better/nicer\n const { builder, utxos } = await createTransaction({\n ...rest,\n assetValue,\n feeRate,\n recipient,\n sender: from,\n });\n\n const tx = await signer.signTransaction({ builder, utxos });\n const txHex = tx.toHex();\n\n return broadcastTx(txHex);\n };\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO: refactor\nasync function buildTx({ assetValue, recipient, memo, feeRate, sender }: UTXOBuildTxParams) {\n const recipientCashAddress = toCashAddress(recipient);\n if (!bchValidateAddress(recipientCashAddress))\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address: recipientCashAddress });\n\n const utxos = await getUtxoApi(chain).scanUTXOs({\n address: stripToCashAddress(sender),\n fetchTxHex: true,\n });\n\n const feeRateWhole = Number(feeRate.toFixed(0));\n const compiledMemo = memo ? await compileMemo(memo) : null;\n\n const targetOutputs = [] as TargetOutput[];\n\n // output to recipient\n targetOutputs.push({\n address: toLegacyAddress(recipient),\n value: assetValue.getBaseValue(\"number\"),\n });\n\n //2. add output memo to targets (optional)\n if (compiledMemo) {\n targetOutputs.push({ script: compiledMemo, value: 0 });\n }\n\n const { inputs, outputs } = accumulative({\n inputs: utxos,\n outputs: targetOutputs,\n feeRate: feeRateWhole,\n chain,\n });\n\n // .inputs and .outputs will be undefined if no solution was found\n if (!(inputs && outputs))\n throw new SwapKitError(\"toolbox_utxo_insufficient_balance\", { sender, assetValue });\n const getNetwork = await getUtxoNetwork();\n const psbt = new Psbt({ network: getNetwork(chain) }); // Network-specific\n\n for (const { hash, index, witnessUtxo } of inputs) {\n psbt.addInput({ hash, index, witnessUtxo });\n }\n\n // Outputs\n for (const output of outputs) {\n const address =\n \"address\" in output && output.address ? output.address : toLegacyAddress(sender);\n const params = output.script\n ? compiledMemo\n ? { script: compiledMemo, value: 0 }\n : undefined\n : { address, value: output.value };\n\n if (params) {\n psbt.addOutput(params);\n }\n }\n\n return { psbt, utxos, inputs: inputs as UTXOType[] };\n}\n\nfunction getAddressFromKeys(keys: { getAddress: (index?: number) => string }) {\n const address = keys.getAddress(0);\n return stripToCashAddress(address);\n}\n",
7
+ "import {\n Chain,\n RequestClient,\n SKConfig,\n SwapKitError,\n type UTXOChain,\n warnOnce,\n} from \"@swapkit/helpers\";\nimport { networks } from \"bitcoinjs-lib\";\nimport { uniqid } from \"../../utils\";\n\n// @ts-ignore\nimport coininfo from \"coininfo\";\n\ntype BlockchairParams<T> = T & { chain: Chain; apiKey?: string };\ntype BlockchairFetchUnspentUtxoParams = BlockchairParams<{\n offset?: number;\n limit?: number;\n address: string;\n}>;\n\nasync function broadcastUTXOTx({ chain, txHash }: { chain: Chain; txHash: string }) {\n const rpcUrl = SKConfig.get(\"rpcUrls\")[chain];\n const body = JSON.stringify({\n jsonrpc: \"2.0\",\n method: \"sendrawtransaction\",\n params: [txHash],\n id: uniqid(),\n });\n\n const response = await RequestClient.post<{\n id: string;\n result: string;\n error: { message: string; code?: number } | null;\n }>(rpcUrl, { headers: { \"Content-Type\": \"application/json\" }, body });\n\n if (response.error) {\n throw new SwapKitError(\"toolbox_utxo_broadcast_failed\", { error: response.error?.message });\n }\n\n if (response.result.includes('\"code\":-26')) {\n throw new SwapKitError(\"toolbox_utxo_invalid_transaction\", {\n error: \"Transaction amount was too low\",\n });\n }\n\n return response.result;\n}\n\nfunction baseUrl(chain: Chain) {\n return `https://api.blockchair.com/${mapChainToBlockchairChain(chain)}`;\n}\n\nfunction getDefaultTxFeeByChain(chain: Chain) {\n switch (chain) {\n case Chain.Bitcoin:\n return 5;\n case Chain.Dogecoin:\n return 10000;\n case Chain.Litecoin:\n return 1;\n default:\n return 2;\n }\n}\n\nfunction mapChainToBlockchairChain(chain: Chain) {\n switch (chain) {\n case Chain.BitcoinCash:\n return \"bitcoin-cash\";\n case Chain.Litecoin:\n return \"litecoin\";\n case Chain.Dash:\n return \"dash\";\n case Chain.Dogecoin:\n return \"dogecoin\";\n case Chain.Polkadot:\n return \"polkadot\";\n default:\n return \"bitcoin\";\n }\n}\n\nasync function getSuggestedTxFee(chain: Chain) {\n try {\n //Use Bitgo API for fee estimation\n //Refer: https://app.bitgo.com/docs/#operation/v2.tx.getfeeestimate\n const { feePerKb } = await RequestClient.get<{\n feePerKb: number;\n cpfpFeePerKb: number;\n numBlocks: number;\n feeByBlockTarget: { 1: number; 3: number };\n }>(`https://app.bitgo.com/api/v2/${chain.toLowerCase()}/tx/fee`);\n const suggestedFee = feePerKb / 1000;\n\n return Math.max(suggestedFee, getDefaultTxFeeByChain(chain));\n } catch (_error) {\n return getDefaultTxFeeByChain(chain);\n }\n}\n\nasync function blockchairRequest<T>(url: string, apiKey?: string): Promise<T> {\n try {\n const response = await RequestClient.get<BlockchairResponse<T>>(url);\n if (!response || response.context.code !== 200)\n throw new SwapKitError(\"toolbox_utxo_api_error\", { error: `Failed to query ${url}` });\n\n return response.data as T;\n } catch (error) {\n if (!apiKey) throw error;\n const response = await RequestClient.get<BlockchairResponse<T>>(\n `${url}${apiKey ? `&key=${apiKey}` : \"\"}`,\n );\n\n if (!response || response.context.code !== 200)\n throw new SwapKitError(\"toolbox_utxo_api_error\", { error: `Failed to query ${url}` });\n\n return response.data as T;\n }\n}\n\nasync function getAddressData({ address, chain, apiKey }: BlockchairParams<{ address?: string }>) {\n if (!address)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"Address is required\" });\n\n try {\n const response = await blockchairRequest<BlockchairAddressResponse>(\n `${baseUrl(chain)}/dashboards/address/${address}?transaction_details=true`,\n apiKey,\n );\n\n return response[address];\n } catch (_error) {\n return { utxo: [], address: { balance: 0, transaction_count: 0 } };\n }\n}\n\nasync function getUnconfirmedBalance({\n address,\n chain,\n apiKey,\n}: BlockchairParams<{ address?: string }>) {\n const response = await getAddressData({ address, chain, apiKey });\n\n return response?.address.balance || 0;\n}\n\nasync function getRawTx({ chain, apiKey, txHash }: BlockchairParams<{ txHash?: string }>) {\n if (!txHash)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"TxHash is required\" });\n\n try {\n const rawTxResponse = await blockchairRequest<BlockchairRawTransactionResponse>(\n `${baseUrl(chain)}/raw/transaction/${txHash}`,\n apiKey,\n );\n return rawTxResponse?.[txHash]?.raw_transaction || \"\";\n } catch (error) {\n console.error(\"Failed to fetch raw transaction:\", error);\n return \"\";\n }\n}\n\nasync function fetchUnspentUtxoBatch({\n chain,\n address,\n apiKey,\n offset = 0,\n limit = 100,\n}: BlockchairFetchUnspentUtxoParams) {\n const response = await blockchairRequest<BlockchairOutputsResponse[]>(\n `${baseUrl(chain)}/outputs?q=is_spent(false),recipient(${address})&limit=${limit}&offset=${offset}`,\n apiKey,\n );\n\n const txs = response\n .filter(({ is_spent }) => !is_spent)\n .map(({ script_hex, block_id, transaction_hash, index, value, spending_signature_hex }) => ({\n hash: transaction_hash,\n index,\n value,\n txHex: spending_signature_hex,\n script_hex,\n is_confirmed: block_id !== -1,\n }));\n\n return txs;\n}\n\nasync function getUnspentUtxos({\n chain,\n address,\n apiKey,\n offset = 0,\n limit = 100,\n}: BlockchairFetchUnspentUtxoParams): Promise<Awaited<ReturnType<typeof fetchUnspentUtxoBatch>>> {\n if (!address)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"Address is required\" });\n\n try {\n const txs = await fetchUnspentUtxoBatch({ chain, address, apiKey, offset, limit });\n\n if (txs.length <= limit) return txs;\n\n const nextBatch = await getUnspentUtxos({\n chain,\n address,\n apiKey,\n offset: offset + limit,\n limit,\n });\n\n return [...txs, ...nextBatch];\n } catch (error) {\n console.error(\"Failed to fetch unspent UTXOs:\", error);\n return [];\n }\n}\n\nasync function scanUTXOs({\n address,\n chain,\n apiKey,\n fetchTxHex = true,\n}: BlockchairParams<{ address: string; fetchTxHex?: boolean }>) {\n const utxos = await getUnspentUtxos({ chain, address, apiKey });\n const results = [];\n\n for (const { hash, index, script_hex, value } of utxos) {\n let txHex: string | undefined;\n if (fetchTxHex) {\n txHex = await getRawTx({ txHash: hash, chain, apiKey });\n }\n results.push({\n address,\n hash,\n index,\n txHex,\n value,\n witnessUtxo: { value, script: Buffer.from(script_hex, \"hex\") },\n });\n }\n return results;\n}\n\nfunction utxoApi(chain: UTXOChain) {\n const apiKey = SKConfig.get(\"apiKeys\").blockchair || \"\";\n\n warnOnce(!apiKey, \"No Blockchair API key found. Functionality will be limited.\");\n\n return {\n broadcastTx: (txHash: string) => broadcastUTXOTx({ txHash, chain }),\n getRawTx: (txHash: string) => getRawTx({ txHash, chain, apiKey }),\n getSuggestedTxFee: () => getSuggestedTxFee(chain),\n getBalance: (address: string) => getUnconfirmedBalance({ address, chain, apiKey }),\n getAddressData: (address: string) => getAddressData({ address, chain, apiKey }),\n scanUTXOs: (params: { address: string; fetchTxHex?: boolean }) =>\n scanUTXOs({ ...params, chain, apiKey }),\n };\n}\n\n/**\n * \"Factory\" to ensure typing for custom UTXO APIs\n */\nexport function createCustomUtxoApi(methods: ReturnType<typeof utxoApi>) {\n return methods;\n}\n\nexport function getUtxoApi(chain: UTXOChain) {\n const customUtxoApi = SKConfig.get(\"apis\")[chain];\n\n if (customUtxoApi) {\n warnOnce(true, \"Using custom UTXO API. Be sure to implement all methods to avoid issues.\");\n return customUtxoApi as ReturnType<typeof utxoApi>;\n }\n\n return utxoApi(chain);\n}\n\nexport function getUtxoNetwork() {\n return function getNetwork(chain: Chain) {\n switch (chain) {\n case Chain.Bitcoin:\n return networks.bitcoin;\n case Chain.BitcoinCash:\n return coininfo.bitcoincash.main.toBitcoinJS();\n case Chain.Dash:\n return coininfo.dash.main.toBitcoinJS();\n case Chain.Litecoin:\n return coininfo.litecoin.main.toBitcoinJS();\n\n case Chain.Dogecoin: {\n const bip32 = { private: 0x04358394, public: 0x043587cf };\n const test = coininfo.dogecoin.test;\n test.versions.bip32 = bip32;\n return coininfo.dogecoin.main.toBitcoinJS();\n }\n default:\n throw new SwapKitError(\"toolbox_utxo_not_supported\", { chain });\n }\n };\n}\n\ninterface BlockchairVin {\n txid: string;\n vout: number;\n scriptSig: {\n asm: string;\n hex: string;\n };\n sequence: number;\n}\n\ninterface BlockchairVout {\n value: number;\n n: number;\n scriptPubKey: {\n asm: string;\n hex: string;\n address: string;\n type: string;\n addresses: string[];\n reqSigs: number;\n };\n}\n\ninterface BlockchairTransaction {\n block_id: number;\n hash: string;\n time: string;\n balance_change: number;\n}\n\ninterface BlockchairUtxo {\n block_id: number;\n transaction_hash: string;\n index: number;\n value: number;\n}\n\ninterface BlockchairAddressCoreData {\n type: string;\n script_hex: string;\n balance: number;\n balance_usd: number;\n received: number;\n received_usd: number;\n spent: number;\n spent_usd: number;\n output_count: number;\n unspent_output_count: number;\n first_seen_receiving: string;\n last_seen_receiving: string;\n first_seen_spending: null | string;\n last_seen_spending: null | string;\n transaction_count: number;\n scripthash_type: null | string;\n}\n\ninterface BlockchairInputOutputCommonData {\n block_id: number;\n transaction_id: number;\n index: number;\n transaction_hash: string;\n date: string;\n time: string;\n value: number;\n value_usd: number;\n recipient: string;\n type: string;\n script_hex: string;\n is_from_coinbase: boolean;\n is_spendable: boolean | null;\n is_spent: boolean;\n lifespan: number | null;\n cdd: number | null;\n}\n\ninterface BlockchairSpendingBlockData {\n spending_block_id: number | null;\n spending_transaction_id: number | null;\n spending_index: number | null;\n spending_transaction_hash: string | null;\n spending_date: string | null;\n spending_time: string | null;\n spending_value_usd: number | null;\n spending_sequence: number | null;\n spending_signature_hex: string | null;\n spending_witness: string | null;\n}\n\ninterface BlockchairAddressResponse {\n [key: string]: {\n address: BlockchairAddressCoreData;\n transactions: BlockchairTransaction[];\n utxo: BlockchairUtxo[];\n };\n}\n\ninterface BlockchairOutputsResponse\n extends BlockchairSpendingBlockData,\n BlockchairInputOutputCommonData {}\n\ninterface BlockchairRawTransactionResponse {\n [key: string]: {\n raw_transaction: string;\n decoded_raw_transaction: {\n txid: string;\n hash: string;\n version: number;\n size: number;\n vsize: number;\n weight: number;\n locktime: number;\n vin: BlockchairVin[];\n vout: BlockchairVout[];\n };\n };\n}\n\ninterface BlockchairResponse<T> {\n data: T;\n context: {\n code: number;\n source: string;\n results: number;\n state: number;\n market_price_usd: number;\n cache: {\n live: boolean;\n duration: number;\n since: string;\n until: string;\n time: any;\n };\n api: {\n version: string;\n last_major_update: string;\n next_major_update: null | string;\n documentation: string;\n notice: string;\n };\n servers: string;\n time: number;\n render_time: number;\n full_time: number;\n request_cost: number;\n };\n}\n",
8
+ "import { SwapKitError } from \"@swapkit/helpers\";\nimport base58check from \"bs58check\";\n// @ts-ignore\nimport cashaddr from \"cashaddrjs\";\n\nenum Format {\n Legacy = \"legacy\",\n Bitpay = \"bitpay\",\n Cashaddr = \"cashaddr\",\n}\nenum UtxoNetwork {\n Mainnet = \"mainnet\",\n Testnet = \"testnet\",\n}\nenum Type {\n P2PKH = \"p2pkh\",\n P2SH = \"p2sh\",\n}\n\nconst VERSION_BYTE = {\n [Format.Legacy]: {\n [UtxoNetwork.Mainnet]: {\n [Type.P2PKH]: 0,\n [Type.P2SH]: 5,\n },\n [UtxoNetwork.Testnet]: {\n [Type.P2PKH]: 111,\n [Type.P2SH]: 196,\n },\n },\n [Format.Bitpay]: {\n [UtxoNetwork.Mainnet]: {\n [Type.P2PKH]: 28,\n [Type.P2SH]: 40,\n },\n [UtxoNetwork.Testnet]: {\n [Type.P2PKH]: 111,\n [Type.P2SH]: 196,\n },\n },\n};\n\ntype DecodedType = {\n format: Format;\n network: UtxoNetwork;\n type: Type;\n hash: any;\n};\n\nfunction isValidAddress(input: any) {\n try {\n decodeAddress(input);\n return true;\n } catch (_error) {\n return false;\n }\n}\n\nfunction detectAddressNetwork(address: string) {\n return decodeAddress(address)?.network;\n}\n\nfunction toLegacyAddress(address: string): string {\n const decoded = decodeAddress(address);\n if (decoded?.format === Format.Legacy) {\n return address;\n }\n return encodeAsLegacy(decoded);\n}\n\nfunction toCashAddress(address: string): string {\n const decoded = decodeAddress(address);\n return encodeAsCashaddr(decoded);\n}\n\nfunction decodeAddress(address: string) {\n try {\n return decodeBase58Address(address);\n } catch (_error) {\n // Try to decode as cashaddr if base58 decoding fails.\n }\n try {\n return decodeCashAddress(address);\n } catch (_error) {\n // Try to decode as bitpay if cashaddr decoding fails.\n }\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n}\n\nfunction decodeBase58Address(address: string) {\n try {\n const payload = base58check.decode(address);\n\n // BASE_58_CHECK_PAYLOAD_LENGTH\n if (payload.length !== 21) throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n const versionByte = payload[0];\n const hash = Array.prototype.slice.call(payload, 1);\n\n switch (versionByte) {\n case VERSION_BYTE[Format.Legacy][UtxoNetwork.Mainnet][Type.P2PKH]:\n return { hash, format: Format.Legacy, network: UtxoNetwork.Mainnet, type: Type.P2PKH };\n\n case VERSION_BYTE[Format.Legacy][UtxoNetwork.Mainnet][Type.P2SH]:\n return { hash, format: Format.Legacy, network: UtxoNetwork.Mainnet, type: Type.P2SH };\n\n case VERSION_BYTE[Format.Legacy][UtxoNetwork.Testnet][Type.P2PKH]:\n return { hash, format: Format.Legacy, network: UtxoNetwork.Testnet, type: Type.P2PKH };\n\n case VERSION_BYTE[Format.Legacy][UtxoNetwork.Testnet][Type.P2SH]:\n return { hash, format: Format.Legacy, network: UtxoNetwork.Testnet, type: Type.P2SH };\n\n case VERSION_BYTE[Format.Bitpay][UtxoNetwork.Mainnet][Type.P2PKH]:\n return { hash, format: Format.Bitpay, network: UtxoNetwork.Mainnet, type: Type.P2PKH };\n\n case VERSION_BYTE[Format.Bitpay][UtxoNetwork.Mainnet][Type.P2SH]:\n return { hash, format: Format.Bitpay, network: UtxoNetwork.Mainnet, type: Type.P2SH };\n\n default:\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n }\n } catch (_error) {\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n }\n}\n\nfunction decodeCashAddress(address: string) {\n if (address.indexOf(\":\") !== -1) {\n try {\n return decodeCashAddressWithPrefix(address);\n } catch (_error) {\n // Try to decode as legacy if cashaddr decoding fails.\n }\n } else {\n const prefixes = [\"bitcoincash\", \"bchtest\", \"bchreg\"];\n for (const prefix of prefixes) {\n try {\n return decodeCashAddressWithPrefix(`${prefix}:${address}`);\n } catch (_error) {\n // Try next prefix if decoding fails.\n }\n }\n }\n\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n}\n\nfunction decodeCashAddressWithPrefix(address: string): DecodedType {\n try {\n const { hash, prefix, type } = cashaddr.decode(address);\n\n return {\n format: Format.Cashaddr,\n hash: Array.prototype.slice.call(hash, 0),\n network: prefix === \"bitcoincash\" ? UtxoNetwork.Mainnet : UtxoNetwork.Testnet,\n type: type === \"P2PKH\" ? Type.P2PKH : Type.P2SH,\n };\n } catch (_error) {\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n }\n}\n\nfunction encodeAsLegacy(decoded: DecodedType) {\n const versionByte = VERSION_BYTE[Format.Legacy][decoded.network][decoded.type];\n const buffer = Buffer.alloc(1 + decoded.hash.length);\n buffer[0] = versionByte;\n buffer.set(decoded.hash, 1);\n return base58check.encode(buffer);\n}\n\nfunction encodeAsCashaddr(decoded: DecodedType) {\n const prefix = decoded.network === UtxoNetwork.Mainnet ? \"bitcoincash\" : \"bchtest\";\n const type = decoded.type === Type.P2PKH ? \"P2PKH\" : \"P2SH\";\n const hash = new Uint8Array(decoded.hash);\n return cashaddr.encode(prefix, type, hash);\n}\n\nexport { detectAddressNetwork, isValidAddress, UtxoNetwork, toCashAddress, toLegacyAddress };\n",
9
+ "import { Chain, SwapKitError, type UTXOChain } from \"@swapkit/helpers\";\n\nimport {\n TX_OVERHEAD,\n UTXOScriptType,\n calculateTxSize,\n getInputSize,\n getOutputSize,\n getScriptTypeForAddress,\n} from \"../helpers\";\nimport type { TargetOutput, UTXOCalculateTxSizeParams, UTXOType } from \"../types\";\n\nexport const getDustThreshold = (chain: UTXOChain) => {\n switch (chain) {\n case Chain.Bitcoin:\n case Chain.BitcoinCash:\n return 550;\n case Chain.Dash:\n case Chain.Litecoin:\n return 5500;\n case Chain.Dogecoin:\n return 100000;\n default:\n throw new SwapKitError(\"toolbox_utxo_not_supported\", { chain });\n }\n};\n\nexport const accumulative = ({\n inputs,\n outputs,\n feeRate: initialFeeRate = 1,\n chain = Chain.Bitcoin,\n}: UTXOCalculateTxSizeParams & { outputs: TargetOutput[]; chain: UTXOChain }) => {\n const feeRate = Math.ceil(initialFeeRate);\n\n const newTxType =\n inputs[0] && \"address\" in inputs[0] && inputs[0].address\n ? getScriptTypeForAddress(inputs[0].address)\n : UTXOScriptType.P2PKH;\n // skip input if adding it would cost more than input is worth\n const filteredInputs = inputs.filter((input) => getInputSize(input) * feeRate <= input.value);\n\n const txSizeWithoutInputs =\n TX_OVERHEAD + outputs.reduce((total, output) => total + getOutputSize(output, newTxType), 0);\n\n const amountToSend = outputs.reduce((total, output) => total + output.value, 0);\n\n let fees = txSizeWithoutInputs * feeRate;\n let inputsValue = 0;\n const inputsToUse: typeof inputs = [];\n\n for (const input of filteredInputs) {\n const inputSize = getInputSize(input);\n const inputFee = feeRate * inputSize;\n\n fees += inputFee;\n inputsValue += input.value;\n\n inputsToUse.push(input);\n\n const totalCost = fees + amountToSend;\n\n // we need more inputs\n if (inputsValue < totalCost) continue;\n\n const remainder = inputsValue - totalCost;\n\n const feeForExtraOutput = feeRate * getOutputSize({ address: \"\", value: 0 }, newTxType);\n\n // potential change address\n if (remainder > feeForExtraOutput) {\n const feeAfterExtraOutput = feeForExtraOutput + fees;\n const remainderAfterExtraOutput = inputsValue - (amountToSend + feeAfterExtraOutput);\n\n // is it worth a change output aka can we send it in the future?\n if (\n remainderAfterExtraOutput >\n Math.max(getInputSize({} as UTXOType) * feeRate, getDustThreshold(chain))\n ) {\n return {\n inputs: inputsToUse,\n outputs: outputs.concat({ value: remainderAfterExtraOutput, address: \"\" }),\n fee: feeAfterExtraOutput,\n };\n }\n }\n return {\n inputs: inputsToUse,\n outputs,\n fee: fees,\n };\n }\n\n // We don't have enough inputs, let's calculate transaction fee accrude to the last input\n return { fee: feeRate * calculateTxSize({ inputs, outputs, feeRate }) };\n};\n",
10
+ "import { SwapKitError } from \"@swapkit/helpers\";\nimport { opcodes, script } from \"bitcoinjs-lib\";\nimport type {\n TargetOutput,\n UTXOCalculateTxSizeParams,\n UTXOInputWithScriptType,\n UTXOType,\n} from \"../types\";\n\n/**\n * Minimum transaction fee\n * 1000 satoshi/kB (similar to current `minrelaytxfee`)\n * @see https://github.com/bitcoin/bitcoin/blob/db88db47278d2e7208c50d16ab10cb355067d071/src/validation.h#L56\n */\nexport const MIN_TX_FEE = 1000;\nexport const TX_OVERHEAD = 4 + 1 + 1 + 4; //10\nexport const OP_RETURN_OVERHEAD = 1 + 8 + 1; //10\nconst TX_INPUT_BASE = 32 + 4 + 1 + 4; // 41\nconst TX_INPUT_PUBKEYHASH = 107;\n\nexport function compileMemo(memo: string) {\n const data = Buffer.from(memo, \"utf8\"); // converts MEMO to buffer\n return script.compile([opcodes.OP_RETURN as number, data]); // Compile OP_RETURN script\n}\n\nexport enum UTXOScriptType {\n P2PKH = \"P2PKH\", // legacy\n // P2SH = 'P2SH', // multisig\n P2WPKH = \"P2WPKH\", // bech32 - native segwit\n // P2TR = \"P2TR\", // taproot\n}\n\nexport const InputSizes: Record<UTXOScriptType, number> = {\n [UTXOScriptType.P2PKH]: 148,\n // [UTXOScriptType.P2SH]: 91,\n [UTXOScriptType.P2WPKH]: 68,\n};\n\nexport const OutputSizes: Record<UTXOScriptType, number> = {\n [UTXOScriptType.P2PKH]: 34,\n // [UTXOScriptType.P2SH]: 91,\n [UTXOScriptType.P2WPKH]: 31,\n};\n\nexport const getScriptTypeForAddress = (address: string) => {\n if (address.startsWith(\"bc1\") || address.startsWith(\"ltc1\")) {\n return UTXOScriptType.P2WPKH;\n }\n // if (address.startsWith('3') || address.startsWith('M')) {\n // return UTXOScriptType.P2SH;\n // }\n if (\n address.startsWith(\"1\") ||\n address.startsWith(\"3\") ||\n address.startsWith(\"L\") ||\n address.startsWith(\"M\") ||\n address.startsWith(\"X\") ||\n address.startsWith(\"D\") ||\n address.startsWith(\"bitcoincash:q\") ||\n address.startsWith(\"q\")\n ) {\n return UTXOScriptType.P2PKH;\n }\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { address });\n};\n\nexport const calculateTxSize = ({ inputs, outputs, feeRate }: UTXOCalculateTxSizeParams) => {\n const newTxType =\n inputs[0] && \"address\" in inputs[0] && inputs[0].address\n ? getScriptTypeForAddress(inputs[0].address)\n : UTXOScriptType.P2PKH;\n const inputSize = inputs\n .filter(\n (utxo) =>\n utxo.value >=\n InputSizes[\"type\" in utxo ? utxo.type : UTXOScriptType.P2PKH] * Math.ceil(feeRate),\n )\n .reduce((total, utxo) => total + getInputSize(utxo), 0);\n\n const outputSize =\n outputs?.reduce((total, output) => total + getOutputSize(output), 0) || OutputSizes[newTxType];\n\n return TX_OVERHEAD + inputSize + outputSize;\n};\n\nexport const getInputSize = (input: UTXOInputWithScriptType | UTXOType) => {\n if (\"type\" in input) {\n return InputSizes[input.type];\n }\n if (\"address\" in input && input.address) {\n return InputSizes[getScriptTypeForAddress(input.address as string)];\n }\n return TX_INPUT_BASE + TX_INPUT_PUBKEYHASH;\n};\n\nexport const getOutputSize = (output: TargetOutput, scriptType?: UTXOScriptType) => {\n if (output?.script) {\n return OP_RETURN_OVERHEAD + output.script.length + (output.script.length >= 74 ? 2 : 1);\n }\n if (scriptType) {\n return OutputSizes[scriptType];\n }\n return OutputSizes[UTXOScriptType.P2PKH];\n};\n",
11
+ "import {\n AssetValue,\n Chain,\n type ChainSigner,\n DerivationPath,\n type DerivationPathArray,\n FeeOption,\n NetworkDerivationPath,\n SwapKitError,\n SwapKitNumber,\n type UTXOChain,\n applyFeeMultiplier,\n derivationPathToString,\n updateDerivationPath,\n} from \"@swapkit/helpers\";\nimport { Psbt, address as btcLibAddress, initEccLib, payments } from \"bitcoinjs-lib\";\nimport type { ECPairInterface } from \"ecpair\";\nimport ECPairFactory from \"ecpair\";\nimport type { UtxoToolboxParams } from \".\";\nimport { getBalance } from \"../../utils\";\nimport {\n UTXOScriptType,\n accumulative,\n calculateTxSize,\n compileMemo,\n getDustThreshold,\n getInputSize,\n getUtxoApi,\n getUtxoNetwork,\n} from \"../helpers\";\nimport type {\n BchECPair,\n TargetOutput,\n UTXOBuildTxParams,\n UTXOTransferParams,\n UTXOType,\n} from \"../types\";\nimport { bchValidateAddress } from \"./bitcoinCash\";\n\nimport secp256k1 from \"@bitcoinerlab/secp256k1\";\n// @ts-ignore\nimport { ECPair, HDNode } from \"@psf/bitcoincashjs-lib\";\nimport { HDKey } from \"@scure/bip32\";\nimport { mnemonicToSeedSync } from \"@scure/bip39\";\n\nexport const nonSegwitChains = [Chain.Dash, Chain.Dogecoin];\n\nfunction addInputsAndOutputs({\n inputs,\n outputs,\n chain,\n psbt,\n sender,\n compiledMemo,\n}: {\n inputs: UTXOType[];\n outputs: TargetOutput[];\n chain: UTXOChain;\n psbt: Psbt;\n sender: string;\n compiledMemo: Buffer<ArrayBufferLike> | null;\n}) {\n for (const utxo of inputs) {\n const witnessInfo = !!utxo.witnessUtxo &&\n !nonSegwitChains.includes(chain) && { witnessUtxo: utxo.witnessUtxo };\n\n const nonWitnessInfo = nonSegwitChains.includes(chain) && {\n nonWitnessUtxo: utxo.txHex ? Buffer.from(utxo.txHex, \"hex\") : undefined,\n };\n\n psbt.addInput({ hash: utxo.hash, index: utxo.index, ...witnessInfo, ...nonWitnessInfo });\n }\n\n for (const output of outputs) {\n const address = \"address\" in output && output.address ? output.address : sender;\n const hasOutputScript = output.script;\n\n if (hasOutputScript && !compiledMemo) {\n continue;\n }\n\n const mappedOutput = hasOutputScript\n ? {\n script: compiledMemo as Buffer<ArrayBufferLike>,\n value: 0,\n }\n : {\n address,\n value: output.value,\n };\n\n initEccLib(secp256k1);\n psbt.addOutput(mappedOutput);\n }\n\n return { psbt, inputs };\n}\n\nasync function createTransaction({\n assetValue,\n recipient,\n memo,\n feeRate,\n sender,\n fetchTxHex = false,\n}: UTXOBuildTxParams): Promise<{\n psbt: Psbt;\n utxos: UTXOType[];\n inputs: UTXOType[];\n}> {\n const chain = assetValue.chain as UTXOChain;\n const compiledMemo = memo ? await compileMemo(memo) : null;\n\n const inputsAndOutputs = await getInputsAndTargetOutputs({\n assetValue,\n recipient,\n memo,\n sender,\n fetchTxHex,\n });\n\n const { inputs, outputs } = accumulative({ ...inputsAndOutputs, feeRate, chain });\n\n // .inputs and .outputs will be undefined if no solution was found\n if (!(inputs && outputs))\n throw new SwapKitError(\"toolbox_utxo_insufficient_balance\", { sender, assetValue });\n const getNetwork = await getUtxoNetwork();\n const psbt = new Psbt({ network: getNetwork(chain) });\n\n if (chain === Chain.Dogecoin) psbt.setMaximumFeeRate(650000000);\n\n const { psbt: mappedPsbt, inputs: mappedInputs } = await addInputsAndOutputs({\n inputs,\n outputs,\n chain,\n psbt,\n sender,\n compiledMemo,\n });\n\n return {\n psbt: mappedPsbt,\n utxos: inputsAndOutputs.inputs,\n inputs: mappedInputs,\n };\n}\n\nexport async function getUTXOAddressValidator() {\n const getNetwork = await getUtxoNetwork();\n\n return function validateAddress({ address, chain }: { address: string; chain: UTXOChain }) {\n if (chain === Chain.BitcoinCash) {\n return bchValidateAddress(address);\n }\n\n try {\n initEccLib(secp256k1);\n btcLibAddress.toOutputScript(address, getNetwork(chain));\n return true;\n } catch (_error) {\n return false;\n }\n };\n}\n\nasync function createSignerWithKeys({\n chain,\n phrase,\n derivationPath,\n}: { chain: UTXOChain; phrase: string; derivationPath: string }) {\n const keyPair = (await getCreateKeysForPath(chain as Chain.Bitcoin))({ phrase, derivationPath });\n\n async function signTransaction(psbt: Psbt) {\n await psbt.signAllInputs(keyPair);\n return psbt;\n }\n\n async function getAddress() {\n const addressGetter = await addressFromKeysGetter(chain);\n return addressGetter(keyPair);\n }\n\n return {\n getAddress,\n signTransaction,\n };\n}\n\nexport async function createUTXOToolbox<T extends UTXOChain>({\n chain,\n ...toolboxParams\n}: (\n | UtxoToolboxParams[T]\n | {\n phrase?: string;\n derivationPath?: DerivationPathArray;\n index?: number;\n }\n) & { chain: T }) {\n const phrase = \"phrase\" in toolboxParams ? toolboxParams.phrase : undefined;\n\n const index = \"index\" in toolboxParams ? toolboxParams.index || 0 : 0;\n\n const derivationPath = derivationPathToString(\n \"derivationPath\" in toolboxParams && toolboxParams.derivationPath\n ? toolboxParams.derivationPath\n : updateDerivationPath(NetworkDerivationPath[chain], { index }),\n );\n\n const signer = phrase\n ? await createSignerWithKeys({ chain, phrase, derivationPath })\n : \"signer\" in toolboxParams\n ? toolboxParams.signer\n : undefined;\n\n function getAddress() {\n return Promise.resolve(signer?.getAddress());\n }\n\n // const { signer } = params || {};\n const getAddressFromKeys = await addressFromKeysGetter(chain);\n const validateAddress = await getUTXOAddressValidator();\n const createKeysForPath = await getCreateKeysForPath(chain);\n\n return {\n accumulative,\n calculateTxSize,\n getAddressFromKeys,\n getAddress,\n validateAddress: (address: string) => validateAddress({ address, chain }),\n broadcastTx: (txHash: string) => getUtxoApi(chain).broadcastTx(txHash),\n createTransaction,\n createKeysForPath,\n getFeeRates: () => getFeeRates(chain),\n getInputsOutputsFee,\n transfer: transfer(signer as UtxoToolboxParams[\"BTC\"][\"signer\"]),\n getPrivateKeyFromMnemonic: (params: { phrase: string; derivationPath: string }) => {\n const keys = createKeysForPath(params);\n return keys.toWIF();\n },\n\n getBalance: getBalance(chain),\n estimateTransactionFee: estimateTransactionFee(chain),\n estimateMaxSendableAmount: estimateMaxSendableAmount(chain),\n };\n}\n\nasync function getInputsOutputsFee({\n assetValue,\n feeOptionKey = FeeOption.Fast,\n feeRate,\n memo,\n sender,\n recipient,\n}: Omit<UTXOBuildTxParams, \"feeRate\"> & {\n feeOptionKey?: FeeOption;\n feeRate?: number;\n}) {\n const chain = assetValue.chain as UTXOChain;\n\n const inputsAndOutputs = await getInputsAndTargetOutputs({\n assetValue,\n sender,\n memo,\n recipient,\n });\n\n const feeRateWhole = feeRate ? Math.floor(feeRate) : (await getFeeRates(chain))[feeOptionKey];\n\n return accumulative({ ...inputsAndOutputs, feeRate: feeRateWhole, chain });\n}\n\nfunction estimateMaxSendableAmount(chain: UTXOChain) {\n return async function estimateMaxSendableAmount({\n from,\n memo,\n feeRate,\n feeOptionKey = FeeOption.Fast,\n recipients = 1,\n }: {\n from: string;\n memo?: string;\n feeRate?: number;\n feeOptionKey?: FeeOption;\n recipients?: number | TargetOutput[];\n }) {\n const addressData = await getUtxoApi(chain).getAddressData(from);\n const feeRateWhole = feeRate ? Math.ceil(feeRate) : (await getFeeRates(chain))[feeOptionKey];\n\n const inputs = addressData?.utxo\n .map((utxo) => ({\n ...utxo,\n // type: utxo.witnessUtxo ? UTXOScriptType.P2WPKH : UTXOScriptType.P2PKH,\n type: UTXOScriptType.P2PKH,\n hash: \"\",\n }))\n .filter(\n (utxo) => utxo.value > Math.max(getDustThreshold(chain), getInputSize(utxo) * feeRateWhole),\n );\n\n if (!inputs?.length) return AssetValue.from({ chain });\n\n const balance = AssetValue.from({\n chain,\n value: inputs.reduce((sum, utxo) => sum + utxo.value, 0),\n });\n\n const outputs =\n typeof recipients === \"number\"\n ? (Array.from({ length: recipients }, () => ({\n address: from,\n value: 0,\n })) as TargetOutput[])\n : recipients;\n\n if (memo) {\n const script = await compileMemo(memo);\n outputs.push({ address: from, script, value: 0 });\n }\n\n const txSize = calculateTxSize({ inputs, outputs, feeRate: feeRateWhole });\n\n const fee = txSize * feeRateWhole;\n\n return balance.sub(fee);\n };\n}\n\nfunction estimateTransactionFee(chain: UTXOChain) {\n return async (params: {\n assetValue: AssetValue;\n recipient: string;\n sender: string;\n memo?: string;\n feeOptionKey?: FeeOption;\n feeRate?: number;\n fetchTxHex?: boolean;\n }) => {\n const inputFees = await getInputsOutputsFee(params);\n\n return AssetValue.from({\n chain,\n value: SwapKitNumber.fromBigInt(BigInt(inputFees.fee), 8).getValue(\"string\"),\n });\n };\n}\n\ntype CreateKeysForPathReturnType = {\n [Chain.BitcoinCash]: BchECPair;\n [Chain.Bitcoin]: ECPairInterface;\n [Chain.Dash]: ECPairInterface;\n [Chain.Dogecoin]: ECPairInterface;\n [Chain.Litecoin]: ECPairInterface;\n};\n\nexport async function getCreateKeysForPath<T extends keyof CreateKeysForPathReturnType>(\n chain: T,\n): Promise<\n (params: {\n wif?: string;\n phrase?: string;\n derivationPath?: string;\n }) => CreateKeysForPathReturnType[T]\n> {\n const getNetwork = await getUtxoNetwork();\n\n switch (chain) {\n case Chain.BitcoinCash: {\n return function createKeysForPath({\n phrase,\n derivationPath = `${DerivationPath.BCH}/0`,\n wif,\n }: { wif?: string; phrase?: string; derivationPath?: string }) {\n const network = getNetwork(chain);\n\n if (wif) {\n return ECPair.fromWIF(wif, network) as BchECPair;\n }\n if (!phrase)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"No phrase provided\" });\n\n const masterHDNode = HDNode.fromSeedBuffer(\n Buffer.from(mnemonicToSeedSync(phrase)),\n network,\n );\n const keyPair = masterHDNode.derivePath(derivationPath).keyPair;\n\n return keyPair as BchECPair;\n } as (params: {\n wif?: string;\n phrase?: string;\n derivationPath?: string;\n }) => CreateKeysForPathReturnType[T];\n }\n case Chain.Bitcoin:\n case Chain.Dogecoin:\n case Chain.Litecoin:\n case Chain.Dash: {\n return function createKeysForPath({\n phrase,\n wif,\n derivationPath,\n }: { phrase?: string; wif?: string; derivationPath: string }) {\n if (!(wif || phrase))\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", {\n error: \"Either phrase or wif must be provided\",\n });\n\n const factory = ECPairFactory(secp256k1);\n const network = getNetwork(chain);\n\n if (wif) return factory.fromWIF(wif, network);\n\n const seed = mnemonicToSeedSync(phrase as string);\n const master = HDKey.fromMasterSeed(seed, network).derive(derivationPath);\n if (!master.privateKey)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", {\n error: \"Could not get private key from phrase\",\n });\n\n return factory.fromPrivateKey(Buffer.from(master.privateKey), { network });\n } as (params: {\n wif?: string;\n phrase?: string;\n derivationPath?: string;\n }) => CreateKeysForPathReturnType[T];\n }\n default:\n throw new SwapKitError(\"toolbox_utxo_not_supported\", { chain });\n }\n}\n\nexport async function addressFromKeysGetter(chain: UTXOChain) {\n const getNetwork = await getUtxoNetwork();\n\n return function getAddressFromKeys(keys: ECPairInterface | BchECPair) {\n if (!keys)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", { error: \"Keys must be provided\" });\n\n const method = nonSegwitChains.includes(chain) ? payments.p2pkh : payments.p2wpkh;\n const { address } = method({ pubkey: keys.publicKey as Buffer, network: getNetwork(chain) });\n if (!address)\n throw new SwapKitError(\"toolbox_utxo_invalid_address\", { error: \"Address not defined\" });\n\n return address;\n };\n}\n\nfunction transfer(signer?: ChainSigner<Psbt, Psbt>) {\n return async function transfer({\n memo,\n recipient,\n feeOptionKey,\n feeRate,\n assetValue,\n }: UTXOTransferParams) {\n const from = await signer?.getAddress();\n\n const chain = assetValue.chain as UTXOChain;\n\n if (!(signer && from)) throw new SwapKitError(\"toolbox_utxo_no_signer\");\n if (!recipient)\n throw new SwapKitError(\"toolbox_utxo_invalid_params\", {\n error: \"Recipient address must be provided\",\n });\n const txFeeRate = feeRate || (await getFeeRates(chain))[feeOptionKey || FeeOption.Fast];\n\n const { psbt } = await createTransaction({\n recipient,\n feeRate: txFeeRate,\n sender: from,\n assetValue,\n memo,\n });\n const signedPsbt = await signer.signTransaction(psbt);\n signedPsbt.finalizeAllInputs(); // Finalise inputs\n // TX extracted and formatted to hex\n return getUtxoApi(chain).broadcastTx(signedPsbt.extractTransaction().toHex());\n };\n}\n\nasync function getFeeRates(chain: UTXOChain) {\n const suggestedFeeRate = await getUtxoApi(chain).getSuggestedTxFee();\n\n return {\n [FeeOption.Average]: suggestedFeeRate,\n [FeeOption.Fast]: applyFeeMultiplier(suggestedFeeRate, FeeOption.Fast),\n [FeeOption.Fastest]: applyFeeMultiplier(suggestedFeeRate, FeeOption.Fastest),\n };\n}\n\nasync function getInputsAndTargetOutputs({\n assetValue,\n recipient,\n memo,\n sender,\n fetchTxHex: fetchTxOverwrite = false,\n}: Omit<UTXOBuildTxParams, \"feeRate\">) {\n const chain = assetValue.chain as UTXOChain;\n\n const fetchTxHex = fetchTxOverwrite || nonSegwitChains.includes(chain);\n\n const inputs = await getUtxoApi(chain).scanUTXOs({ address: sender, fetchTxHex });\n\n //1. add output amount and recipient to targets\n //2. add output memo to targets (optional)\n\n return {\n inputs,\n outputs: [\n { address: recipient, value: Number(assetValue.bigIntValue) },\n ...(memo ? [{ address: \"\", script: await compileMemo(memo), value: 0 }] : []),\n ],\n };\n}\n"
12
+ ],
13
+ "mappings": "uFAAA,cACE,kBAGA,0BCJF,sBACE,yBACA,cACA,gCAGF,gBACE,gBAGA,4BACA,mBACA,4BACA,2BACA,0BAEF,eAAS,uBChBT,gBACE,mBACA,cACA,kBACA,cAEA,0BAEF,mBAAS,uBAIT,wBASA,eAAe,EAAe,EAAG,QAAO,UAA4C,CAClF,IAAM,EAAS,EAAS,IAAI,SAAS,EAAE,GACjC,EAAO,KAAK,UAAU,CAC1B,QAAS,MACT,OAAQ,qBACR,OAAQ,CAAC,CAAM,EACf,GAAI,GAAO,CACb,CAAC,EAEK,EAAW,MAAM,EAAc,KAIlC,EAAQ,CAAE,QAAS,CAAE,eAAgB,kBAAmB,EAAG,MAAK,CAAC,EAEpE,GAAI,EAAS,MACX,MAAM,IAAI,EAAa,gCAAiC,CAAE,MAAO,EAAS,OAAO,OAAQ,CAAC,EAG5F,GAAI,EAAS,OAAO,SAAS,YAAY,EACvC,MAAM,IAAI,EAAa,mCAAoC,CACzD,MAAO,gCACT,CAAC,EAGH,OAAO,EAAS,OAGlB,SA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 @@
11
11
  "@cosmjs/proto-signing": "0.33.1",
12
12
  "@cosmjs/stargate": "0.33.1",
13
13
  "@polkadot/api": "15.9.2",
14
- "@polkadot/keyring": "13.4.4",
15
- "@polkadot/util": "13.4.4",
16
- "@polkadot/util-crypto": "13.4.4",
14
+ "@polkadot/keyring": "13.5.1",
15
+ "@polkadot/util": "13.5.1",
16
+ "@polkadot/util-crypto": "13.5.1",
17
17
  "@psf/bitcoincashjs-lib": "4.0.3",
18
18
  "@radixdlt/babylon-gateway-api-sdk": "1.10.1",
19
19
  "@radixdlt/radix-dapp-toolkit": "2.2.1",
20
- "@scure/base": "1.2.4",
21
- "@scure/bip32": "1.6.2",
22
- "@scure/bip39": "1.5.4",
23
- "@swapkit/helpers": "3.0.0-beta.2",
20
+ "@scure/base": "1.2.6",
21
+ "@scure/bip32": "1.7.0",
22
+ "@scure/bip39": "1.6.0",
23
+ "@solana/spl-memo": "0.2.5",
24
+ "@solana/spl-token": "0.4.13",
25
+ "@solana/web3.js": "1.98.2",
26
+ "@swapkit/helpers": "3.0.0-beta.15",
24
27
  "base64-js": "1.5.1",
25
28
  "bitcoinjs-lib": "6.1.7",
26
29
  "bs58check": "4.0.0",
@@ -28,65 +31,74 @@
28
31
  "coininfo": "5.2.1",
29
32
  "cosmjs-types": "0.9.0",
30
33
  "ecpair": "2.1.0",
31
- "ethers": "6.13.5",
32
- "micro-key-producer": "0.7.5",
33
- "protobufjs": "7.4.0",
34
- "ts-pattern": "5.7.0",
35
- "xrpl": "4.2.0"
36
- },
37
- "peerDependencies": {
38
- "@solana/spl-memo": "0.2.5",
39
- "@solana/spl-token": "0.4.13",
40
- "@solana/web3.js": "1.98.0"
34
+ "ethers": "6.14.3",
35
+ "micro-key-producer": "0.7.6",
36
+ "near-api-js": "^6.1.0",
37
+ "near-sdk-js": "^2.0.0",
38
+ "near-seed-phrase": "^0.2.0",
39
+ "protobufjs": "7.5.3",
40
+ "tronweb": "6.0.3",
41
+ "ts-pattern": "5.7.1",
42
+ "xrpl": "4.3.0"
41
43
  },
42
44
  "devDependencies": {
43
- "@nomicfoundation/hardhat-ethers": "3.0.8",
45
+ "@nomicfoundation/hardhat-ethers": "3.0.9",
44
46
  "@nomicfoundation/hardhat-toolbox": "5.0.0",
45
47
  "@polkadot/types": "15.9.2",
46
- "@types/bn.js": "5.1.6",
48
+ "@types/bn.js": "5.2.0",
47
49
  "@types/crypto-js": "4.2.2",
48
50
  "@types/elliptic": "6.4.18",
49
- "hardhat": "2.23.0"
51
+ "hardhat": "2.24.2"
50
52
  },
51
53
  "exports": {
52
54
  ".": {
53
- "default": "./dist/index.js",
54
- "require": "./dist/index.cjs",
55
+ "default": "./dist/src/index.js",
56
+ "require": "./dist/src/index.cjs",
55
57
  "types": "./src/index.ts"
56
58
  },
57
59
  "./cosmos": {
58
- "default": "./dist/cosmos/index.js",
59
- "require": "./dist/cosmos/index.cjs",
60
+ "default": "./dist/src/cosmos/index.js",
61
+ "require": "./dist/src/cosmos/index.cjs",
60
62
  "types": "./src/cosmos/index.ts"
61
63
  },
62
64
  "./evm": {
63
- "default": "./dist/evm/index.js",
64
- "require": "./dist/evm/index.cjs",
65
+ "default": "./dist/src/evm/index.js",
66
+ "require": "./dist/src/evm/index.cjs",
65
67
  "types": "./src/evm/index.ts"
66
68
  },
69
+ "./near": {
70
+ "default": "./dist/near/index.js",
71
+ "require": "./dist/near/index.cjs",
72
+ "types": "./src/near/index.ts"
73
+ },
67
74
  "./radix": {
68
- "default": "./dist/radix/index.js",
69
- "require": "./dist/radix/index.cjs",
75
+ "default": "./dist/src/radix/index.js",
76
+ "require": "./dist/src/radix/index.cjs",
70
77
  "types": "./src/radix/index.ts"
71
78
  },
72
79
  "./ripple": {
73
- "default": "./dist/ripple/index.js",
74
- "require": "./dist/ripple/index.cjs",
80
+ "default": "./dist/src/ripple/index.js",
81
+ "require": "./dist/src/ripple/index.cjs",
75
82
  "types": "./src/ripple/index.ts"
76
83
  },
77
84
  "./solana": {
78
- "default": "./dist/solana/index.js",
79
- "require": "./dist/solana/index.cjs",
85
+ "default": "./dist/src/solana/index.js",
86
+ "require": "./dist/src/solana/index.cjs",
80
87
  "types": "./src/solana/index.ts"
81
88
  },
82
89
  "./substrate": {
83
- "default": "./dist/substrate/index.js",
84
- "require": "./dist/substrate/index.cjs",
90
+ "default": "./dist/src/substrate/index.js",
91
+ "require": "./dist/src/substrate/index.cjs",
85
92
  "types": "./src/substrate/index.ts"
86
93
  },
94
+ "./tron": {
95
+ "default": "./dist/src/tron/index.js",
96
+ "require": "./dist/src/tron/index.cjs",
97
+ "types": "./src/tron/index.ts"
98
+ },
87
99
  "./utxo": {
88
- "default": "./dist/utxo/index.js",
89
- "require": "./dist/utxo/index.cjs",
100
+ "default": "./dist/src/utxo/index.js",
101
+ "require": "./dist/src/utxo/index.cjs",
90
102
  "types": "./src/utxo/index.ts"
91
103
  }
92
104
  },
@@ -107,5 +119,5 @@
107
119
  "type-check:go": "tsgo"
108
120
  },
109
121
  "type": "module",
110
- "version": "1.0.0-beta.2"
122
+ "version": "1.0.0-beta.20"
111
123
  }