@swapkit/toolboxes 5.4.1 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/dist/{chunk-4428244x.js → chunk-exyqap7m.js} +1 -1
- package/dist/chunk-ncc6qmj6.js +1 -0
- package/dist/{chunk-as9fracn.js → chunk-xdkdc1f0.js} +1 -1
- package/dist/{chunk-rn33j2bm.js → chunk-ygq25ce3.js} +2 -2
- package/dist/src/aleo/index.js +1 -1
- package/dist/src/aptos/index.js +1 -1
- package/dist/src/cardano/index.js +1 -1
- package/dist/src/cosmos/index.js +1 -1
- package/dist/src/evm/index.js +1 -1
- package/dist/src/hypercore/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/near/index.js +1 -1
- package/dist/src/radix/index.js +1 -1
- package/dist/src/ripple/index.js +1 -1
- package/dist/src/solana/index.js +1 -1
- package/dist/src/starknet/index.js +1 -1
- package/dist/src/stellar/index.js +1 -1
- package/dist/src/substrate/index.js +1 -1
- package/dist/src/sui/index.js +1 -1
- package/dist/src/ton/index.js +1 -1
- package/dist/src/tron/index.js +1 -1
- package/dist/src/utxo/index.js +1 -1
- package/dist/types/cosmos/types.d.ts +0 -1
- package/dist/types/evm/toolbox/baseEVMToolbox.d.ts +1 -0
- package/dist/types/evm/toolbox/op.d.ts +8 -0
- package/dist/types/near/toolbox.d.ts +0 -2
- package/dist/types/near/types/toolbox.d.ts +0 -2
- package/dist/types/utxo/__tests__/fixtures/utxo.d.ts +6 -5
- package/dist/types/utxo/helpers/addressType.d.ts +8 -0
- package/dist/types/utxo/helpers/network.d.ts +4 -0
- package/dist/types/utxo/helpers/scriptTypes.d.ts +40 -0
- package/dist/types/utxo/helpers/txSize.d.ts +7 -6
- package/dist/types/utxo/helpers/xpubDerivation.d.ts +4 -2
- package/dist/types/utxo/index.d.ts +1 -1
- package/dist/types/utxo/toolbox/bitcoinCash.d.ts +5 -8
- package/dist/types/utxo/toolbox/index.d.ts +3 -7
- package/dist/types/utxo/toolbox/params.d.ts +24 -19
- package/dist/types/utxo/toolbox/utxo.d.ts +51 -36
- package/dist/types/utxo/toolbox/validators.d.ts +1 -2
- package/dist/types/utxo/toolbox/zcash.d.ts +6 -8
- package/dist/types/utxo/types.d.ts +4 -1
- package/package.json +2 -2
- package/dist/chunk-dssawneq.js +0 -1
package/dist/src/utxo/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fa as it,ga as vt}from"../../chunk-as9fracn.js";import"../../chunk-4428244x.js";import{NetworkDerivationPath as en}from"@swapkit/helpers";function R(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`${e} must be a non-negative integer, got: ${t}`)}function G({accountIndex:e,chain:t,derivationPath:n}){if(e!==void 0)R("accountIndex",e);let[s,r,o]=n??en[t];return[s,r,e??o]}function ye({accountIndex:e,change:t=!1,chain:n,derivationPath:s,index:r}){return R("index",r),[...G({accountIndex:e,chain:n,derivationPath:s}),Number(t),r]}function oe(e){return e[2]??0}function tn({deriveAddress:e,getBalance:t,getUtxos:n}){async function s(i){let{accountIndex:c,count:a,startIndex:l=0,change:u=!1}=i;if(R("count",a),a<1)throw RangeError("count must be at least 1");R("startIndex",l);let d=[];for(let h=0;h<a;h++){let m=await e({accountIndex:c,change:u,index:l+h});if(m)d.push(m)}return d}async function r(i){let{gapLimit:c=20,change:a=!1}=i??{},l=[],u=0,d=0;while(u<c){let h=await e({change:a,index:d});if(!h)break;if((await t(h.address)).some((x)=>x.getValue("number")>0))l.push(h),u=0;else u++;d++}return l}async function o(i=20){let[c,a]=await Promise.all([r({change:!1,gapLimit:i}),r({change:!0,gapLimit:i})]),l=[...c,...a],u=await Promise.all(l.map(async(h)=>{let g=(await t(h.address)).reduce((x,P)=>x+P.getValue("number"),0);return{...h,balance:g}})),d=u.reduce((h,m)=>h+m.balance,0);return{addresses:u,total:d}}async function p(i=20){let[c,a]=await Promise.all([r({change:!1,gapLimit:i}),r({change:!0,gapLimit:i})]),l=[...c,...a];return(await Promise.all(l.map(async(d)=>(await n(d.address)).map((m)=>({...m,address:d.address,derivationIndex:d.index,isChange:d.change}))))).flat()}return{deriveAddresses:s,getAggregatedBalance:o,getAggregatedUtxos:p,scanForAddresses:r}}import{Chain as O,getRPCUrl as nn,RequestClient as Be,SKConfig as rn,SwapKitError as X,warnOnce as sn}from"@swapkit/helpers";import{NETWORKS as ae}from"@swapkit/utxo-signer";async function on({chain:e,txHash:t}){let n=`${ie(e)}/push/transaction`,s=JSON.stringify({data:t});try{let r=await Be.post(n,{body:s,headers:{"Content-Type":"application/json"}});if(r.context.code!==200)throw new X("toolbox_utxo_broadcast_failed",{error:r.context.error||"Transaction broadcast failed"});return r.data?.transaction_hash||t}catch(r){let o=await nn(e);if(o){let p=JSON.stringify({id:it(),jsonrpc:"2.0",method:"sendrawtransaction",params:[t]}),i=await Be.post(o,{body:p,headers:{"Content-Type":"application/json"}});if(i.error)throw new X("toolbox_utxo_broadcast_failed",{error:i.error?.message});if(i.result.includes('"code":-26'))throw new X("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return i.result}throw r}}function ie(e){return`https://api.blockchair.com/${an(e)}`}function ot(e){switch(e){case O.Bitcoin:return 5;case O.Dogecoin:return 1e4;case O.Litecoin:return 1;case O.Zcash:return 1;default:return 2}}function an(e){switch(e){case O.BitcoinCash:return"bitcoin-cash";case O.Litecoin:return"litecoin";case O.Dash:return"dash";case O.Dogecoin:return"dogecoin";case O.Zcash:return"zcash";case O.Polkadot:return"polkadot";default:return"bitcoin"}}async function cn(e){try{let{feePerKb:t}=await Be.get(`https://app.bitgo.com/api/v2/${e.toLowerCase()}/tx/fee`),n=t/1000;return Math.max(n,ot(e))}catch{return ot(e)}}async function be(e,t){let n=await Be.get(`${e}${t?`${e.includes("?")?"&":"?"}key=${t}`:""}`);if(!n||n.context.code!==200)throw new X("toolbox_utxo_api_error",{error:`Failed to query ${e}`});return n.data}async function un({chain:e,apiKey:t}){let n=await be(`${ie(e)}/stats`,t);if(typeof n.best_block_height!=="number")throw new X("toolbox_utxo_api_error",{error:"Missing best_block_height in stats response"});return n.best_block_height}async function ct({address:e,chain:t,apiKey:n}){if(!e)throw new X("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await be(`${ie(t)}/dashboards/address/${e}?transaction_details=true`,n))[e]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function dn({address:e,chain:t,apiKey:n}){return(await ct({address:e,apiKey:n,chain:t}))?.address.balance||0}async function ut({chain:e,apiKey:t,txHash:n}){if(!n)throw new X("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await be(`${ie(e)}/raw/transaction/${n}`,t))?.[n]?.raw_transaction||""}catch(s){let r=s instanceof Error?s.message:String(s);return console.error(`Failed to fetch raw transaction: ${r}`),""}}var pn=4294967294;async function ln({chain:e,apiKey:t,txHash:n}){if(!n)throw new X("toolbox_utxo_invalid_params",{error:"TxHash is required"});let r=(await be(`${ie(e)}/dashboards/transaction/${n}`,t))?.[n];if(!r)throw new X("toolbox_utxo_tx_not_found",{txHash:n});let{transaction:o,inputs:p,outputs:i}=r,c=p.map((l)=>l.spending_sequence),a=o.is_rbf===!0||c.some((l)=>l<pn);return{blockId:o.block_id,confirmed:o.block_id!==-1,fee:o.fee,inputs:p,isRBF:a,outputs:i,sequences:c,size:o.size,txid:o.hash,weight:o.weight}}async function hn({chain:e,address:t,apiKey:n,offset:s=0,limit:r=30}){return(await be(`${ie(e)}/outputs?q=recipient(${t}),is_spent(false)&s=value(desc)&fields=is_spent,transaction_hash,index,value,script_hex,block_id,spending_signature_hex&limit=${r}&offset=${s}`,n)).map(({is_spent:c,script_hex:a,block_id:l,transaction_hash:u,index:d,value:h,spending_signature_hex:m})=>({hash:u,index:d,is_confirmed:l!==-1,is_spent:c,script_hex:a,txHex:m,value:h}))}function fn(e){return e.reduce((t,n)=>t+n.value,0)}function at(e,t){let n=[...e].sort((s,r)=>r.value-s.value);if(t){let s=[],r=0;for(let o of n)if(s.push(o),r+=o.value,r>=t)break;return s}return n}async function dt({chain:e,address:t,apiKey:n,targetValue:s,accumulativeValue:r=0,offset:o=0,limit:p=30}){if(!t)throw new X("toolbox_utxo_invalid_params",{error:"Address is required"});try{let i=await hn({address:t,apiKey:n,chain:e,limit:p,offset:o,targetValue:s}),a=i.length<p,l=i.filter(({is_spent:x})=>!x),u=fn(l),d=r+u,h=s&&d>=s;if(a||h)return at(l,s);let m=await dt({accumulativeValue:d,address:t,apiKey:n,chain:e,limit:p,offset:o+p,targetValue:s}),g=[...l,...m];return at(g,s)}catch(i){let c=i instanceof Error?i.message:String(i);return console.error(`Failed to fetch unspent UTXOs: ${c}`),[]}}async function mn({address:e,chain:t,apiKey:n,fetchTxHex:s=!0,targetValue:r}){let o=await dt({address:e,apiKey:n,chain:t,targetValue:r}),p=s?await Promise.all(o.map(({hash:i})=>ut({apiKey:n,chain:t,txHash:i}))):[];return o.map(({hash:i,index:c,script_hex:a,value:l},u)=>({address:e,hash:i,index:c,txHex:s?p[u]:void 0,value:l,witnessUtxo:{script:Buffer.from(a,"hex"),value:l}}))}function A(e){let t=rn.get("apiKeys").blockchair||"";return sn({condition:!t,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(n)=>on({chain:e,txHash:n}),getAddressData:(n)=>ct({address:n,apiKey:t,chain:e}),getBalance:(n)=>dn({address:n,apiKey:t,chain:e}),getBlockHeight:()=>un({apiKey:t,chain:e}),getRawTx:(n)=>ut({apiKey:t,chain:e,txHash:n}),getSuggestedTxFee:()=>cn(e),getTransactionDetails:(n)=>ln({apiKey:t,chain:e,txHash:n}),getUtxos:(n)=>mn({...n,apiKey:t,chain:e})}}function Er(e){return e}function Mr(){return function(t){switch(t){case O.Bitcoin:return ae.bitcoin;case O.BitcoinCash:return ae.bitcoinCash;case O.Dash:return ae.dash;case O.Litecoin:return ae.litecoin;case O.Dogecoin:return ae.dogecoin;case O.Zcash:return ae.zcash;default:throw new X("toolbox_utxo_not_supported",{chain:t})}}}import{sha256 as vn}from"@noble/hashes/sha2.js";import{createBase58check as Pn}from"@scure/base";import{SwapKitError as lt}from"@swapkit/helpers";import{CashAddrType as ke,decodeCashAddr as gn,encodeCashAddr as xn}from"@swapkit/utxo-signer";var Tn={P2PKH:ke.P2PKH,P2SH:ke.P2SH},yn={[ke.P2PKH]:"P2PKH",[ke.P2SH]:"P2SH"};function bn(e,t,n){return xn({hash:n,prefix:e,type:Tn[t]})}function wn(e){let t=gn(e),n=yn[t.type];if(!n)throw Error(`Unknown CashAddr type: ${t.type}`);return{hash:t.hash,prefix:t.prefix,type:n}}var Ne={decode:wn,encode:bn};var ht=Pn(vn);var ft;((n)=>{n.Mainnet="mainnet";n.Testnet="testnet"})(ft||={});var j={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}},_n={["p2pkh"]:"pkh",["p2sh"]:"sh"};function Gr(e){return Fe(e)!==void 0}function jr(e){return Ze(e).network}function z(e){let t=Ze(e);if(t.format==="legacy")return e;return On(t)}function Xe(e){let t=Ze(e);return Cn(t)}function Fe(e){if(typeof e!=="string")return;let t=An(e)??Un(e);return t&&{...t,scriptType:_n[t.type]}}function Ze(e){let t=Fe(e);if(!t)throw new lt("toolbox_utxo_invalid_address",{address:e});return t}function An(e){try{let t=ht.decode(e);if(t.length!==21)throw new lt("toolbox_utxo_invalid_address",{address:e});let n=t[0],s=Array.prototype.slice.call(t,1);switch(n){case j.legacy.mainnet.p2pkh:return{format:"legacy",hash:s,network:"mainnet",type:"p2pkh"};case j.legacy.mainnet.p2sh:return{format:"legacy",hash:s,network:"mainnet",type:"p2sh"};case j.legacy.testnet.p2pkh:return{format:"legacy",hash:s,network:"testnet",type:"p2pkh"};case j.legacy.testnet.p2sh:return{format:"legacy",hash:s,network:"testnet",type:"p2sh"};case j.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:s,network:"mainnet",type:"p2pkh"};case j.bitpay.mainnet.p2sh:return{format:"bitpay",hash:s,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function Un(e){if(e.indexOf(":")!==-1)try{return pt(e)}catch{}else{let t=["bitcoincash","bchtest","bchreg"];for(let n of t)try{return pt(`${n}:${e}`)}catch{}}return}function pt(e){try{let{hash:t,prefix:n,type:s}=Ne.decode(e);return{format:"cashaddr",hash:Array.prototype.slice.call(t,0),network:n==="bitcoincash"?"mainnet":"testnet",type:s==="P2PKH"?"p2pkh":"p2sh"}}catch{return}}function On(e){let t=j.legacy[e.network][e.type],n=Buffer.alloc(1+e.hash.length);return n[0]=t,n.set(e.hash,1),ht.encode(n)}function Cn(e){let t=e.network==="mainnet"?"bitcoincash":"bchtest",n=e.type==="p2pkh"?"P2PKH":"P2SH",s=new Uint8Array(e.hash);return Ne.encode(t,n,s)}import{Chain as J,SwapKitError as Ve}from"@swapkit/helpers";import{SwapKitError as Sn,UTXO_SCRIPT_TYPE_LIST as Bn,UTXO_SCRIPT_TYPES as mt,UTXOScriptType as ce}from"@swapkit/helpers";import{Script as kn}from"@swapkit/utxo-signer";import{UTXOScriptType as Tt}from"@swapkit/helpers";var es=1000,Le=10,Xn=2,Fn=10;function F(e){let t=new Uint8Array(Buffer.from(e,"utf8"));return kn.encode(["RETURN",t])}function gt(e){return Object.fromEntries(Bn.map((t)=>[t,mt[t][e]]))}var xt=gt("inputSize"),Ke=gt("outputSize"),ze=(e)=>mt[e].witness,ve=(e)=>{if(e.startsWith("bc1")||e.startsWith("tb1")||e.startsWith("ltc1")||e.startsWith("tltc1"))return ce.P2WPKH;if(e.startsWith("1")||e.startsWith("m")||e.startsWith("n")||e.startsWith("bitcoincash:q")||e.startsWith("bitcoincash:p")||e.startsWith("q")||e.startsWith("p")||e.startsWith("L")||e.startsWith("M")||e.startsWith("3")||e.startsWith("D")||e.startsWith("A")||e.startsWith("9")||e.startsWith("X")||e.startsWith("7")||e.startsWith("y")||e.startsWith("t1")||e.startsWith("t3")||e.startsWith("tm"))return ce.P2PKH;throw new Sn("toolbox_utxo_invalid_address",{address:e})},ue=({inputs:e,outputs:t,feeRate:n})=>{let s=e[0]?we(e[0]):ce.P2PKH,r=n?e.filter((a)=>a.value>=xt["type"in a&&a.type?a.type:ce.P2PKH]*Math.ceil(n)):e,o=0,p=0;for(let a of r)if(o+=Y(a),!ze(we(a)))p++;let i=t?.reduce((a,l)=>a+De(l),0)||Ke[s],c=p<r.length;return Le+o+i+$e(c,p)},we=(e)=>{if("type"in e&&e.type)return e.type;if("address"in e&&e.address)return ve(e.address);return ce.P2PKH},Y=(e)=>xt[we(e)],$e=(e,t)=>e?Math.ceil((Xn+t)/4):0,De=(e,t)=>{if(e?.script)return Fn+e.script.length+(e.script.length>=74?2:1);if(t)return Ke[t];if("address"in e&&e.address)return Ke[ve(e.address)];return Ke[ce.P2PKH]};function Pe(e){switch(e){case J.Bitcoin:case J.BitcoinCash:return 550;case J.Dash:case J.Litecoin:return 5500;case J.Dogecoin:return 1e5;case J.Zcash:return 546;default:throw new Ve("toolbox_utxo_not_supported",{chain:e})}}function K({inputs:e,outputs:t,feeRate:n=1,chain:s=J.Bitcoin,changeAddress:r="",sweep:o=!1}){let p=Pe(s),i=e.filter((g)=>{let x=Y(g)*n;return o?g.value>Math.max(x,p):x<=g.value});if(o){let g=Math.ceil(n*ue({inputs:i,outputs:t})),x=i.reduce((B,W)=>B+W.value,0),P=x-g;if(P<=p)throw new Ve("toolbox_sweep_amount_too_low",{available:x,dustThreshold:p,fee:g});let V=t.findIndex((B)=>("address"in B)&&B.address);if(V===-1)throw new Ve("toolbox_utxo_invalid_params",{error:"Sweep requires a recipient output"});return{fee:g,inputs:i,outputs:t.map((B,W)=>W===V?{...B,value:P}:B)}}let c=Le+t.reduce((g,x)=>g+De(x),0),a=t.reduce((g,x)=>g+x.value,0),l=0,u=0,d=!1,h=0,m=[];for(let g of i){if(l+=Y(g),ze(we(g)))d=!0;else u++;h+=g.value,m.push(g);let x=(c+l+$e(d,u))*n,P=x+a;if(h<P)continue;let V=h-P,B=n*De({address:r,value:0});if(V>B){let W=B+x,me=h-(a+Math.ceil(W));if(me>Math.max(Y({value:0})*n,Pe(s)))return{fee:Math.ceil(W),inputs:m,outputs:t.concat({address:r,value:me})}}return{fee:Math.ceil(x),inputs:m,outputs:t}}return{fee:Math.ceil(n*ue({inputs:e,outputs:t}))}}import{Chain as fe,SwapKitError as Kr}from"@swapkit/helpers";import{hex as Kt}from"@scure/base";import{Chain as Qn,derivationPathToString as er,FeeOption as tr,resolveDerivationPath as nr,SwapKitError as M}from"@swapkit/helpers";import{BCHSigHash as rr,CashAddrPrefix as Dt,CashAddrType as It,encodeCashAddr as Ht,NETWORKS as sr,p2pkh as Rt,Transaction as Wt}from"@swapkit/utxo-signer";import{secp256k1 as Kn}from"@noble/curves/secp256k1.js";import{hex as Q}from"@scure/base";import{HDKey as Pt}from"@scure/bip32";import{mnemonicToSeedSync as Je}from"@scure/bip39";import{AssetValue as je,applyFeeMultiplier as yt,Chain as U,derivationPathToString as Ae,FeeOption as D,NetworkDerivationPath as _t,SwapKitError as w,SwapKitNumber as Dn,updateDerivationPath as In,warnOnce as Hn}from"@swapkit/helpers";import{BCHSigHash as Qe,CashAddrPrefix as Rn,CashAddrType as Wn,encodeCashAddr as En,getAddressScriptType as Mn,NETWORKS as pe,OutScript as Nn,p2pkh as bt,p2wpkh as Zn,RBF_SEQUENCE as Ln,SigHash as At,Transaction as Ye,WIF as Ut}from"@swapkit/utxo-signer";import{match as Ot}from"ts-pattern";import{getZcashAddressType as qe,validateZcashAddress as Ge}from"@swapkit/utxo-signer";function de(e){return e.replace(/(bchtest:|bitcoincash:)/,"")}function Ie(e){if(typeof e!=="string")return null;let t=Fe(de(e));if(!t||t.network!=="mainnet")return null;return t.scriptType}function _e(e){return Ie(e)!==null}var Re=[U.Dash,U.Dogecoin,U.Zcash,U.BitcoinCash],He=[U.Bitcoin];function et({address:e,chain:t}){return Ot(t).with(U.BitcoinCash,()=>Ie(e)).with(U.Zcash,()=>qe(e)).otherwise(()=>Mn(e,S(t)))}function Ct({address:e,chain:t}){return et({address:e,chain:t})!==null}function S(e){return Ot(e).with(U.Bitcoin,()=>pe.bitcoin).with(U.BitcoinCash,()=>pe.bitcoinCash).with(U.Dash,()=>pe.dash).with(U.Dogecoin,()=>pe.dogecoin).with(U.Litecoin,()=>pe.litecoin).with(U.Zcash,()=>pe.zcash).exhaustive()}function zn({phrase:e,derivationPath:t,network:n,seed:s}){let r=s??Je(e),p=Pt.fromMasterSeed(r,n.bip32).derive(t);if(!p.privateKey)throw new w("toolbox_utxo_invalid_params",{error:"Could not derive private key from phrase"});return p.privateKey}function wt(e){return Kn.getPublicKey(e,!0)}function Ue({publicKey:e,chain:t,network:n}){if(t===U.BitcoinCash){let o=bt(e,n);if(!o.hash)throw new w("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return En({hash:o.hash,prefix:Rn.MAINNET,type:Wn.P2PKH}).replace(/^bitcoincash:/,"")}let r=!Re.includes(t)?Zn(e,n):bt(e,n);if(!r.address)throw new w("toolbox_utxo_invalid_address",{error:"Could not derive address"});return r.address}function le({phrase:e,derivationPath:t,chain:n,wif:s,seed:r}){let o=S(n);if(s){let a=Ut(o).decode(s),l=wt(a);return{privateKey:a,publicKey:l}}if(!e)throw new w("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let p=t||Ae(_t[n]),i=zn({derivationPath:p,network:o,phrase:e,seed:r}),c=wt(i);return{privateKey:i,publicKey:c}}function $n(e,t){return Ut(S(t)).encode(e)}function Vn({phrase:e,derivationPath:t,chain:n,seed:s}){let r=t.split("/");if(r.length<4)throw new w("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${r.length}): ${t}`});let o=S(n),p=s??Je(e),i=Pt.fromMasterSeed(p,o.bip32),c=r.slice(0,4).join("/");return i.derive(c)}function qn(e){try{let{type:t}=Nn.decode(e);return t==="wpkh"||t==="tr"}catch{return!1}}function ee({inputs:e,outputs:t,chain:n,tx:s,sender:r,compiledMemo:o,enableRBF:p=!1}){let i=S(n),c=!Re.includes(n),a=p?Ln:void 0,l=new Set;for(let u of e){let d=`${u.hash}:${u.index}`;if(l.has(d))throw new w("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});l.add(d);let h=typeof u.hash==="string"?Q.decode(u.hash):u.hash;if(c&&u.witnessUtxo&&qn(u.witnessUtxo.script))s.addInput({index:u.index,sequence:a,txid:h,witnessUtxo:{amount:BigInt(u.witnessUtxo.value),script:u.witnessUtxo.script}});else if(u.txHex)s.addInput({index:u.index,nonWitnessUtxo:Q.decode(u.txHex),sequence:a,txid:h,...n===U.BitcoinCash?{sighashType:Qe.ALL}:{}});else throw new w("toolbox_utxo_invalid_params",{error:`Input ${d} cannot be signed from its witnessUtxo alone: it needs its previous transaction (txHex)`})}for(let u of t){let d="address"in u&&u.address?u.address:r;if(n===U.BitcoinCash)d=z(d);if(u.script)if(o)s.addOutput({amount:0n,script:o});else throw new w("toolbox_utxo_invalid_params",{error:"An output carrying a script needs the compiled memo it carries"});else s.addOutputAddress(d,BigInt(u.value),i)}return{inputs:e,tx:s}}async function he(e){let t=await A(e).getSuggestedTxFee();return{[D.Average]:t,[D.Fast]:yt(t,D.Fast),[D.Fastest]:yt(t,D.Fastest)}}async function St({assetValue:e,recipient:t,memo:n,sender:s,sweep:r,fetchTxHex:o=!1},p,{forEstimateOnly:i=!1}={}){let c=e.chain,a=Re.includes(c)||ve(s)===Tt.P2PKH,l=o||!i&&a,u=e.getBaseValue("number"),d=r?void 0:p??(await he(c))[D.Fastest],h=r||d===void 0?void 0:Math.ceil(u+d*5000);return{inputs:await A(c).getUtxos({address:s,fetchTxHex:l,targetValue:h}),outputs:[{address:t,value:r?0:u},...n?[{address:"",script:F(n),value:0}]:[]]}}async function Bt({assetValue:e,recipient:t,memo:n,feeRate:s,sender:r,fetchTxHex:o=!1,enableRBF:p=!1,sweep:i}){let c=e.chain,a=n?F(n):null,l=await St({assetValue:e,fetchTxHex:o,memo:n,recipient:t,sender:r,sweep:i},s),{inputs:u,outputs:d}=K({...l,chain:c,changeAddress:r,feeRate:s,sweep:i});if(!(u&&d))throw new w("toolbox_utxo_insufficient_balance",{assetValue:e,sender:r});let h=new Ye({allowUnknownOutputs:!!a,version:1}),{inputs:m,tx:g}=ee({chain:c,compiledMemo:a,enableRBF:p,inputs:u,outputs:d,sender:r,tx:h});return{inputs:m,tx:g,utxos:l.inputs}}async function kt({assetValue:e,feeOptionKey:t=D.Fast,feeRate:n,memo:s,sender:r,recipient:o,sweep:p}){let i=e.chain,c,a;if(n!==void 0)c=n,a=Math.floor(n);else{let u=await he(i);c=u[D.Fastest],a=u[t]}let l=await St({assetValue:e,memo:s,recipient:o,sender:r,sweep:p},c,{forEstimateOnly:!0});return K({...l,chain:i,changeAddress:r,feeRate:a,sweep:p})}function Gn(e){return async function({from:n,memo:s,feeRate:r,feeOptionKey:o=D.Fast,recipient:p=n,recipients:i=1}){let c=r??(await he(e))[o],l=(await A(e).getUtxos({address:n,fetchTxHex:!1})).filter((g)=>g.value>Math.max(Pe(e),Y(g)*c));if(!l.length)return je.from({chain:e});let u=typeof i==="number"?Math.max(i,1):i.length,d=typeof i==="number"||u===0?Array.from({length:u||1},()=>({address:p,value:0})):[...i];if(s)d.push({address:n,script:F(s),value:0});let{outputs:h}=K({chain:e,feeRate:c,inputs:l,outputs:d,sweep:!0}),m=h?.[0]?.value??0;return je.from({chain:e,value:BigInt(m)})}}function jn(e){return async function(n){let{fee:s}=await kt(n);return je.from({chain:e,value:Dn.fromBigInt(BigInt(s),8).getValue("string")})}}function Yn({chain:e,phrase:t,derivationPath:n,seed:s}){let r=S(e),{privateKey:o,publicKey:p}=le({chain:e,derivationPath:n,phrase:t,seed:s}),i=e===U.BitcoinCash?[Qe.ALL]:[At.ALL];return{getAddress:()=>Ue({chain:e,network:r,publicKey:p}),privateKey:o,publicKey:p,signTransaction:(c)=>(c.sign(o,i),c)}}function Jn(e,t){return async function({memo:s,recipient:r,feeOptionKey:o,feeRate:p,assetValue:i,enableRBF:c=!1,sweep:a}){let l=await t?.getAddress();if(!(t&&l))throw new w("toolbox_utxo_no_signer");if(!r)throw new w("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});Hn({condition:c&&!He.includes(e),id:`rbf_not_supported_${e}`,warning:`RBF (Replace-by-Fee) is not reliably supported on ${e}. Transaction will be created without RBF signaling.`});let u=c&&He.includes(e),d=p||(await he(e))[o||D.Fast],{tx:h}=await Bt({assetValue:i,enableRBF:u,feeRate:d,memo:s,recipient:r,sender:l,sweep:a}),m=await t.signTransaction(h);return m.finalize(),A(e).broadcastTx(Q.encode(m.extract()))}}function Xt(e){return(t)=>Ct({address:t,chain:e})}function Ft(e){let t=S(e);return function(s){if(!s)throw new w("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return Ue({chain:e,network:t,publicKey:s.publicKey})}}function te({chain:e,...t}){let n="phrase"in t?t.phrase:void 0,s="index"in t?t.index||0:0,r=n?Je(n):void 0,o="derivationPath"in t&&t.derivationPath?t.derivationPath:In(_t[e],{index:s}),p=Ae(o),i=n?Yn({chain:e,derivationPath:p,phrase:n,seed:r}):void 0,c="signer"in t?t.signer:void 0,a=i||c,l=n?le({chain:e,derivationPath:p,phrase:n,seed:r}):void 0;function u(){if(a)return a.getAddress();return Promise.resolve(void 0)}function d(f){if(!n)return;let T=G({accountIndex:f,chain:e,derivationPath:o});return Vn({chain:e,derivationPath:Ae(T),phrase:n,seed:r})}let h=d();function m(){if(!h)return;return h.publicExtendedKey}function g({accountIndex:f}={}){let T=f===void 0?h:d(f);if(!T)return;let y=G({accountIndex:f,chain:e,derivationPath:o});return{accountIndex:oe(y),path:Ae(y),xpub:T.publicExtendedKey}}function x({accountIndex:f,index:T,change:y=!1}){let v=f===void 0?h:d(f);if(!v)return;let b=ye({accountIndex:f,chain:e,change:y,derivationPath:o,index:T}),k=S(e),H=v.deriveChild(Number(y)).deriveChild(T);if(!H.publicKey)throw new w("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let C=Ue({chain:e,network:k,publicKey:H.publicKey}),N=Q.encode(H.publicKey);return{accountIndex:oe(b),address:C,change:y,index:T,path:Ae(b),pubkey:N}}async function P(f){if(!He.includes(e))return{reason:`RBF is not supported on ${e}`,supported:!1};let T=await A(e).getTransactionDetails(f);return{canReplace:T.isRBF&&!T.confirmed,confirmed:T.confirmed,enabled:T.isRBF,fee:T.fee,sequences:T.sequences,supported:!0}}async function V({txid:f,newFeeRate:T,recipient:y,memo:v}){if(!He.includes(e))throw new w("toolbox_utxo_rbf_not_supported",{chain:e});let b=await A(e).getTransactionDetails(f);if(!b.isRBF)throw new w("toolbox_utxo_tx_not_replaceable",{txid:f});if(b.confirmed)throw new w("toolbox_utxo_tx_already_confirmed",{blockId:b.blockId,txid:f});let k=b.inputs.reduce((_,L)=>_+L.value,0),C=b.outputs.find((_)=>_.recipient===y)?.value||0;if(C===0)throw new w("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let N=await Promise.all(b.inputs.map(async(_)=>{let L=await A(e).getRawTx(_.transaction_hash);return{address:_.recipient,hash:_.transaction_hash,index:_.index,txHex:L,value:_.value,witnessUtxo:void 0}})),E=v?F(v):null,ge=k-C-b.fee,xe=await u(),re=[];if(E)re.push({address:"",script:E,value:0});if(ge>Pe(e)&&xe)re.push({address:xe,value:ge});let Ce=ue({inputs:N.map((_)=>({..._,type:ve(_.address)})),outputs:[{address:y,value:C},...re]}),Z=Math.ceil(Ce*T);if(Z<=b.fee)throw new w("toolbox_utxo_rbf_fee_too_low",{newFee:Z,originalFee:b.fee});let Te=Z-b.fee,q=C-Te;if(q<=0)throw new w("toolbox_utxo_rbf_insufficient_change");let Se=new Ye({allowUnknownOutputs:!!E,version:1}),se=[{address:y,value:q},...re];return ee({chain:e,compiledMemo:E,inputs:N,outputs:se,sender:xe||y,tx:Se}),{feeDelta:Te,newFee:Z,originalFee:b.fee,tx:Se}}async function B({txid:f,newFeeRate:T,recipient:y,memo:v}){let{tx:b,originalFee:k,newFee:H}=await V({memo:v,newFeeRate:T,recipient:y,txid:f}),C=await Ee(b);C.finalize();let N=await A(e).broadcastTx(Q.encode(C.extract()));return{newFee:H,originalFee:k,txid:N}}function W({accountIndex:f,index:T,change:y=!1}){R("index",T);let v=f===void 0?h:d(f);if(!v)return;return v.deriveChild(Number(y)).deriveChild(T).privateKey||void 0}function me({tx:f,inputDerivations:T}){if(!h)throw new w("toolbox_utxo_no_signer");let y=e===U.BitcoinCash?[Qe.ALL]:[At.ALL];for(let v=0;v<T.length;v++){let b=T[v];if(!b)continue;let{derivationIndex:k,isChange:H}=b,C=W({change:H,index:k});if(!C)throw new w("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${v} at index ${k}`});f.signIdx(C,v,y)}return f}async function Gt({utxos:f,recipient:T,assetValue:y,memo:v,feeRate:b,feeOptionKey:k,changeAddress:H,sweep:C}){if(C)throw new w("toolbox_utxo_invalid_params",{error:"Sweep is not supported for transfers from multiple addresses"});if(!h)throw new w("toolbox_utxo_no_signer");let N=b||(await he(e))[k||D.Fast],E=v?F(v):null,ge=[{address:T,value:y.getBaseValue("number")}];if(E)ge.push({address:"",script:E,value:0});let xe=f.map(({address:se,hash:_,index:L,value:Jt,txHex:Qt,witnessUtxo:Me})=>({address:se,hash:_,index:L,txHex:Qt,value:Jt,witnessUtxo:Me?{script:Me.script,value:Me.value}:void 0})),re=f[0]?.address,Ce=H||await u()||re||T,{inputs:Z,outputs:Te}=K({chain:e,changeAddress:Ce,feeRate:N,inputs:xe,outputs:ge});if(!(Z&&Te))throw new w("toolbox_utxo_insufficient_balance",{assetValue:y,sender:"multiple addresses"});let q=new Ye({allowUnknownOutputs:!!E,version:1});ee({chain:e,compiledMemo:E,inputs:Z,outputs:Te,sender:Ce,tx:q});let Se=Z.map((se)=>{let _=f.find((L)=>L.hash===se.hash&&L.index===se.index);return _?{derivationIndex:_.derivationIndex,isChange:_.isChange}:{derivationIndex:0,isChange:!1}});return me({inputDerivations:Se,tx:q}),q.finalize(),A(e).broadcastTx(Q.encode(q.extract()))}function jt({address:f,gapLimit:T=20}){if(!h)return;for(let y=0;y<T;y++){let v=x({change:!1,index:y}),b=x({change:!0,index:y}),k=v?.address===f?!1:b?.address===f;if(v?.address===f||b?.address===f)return{change:k,index:y}}return}function Ee(f){if(!a)throw new w("toolbox_utxo_no_signer");return a.signTransaction(f)}async function Yt(f){let T=await Ee(f);return T.finalize(),await A(e).broadcastTx(Q.encode(T.extract()))}return{accumulative:K,broadcastTx:(f)=>A(e).broadcastTx(f),bumpFee:B,calculateTxSize:ue,createKeysForPath:(f)=>le({...f,chain:e}),createReplacementTransaction:V,createTransaction:Bt,deriveAddressAtIndex:x,derivePrivateKeyAtIndex:W,estimateMaxSendableAmount:Gn(e),estimateTransactionFee:jn(e),getAddress:u,getAddressFromKeys:Ft(e),getAddressType:(f)=>et({address:f,chain:e}),getBalance:vt(e),getExtendedPublicKey:m,getExtendedPublicKeyInfo:g,getFeeRates:()=>he(e),getInputsOutputsFee:kt,getNetworkForChain:()=>S(e),getPrivateKeyFromMnemonic:(f)=>$n(le({...f,chain:e}).privateKey,e),isRBFEnabled:P,keys:l,resolveDerivationIndex:jt,signAndBroadcastTransaction:Yt,signTransaction:Ee,signTransactionWithMultipleKeys:me,transfer:Jn(e,a),transferFromMultipleAddresses:Gt,validateAddress:Xt(e)}}var I=Qn.BitcoinCash;function We(e){return de(Xe(e))}function or(e){let t=S(I);function n(r){return r.sign(e.privateKey,[rr.ALL]),r}function s(){let r=Rt(e.publicKey,t);if(!r.hash)throw new M("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let o=Ht({hash:r.hash,prefix:Dt.MAINNET,type:It.P2PKH});return Promise.resolve(o.replace(/^bitcoincash:/,""))}return{getAddress:s,signTransaction:n}}function Et(e){let t="phrase"in e?e.phrase:void 0,n="index"in e?e.index||0:0,s="derivationPath"in e?e.derivationPath:void 0,r=nr({chain:I,derivationPath:s,index:n}),o=er(r),p=t?le({chain:I,derivationPath:o,phrase:t}):void 0,i=p?or(p):("signer"in e)?e.signer:void 0;function c(){return Promise.resolve(i?.getAddress())}let{getBalance:a,getFeeRates:l,broadcastTx:u,...d}=te(t?{chain:I,derivationPath:r,phrase:t}:{chain:I});function h(x,P=!0){return a(de(Xe(x)))}function m(x){if(!i)throw new M("toolbox_utxo_no_signer");return i.signTransaction(x)}async function g(x){let P=await m(x);return P.finalize(),await u(Kt.encode(P.extract()))}return{...d,broadcastTx:u,buildTx:ir,createTransaction:Mt,getAddress:c,getAddressFromKeys:cr,getBalance:h,getFeeRates:l,signAndBroadcastTransaction:g,signTransaction:m,stripPrefix:de,stripToCashAddress:We,transfer:ar({broadcastTx:u,getFeeRates:l,signer:i}),validateAddress:_e}}async function Mt({assetValue:e,recipient:t,memo:n,feeRate:s,sender:r,sweep:o}){if(!_e(t))throw new M("toolbox_utxo_invalid_address",{address:t});let p=Math.ceil(e.getBaseValue("number")+s*7500),i=await A(I).getUtxos({address:We(r),fetchTxHex:!0,targetValue:o?void 0:p}),c=n?F(n):null,a=[],l=z(t);if(a.push({address:l,value:o?0:e.getBaseValue("number")}),c)a.push({script:c,value:0});let{inputs:u,outputs:d}=K({chain:I,feeRate:s,inputs:i,outputs:a,sweep:o});if(!(u&&d))throw new M("toolbox_utxo_insufficient_balance",{assetValue:e,sender:r});let h=new Wt({allowUnknownOutputs:!!c,version:1}),m=z(r),{inputs:g,tx:x}=ee({chain:I,compiledMemo:c,inputs:u,outputs:d.map((P)=>("address"in P)&&P.address?{...P,address:z(P.address)}:P),sender:m,tx:h});return{inputs:g,tx:x,utxos:u}}function ar({broadcastTx:e,getFeeRates:t,signer:n}){return async function({recipient:r,assetValue:o,feeOptionKey:p=tr.Fast,sweep:i,...c}){let a=await n?.getAddress();if(!(n&&a))throw new M("toolbox_utxo_no_signer");if(!r)throw new M("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let l=c.feeRate||(await t())[p],{tx:u}=await Mt({...c,assetValue:o,feeRate:l,recipient:r,sender:a,sweep:i}),d=await n.signTransaction(u);return d.finalize(),e(Kt.encode(d.extract()))}}async function ir({assetValue:e,recipient:t,memo:n,feeRate:s,sender:r}){let o=Xe(t);if(!_e(o))throw new M("toolbox_utxo_invalid_address",{address:o});let p=Math.ceil(e.getBaseValue("number")+s*7500),i=await A(I).getUtxos({address:We(r),fetchTxHex:!0,targetValue:p}),c=Number(s.toFixed(0)),a=n?F(n):null,l=[];if(l.push({address:z(t),value:e.getBaseValue("number")}),a)l.push({script:a,value:0});let{inputs:u,outputs:d}=K({chain:I,feeRate:c,inputs:i,outputs:l});if(!(u&&d))throw new M("toolbox_utxo_insufficient_balance",{assetValue:e,sender:r});let h=new Wt({allowUnknownOutputs:!!a,version:1}),{inputs:m,tx:g}=ee({chain:I,compiledMemo:a,inputs:u,outputs:d,sender:z(r),tx:h});return{inputs:m,tx:g,utxos:i}}function cr(e){let t=sr.bitcoinCash,n=Rt(e.publicKey,t);if(!n.hash)throw new M("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return Ht({hash:n.hash,prefix:Dt.MAINNET,type:It.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as ur,hex as dr}from"@scure/base";import{HDKey as zt}from"@scure/bip32";import{mnemonicToSeedSync as $t}from"@scure/bip39";import{Chain as Oe,derivationPathToString as pr,FeeOption as lr,resolveDerivationPath as hr,SKConfig as rt,SwapKitError as ne}from"@swapkit/helpers";import{Address as fr,createZcashTransaction as mr,getZcashConsensusBranchId as gr,isTransparentZcashAddress as Nt,OutScript as xr,PCZT as Tr,utils as Vt,WIF as yr,ZCASH_NETWORK as br,ZCASH_TEST_NETWORK as wr,ZcashConsensusBranchId as Zt,ZcashPSBT as vr,ZcashSigHash as tt,ZcashVersionGroupId as Pr}from"@swapkit/utxo-signer";import{match as _r,P as nt}from"ts-pattern";function st(){let{isStagenet:e}=rt.get("envs");return e?wr:br}var Ar=ur(Vt.sha256);function Ur(e){return Ar.encode(e)}function Or({phrase:e,derivationPath:t}){let n=$t(e),r=zt.fromMasterSeed(n).derive(t);if(!r.privateKey||!r.publicKey)throw new ne("toolbox_utxo_invalid_params");let{privateKey:o,publicKey:p}=r,i=Vt.hash160(p),{isStagenet:c}=rt.get("envs"),a=c?new Uint8Array([29,37]):new Uint8Array([28,184]),l=new Uint8Array(a.length+i.length);l.set(a,0),l.set(i,a.length);let u=Ur(l);return{getAddress:()=>Promise.resolve(u),signTransaction:(d)=>{if(d instanceof vr){let h=d.toPCZT();return h.signAllInputs(o,p,tt.ALL),h.finalizeAllInputs(),Promise.resolve(h.extract())}if(d instanceof Tr)return d.signAllInputs(o,p,tt.ALL),d.finalizeAllInputs(),Promise.resolve(d.extract());return d.signAllInputs(o,p,tt.ALL),Promise.resolve(d)}}}function Cr({inputs:e,outputs:t,tx:n,sender:s,compiledMemo:r}){let o=st();for(let p of e){let i=fr(o).decode(s),c=xr.encode(i);n.addInput({index:p.index,script:c,sequence:4294967295,txid:dr.decode(p.hash),value:BigInt(p.value)})}for(let p of t){let i="address"in p&&p.address?p.address:s,c=p.script;if(c&&!r)continue;if(c&&r)n.addOutput({amount:0n,script:r});else n.addOutputAddress(i,BigInt(p.value),o)}return{inputs:e,tx:n}}async function Sr(){let{isStagenet:e}=rt.get("envs");if(e)return Zt.IRONWOOD;try{let t=await A(Oe.Zcash).getBlockHeight();return gr(t+1)}catch{return Zt.IRONWOOD}}async function Lt(e){let{assetValue:t,recipient:n,memo:s,feeRate:r,sender:o,fetchTxHex:p,sweep:i}=e,c=st();if(!Nt(o,c))throw new ne("toolbox_utxo_invalid_address",{address:o});if(!Nt(n,c))throw new ne("toolbox_utxo_invalid_address",{address:n,error:"Zcash transaction creation currently supports transparent addresses only"});let a=s?F(s):null,l=await A(Oe.Zcash).getUtxos({address:o,fetchTxHex:p!==!1}),u=[{address:n,value:i?0:Number(t.getBaseValue("string"))},...a?[{script:a,value:0}]:[]],{inputs:d,outputs:h}=K({chain:Oe.Zcash,changeAddress:o,feeRate:r,inputs:l,outputs:u,sweep:i});if(!(d&&h))throw new ne("toolbox_utxo_insufficient_balance",{assetValue:t,sender:o});let m=mr({consensusBranchId:await Sr(),expiryHeight:0,lockTime:0,version:4,versionGroupId:Pr.SAPLING}),{tx:g,inputs:x}=Cr({compiledMemo:a,inputs:d,outputs:h,sender:o,tx:m});return{inputs:x,outputs:h,tx:g}}function qt(e){let t=_r(e).with({signer:nt.not(nt.nullish)},({signer:c})=>c).with({phrase:nt.string},({phrase:c,derivationPath:a,index:l=0})=>{let u=hr({chain:Oe.Zcash,derivationPath:a,index:l}),d=pr(u);return Or({derivationPath:d,phrase:c})}).otherwise(()=>{return}),n=te({chain:Oe.Zcash,signer:t});async function s(c){if(!t)throw new ne("toolbox_utxo_no_signer");return await t.signTransaction(c)}async function r(c){let a=await s(c);return n.broadcastTx(a.toHex())}async function o({recipient:c,assetValue:a,feeOptionKey:l=lr.Fast,sweep:u,...d}){let h=await t?.getAddress();if(!(t&&h))throw new ne("toolbox_utxo_no_signer");let m=d.feeRate||(await n.getFeeRates())[l],{tx:g}=await Lt({...d,assetValue:a,feeRate:m,recipient:c,sender:h,sweep:u}),P=(await t.signTransaction(g)).toHex();return n.broadcastTx(P)}function p({phrase:c,derivationPath:a="m/44'/133'/0'/0/0"}){let l=$t(c),d=zt.fromMasterSeed(l).derive(a);if(!d.privateKey||!d.publicKey)throw new ne("toolbox_utxo_invalid_params");return{privateKey:d.privateKey,publicKey:d.publicKey}}function i({phrase:c,derivationPath:a="m/44'/133'/0'/0/0"}){let l=p({derivationPath:a,phrase:c}),u=st();return yr(u).encode(l.privateKey)}return{...n,createKeysForPath:p,createTransaction:Lt,getPrivateKeyFromMnemonic:i,signAndBroadcastTransaction:r,signTransaction:s,transfer:o,validateAddress:Ge}}import{hex as Br}from"@scure/base";import{HDKey as kr}from"@scure/bip32";import{derivationPathToString as Xr}from"@swapkit/helpers";function Fr({xpub:e,chain:t,count:n,startIndex:s=0,accountIndex:r}){if(R("count",n),n<1)throw RangeError("count must be at least 1");R("startIndex",s);let o=S(t),p=kr.fromExtendedKey(e,o.bip32),i=G({accountIndex:r,chain:t}),c=oe(i),a=[];for(let l of[!1,!0]){let u=p.deriveChild(Number(l));for(let d=0;d<n;d++){let h=s+d,m=u.deriveChild(h);if(!m.publicKey)continue;let g=ye({accountIndex:r,chain:t,change:l,index:h});a.push({accountIndex:c,address:Ue({chain:t,network:o,publicKey:m.publicKey}),change:l,index:h,path:Xr(g),pubkey:Br.encode(m.publicKey)})}}return a}function Qs(e,t){switch(e){case fe.BitcoinCash:return Et(t||{});case fe.Zcash:return qt(t);case fe.Bitcoin:case fe.Dogecoin:case fe.Litecoin:case fe.Dash:return te({chain:e,...t});default:throw new Kr("toolbox_utxo_not_supported",{chain:e})}}export{xt as InputSizes,es as MIN_TX_FEE,Fn as OP_RETURN_OVERHEAD,Ke as OutputSizes,Xn as SEGWIT_MARKER_FLAG_WEIGHT,Le as TX_OVERHEAD,Tt as UTXOScriptType,ft as UtxoNetwork,K as accumulative,ee as addInputsAndOutputs,Ft as addressFromKeysGetter,R as assertDerivationIndex,ue as calculateTxSize,F as compileMemo,Et as createBCHToolbox,Er as createCustomUtxoApi,tn as createHDWalletHelpers,te as createUTXOToolbox,qt as createZcashToolbox,Fr as deriveAddressesFromXpub,jr as detectAddressNetwork,Ie as getBchAddressType,Pe as getDustThreshold,we as getInputScriptType,Y as getInputSize,S as getNetworkForChain,De as getOutputSize,ve as getScriptTypeForAddress,oe as getUTXOAccountIndexFromPath,G as getUTXOAccountPath,ye as getUTXOAddressPath,Xt as getUTXOAddressValidator,et as getUtxoAddressType,A as getUtxoApi,Mr as getUtxoNetwork,Qs as getUtxoToolbox,$e as getWitnessOverhead,qe as getZcashAddressType,ze as isSegwitScriptType,Gr as isValidAddress,Re as nonSegwitChains,de as stripPrefix,We as stripToCashAddress,Xe as toCashAddress,z as toLegacyAddress,Fe as tryDecodeAddress,_e as validateBchAddress,Ct as validateUtxoAddress,Ge as validateZcashAddress};
|
|
1
|
+
import{ha as St,ia as jt}from"../../chunk-xdkdc1f0.js";import"../../chunk-exyqap7m.js";import{NetworkDerivationPath as Sn}from"@swapkit/helpers";function Z(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`${e} must be a non-negative integer, got: ${t}`)}function ee({accountIndex:e,chain:t,derivationPath:n}){if(e!==void 0)Z("accountIndex",e);let[r,s,a]=n??Sn[t];return[r,s,e??a]}function Ae({accountIndex:e,change:t=!1,chain:n,derivationPath:r,index:s}){return Z("index",s),[...ee({accountIndex:e,chain:n,derivationPath:r}),Number(t),s]}function pe(e){return e[2]??0}function Cn({deriveAddress:e,getBalance:t,getUtxos:n}){async function r(o){let{accountIndex:p,count:c,startIndex:u=0,change:i=!1}=o;if(Z("count",c),c<1)throw RangeError("count must be at least 1");Z("startIndex",u);let l=[];for(let h=0;h<c;h++){let m=await e({accountIndex:p,change:i,index:u+h});if(m)l.push(m)}return l}async function s(o){let{gapLimit:p=20,change:c=!1}=o??{},u=[],i=0,l=0;while(i<p){let h=await e({change:c,index:l});if(!h)break;if((await t(h.address)).some((y)=>y.getValue("number")>0))u.push(h),i=0;else i++;l++}return u}async function a(o=20){let[p,c]=await Promise.all([s({change:!1,gapLimit:o}),s({change:!0,gapLimit:o})]),u=[...p,...c],i=await Promise.all(u.map(async(h)=>{let f=(await t(h.address)).reduce((y,b)=>y+b.getValue("number"),0);return{...h,balance:f}})),l=i.reduce((h,m)=>h+m.balance,0);return{addresses:i,total:l}}async function d(o=20){let[p,c]=await Promise.all([s({change:!1,gapLimit:o}),s({change:!0,gapLimit:o})]),u=[...p,...c];return(await Promise.all(u.map(async(l)=>(await n(l.address)).map((m)=>({...m,address:l.address,derivationIndex:l.index,isChange:l.change}))))).flat()}return{deriveAddresses:r,getAggregatedBalance:a,getAggregatedUtxos:d,scanForAddresses:s}}import{Chain as C,getRPCUrl as Xn,RequestClient as Re,SKConfig as Bn,SwapKitError as H,warnOnce as kn}from"@swapkit/helpers";import{NETWORKS as le}from"@swapkit/utxo-signer";async function Kn({chain:e,txHash:t}){let n=`${he(e)}/push/transaction`,r=JSON.stringify({data:t});try{let s=await Re.post(n,{body:r,headers:{"Content-Type":"application/json"}});if(s.context.code!==200)throw new H("toolbox_utxo_broadcast_failed",{error:s.context.error||"Transaction broadcast failed"});return s.data?.transaction_hash||t}catch(s){let a=await Xn(e);if(a){let d=JSON.stringify({id:St(),jsonrpc:"2.0",method:"sendrawtransaction",params:[t]}),o=await Re.post(a,{body:d,headers:{"Content-Type":"application/json"}});if(o.error)throw new H("toolbox_utxo_broadcast_failed",{error:o.error?.message});if(o.result.includes('"code":-26'))throw new H("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return o.result}throw s}}function he(e){return`https://api.blockchair.com/${Fn(e)}`}function _t(e){switch(e){case C.Bitcoin:return 5;case C.Dogecoin:return 1e4;case C.Litecoin:return 1;case C.Zcash:return 1;default:return 2}}function Fn(e){switch(e){case C.BitcoinCash:return"bitcoin-cash";case C.Litecoin:return"litecoin";case C.Dash:return"dash";case C.Dogecoin:return"dogecoin";case C.Zcash:return"zcash";case C.Polkadot:return"polkadot";default:return"bitcoin"}}async function Dn(e){try{let{feePerKb:t}=await Re.get(`https://app.bitgo.com/api/v2/${e.toLowerCase()}/tx/fee`),n=t/1000;return Math.max(n,_t(e))}catch{return _t(e)}}async function _e(e,t){let n=await Re.get(`${e}${t?`${e.includes("?")?"&":"?"}key=${t}`:""}`);if(!n||n.context.code!==200)throw new H("toolbox_utxo_api_error",{error:`Failed to query ${e}`});return n.data}async function In({chain:e,apiKey:t}){let n=await _e(`${he(e)}/stats`,t);if(typeof n.best_block_height!=="number")throw new H("toolbox_utxo_api_error",{error:"Missing best_block_height in stats response"});return n.best_block_height}async function Ct({address:e,chain:t,apiKey:n}){if(!e)throw new H("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await _e(`${he(t)}/dashboards/address/${e}?transaction_details=true`,n))[e]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function Hn({address:e,chain:t,apiKey:n}){return(await Ct({address:e,apiKey:n,chain:t}))?.address.balance||0}async function Xt({chain:e,apiKey:t,txHash:n}){if(!n)throw new H("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await _e(`${he(e)}/raw/transaction/${n}`,t))?.[n]?.raw_transaction||""}catch(r){let s=r instanceof Error?r.message:String(r);return console.error(`Failed to fetch raw transaction: ${s}`),""}}var Rn=4294967294;async function En({chain:e,apiKey:t,txHash:n}){if(!n)throw new H("toolbox_utxo_invalid_params",{error:"TxHash is required"});let s=(await _e(`${he(e)}/dashboards/transaction/${n}`,t))?.[n];if(!s)throw new H("toolbox_utxo_tx_not_found",{txHash:n});let{transaction:a,inputs:d,outputs:o}=s,p=d.map((u)=>u.spending_sequence),c=a.is_rbf===!0||p.some((u)=>u<Rn);return{blockId:a.block_id,confirmed:a.block_id!==-1,fee:a.fee,inputs:d,isRBF:c,outputs:o,sequences:p,size:a.size,txid:a.hash,weight:a.weight}}async function Mn({chain:e,address:t,apiKey:n,offset:r=0,limit:s=30}){return(await _e(`${he(e)}/outputs?q=recipient(${t}),is_spent(false)&s=value(desc)&fields=is_spent,transaction_hash,index,value,script_hex,block_id,spending_signature_hex&limit=${s}&offset=${r}`,n)).map(({is_spent:p,script_hex:c,block_id:u,transaction_hash:i,index:l,value:h,spending_signature_hex:m})=>({hash:i,index:l,is_confirmed:u!==-1,is_spent:p,script_hex:c,txHex:m,value:h}))}function Nn(e){return e.reduce((t,n)=>t+n.value,0)}function Ot(e,t){let n=[...e].sort((r,s)=>s.value-r.value);if(t){let r=[],s=0;for(let a of n)if(r.push(a),s+=a.value,s>=t)break;return r}return n}async function Bt({chain:e,address:t,apiKey:n,targetValue:r,accumulativeValue:s=0,offset:a=0,limit:d=30}){if(!t)throw new H("toolbox_utxo_invalid_params",{error:"Address is required"});try{let o=await Mn({address:t,apiKey:n,chain:e,limit:d,offset:a,targetValue:r}),c=o.length<d,u=o.filter(({is_spent:y})=>!y),i=Nn(u),l=s+i,h=r&&l>=r;if(c||h)return Ot(u,r);let m=await Bt({accumulativeValue:l,address:t,apiKey:n,chain:e,limit:d,offset:a+d,targetValue:r}),f=[...u,...m];return Ot(f,r)}catch(o){let p=o instanceof Error?o.message:String(o);return console.error(`Failed to fetch unspent UTXOs: ${p}`),[]}}async function Zn({address:e,chain:t,apiKey:n,fetchTxHex:r=!0,targetValue:s}){let a=await Bt({address:e,apiKey:n,chain:t,targetValue:s}),d=r?await Promise.all(a.map(({hash:o})=>Xt({apiKey:n,chain:t,txHash:o}))):[];return a.map(({hash:o,index:p,script_hex:c,value:u},i)=>({address:e,hash:o,index:p,txHex:r?d[i]:void 0,value:u,witnessUtxo:{script:Buffer.from(c,"hex"),value:u}}))}function O(e){let t=Bn.get("apiKeys").blockchair||"";return kn({condition:!t,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(n)=>Kn({chain:e,txHash:n}),getAddressData:(n)=>Ct({address:n,apiKey:t,chain:e}),getBalance:(n)=>Hn({address:n,apiKey:t,chain:e}),getBlockHeight:()=>In({apiKey:t,chain:e}),getRawTx:(n)=>Xt({apiKey:t,chain:e,txHash:n}),getSuggestedTxFee:()=>Dn(e),getTransactionDetails:(n)=>En({apiKey:t,chain:e,txHash:n}),getUtxos:(n)=>Zn({...n,apiKey:t,chain:e})}}function Ds(e){return e}function Is(){return function(t){switch(t){case C.Bitcoin:return le.bitcoin;case C.BitcoinCash:return le.bitcoinCash;case C.Dash:return le.dash;case C.Litecoin:return le.litecoin;case C.Dogecoin:return le.dogecoin;case C.Zcash:return le.zcash;default:throw new H("toolbox_utxo_not_supported",{chain:t})}}}import{sha256 as Gn}from"@noble/hashes/sha2.js";import{createBase58check as Yn}from"@scure/base";import{SwapKitError as Kt}from"@swapkit/helpers";import{CashAddrType as Ee,decodeCashAddr as zn,encodeCashAddr as Wn}from"@swapkit/utxo-signer";var Ln={P2PKH:Ee.P2PKH,P2SH:Ee.P2SH},$n={[Ee.P2PKH]:"P2PKH",[Ee.P2SH]:"P2SH"};function Vn(e,t,n){return Wn({hash:n,prefix:e,type:Ln[t]})}function qn(e){let t=zn(e),n=$n[t.type];if(!n)throw Error(`Unknown CashAddr type: ${t.type}`);return{hash:t.hash,prefix:t.prefix,type:n}}var st={decode:qn,encode:Vn};var Ft=Yn(Gn);var Dt;((n)=>{n.Mainnet="mainnet";n.Testnet="testnet"})(Dt||={});var te={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}},jn={["p2pkh"]:"pkh",["p2sh"]:"sh"};function Ws(e){return Ne(e)!==void 0}function Ls(e){return ot(e).network}function G(e){let t=ot(e);if(t.format==="legacy")return e;return er(t)}function Me(e){let t=ot(e);return tr(t)}function Ne(e){if(typeof e!=="string")return;let t=Jn(e)??Qn(e);return t&&{...t,scriptType:jn[t.type]}}function ot(e){let t=Ne(e);if(!t)throw new Kt("toolbox_utxo_invalid_address",{address:e});return t}function Jn(e){try{let t=Ft.decode(e);if(t.length!==21)throw new Kt("toolbox_utxo_invalid_address",{address:e});let n=t[0],r=Array.prototype.slice.call(t,1);switch(n){case te.legacy.mainnet.p2pkh:return{format:"legacy",hash:r,network:"mainnet",type:"p2pkh"};case te.legacy.mainnet.p2sh:return{format:"legacy",hash:r,network:"mainnet",type:"p2sh"};case te.legacy.testnet.p2pkh:return{format:"legacy",hash:r,network:"testnet",type:"p2pkh"};case te.legacy.testnet.p2sh:return{format:"legacy",hash:r,network:"testnet",type:"p2sh"};case te.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2pkh"};case te.bitpay.mainnet.p2sh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function Qn(e){if(e.indexOf(":")!==-1)try{return kt(e)}catch{}else{let t=["bitcoincash","bchtest","bchreg"];for(let n of t)try{return kt(`${n}:${e}`)}catch{}}return}function kt(e){try{let{hash:t,prefix:n,type:r}=st.decode(e);return{format:"cashaddr",hash:Array.prototype.slice.call(t,0),network:n==="bitcoincash"?"mainnet":"testnet",type:r==="P2PKH"?"p2pkh":"p2sh"}}catch{return}}function er(e){let t=te.legacy[e.network][e.type],n=Buffer.alloc(1+e.hash.length);return n[0]=t,n.set(e.hash,1),Ft.encode(n)}function tr(e){let t=e.network==="mainnet"?"bitcoincash":"bchtest",n=e.type==="p2pkh"?"P2PKH":"P2SH",r=new Uint8Array(e.hash);return st.encode(t,n,r)}import{Chain as oe,SwapKitError as Tt}from"@swapkit/helpers";import{SwapKitError as qe,UTXO_SCRIPT_TYPE_LIST as Ar,UTXO_SCRIPT_TYPES as $t,UTXOScriptType as Ge}from"@swapkit/helpers";import{Script as _r}from"@swapkit/utxo-signer";import{Chain as at}from"@swapkit/helpers";import{getAddressScriptType as rr,getTransparentZcashAddressType as sr,getZcashAddressType as or}from"@swapkit/utxo-signer";import{match as ar}from"ts-pattern";import{Chain as fe}from"@swapkit/helpers";import{NETWORKS as Te}from"@swapkit/utxo-signer";import{match as nr}from"ts-pattern";function P(e){return nr(e).with(fe.Bitcoin,()=>Te.bitcoin).with(fe.BitcoinCash,()=>Te.bitcoinCash).with(fe.Dash,()=>Te.dash).with(fe.Dogecoin,()=>Te.dogecoin).with(fe.Litecoin,()=>Te.litecoin).with(fe.Zcash,()=>Te.zcash).exhaustive()}function z(e){return e.replace(/(bchtest:|bitcoincash:)/,"")}function Oe(e){if(typeof e!=="string")return null;let t=Ne(z(e));if(!t||t.network!=="mainnet")return null;return t.scriptType}var ir=["sprout","sapling","unified"];function cr(e){let t=sr(e,P(at.Zcash));if(t)return t;let n=or(e);return n&&ir.includes(n)?n:null}function Y({address:e,chain:t}){return ar(t).with(at.BitcoinCash,()=>Oe(e)).with(at.Zcash,()=>cr(e)).otherwise(()=>rr(e,P(t)))}import{Chain as ne,derivationPathToString as It,getPurposeFromPath as dr,getUTXOScriptTypeForPath as Ht,getUTXOScriptTypeForPurpose as Mt,resolveDerivationPath as ur,SwapKitError as Se,UTXO_SCRIPT_TYPE_LIST as Rt,UTXO_SCRIPT_TYPES as me,UTXOChains as pr,UTXOScriptType as S,updateDerivationPath as lr,warnOnce as hr}from"@swapkit/helpers";import{CashAddrPrefix as fr,CashAddrType as Tr,encodeCashAddr as mr,OutScript as Nt,p2pkh as yr,p2sh as gr,p2tr as xr,p2wpkh as Et}from"@swapkit/utxo-signer";var Ze=Object.freeze([S.P2PKH]),br=Object.freeze({[ne.Bitcoin]:Rt,[ne.BitcoinCash]:Ze,[ne.Dash]:Ze,[ne.Dogecoin]:Ze,[ne.Litecoin]:Rt,[ne.Zcash]:Ze});function We(e){return br[e]}function it(e){return We(e).some((t)=>me[t].witness)}function ye(e,t){return We(e).includes(t)}function Le(e,t){if(ye(e,t))return t;throw new Se("toolbox_utxo_unsupported_script_type",{chain:e,error:`${e} cannot encode ${t}; supported: ${We(e).join(", ")}`,scriptType:t,supported:We(e)})}var Zt=pr.filter((e)=>!it(e));function wr({purpose:e,scriptType:t}){let n=Mt(e);return n===void 0||n===t}function ct({chain:e,purpose:t,scriptType:n}){hr({condition:!wr({purpose:t,scriptType:n}),id:`utxo_off_standard_encoding_${e}_${t}_${n}`,warning:`${e}: encoding m/${t}' keys as ${n}, not the ${Mt(t)} the path implies. No other wallet derives these addresses: move funds out of them, never receive into them.`})}function $e({chain:e,derivationPath:t,index:n=0,scriptType:r}){if(t){if(!r){let o=Ht(t);throw new Se("toolbox_utxo_invalid_params",{chain:e,derivationPath:It(t),error:`scriptType is required alongside derivationPath: getUTXOScriptTypeForPath gives the standard one${o?` (${o})`:""}, or state another deliberately.`})}return Le(e,r),ct({chain:e,purpose:dr(t),scriptType:r}),{derivationPath:t,scriptType:r}}let s=ur({chain:e,index:n}),a=r?lr(s,{purpose:me[r].purpose}):s,d=r??Ht(a);if(!d)throw new Se("toolbox_utxo_invalid_params",{chain:e,derivationPath:It(a),error:`${e}: the default derivation path has no standard script type`});return Le(e,d),{derivationPath:a,scriptType:d}}function Pr(e){return e.length===32?e:e.slice(1)}function ze(e,t){if(!e.address)throw new Se("toolbox_utxo_invalid_address",{error:`Could not derive a ${t} address`});return e}var Ur={[S.P2PKH]:(e,t)=>{let{address:n,script:r}=ze(yr(e,t),S.P2PKH);return{address:n,script:r}},[S.P2SH_P2WPKH]:(e,t)=>{let n=Et(e,t),{address:r,script:s}=ze(gr(n,t),S.P2SH_P2WPKH);return{address:r,redeemScript:n.script,script:s}},[S.P2WPKH]:(e,t)=>{let{address:n,script:r}=ze(Et(e,t),S.P2WPKH);return{address:n,script:r}},[S.P2TR]:(e,t)=>{let n=Pr(e),{address:r,script:s}=ze(xr(n,void 0,t),S.P2TR);return{address:r,script:s,tapInternalKey:n}}};function Ve(e,t,n){return Ur[e](t,n)}function dt(e,t){if(e!==ne.BitcoinCash)return t.address;let n=Nt.decode(t.script);if(n.type!=="pkh")throw new Se("toolbox_utxo_invalid_address",{chain:e,error:`Cannot encode ${n.type} as CashAddr`});return mr({hash:n.hash,prefix:fr.MAINNET,type:Tr.P2PKH}).replace(/^bitcoincash:/,"")}var vr=Object.freeze({pkh:S.P2PKH,sh:S.P2SH_P2WPKH,tr:S.P2TR,wpkh:S.P2WPKH}),zt=Object.freeze({pkh:me[S.P2PKH].outputSize,sh:me[S.P2SH_P2WPKH].outputSize,tr:me[S.P2TR].outputSize,wpkh:me[S.P2WPKH].outputSize,wsh:43});function Wt(e){return e in zt}function Lt(e){return Wt(e)?zt[e]:void 0}function Ce(e){return vr[e]}function ut(e){try{let{type:t}=Nt.decode(e);return Wt(t)?Ce(t):void 0}catch{return}}import{UTXOScriptType as se}from"@swapkit/helpers";var po=1000,lt=10,Or=2,Sr=10;function R(e){let t=new Uint8Array(Buffer.from(e,"utf8"));return _r.encode(["RETURN",t])}function Vt(e){return Object.fromEntries(Ar.map((t)=>[t,$t[t][e]]))}var qt=Vt("inputSize"),pt=Vt("outputSize"),ht=(e)=>$t[e].witness,Ye=(e,t)=>{let n=Y({address:e,chain:t});if(!n)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let r=Ce(n);if(!r||!ye(t,r))throw new qe("toolbox_utxo_unsupported_script_type",{address:e,addressType:n,chain:t,error:"Address is valid but its script type is not one the SDK spends from"});return r},Cr=(e,t)=>{let n=Y({address:e,chain:t});if(!n)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let r=Lt(n);if(!r)throw new qe("toolbox_utxo_unsupported_script_type",{address:e,addressType:n,chain:t,error:"Address is valid but a transparent transaction cannot pay to it"});return r},ge=({chain:e,inputs:t,outputs:n,feeRate:r})=>{let s=t[0]?Xe(t[0],e):Ge.P2PKH,a=r?t.filter((u)=>u.value>=qt["type"in u&&u.type?u.type:Ge.P2PKH]*Math.ceil(r)):t,d=0,o=0;for(let u of a)if(d+=re(u,e),!ht(Xe(u,e)))o++;let p=n?.reduce((u,i)=>u+je(i,e),0)||pt[s],c=o<a.length;return lt+d+p+ft(c,o)},Xe=(e,t)=>{if("type"in e&&e.type)return e.type;if("address"in e&&e.address)return Ye(e.address,t);return Ge.P2PKH},re=(e,t)=>qt[Xe(e,t)],ft=(e,t)=>e?Math.ceil((Or+t)/4):0,je=(e,t,n)=>{if(e?.script)return Sr+e.script.length+(e.script.length>=74?2:1);if(n)return pt[n];if("address"in e&&e.address)return Cr(e.address,t);return pt[Ge.P2PKH]};function Be(e){switch(e){case oe.Bitcoin:case oe.BitcoinCash:return 550;case oe.Dash:case oe.Litecoin:return 5500;case oe.Dogecoin:return 1e5;case oe.Zcash:return 546;default:throw new Tt("toolbox_utxo_not_supported",{chain:e})}}function E({inputs:e,outputs:t,feeRate:n=1,chain:r=oe.Bitcoin,changeAddress:s="",sweep:a=!1}){let d=Be(r),o=e.filter((f)=>{let y=re(f,r)*n;return a?f.value>Math.max(y,d):y<=f.value});if(a){let f=Math.ceil(n*ge({chain:r,inputs:o,outputs:t})),y=o.reduce((B,W)=>B+W.value,0),b=y-f;if(b<=d)throw new Tt("toolbox_sweep_amount_too_low",{available:y,dustThreshold:d,fee:f});let A=t.findIndex((B)=>("address"in B)&&B.address);if(A===-1)throw new Tt("toolbox_utxo_invalid_params",{error:"Sweep requires a recipient output"});return{fee:f,inputs:o,outputs:t.map((B,W)=>W===A?{...B,value:b}:B)}}let p=lt+t.reduce((f,y)=>f+je(y,r),0),c=t.reduce((f,y)=>f+y.value,0),u=0,i=0,l=!1,h=0,m=[];for(let f of o){if(u+=re(f,r),ht(Xe(f,r)))l=!0;else i++;h+=f.value,m.push(f);let y=(p+u+ft(l,i))*n,b=y+c;if(h<b)continue;let A=h-b,B=n*je({address:s,value:0},r);if(A>B){let W=B+y,Ie=h-(c+Math.ceil(W));if(Ie>Math.max(re({value:0},r)*n,Be(r)))return{fee:Math.ceil(W),inputs:m,outputs:t.concat({address:s,value:Ie})}}return{fee:Math.ceil(y),inputs:m,outputs:t}}return{fee:Math.ceil(n*ge({chain:r,inputs:e,outputs:t}))}}import{Chain as we,SwapKitError as Cs}from"@swapkit/helpers";import{hex as un}from"@scure/base";import{Chain as qr,derivationPathToString as Gr,FeeOption as Yr,resolveDerivationPath as jr,SwapKitError as L}from"@swapkit/helpers";import{BCHSigHash as Jr,CashAddrPrefix as pn,CashAddrType as ln,encodeCashAddr as hn,NETWORKS as Qr,p2pkh as fn,Transaction as Tn}from"@swapkit/utxo-signer";import{secp256k1 as Xr}from"@noble/curves/secp256k1.js";import{hex as ae}from"@scure/base";import{HDKey as Jt}from"@scure/bip32";import{mnemonicToSeedSync as xt}from"@scure/bip39";import{AssetValue as mt,applyFeeMultiplier as Gt,Chain as Ke,derivationPathToString as ke,FeeOption as M,NetworkDerivationPath as Br,SwapKitError as U,SwapKitNumber as kr,UTXO_SCRIPT_TYPES as Kr,warnOnce as Fr}from"@swapkit/helpers";import{BCHSigHash as Qt,RBF_SEQUENCE as Dr,SigHash as Yt,Transaction as yt,utils as Ir,WIF as en}from"@swapkit/utxo-signer";var Je=[Ke.Bitcoin];function tn({address:e,chain:t}){return Y({address:e,chain:t})!==null}function Hr({phrase:e,derivationPath:t,network:n,seed:r}){let s=r??xt(e),d=Jt.fromMasterSeed(s,n.bip32).derive(t);if(!d.privateKey)throw new U("toolbox_utxo_invalid_params",{error:"Could not derive private key from phrase"});return d.privateKey}function gt(e){return Xr.getPublicKey(e,!0)}function Fe({publicKey:e,chain:t,network:n,scriptType:r}){return dt(t,Ve(r,e,n))}function xe({phrase:e,derivationPath:t,chain:n,wif:r,seed:s}){let a=P(n);if(r){let c=en(a).decode(r),u=gt(c);return{privateKey:c,publicKey:u}}if(!e)throw new U("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let d=t||ke(Br[n]),o=Hr({derivationPath:d,network:a,phrase:e,seed:s}),p=gt(o);return{privateKey:o,publicKey:p}}function Rr(e,t){return en(P(t)).encode(e)}function Er({phrase:e,derivationPath:t,chain:n,seed:r}){let s=t.split("/");if(s.length<4)throw new U("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${s.length}): ${t}`});let a=P(n),d=r??xt(e),o=Jt.fromMasterSeed(d,a.bip32),p=s.slice(0,4).join("/");return o.derive(p)}function Mr(e,t){if(!e||!Kr[e].witness)return!1;return e!==se.P2SH_P2WPKH||!!t}function nn({chain:e,script:t,publicKey:n,network:r}){let s=ut(t);if(s!==se.P2SH_P2WPKH&&s!==se.P2TR)return{};if(!ye(e,s))return{};let a=Ve(s,n,r);if(Ir.compareBytes(a.script,t)!==0)return{};return s===se.P2TR?{tapInternalKey:a.tapInternalKey}:{redeemScript:a.redeemScript}}function Nr(e,t,n){if(!n)return!1;let r=Y({address:e,chain:t}),s=r?Ce(r):void 0;if(!s||!ye(t,s))return!1;let a=dt(t,Ve(s,n,P(t)));return t===Ke.BitcoinCash?z(a)===z(e):a===e}function Zr(e){return e.witnessUtxo?.script??e.nonWitnessUtxo?.outputs[e.index??0]?.script}function bt({chain:e,tx:t,publicKey:n,network:r,indexes:s}){let a=s??Array.from({length:t.inputsLength},(o,p)=>p),d=[];for(let o of a){let p=t.getInput(o),c=Zr(p);if(!c)continue;let{redeemScript:u,tapInternalKey:i}=nn({chain:e,network:r,publicKey:n,script:c}),l={index:o};if(u&&!p.redeemScript)l.redeemScript=u;if(i&&!p.tapInternalKey)l.tapInternalKey=i;if(l.redeemScript||l.tapInternalKey)d.push(l)}return d}function ie({inputs:e,outputs:t,chain:n,tx:r,sender:s,compiledMemo:a,enableRBF:d=!1}){let o=P(n),p=it(n),c=d?Dr:void 0,u=new Set;for(let i of e){let l=`${i.hash}:${i.index}`;if(u.has(l))throw new U("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});u.add(l);let h=typeof i.hash==="string"?ae.decode(i.hash):i.hash,m=i.witnessUtxo?ut(i.witnessUtxo.script):void 0,f=i.publicKey&&i.witnessUtxo?nn({chain:n,network:o,publicKey:i.publicKey,script:i.witnessUtxo.script}):{};if(p&&i.witnessUtxo&&Mr(m,f.redeemScript))r.addInput({...f,index:i.index,sequence:c,txid:h,witnessUtxo:{amount:BigInt(i.witnessUtxo.value),script:i.witnessUtxo.script}});else if(i.txHex)r.addInput({...f,index:i.index,nonWitnessUtxo:ae.decode(i.txHex),sequence:c,txid:h,...n===Ke.BitcoinCash?{sighashType:Qt.ALL}:{}});else throw new U("toolbox_utxo_invalid_params",{error:`Input ${l} cannot be signed from its witnessUtxo alone: it needs its previous transaction (txHex), or — if it is a nested-segwit output — the public key that controls it, which its redeemScript derives from`})}for(let i of t){let l="address"in i&&i.address?i.address:s;if(n===Ke.BitcoinCash)l=G(l);if(i.script)if(a)r.addOutput({amount:0n,script:a});else throw new U("toolbox_utxo_invalid_params",{error:"An output carrying a script needs the compiled memo it carries"});else r.addOutputAddress(l,BigInt(i.value),o)}return{inputs:e,tx:r}}async function be(e){let t=await O(e).getSuggestedTxFee();return{[M.Average]:t,[M.Fast]:Gt(t,M.Fast),[M.Fastest]:Gt(t,M.Fastest)}}async function rn({assetValue:e,recipient:t,memo:n,sender:r,sweep:s,fetchTxHex:a=!1,publicKey:d},o,{forEstimateOnly:p=!1}={}){let c=e.chain,u=Ye(r,c),i=u===se.P2PKH||u===se.P2SH_P2WPKH&&!Nr(r,c,d),l=a||!p&&i,h=e.getBaseValue("number"),m=s?void 0:o??(await be(c))[M.Fastest],f=s||m===void 0?void 0:Math.ceil(h+m*5000);return{inputs:await O(c).getUtxos({address:r,fetchTxHex:l,targetValue:f}),outputs:[{address:t,value:s?0:h},...n?[{address:"",script:R(n),value:0}]:[]]}}async function sn({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s,fetchTxHex:a=!1,enableRBF:d=!1,sweep:o,publicKey:p}){let c=e.chain,u=n?R(n):null,i=await rn({assetValue:e,fetchTxHex:a,memo:n,publicKey:p,recipient:t,sender:s,sweep:o},r),{inputs:l,outputs:h}=E({...i,chain:c,changeAddress:s,feeRate:r,sweep:o});if(!(l&&h))throw new U("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let m=p?l.map((A)=>({...A,publicKey:p})):l,f=new yt({allowUnknownOutputs:!!u,version:1}),{inputs:y,tx:b}=ie({chain:c,compiledMemo:u,enableRBF:d,inputs:m,outputs:h,sender:s,tx:f});return{inputs:y,tx:b,utxos:i.inputs}}async function on({assetValue:e,feeOptionKey:t=M.Fast,feeRate:n,memo:r,sender:s,recipient:a,sweep:d}){let o=e.chain,p,c;if(n!==void 0)p=n,c=Math.floor(n);else{let i=await be(o);p=i[M.Fastest],c=i[t]}let u=await rn({assetValue:e,memo:r,recipient:a,sender:s,sweep:d},p,{forEstimateOnly:!0});return E({...u,chain:o,changeAddress:s,feeRate:c,sweep:d})}function zr(e){return async function({from:n,memo:r,feeRate:s,feeOptionKey:a=M.Fast,recipient:d=n,recipients:o=1}){let p=s??(await be(e))[a],u=(await O(e).getUtxos({address:n,fetchTxHex:!1})).filter((f)=>f.value>Math.max(Be(e),re(f,e)*p));if(!u.length)return mt.from({chain:e});let i=typeof o==="number"?Math.max(o,1):o.length,l=typeof o==="number"||i===0?Array.from({length:i||1},()=>({address:d,value:0})):[...o];if(r)l.push({address:n,script:R(r),value:0});let{outputs:h}=E({chain:e,feeRate:p,inputs:u,outputs:l,sweep:!0}),m=h?.[0]?.value??0;return mt.from({chain:e,value:BigInt(m)})}}function Wr(e){return async function(n){let{fee:r}=await on(n);return mt.from({chain:e,value:kr.fromBigInt(BigInt(r),8).getValue("string")})}}function Lr({chain:e,phrase:t,derivationPath:n,scriptType:r,seed:s}){let a=P(e),{privateKey:d,publicKey:o}=xe({chain:e,derivationPath:n,phrase:t,seed:s}),p=an(e);return{getAddress:()=>Fe({chain:e,network:a,publicKey:o,scriptType:r}),privateKey:d,publicKey:o,signTransaction:(c)=>{for(let{index:u,...i}of bt({chain:e,network:a,publicKey:o,tx:c}))c.updateInput(u,i);return c.sign(d,p),c}}}function an(e){return e===Ke.BitcoinCash?[Qt.ALL]:[Yt.ALL,Yt.DEFAULT]}function $r(e,t){return async function({memo:r,recipient:s,feeOptionKey:a,feeRate:d,assetValue:o,enableRBF:p=!1,sweep:c}){let u=await t?.getAddress();if(!(t&&u))throw new U("toolbox_utxo_no_signer");if(!s)throw new U("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});Fr({condition:p&&!Je.includes(e),id:`rbf_not_supported_${e}`,warning:`RBF (Replace-by-Fee) is not reliably supported on ${e}. Transaction will be created without RBF signaling.`});let i=p&&Je.includes(e),l=d||(await be(e))[a||M.Fast],{tx:h}=await sn({assetValue:o,enableRBF:i,feeRate:l,memo:r,publicKey:t.publicKey,recipient:s,sender:u,sweep:c}),m=await t.signTransaction(h);return m.finalize(),O(e).broadcastTx(ae.encode(m.extract()))}}function cn(e){return(t)=>tn({address:t,chain:e})}function dn(e,{scriptType:t}){let n=P(e);return function(s){if(!s)throw new U("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return Fe({chain:e,network:n,publicKey:s.publicKey,scriptType:t})}}function ce(e){let{chain:t}=e,n=e.phrase?e:void 0,r=n?.phrase,s=n?.index??0,a=r?xt(r):void 0,{derivationPath:d,scriptType:o}=$e({chain:t,derivationPath:n?.derivationPath,index:s,scriptType:e.scriptType}),p=ke(d),c=r?Lr({chain:t,derivationPath:p,phrase:r,scriptType:o,seed:a}):void 0,u=n?void 0:e.signer,i=c||u,l=r?xe({chain:t,derivationPath:p,phrase:r,seed:a}):void 0;function h(){if(i)return i.getAddress();return Promise.resolve(void 0)}function m(T){if(!r)return;let g=ee({accountIndex:T,chain:t,derivationPath:d});return Er({chain:t,derivationPath:ke(g),phrase:r,seed:a})}let f=m();function y(){if(!f)return;return f.publicExtendedKey}function b({accountIndex:T}={}){let g=T===void 0?f:m(T);if(!g)return;let w=ee({accountIndex:T,chain:t,derivationPath:d});return{accountIndex:pe(w),path:ke(w),xpub:g.publicExtendedKey}}function A({accountIndex:T,index:g,change:w=!1}){let _=T===void 0?f:m(T);if(!_)return;let x=Ae({accountIndex:T,chain:t,change:w,derivationPath:d,index:g}),k=P(t),F=_.deriveChild(Number(w)).deriveChild(g);if(!F.publicKey)throw new U("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let X=Fe({chain:t,network:k,publicKey:F.publicKey,scriptType:o}),K=ae.encode(F.publicKey);return{accountIndex:pe(x),address:X,change:w,index:g,path:ke(x),pubkey:K}}async function B(T){if(!Je.includes(t))return{reason:`RBF is not supported on ${t}`,supported:!1};let g=await O(t).getTransactionDetails(T);return{canReplace:g.isRBF&&!g.confirmed,confirmed:g.confirmed,enabled:g.isRBF,fee:g.fee,sequences:g.sequences,supported:!0}}async function W({txid:T,newFeeRate:g,recipient:w,memo:_}){if(!Je.includes(t))throw new U("toolbox_utxo_rbf_not_supported",{chain:t});let x=await O(t).getTransactionDetails(T);if(!x.isRBF)throw new U("toolbox_utxo_tx_not_replaceable",{txid:T});if(x.confirmed)throw new U("toolbox_utxo_tx_already_confirmed",{blockId:x.blockId,txid:T});let k=x.inputs.reduce((v,I)=>v+I.value,0),X=x.outputs.find((v)=>v.recipient===w)?.value||0;if(X===0)throw new U("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let K=await Promise.all(x.inputs.map(async(v)=>{let I=await O(t).getRawTx(v.transaction_hash);return{address:v.recipient,hash:v.transaction_hash,index:v.index,publicKey:l?.publicKey,txHex:I,value:v.value,witnessUtxo:void 0}})),D=_?R(_):null,J=k-X-x.fee,Pe=await h(),ue=[];if(D)ue.push({address:"",script:D,value:0});if(J>Be(t)&&Pe)ue.push({address:Pe,value:J});let He=ge({chain:t,inputs:K.map((v)=>({...v,type:Ye(v.address,t)})),outputs:[{address:w,value:X},...ue]}),V=Math.ceil(He*g);if(V<=x.fee)throw new U("toolbox_utxo_rbf_fee_too_low",{newFee:V,originalFee:x.fee});let Ue=V-x.fee,Q=X-Ue;if(Q<=0)throw new U("toolbox_utxo_rbf_insufficient_change");let ve=new yt({allowUnknownOutputs:!!D,version:1}),tt=[{address:w,value:Q},...ue];return ie({chain:t,compiledMemo:D,inputs:K,outputs:tt,sender:Pe||w,tx:ve}),{feeDelta:Ue,newFee:V,originalFee:x.fee,tx:ve}}async function Ie({txid:T,newFeeRate:g,recipient:w,memo:_}){let{tx:x,originalFee:k,newFee:F}=await W({memo:_,newFeeRate:g,recipient:w,txid:T}),X=await et(x);X.finalize();let K=await O(t).broadcastTx(ae.encode(X.extract()));return{newFee:F,originalFee:k,txid:K}}function vt({accountIndex:T,index:g,change:w=!1}){Z("index",g);let _=T===void 0?f:m(T);if(!_)return;return _.deriveChild(Number(w)).deriveChild(g).privateKey||void 0}function At({tx:T,inputDerivations:g}){if(!f)throw new U("toolbox_utxo_no_signer");let w=an(t),_=P(t);for(let x=0;x<g.length;x++){let k=g[x];if(!k)continue;let{derivationIndex:F,isChange:X}=k,K=vt({change:X,index:F});if(!K)throw new U("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${x} at index ${F}`});for(let{index:D,...J}of bt({chain:t,indexes:[x],network:_,publicKey:gt(K),tx:T}))T.updateInput(D,J);T.signIdx(K,x,w)}return T}async function vn({utxos:T,recipient:g,assetValue:w,memo:_,feeRate:x,feeOptionKey:k,changeAddress:F,sweep:X}){if(X)throw new U("toolbox_utxo_invalid_params",{error:"Sweep is not supported for transfers from multiple addresses"});if(!f)throw new U("toolbox_utxo_no_signer");let K=x||(await be(t))[k||M.Fast],D=_?R(_):null,J=[{address:g,value:w.getBaseValue("number")}];if(D)J.push({address:"",script:D,value:0});let Pe=T.map(({address:v,hash:I,index:q,value:nt,txHex:On,witnessUtxo:rt})=>({address:v,hash:I,index:q,txHex:On,value:nt,witnessUtxo:rt?{script:rt.script,value:rt.value}:void 0})),ue=T[0]?.address,He=F||await h()||ue||g,{inputs:V,outputs:Ue}=E({chain:t,changeAddress:He,feeRate:K,inputs:Pe,outputs:J});if(!(V&&Ue))throw new U("toolbox_utxo_insufficient_balance",{assetValue:w,sender:"multiple addresses"});let Q=new yt({allowUnknownOutputs:!!D,version:1}),ve=V.map((v)=>{let I=T.find((q)=>q.hash===v.hash&&q.index===v.index);return I?{derivationIndex:I.derivationIndex,isChange:I.isChange}:{derivationIndex:0,isChange:!1}}),tt=V.map((v,I)=>{let q=ve[I],nt=q?f.deriveChild(Number(q.isChange)).deriveChild(q.derivationIndex).publicKey:null;return{...v,publicKey:nt??void 0}});return ie({chain:t,compiledMemo:D,inputs:tt,outputs:Ue,sender:He,tx:Q}),At({inputDerivations:ve,tx:Q}),Q.finalize(),O(t).broadcastTx(ae.encode(Q.extract()))}function An({address:T,gapLimit:g=20}){if(!f)return;for(let w=0;w<g;w++){let _=A({change:!1,index:w}),x=A({change:!0,index:w}),k=_?.address===T?!1:x?.address===T;if(_?.address===T||x?.address===T)return{change:k,index:w}}return}function et(T){if(!i)throw new U("toolbox_utxo_no_signer");return i.signTransaction(T)}async function _n(T){let g=await et(T);return g.finalize(),await O(t).broadcastTx(ae.encode(g.extract()))}return{accumulative:E,broadcastTx:(T)=>O(t).broadcastTx(T),bumpFee:Ie,calculateTxSize:(T)=>ge({...T,chain:t}),createKeysForPath:(T)=>xe({...T,chain:t}),createReplacementTransaction:W,createTransaction:(T)=>sn({publicKey:l?.publicKey,...T}),deriveAddressAtIndex:A,derivePrivateKeyAtIndex:vt,estimateMaxSendableAmount:zr(t),estimateTransactionFee:Wr(t),getAddress:h,getAddressFromKeys:dn(t,{scriptType:o}),getAddressType:(T)=>Y({address:T,chain:t}),getBalance:jt(t),getExtendedPublicKey:y,getExtendedPublicKeyInfo:b,getFeeRates:()=>be(t),getInputsOutputsFee:on,getNetworkForChain:()=>P(t),getPrivateKeyFromMnemonic:(T)=>Rr(xe({...T,chain:t}).privateKey,t),isRBFEnabled:B,keys:l,resolveDerivationIndex:An,scriptType:o,signAndBroadcastTransaction:_n,signTransaction:et,signTransactionWithMultipleKeys:At,transfer:$r(t,i),transferFromMultipleAddresses:vn,validateAddress:cn(t)}}import{getZcashAddressType as Vr,validateZcashAddress as wt}from"@swapkit/utxo-signer";function De(e){return Oe(e)!==null}var N=qr.BitcoinCash;function Qe(e){return z(Me(e))}function es(e){let t=P(N);function n(s){return s.sign(e.privateKey,[Jr.ALL]),s}function r(){let s=fn(e.publicKey,t);if(!s.hash)throw new L("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let a=hn({hash:s.hash,prefix:pn.MAINNET,type:ln.P2PKH});return Promise.resolve(a.replace(/^bitcoincash:/,""))}return{getAddress:r,signTransaction:n}}function mn(e={}){let t="phrase"in e?e.phrase:void 0,n="index"in e?e.index||0:0,r="derivationPath"in e?e.derivationPath:void 0,s=jr({chain:N,derivationPath:r,index:n}),a=Gr(s),d=t?xe({chain:N,derivationPath:a,phrase:t}):void 0,o=d?es(d):("signer"in e)?e.signer:void 0;function p(){return Promise.resolve(o?.getAddress())}let c="scriptType"in e?e.scriptType:void 0,{getBalance:u,getFeeRates:i,broadcastTx:l,...h}=ce(t?{chain:N,index:n,phrase:t,...r?{derivationPath:r,scriptType:c}:{scriptType:c}}:{chain:N,scriptType:c});function m(b,A=!0){return u(z(Me(b)))}function f(b){if(!o)throw new L("toolbox_utxo_no_signer");return o.signTransaction(b)}async function y(b){let A=await f(b);return A.finalize(),await l(un.encode(A.extract()))}return{...h,broadcastTx:l,buildTx:ns,createTransaction:yn,getAddress:p,getAddressFromKeys:rs,getBalance:m,getFeeRates:i,signAndBroadcastTransaction:y,signTransaction:f,stripPrefix:z,stripToCashAddress:Qe,transfer:ts({broadcastTx:l,getFeeRates:i,signer:o}),validateAddress:De}}async function yn({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s,sweep:a}){if(!De(t))throw new L("toolbox_utxo_invalid_address",{address:t});let d=Math.ceil(e.getBaseValue("number")+r*7500),o=await O(N).getUtxos({address:Qe(s),fetchTxHex:!0,targetValue:a?void 0:d}),p=n?R(n):null,c=[],u=G(t);if(c.push({address:u,value:a?0:e.getBaseValue("number")}),p)c.push({script:p,value:0});let{inputs:i,outputs:l}=E({chain:N,feeRate:r,inputs:o,outputs:c,sweep:a});if(!(i&&l))throw new L("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let h=new Tn({allowUnknownOutputs:!!p,version:1}),m=G(s),{inputs:f,tx:y}=ie({chain:N,compiledMemo:p,inputs:i,outputs:l.map((b)=>("address"in b)&&b.address?{...b,address:G(b.address)}:b),sender:m,tx:h});return{inputs:f,tx:y,utxos:i}}function ts({broadcastTx:e,getFeeRates:t,signer:n}){return async function({recipient:s,assetValue:a,feeOptionKey:d=Yr.Fast,sweep:o,...p}){let c=await n?.getAddress();if(!(n&&c))throw new L("toolbox_utxo_no_signer");if(!s)throw new L("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let u=p.feeRate||(await t())[d],{tx:i}=await yn({...p,assetValue:a,feeRate:u,recipient:s,sender:c,sweep:o}),l=await n.signTransaction(i);return l.finalize(),e(un.encode(l.extract()))}}async function ns({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s}){let a=Me(t);if(!De(a))throw new L("toolbox_utxo_invalid_address",{address:a});let d=Math.ceil(e.getBaseValue("number")+r*7500),o=await O(N).getUtxos({address:Qe(s),fetchTxHex:!0,targetValue:d}),p=Number(r.toFixed(0)),c=n?R(n):null,u=[];if(u.push({address:G(t),value:e.getBaseValue("number")}),c)u.push({script:c,value:0});let{inputs:i,outputs:l}=E({chain:N,feeRate:p,inputs:o,outputs:u});if(!(i&&l))throw new L("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let h=new Tn({allowUnknownOutputs:!!c,version:1}),{inputs:m,tx:f}=ie({chain:N,compiledMemo:c,inputs:i,outputs:l,sender:G(s),tx:h});return{inputs:m,tx:f,utxos:o}}function rs(e){let t=Qr.bitcoinCash,n=fn(e.publicKey,t);if(!n.hash)throw new L("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return hn({hash:n.hash,prefix:pn.MAINNET,type:ln.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as ss,hex as os}from"@scure/base";import{HDKey as bn}from"@scure/bip32";import{mnemonicToSeedSync as wn}from"@scure/bip39";import{Chain as j,derivationPathToString as as,FeeOption as is,SwapKitError as de}from"@swapkit/helpers";import{Address as cs,createZcashTransaction as ds,getZcashConsensusBranchId as us,isTransparentZcashAddress as gn,OutScript as ps,PCZT as ls,utils as Pn,WIF as hs,ZcashConsensusBranchId as fs,ZcashPSBT as Ts,ZcashSigHash as Pt,ZcashVersionGroupId as ms}from"@swapkit/utxo-signer";import{match as ys,P as Ut}from"ts-pattern";var gs=ss(Pn.sha256);function xs(e){return gs.encode(e)}function bs({phrase:e,derivationPath:t}){let n=wn(e),s=bn.fromMasterSeed(n).derive(t);if(!s.privateKey||!s.publicKey)throw new de("toolbox_utxo_invalid_params");let{privateKey:a,publicKey:d}=s,o=Pn.hash160(d),p=new Uint8Array([28,184]),c=new Uint8Array(p.length+o.length);c.set(p,0),c.set(o,p.length);let u=xs(c);return{getAddress:()=>Promise.resolve(u),signTransaction:(i)=>{if(i instanceof Ts){let l=i.toPCZT();return l.signAllInputs(a,d,Pt.ALL),l.finalizeAllInputs(),Promise.resolve(l.extract())}if(i instanceof ls)return i.signAllInputs(a,d,Pt.ALL),i.finalizeAllInputs(),Promise.resolve(i.extract());return i.signAllInputs(a,d,Pt.ALL),Promise.resolve(i)}}}function ws({inputs:e,outputs:t,tx:n,sender:r,compiledMemo:s}){let a=P(j.Zcash);for(let d of e){let o=cs(a).decode(r),p=ps.encode(o);n.addInput({index:d.index,script:p,sequence:4294967295,txid:os.decode(d.hash),value:BigInt(d.value)})}for(let d of t){let o="address"in d&&d.address?d.address:r,p=d.script;if(p&&!s)continue;if(p&&s)n.addOutput({amount:0n,script:s});else n.addOutputAddress(o,BigInt(d.value),a)}return{inputs:e,tx:n}}async function Ps(){try{let e=await O(j.Zcash).getBlockHeight();return us(e+1)}catch{return fs.IRONWOOD}}async function xn(e){let{assetValue:t,recipient:n,memo:r,feeRate:s,sender:a,fetchTxHex:d,sweep:o}=e,p=P(j.Zcash);if(!gn(a,p))throw new de("toolbox_utxo_invalid_address",{address:a});if(!gn(n,p))throw new de("toolbox_utxo_invalid_address",{address:n,error:"Zcash transaction creation currently supports transparent addresses only"});let c=r?R(r):null,u=await O(j.Zcash).getUtxos({address:a,fetchTxHex:d!==!1}),i=[{address:n,value:o?0:Number(t.getBaseValue("string"))},...c?[{script:c,value:0}]:[]],{inputs:l,outputs:h}=E({chain:j.Zcash,changeAddress:a,feeRate:s,inputs:u,outputs:i,sweep:o});if(!(l&&h))throw new de("toolbox_utxo_insufficient_balance",{assetValue:t,sender:a});let m=ds({consensusBranchId:await Ps(),expiryHeight:0,lockTime:0,version:4,versionGroupId:ms.SAPLING}),{tx:f,inputs:y}=ws({compiledMemo:c,inputs:l,outputs:h,sender:a,tx:m});return{inputs:y,outputs:h,tx:f}}function Un(e={}){let t="scriptType"in e?e.scriptType:void 0,n=ys(e).with({signer:Ut.not(Ut.nullish)},({signer:c})=>c).with({phrase:Ut.string},({phrase:c,derivationPath:u,index:i=0})=>{let{derivationPath:l}=$e({chain:j.Zcash,derivationPath:u,index:i,scriptType:t}),h=as(l);return bs({derivationPath:h,phrase:c})}).otherwise(()=>{return}),r=ce({chain:j.Zcash,scriptType:t,signer:n});async function s(c){if(!n)throw new de("toolbox_utxo_no_signer");return await n.signTransaction(c)}async function a(c){let u=await s(c);return r.broadcastTx(u.toHex())}async function d({recipient:c,assetValue:u,feeOptionKey:i=is.Fast,sweep:l,...h}){let m=await n?.getAddress();if(!(n&&m))throw new de("toolbox_utxo_no_signer");let f=h.feeRate||(await r.getFeeRates())[i],{tx:y}=await xn({...h,assetValue:u,feeRate:f,recipient:c,sender:m,sweep:l}),A=(await n.signTransaction(y)).toHex();return r.broadcastTx(A)}function o({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let i=wn(c),h=bn.fromMasterSeed(i).derive(u);if(!h.privateKey||!h.publicKey)throw new de("toolbox_utxo_invalid_params");return{privateKey:h.privateKey,publicKey:h.publicKey}}function p({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let i=o({derivationPath:u,phrase:c}),l=P(j.Zcash);return hs(l).encode(i.privateKey)}return{...r,createKeysForPath:o,createTransaction:xn,getPrivateKeyFromMnemonic:p,signAndBroadcastTransaction:a,signTransaction:s,transfer:d,validateAddress:wt}}import{hex as Us}from"@scure/base";import{HDKey as vs}from"@scure/bip32";import{derivationPathToString as As,NetworkDerivationPath as _s,updateDerivationPath as Os}from"@swapkit/helpers";function Ss({xpub:e,chain:t,count:n,startIndex:r=0,accountIndex:s,purpose:a,scriptType:d}){if(Z("count",n),n<1)throw RangeError("count must be at least 1");Z("startIndex",r),Le(t,d),ct({chain:t,purpose:a,scriptType:d});let o=P(t),p=vs.fromExtendedKey(e,o.bip32),c=a===void 0?void 0:Os(_s[t],{purpose:a}),u=ee({accountIndex:s,chain:t,derivationPath:c}),i=pe(u),l=[];for(let h of[!1,!0]){let m=p.deriveChild(Number(h));for(let f=0;f<n;f++){let y=r+f,b=m.deriveChild(y);if(!b.publicKey)continue;let A=Ae({accountIndex:s,chain:t,change:h,derivationPath:c,index:y});l.push({accountIndex:i,address:Fe({chain:t,network:o,publicKey:b.publicKey,scriptType:d}),change:h,index:y,pubkey:Us.encode(b.publicKey),...a===void 0?{}:{path:As(A)}})}}return l}function ma(e,t){switch(e){case we.BitcoinCash:return mn(t||{});case we.Zcash:return Un(t);case we.Bitcoin:case we.Dogecoin:case we.Litecoin:case we.Dash:return ce({chain:e,...t});default:throw new Cs("toolbox_utxo_not_supported",{chain:e})}}export{qt as InputSizes,po as MIN_TX_FEE,Sr as OP_RETURN_OVERHEAD,pt as OutputSizes,Or as SEGWIT_MARKER_FLAG_WEIGHT,lt as TX_OVERHEAD,se as UTXOScriptType,Dt as UtxoNetwork,E as accumulative,ie as addInputsAndOutputs,dn as addressFromKeysGetter,Z as assertDerivationIndex,ge as calculateTxSize,R as compileMemo,mn as createBCHToolbox,Ds as createCustomUtxoApi,Cn as createHDWalletHelpers,ce as createUTXOToolbox,Un as createZcashToolbox,Ss as deriveAddressesFromXpub,Ls as detectAddressNetwork,Oe as getBchAddressType,Be as getDustThreshold,Xe as getInputScriptType,re as getInputSize,bt as getMissingSpendingMetadata,P as getNetworkForChain,je as getOutputSize,Cr as getOutputSizeForAddress,Ye as getScriptTypeForAddress,pe as getUTXOAccountIndexFromPath,ee as getUTXOAccountPath,Ae as getUTXOAddressPath,cn as getUTXOAddressValidator,Y as getUtxoAddressType,O as getUtxoApi,Is as getUtxoNetwork,ma as getUtxoToolbox,ft as getWitnessOverhead,Vr as getZcashAddressType,ht as isSegwitScriptType,Ws as isValidAddress,Zt as nonSegwitChains,z as stripPrefix,Qe as stripToCashAddress,Me as toCashAddress,G as toLegacyAddress,Ne as tryDecodeAddress,De as validateBchAddress,tn as validateUtxoAddress,wt as validateZcashAddress};
|
|
@@ -218,4 +218,5 @@ export declare const isEIP7702Transaction: (tx: EVMTxParams) => boolean;
|
|
|
218
218
|
export declare const isEIP1559Transaction: (tx: EVMTxParams) => boolean;
|
|
219
219
|
type EVMTxType = "eip7702" | "eip1559" | "legacy";
|
|
220
220
|
export declare const getEVMTxType: (tx: EVMTxParams, isEIP1559Compatible?: boolean) => EVMTxType;
|
|
221
|
+
export declare function maxBigInt(first: bigint, second: bigint): bigint;
|
|
221
222
|
export {};
|
|
@@ -2,6 +2,14 @@ import { Chain, FeeOption } from "@swapkit/helpers";
|
|
|
2
2
|
import type { Authorization, TransactionRequest } from "ethers";
|
|
3
3
|
import { Contract } from "ethers";
|
|
4
4
|
import type { EVMToolboxParams } from "../types";
|
|
5
|
+
export declare function scaleEIP1559Fees({ feeOption, maxFeePerGas, maxPriorityFeePerGas, }: {
|
|
6
|
+
feeOption: FeeOption;
|
|
7
|
+
maxFeePerGas: bigint;
|
|
8
|
+
maxPriorityFeePerGas: bigint;
|
|
9
|
+
}): {
|
|
10
|
+
maxFeePerGas: bigint;
|
|
11
|
+
maxPriorityFeePerGas: bigint;
|
|
12
|
+
};
|
|
5
13
|
export declare function createOPStackToolbox(chain: Chain.Optimism | Chain.Base | Chain.Unichain): ({ provider, ...toolboxSignerParams }: EVMToolboxParams) => {
|
|
6
14
|
estimateL1Gas: (tx: TransactionRequest) => Promise<any>;
|
|
7
15
|
estimateL1GasCost: (tx: TransactionRequest) => Promise<bigint | undefined>;
|
|
@@ -31,8 +31,6 @@ export declare function getNearToolbox(toolboxParams?: NearToolboxParams): {
|
|
|
31
31
|
createContractFunctionCall: ({ args, attachedDeposit, contractId, gas, methodName, sender: accountId, }: ContractFunctionCallParams) => Promise<Transaction>;
|
|
32
32
|
createSubAccount: (subAccountId: string, publicKey: string, initialBalance: string) => Promise<string>;
|
|
33
33
|
createTransaction: ({ recipient, assetValue, memo, attachedDeposit, sender, functionCall, sweep, }: NearCreateTransactionParams) => Promise<Transaction>;
|
|
34
|
-
/** @deprecated Use `estimateGasLimit` instead */
|
|
35
|
-
estimateGas: (params: NearGasEstimateParams, account?: Account) => Promise<AssetValue>;
|
|
36
34
|
estimateGasLimit: (params: NearGasEstimateParams, account?: Account) => Promise<AssetValue>;
|
|
37
35
|
estimateTransactionFee: (params: NearTransferParams | NearGasEstimateParams, protocolConfigParam?: NearProtocolConfig) => Promise<AssetValue>;
|
|
38
36
|
executeBatchTransaction: (batch: BatchTransaction) => Promise<string>;
|
|
@@ -43,8 +43,6 @@ export interface NearToolbox {
|
|
|
43
43
|
createContract: <T extends Contract = Contract>(contractInterface: NearContractInterface) => Promise<T>;
|
|
44
44
|
executeBatchTransaction: (batch: BatchTransaction) => Promise<string>;
|
|
45
45
|
getGasPrice: () => Promise<string>;
|
|
46
|
-
/** @deprecated Use `estimateGasLimit` instead */
|
|
47
|
-
estimateGas: (params: NearGasEstimateParams, account?: Account) => Promise<AssetValue>;
|
|
48
46
|
estimateGasLimit: (params: NearGasEstimateParams, account?: Account) => Promise<AssetValue>;
|
|
49
47
|
serializeTransaction: (params: Transaction) => string;
|
|
50
48
|
}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import { type DerivationPathArray } from "@swapkit/helpers";
|
|
1
|
+
import { type DerivationPathArray, UTXOScriptType } from "@swapkit/helpers";
|
|
2
2
|
import { Transaction } from "@swapkit/utxo-signer";
|
|
3
3
|
export declare const TEST_PHRASE = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
|
|
4
4
|
export declare const RECIPIENT = "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu";
|
|
5
5
|
export declare const CHANGE_ADDRESS = "bc1qnjg0jd8228aq7egyzacy8cys3knf9xvrerkf9g";
|
|
6
6
|
export declare const HASH = "0000000000000000000000000000000000000000000000000000000000000001";
|
|
7
|
-
export type FlowScriptType = "legacy" | "segwit";
|
|
7
|
+
export type FlowScriptType = "legacy" | "segwit" | "nested" | "taproot";
|
|
8
8
|
export declare const PATHS: Record<FlowScriptType, DerivationPathArray>;
|
|
9
|
+
export declare const SCRIPT_TYPES: Record<FlowScriptType, UTXOScriptType>;
|
|
9
10
|
export declare const ADDRESSES: Record<FlowScriptType, string>;
|
|
10
11
|
export declare function previousTransaction(script: Uint8Array, value: number, salt?: number): string;
|
|
11
12
|
export declare function txidOf(rawTx: string): string;
|
|
@@ -37,7 +38,6 @@ export declare function installMockApi(utxos: {
|
|
|
37
38
|
};
|
|
38
39
|
export declare function scriptFor(scriptType: FlowScriptType, publicKey: Uint8Array): import("@swapkit/utxo-signer/utils").Bytes;
|
|
39
40
|
export declare function toolboxFor(scriptType: FlowScriptType): {
|
|
40
|
-
address: string;
|
|
41
41
|
publicKey: Uint8Array<ArrayBufferLike>;
|
|
42
42
|
script: import("@swapkit/utxo-signer/utils").Bytes;
|
|
43
43
|
toolbox: {
|
|
@@ -48,7 +48,7 @@ export declare function toolboxFor(scriptType: FlowScriptType): {
|
|
|
48
48
|
originalFee: number;
|
|
49
49
|
txid: string;
|
|
50
50
|
}>;
|
|
51
|
-
calculateTxSize: (
|
|
51
|
+
calculateTxSize: (params: Omit<import("../..").UTXOCalculateTxSizeParams, "chain">) => number;
|
|
52
52
|
createKeysForPath: (params: {
|
|
53
53
|
wif?: string;
|
|
54
54
|
phrase?: string;
|
|
@@ -58,7 +58,7 @@ export declare function toolboxFor(scriptType: FlowScriptType): {
|
|
|
58
58
|
publicKey: Uint8Array<ArrayBufferLike> & Uint8Array<ArrayBuffer>;
|
|
59
59
|
};
|
|
60
60
|
createReplacementTransaction: ({ txid, newFeeRate, recipient, memo, }: import("../..").RBFTransactionParams) => Promise<import("../../toolbox/utxo").ReplacementTransactionResult>;
|
|
61
|
-
createTransaction: (
|
|
61
|
+
createTransaction: (params: import("../..").UTXOBuildTxParams) => Promise<{
|
|
62
62
|
inputs: import("../..").UTXOType[];
|
|
63
63
|
tx: Transaction;
|
|
64
64
|
utxos: {
|
|
@@ -154,6 +154,7 @@ export declare function toolboxFor(scriptType: FlowScriptType): {
|
|
|
154
154
|
change: boolean;
|
|
155
155
|
index: number;
|
|
156
156
|
} | undefined;
|
|
157
|
+
scriptType: UTXOScriptType;
|
|
157
158
|
signAndBroadcastTransaction: (tx: InstanceType<typeof Transaction>) => Promise<string>;
|
|
158
159
|
signTransaction: (tx: InstanceType<typeof Transaction>) => Transaction | Promise<Transaction>;
|
|
159
160
|
signTransactionWithMultipleKeys: ({ tx, inputDerivations, }: {
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type UTXOChain } from "@swapkit/helpers";
|
|
2
|
+
export declare function stripPrefix(address: string): string;
|
|
3
|
+
export declare function getBchAddressType(address: string): "pkh" | "sh" | null;
|
|
4
|
+
export declare function getUtxoAddressType({ address, chain }: {
|
|
5
|
+
address: string;
|
|
6
|
+
chain: UTXOChain;
|
|
7
|
+
}): "pkh" | "sh" | "sprout" | "sapling" | "unified" | "wpkh" | "wsh" | "tr" | null;
|
|
8
|
+
export type UtxoAddressType = NonNullable<ReturnType<typeof getUtxoAddressType>>;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type DerivationPathArray, type UTXOChain, UTXOScriptType } from "@swapkit/helpers";
|
|
2
|
+
import { type AddressScriptType, type BTCNetwork } from "@swapkit/utxo-signer";
|
|
3
|
+
import type { UtxoAddressType } from "./addressType";
|
|
4
|
+
export declare const SUPPORTED_SCRIPT_TYPES: Readonly<Record<UTXOChain, readonly UTXOScriptType[]>>;
|
|
5
|
+
export declare function getSupportedScriptTypes(chain: UTXOChain): readonly UTXOScriptType[];
|
|
6
|
+
export declare function chainSupportsSegwit(chain: UTXOChain): boolean;
|
|
7
|
+
export declare function isScriptTypeSupported(chain: UTXOChain, scriptType: UTXOScriptType): boolean;
|
|
8
|
+
export declare function assertScriptTypeSupported(chain: UTXOChain, scriptType: UTXOScriptType): UTXOScriptType;
|
|
9
|
+
export declare const nonSegwitChains: UTXOChain[];
|
|
10
|
+
export declare function isStandardEncoding({ purpose, scriptType }: {
|
|
11
|
+
purpose?: number;
|
|
12
|
+
scriptType: UTXOScriptType;
|
|
13
|
+
}): boolean;
|
|
14
|
+
export declare function warnOffStandardEncoding({ chain, purpose, scriptType, }: {
|
|
15
|
+
chain: UTXOChain;
|
|
16
|
+
purpose?: number;
|
|
17
|
+
scriptType: UTXOScriptType;
|
|
18
|
+
}): void;
|
|
19
|
+
export declare function resolveUTXODerivation({ chain, derivationPath, index, scriptType, }: {
|
|
20
|
+
chain: UTXOChain;
|
|
21
|
+
derivationPath?: DerivationPathArray;
|
|
22
|
+
index?: number;
|
|
23
|
+
scriptType?: UTXOScriptType;
|
|
24
|
+
}): {
|
|
25
|
+
derivationPath: DerivationPathArray;
|
|
26
|
+
scriptType: UTXOScriptType;
|
|
27
|
+
};
|
|
28
|
+
export type UTXOAddressAndScripts = {
|
|
29
|
+
address: string;
|
|
30
|
+
script: Uint8Array;
|
|
31
|
+
redeemScript?: Uint8Array;
|
|
32
|
+
tapInternalKey?: Uint8Array;
|
|
33
|
+
};
|
|
34
|
+
export declare function toXOnlyPublicKey(publicKey: Uint8Array): Uint8Array<ArrayBufferLike>;
|
|
35
|
+
export declare function deriveAddressAndScripts(scriptType: UTXOScriptType, publicKey: Uint8Array, network: BTCNetwork): UTXOAddressAndScripts;
|
|
36
|
+
export declare function formatAddress(chain: UTXOChain, derived: UTXOAddressAndScripts): string;
|
|
37
|
+
export declare const OUTPUT_SIZE_BY_ADDRESS_TYPE: Readonly<Record<AddressScriptType, number>>;
|
|
38
|
+
export declare function getOutputSizeForAddressType(addressType: UtxoAddressType): number | undefined;
|
|
39
|
+
export declare function getScriptTypeForAddressType(addressType: UtxoAddressType): UTXOScriptType | undefined;
|
|
40
|
+
export declare function classifyScript(script: Uint8Array): UTXOScriptType | undefined;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { UTXOScriptType } from "@swapkit/helpers";
|
|
1
|
+
import { type UTXOChain, UTXOScriptType } from "@swapkit/helpers";
|
|
2
2
|
import type { TargetOutput, UTXOCalculateTxSizeParams, UTXOInputWithScriptType, UTXOSizeInput, UTXOType } from "../types";
|
|
3
3
|
/**
|
|
4
4
|
* Minimum transaction fee
|
|
@@ -14,10 +14,11 @@ export { UTXOScriptType } from "@swapkit/helpers";
|
|
|
14
14
|
export declare const InputSizes: Record<UTXOScriptType, number>;
|
|
15
15
|
export declare const OutputSizes: Record<UTXOScriptType, number>;
|
|
16
16
|
export declare const isSegwitScriptType: (scriptType: UTXOScriptType) => boolean;
|
|
17
|
-
export declare const getScriptTypeForAddress: (address: string) => UTXOScriptType
|
|
18
|
-
export declare const
|
|
19
|
-
export declare const
|
|
20
|
-
export declare const
|
|
17
|
+
export declare const getScriptTypeForAddress: (address: string, chain: UTXOChain) => UTXOScriptType;
|
|
18
|
+
export declare const getOutputSizeForAddress: (address: string, chain: UTXOChain) => number;
|
|
19
|
+
export declare const calculateTxSize: ({ chain, inputs, outputs, feeRate }: UTXOCalculateTxSizeParams) => number;
|
|
20
|
+
export declare const getInputScriptType: (input: UTXOInputWithScriptType | UTXOType | UTXOSizeInput, chain: UTXOChain) => UTXOScriptType;
|
|
21
|
+
export declare const getInputSize: (input: UTXOInputWithScriptType | UTXOType | UTXOSizeInput, chain: UTXOChain) => number;
|
|
21
22
|
/** BIP-141: marker/flag plus one empty witness-stack byte for each legacy input in a witness transaction. */
|
|
22
23
|
export declare const getWitnessOverhead: (hasWitness: boolean, legacyInputCount: number) => number;
|
|
23
|
-
export declare const getOutputSize: (output: TargetOutput, scriptType?: UTXOScriptType) => number;
|
|
24
|
+
export declare const getOutputSize: (output: TargetOutput, chain: UTXOChain, scriptType?: UTXOScriptType) => number;
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import { type UTXOChain } from "@swapkit/helpers";
|
|
1
|
+
import { type UTXOChain, type UTXOScriptType } from "@swapkit/helpers";
|
|
2
2
|
import type { DerivedAddress, HDWalletAccountParams } from "../types";
|
|
3
3
|
export type DeriveAddressesFromXpubParams = HDWalletAccountParams & {
|
|
4
4
|
xpub: string;
|
|
5
5
|
chain: UTXOChain;
|
|
6
6
|
count: number;
|
|
7
7
|
startIndex?: number;
|
|
8
|
+
purpose?: number;
|
|
9
|
+
scriptType: UTXOScriptType;
|
|
8
10
|
};
|
|
9
|
-
export declare function deriveAddressesFromXpub({ xpub, chain, count, startIndex, accountIndex, }: DeriveAddressesFromXpubParams): DerivedAddress[];
|
|
11
|
+
export declare function deriveAddressesFromXpub({ xpub, chain, count, startIndex, accountIndex, purpose, scriptType, }: DeriveAddressesFromXpubParams): DerivedAddress[];
|
|
@@ -2,6 +2,6 @@ export * from "./hdWallet";
|
|
|
2
2
|
export * from "./helpers";
|
|
3
3
|
export * from "./toolbox";
|
|
4
4
|
export * from "./toolbox/bitcoinCash";
|
|
5
|
-
export { addInputsAndOutputs, addressFromKeysGetter, createUTXOToolbox, getNetworkForChain, getUTXOAddressValidator, getUtxoAddressType, nonSegwitChains, type UtxoAddressType, validateUtxoAddress, } from "./toolbox/utxo";
|
|
5
|
+
export { addInputsAndOutputs, addressFromKeysGetter, createUTXOToolbox, getMissingSpendingMetadata, getNetworkForChain, getUTXOAddressValidator, getUtxoAddressType, nonSegwitChains, type UtxoAddressType, validateUtxoAddress, } from "./toolbox/utxo";
|
|
6
6
|
export * from "./toolbox/zcash";
|
|
7
7
|
export * from "./types";
|
|
@@ -1,15 +1,11 @@
|
|
|
1
|
-
import { Chain,
|
|
1
|
+
import { Chain, FeeOption } from "@swapkit/helpers";
|
|
2
2
|
import { Transaction } from "@swapkit/utxo-signer";
|
|
3
3
|
import { accumulative } from "../helpers";
|
|
4
4
|
import type { TargetOutput, UTXOBuildTxParams, UTXOTransferParams, UTXOType } from "../types";
|
|
5
|
-
import type { UtxoToolboxParams } from "./params";
|
|
5
|
+
import type { UTXOToolboxDerivationParams, UtxoToolboxParams } from "./params";
|
|
6
6
|
import { stripPrefix, validateBchAddress } from "./validators";
|
|
7
7
|
export declare function stripToCashAddress(address: string): string;
|
|
8
|
-
export declare function createBCHToolbox<T extends typeof Chain.BitcoinCash>(toolboxParams
|
|
9
|
-
phrase?: string;
|
|
10
|
-
derivationPath?: DerivationPathArray;
|
|
11
|
-
index?: number;
|
|
12
|
-
}): {
|
|
8
|
+
export declare function createBCHToolbox<T extends typeof Chain.BitcoinCash>(toolboxParams?: UtxoToolboxParams[T] | UTXOToolboxDerivationParams): {
|
|
13
9
|
broadcastTx: (txHash: string) => Promise<string>;
|
|
14
10
|
buildTx: typeof buildTx;
|
|
15
11
|
createTransaction: typeof createTransaction;
|
|
@@ -33,7 +29,7 @@ export declare function createBCHToolbox<T extends typeof Chain.BitcoinCash>(too
|
|
|
33
29
|
originalFee: number;
|
|
34
30
|
txid: string;
|
|
35
31
|
}>;
|
|
36
|
-
calculateTxSize: (
|
|
32
|
+
calculateTxSize: (params: Omit<import("..").UTXOCalculateTxSizeParams, "chain">) => number;
|
|
37
33
|
createKeysForPath: (params: {
|
|
38
34
|
wif?: string;
|
|
39
35
|
phrase?: string;
|
|
@@ -114,6 +110,7 @@ export declare function createBCHToolbox<T extends typeof Chain.BitcoinCash>(too
|
|
|
114
110
|
change: boolean;
|
|
115
111
|
index: number;
|
|
116
112
|
} | undefined;
|
|
113
|
+
scriptType: import("@swapkit/helpers").UTXOScriptType;
|
|
117
114
|
signTransactionWithMultipleKeys: ({ tx, inputDerivations, }: {
|
|
118
115
|
tx: InstanceType<typeof Transaction>;
|
|
119
116
|
inputDerivations: import("..").InputDerivation[];
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { Chain, type
|
|
1
|
+
import { Chain, type UTXOChain } from "@swapkit/helpers";
|
|
2
2
|
import { createBCHToolbox } from "./bitcoinCash";
|
|
3
|
-
import type { UtxoToolboxParams } from "./params";
|
|
3
|
+
import type { UTXOToolboxDerivationParams, UtxoToolboxParams } from "./params";
|
|
4
4
|
import { createUTXOToolbox } from "./utxo";
|
|
5
5
|
import { createZcashToolbox } from "./zcash";
|
|
6
6
|
type BCHToolbox = ReturnType<typeof createBCHToolbox>;
|
|
@@ -17,11 +17,7 @@ export type UTXOToolboxes = {
|
|
|
17
17
|
export type UTXOWallets = {
|
|
18
18
|
[key in keyof UTXOToolboxes]: UTXOToolboxes[key];
|
|
19
19
|
};
|
|
20
|
-
export declare function getUtxoToolbox<T extends keyof UTXOToolboxes>(chain: T, params?: UtxoToolboxParams[T] |
|
|
21
|
-
phrase?: string;
|
|
22
|
-
derivationPath?: DerivationPathArray;
|
|
23
|
-
index?: number;
|
|
24
|
-
}): UTXOToolboxes[T];
|
|
20
|
+
export declare function getUtxoToolbox<T extends keyof UTXOToolboxes>(chain: T, params?: UtxoToolboxParams[T] | UTXOToolboxDerivationParams): UTXOToolboxes[T];
|
|
25
21
|
export { assertDerivationIndex, type CreateHDWalletHelpersParams, createHDWalletHelpers, getUTXOAccountIndexFromPath, getUTXOAccountPath, getUTXOAddressPath, } from "../hdWallet";
|
|
26
22
|
export { type DeriveAddressesFromXpubParams, deriveAddressesFromXpub } from "../helpers/xpubDerivation";
|
|
27
23
|
export { stripToCashAddress } from "./bitcoinCash";
|
|
@@ -1,23 +1,28 @@
|
|
|
1
|
-
import { Chain, type ChainSigner } from "@swapkit/helpers";
|
|
1
|
+
import { Chain, type ChainSigner, type DerivationPathArray } from "@swapkit/helpers";
|
|
2
|
+
import type { UTXOScriptType } from "../helpers";
|
|
2
3
|
export type UTXOSigner = ChainSigner<any, any>;
|
|
3
4
|
export type ZcashSigner = ChainSigner<any, any>;
|
|
5
|
+
export type UTXOToolboxSignerParams<S = UTXOSigner> = {
|
|
6
|
+
signer?: S;
|
|
7
|
+
phrase?: undefined;
|
|
8
|
+
scriptType?: UTXOScriptType;
|
|
9
|
+
};
|
|
4
10
|
export type UtxoToolboxParams = {
|
|
5
|
-
[Chain.BitcoinCash]:
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
[Chain.
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
[Chain.Dogecoin]: {
|
|
12
|
-
signer?: UTXOSigner;
|
|
13
|
-
};
|
|
14
|
-
[Chain.Litecoin]: {
|
|
15
|
-
signer?: UTXOSigner;
|
|
16
|
-
};
|
|
17
|
-
[Chain.Dash]: {
|
|
18
|
-
signer?: UTXOSigner;
|
|
19
|
-
};
|
|
20
|
-
[Chain.Zcash]: {
|
|
21
|
-
signer?: ZcashSigner;
|
|
22
|
-
};
|
|
11
|
+
[Chain.BitcoinCash]: UTXOToolboxSignerParams;
|
|
12
|
+
[Chain.Bitcoin]: UTXOToolboxSignerParams;
|
|
13
|
+
[Chain.Dogecoin]: UTXOToolboxSignerParams;
|
|
14
|
+
[Chain.Litecoin]: UTXOToolboxSignerParams;
|
|
15
|
+
[Chain.Dash]: UTXOToolboxSignerParams;
|
|
16
|
+
[Chain.Zcash]: UTXOToolboxSignerParams<ZcashSigner>;
|
|
23
17
|
};
|
|
18
|
+
export type UTXOToolboxDerivationParams = {
|
|
19
|
+
phrase: string;
|
|
20
|
+
index?: number;
|
|
21
|
+
signer?: undefined;
|
|
22
|
+
} & ({
|
|
23
|
+
derivationPath: DerivationPathArray;
|
|
24
|
+
scriptType: UTXOScriptType;
|
|
25
|
+
} | {
|
|
26
|
+
derivationPath?: undefined;
|
|
27
|
+
scriptType?: UTXOScriptType;
|
|
28
|
+
});
|