@swapkit/toolboxes 6.6.0 → 6.6.1
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
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# @swapkit/toolboxes
|
|
2
2
|
|
|
3
|
+
## 6.6.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#487](https://github.com/swapkit/sdk/pull/487) [`4c192c9`](https://github.com/swapkit/sdk/commit/4c192c939cb142989c13048f31fe681a15312020) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Zcash transactions now pay the ZIP-317 conventional fee instead of a per-byte rate. Coin selection, fee estimation and sweeps price inputs per logical action, so UTXOs worth more than their marginal cost are no longer dropped as uneconomical and payable wallets are no longer rejected. The marginal fee switches from 5,000 to 1,000 zats at mainnet height 3,590,000 (ZIP 2009). `accumulative` takes an optional `marginalFee` for Zcash and `calculateZcashFee` is exported so the API can share the same fee. `feeRate` and `FeeOption` have no effect on Zcash because ZIP-317 has no fee market; the conventional fee for the expected mining height is always paid. Other UTXO chains are unchanged.
|
|
8
|
+
- [#484](https://github.com/swapkit/sdk/pull/484) [`c03235b`](https://github.com/swapkit/sdk/commit/c03235b7a06fc3c71c67c0407a2c8c5159b4cb17) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@6.4.3)
|
|
9
|
+
|
|
3
10
|
## 6.6.0
|
|
4
11
|
|
|
5
12
|
### Minor Changes
|
package/dist/src/utxo/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ia as St,ja as tr}from"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";import{NetworkDerivationPath as Kr}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 re({accountIndex:e,chain:t,derivationPath:r}){if(e!==void 0)Z("accountIndex",e);let[n,o,i]=r??Kr[t];return[n,o,e??i]}function Oe({accountIndex:e,change:t=!1,chain:r,derivationPath:n,index:o}){return Z("index",o),[...re({accountIndex:e,chain:r,derivationPath:n}),Number(t),o]}function pe(e){return e[2]??0}function Fr({deriveAddress:e,getBalance:t,getUtxos:r}){async function n(s){let{accountIndex:p,count:c,startIndex:u=0,change:a=!1}=s;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:a,index:u+h});if(m)l.push(m)}return l}async function o(s){let{gapLimit:p=20,change:c=!1}=s??{},u=[],a=0,l=0;while(a<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),a=0;else a++;l++}return u}async function i(s=20){let[p,c]=await Promise.all([o({change:!1,gapLimit:s}),o({change:!0,gapLimit:s})]),u=[...p,...c],a=await Promise.all(u.map(async(h)=>{let f=(await t(h.address)).reduce((y,x)=>y+x.getValue("number"),0);return{...h,balance:f}})),l=a.reduce((h,m)=>h+m.balance,0);return{addresses:a,total:l}}async function d(s=20){let[p,c]=await Promise.all([o({change:!1,gapLimit:s}),o({change:!0,gapLimit:s})]),u=[...p,...c];return(await Promise.all(u.map(async(l)=>(await r(l.address)).map((m)=>({...m,address:l.address,derivationIndex:l.index,isChange:l.change}))))).flat()}return{deriveAddresses:n,getAggregatedBalance:i,getAggregatedUtxos:d,scanForAddresses:o}}import{Chain as C,getRPCUrl as Dr,RequestClient as Re,SKConfig as Ct,SwapKitError as R,warnOnce as Ir}from"@swapkit/helpers";import{NETWORKS as le}from"@swapkit/utxo-signer";async function Hr({chain:e,txHash:t}){let r=`${he(e)}/push/transaction`,n=JSON.stringify({data:t});try{let o=await Re.post(r,{body:n,headers:{"Content-Type":"application/json"}});if(o.context.code!==200)throw new R("toolbox_utxo_broadcast_failed",{error:o.context.error||"Transaction broadcast failed"});return o.data?.transaction_hash||t}catch(o){let i=await Dr(e);if(i){let d=JSON.stringify({id:St(),jsonrpc:"2.0",method:"sendrawtransaction",params:[t]}),s=await Re.post(i,{body:d,headers:{"Content-Type":"application/json"}});if(s.error)throw new R("toolbox_utxo_broadcast_failed",{error:s.error?.message});if(s.result.includes('"code":-26'))throw new R("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return s.result}throw o}}function he(e){return`${(Ct.get("blockchairApiUrl")||"https://api.blockchair.com").replace(/\/+$/,"")}/${Rr(e)}`}function At(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 Rr(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 Mr(e){try{let{feePerKb:t}=await Re.get(`https://app.bitgo.com/api/v2/${e.toLowerCase()}/tx/fee`),r=t/1000;return Math.max(r,At(e))}catch{return At(e)}}async function Se(e,t){let r=await Re.get(`${e}${t?`${e.includes("?")?"&":"?"}key=${t}`:""}`);if(!r||r.context.code!==200)throw new R("toolbox_utxo_api_error",{error:`Failed to query ${e}`});return r.data}async function Er({chain:e,apiKey:t}){let r=await Se(`${he(e)}/stats`,t);if(typeof r.best_block_height!=="number")throw new R("toolbox_utxo_api_error",{error:"Missing best_block_height in stats response"});return r.best_block_height}async function Xt({address:e,chain:t,apiKey:r}){if(!e)throw new R("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await Se(`${he(t)}/dashboards/address/${e}?transaction_details=true`,r))[e]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function Nr({address:e,chain:t,apiKey:r}){return(await Xt({address:e,apiKey:r,chain:t}))?.address.balance||0}async function Bt({chain:e,apiKey:t,txHash:r}){if(!r)throw new R("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await Se(`${he(e)}/raw/transaction/${r}`,t))?.[r]?.raw_transaction||""}catch(n){let o=n instanceof Error?n.message:String(n);return console.error(`Failed to fetch raw transaction: ${o}`),""}}var Wr=4294967294;async function Zr({chain:e,apiKey:t,txHash:r}){if(!r)throw new R("toolbox_utxo_invalid_params",{error:"TxHash is required"});let o=(await Se(`${he(e)}/dashboards/transaction/${r}`,t))?.[r];if(!o)throw new R("toolbox_utxo_tx_not_found",{txHash:r});let{transaction:i,inputs:d,outputs:s}=o,p=d.map((u)=>u.spending_sequence),c=i.is_rbf===!0||p.some((u)=>u<Wr);return{blockId:i.block_id,confirmed:i.block_id!==-1,fee:i.fee,inputs:d,isRBF:c,outputs:s,sequences:p,size:i.size,txid:i.hash,weight:i.weight}}async function zr({chain:e,address:t,apiKey:r,offset:n=0,limit:o=30}){return(await Se(`${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=${o}&offset=${n}`,r)).map(({is_spent:p,script_hex:c,block_id:u,transaction_hash:a,index:l,value:h,spending_signature_hex:m})=>({hash:a,index:l,is_confirmed:u!==-1,is_spent:p,script_hex:c,txHex:m,value:h}))}function $r(e){return e.reduce((t,r)=>t+r.value,0)}function Ot(e,t){let r=[...e].sort((n,o)=>o.value-n.value);if(t){let n=[],o=0;for(let i of r)if(n.push(i),o+=i.value,o>=t)break;return n}return r}async function kt({chain:e,address:t,apiKey:r,targetValue:n,accumulativeValue:o=0,offset:i=0,limit:d=30}){if(!t)throw new R("toolbox_utxo_invalid_params",{error:"Address is required"});try{let s=await zr({address:t,apiKey:r,chain:e,limit:d,offset:i,targetValue:n}),c=s.length<d,u=s.filter(({is_spent:y})=>!y),a=$r(u),l=o+a,h=n&&l>=n;if(c||h)return Ot(u,n);let m=await kt({accumulativeValue:l,address:t,apiKey:r,chain:e,limit:d,offset:i+d,targetValue:n}),f=[...u,...m];return Ot(f,n)}catch(s){let p=s instanceof Error?s.message:String(s);return console.error(`Failed to fetch unspent UTXOs: ${p}`),[]}}async function Lr({address:e,chain:t,apiKey:r,fetchTxHex:n=!0,targetValue:o}){let i=await kt({address:e,apiKey:r,chain:t,targetValue:o}),d=n?await Promise.all(i.map(({hash:s})=>Bt({apiKey:r,chain:t,txHash:s}))):[];return i.map(({hash:s,index:p,script_hex:c,value:u},a)=>({address:e,hash:s,index:p,txHex:n?d[a]:void 0,value:u,witnessUtxo:{script:Buffer.from(c,"hex"),value:u}}))}function A(e){let t=Ct.get("apiKeys").blockchair||"";return Ir({condition:!t,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(r)=>Hr({chain:e,txHash:r}),getAddressData:(r)=>Xt({address:r,apiKey:t,chain:e}),getBalance:(r)=>Nr({address:r,apiKey:t,chain:e}),getBlockHeight:()=>Er({apiKey:t,chain:e}),getRawTx:(r)=>Bt({apiKey:t,chain:e,txHash:r}),getSuggestedTxFee:()=>Mr(e),getTransactionDetails:(r)=>Zr({apiKey:t,chain:e,txHash:r}),getUtxos:(r)=>Lr({...r,apiKey:t,chain:e})}}function Lo(e){return e}function Vo(){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 R("toolbox_utxo_not_supported",{chain:t})}}}import{sha256 as Qr}from"@noble/hashes/sha2.js";import{createBase58check as en}from"@scure/base";import{SwapKitError as Ft}from"@swapkit/helpers";import{CashAddrType as Me,decodeCashAddr as Vr,encodeCashAddr as qr}from"@swapkit/utxo-signer";var Yr={P2PKH:Me.P2PKH,P2SH:Me.P2SH},Gr={[Me.P2PKH]:"P2PKH",[Me.P2SH]:"P2SH"};function jr(e,t,r){return qr({hash:r,prefix:e,type:Yr[t]})}function Jr(e){let t=Vr(e),r=Gr[t.type];if(!r)throw Error(`Unknown CashAddr type: ${t.type}`);return{hash:t.hash,prefix:t.prefix,type:r}}var st={decode:Jr,encode:jr};var Dt=en(Qr);var It;((r)=>{r.Mainnet="mainnet";r.Testnet="testnet"})(It||={});var ne={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}},tn={["p2pkh"]:"pkh",["p2sh"]:"sh"};function ts(e){return Ne(e)!==void 0}function rs(e){return it(e).network}function G(e){let t=it(e);if(t.format==="legacy")return e;return on(t)}function Ee(e){let t=it(e);return sn(t)}function Ne(e){if(typeof e!=="string")return;let t=rn(e)??nn(e);return t&&{...t,scriptType:tn[t.type]}}function it(e){let t=Ne(e);if(!t)throw new Ft("toolbox_utxo_invalid_address",{address:e});return t}function rn(e){try{let t=Dt.decode(e);if(t.length!==21)throw new Ft("toolbox_utxo_invalid_address",{address:e});let r=t[0],n=Array.prototype.slice.call(t,1);switch(r){case ne.legacy.mainnet.p2pkh:return{format:"legacy",hash:n,network:"mainnet",type:"p2pkh"};case ne.legacy.mainnet.p2sh:return{format:"legacy",hash:n,network:"mainnet",type:"p2sh"};case ne.legacy.testnet.p2pkh:return{format:"legacy",hash:n,network:"testnet",type:"p2pkh"};case ne.legacy.testnet.p2sh:return{format:"legacy",hash:n,network:"testnet",type:"p2sh"};case ne.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:n,network:"mainnet",type:"p2pkh"};case ne.bitpay.mainnet.p2sh:return{format:"bitpay",hash:n,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function nn(e){if(e.indexOf(":")!==-1)try{return Kt(e)}catch{}else{let t=["bitcoincash","bchtest","bchreg"];for(let r of t)try{return Kt(`${r}:${e}`)}catch{}}return}function Kt(e){try{let{hash:t,prefix:r,type:n}=st.decode(e);return{format:"cashaddr",hash:Array.prototype.slice.call(t,0),network:r==="bitcoincash"?"mainnet":"testnet",type:n==="P2PKH"?"p2pkh":"p2sh"}}catch{return}}function on(e){let t=ne.legacy[e.network][e.type],r=Buffer.alloc(1+e.hash.length);return r[0]=t,r.set(e.hash,1),Dt.encode(r)}function sn(e){let t=e.network==="mainnet"?"bitcoincash":"bchtest",r=e.type==="p2pkh"?"P2PKH":"P2SH",n=new Uint8Array(e.hash);return st.encode(t,r,n)}import{Chain as ae,SwapKitError as mt}from"@swapkit/helpers";import{SwapKitError as qe,UTXO_SCRIPT_TYPE_LIST as On,UTXO_SCRIPT_TYPES as Vt,UTXOScriptType as Ye}from"@swapkit/helpers";import{Script as Sn}from"@swapkit/utxo-signer";import{Chain as Ht}from"@swapkit/helpers";import{getAddressScriptType as cn,getZcashAddressType as dn}from"@swapkit/utxo-signer";import{match as un}from"ts-pattern";import{Chain as fe}from"@swapkit/helpers";import{NETWORKS as Te}from"@swapkit/utxo-signer";import{match as an}from"ts-pattern";function U(e){return an(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 Ce(e){if(typeof e!=="string")return null;let t=Ne(z(e));if(!t||t.network!=="mainnet")return null;return t.scriptType}function j({address:e,chain:t}){return un(t).with(Ht.BitcoinCash,()=>Ce(e)).with(Ht.Zcash,()=>dn(e)).otherwise(()=>cn(e,U(t)))}import{Chain as oe,derivationPathToString as Rt,getPurposeFromPath as pn,getUTXOScriptTypeForPath as Mt,getUTXOScriptTypeForPurpose as Wt,resolveDerivationPath as ln,SwapKitError as Xe,UTXO_SCRIPT_TYPE_LIST as Et,UTXO_SCRIPT_TYPES as me,UTXOChains as hn,UTXOScriptType as O,updateDerivationPath as fn,warnOnce as Tn}from"@swapkit/helpers";import{CashAddrPrefix as mn,CashAddrType as yn,encodeCashAddr as gn,OutScript as Zt,p2pkh as xn,p2sh as bn,p2tr as wn,p2wpkh as Nt}from"@swapkit/utxo-signer";var We=Object.freeze([O.P2PKH]),Pn=Object.freeze({[oe.Bitcoin]:Et,[oe.BitcoinCash]:We,[oe.Dash]:We,[oe.Dogecoin]:We,[oe.Litecoin]:Et,[oe.Zcash]:We});function ze(e){return Pn[e]}function ct(e){return ze(e).some((t)=>me[t].witness)}function ye(e,t){return ze(e).includes(t)}function $e(e,t){if(ye(e,t))return t;throw new Xe("toolbox_utxo_unsupported_script_type",{chain:e,error:`${e} cannot encode ${t}; supported: ${ze(e).join(", ")}`,scriptType:t,supported:ze(e)})}var zt=hn.filter((e)=>!ct(e));function Un({purpose:e,scriptType:t}){let r=Wt(e);return r===void 0||r===t}function dt({chain:e,purpose:t,scriptType:r}){Tn({condition:!Un({purpose:t,scriptType:r}),id:`utxo_off_standard_encoding_${e}_${t}_${r}`,warning:`${e}: encoding m/${t}' keys as ${r}, not the ${Wt(t)} the path implies. No other wallet derives these addresses: move funds out of them, never receive into them.`})}function Le({chain:e,derivationPath:t,index:r=0,scriptType:n}){if(t){if(!n){let s=Mt(t);throw new Xe("toolbox_utxo_invalid_params",{chain:e,derivationPath:Rt(t),error:`scriptType is required alongside derivationPath: getUTXOScriptTypeForPath gives the standard one${s?` (${s})`:""}, or state another deliberately.`})}return $e(e,n),dt({chain:e,purpose:pn(t),scriptType:n}),{derivationPath:t,scriptType:n}}let o=ln({chain:e,index:r}),i=n?fn(o,{purpose:me[n].purpose}):o,d=n??Mt(i);if(!d)throw new Xe("toolbox_utxo_invalid_params",{chain:e,derivationPath:Rt(i),error:`${e}: the default derivation path has no standard script type`});return $e(e,d),{derivationPath:i,scriptType:d}}function _n(e){return e.length===32?e:e.slice(1)}function Ze(e,t){if(!e.address)throw new Xe("toolbox_utxo_invalid_address",{error:`Could not derive a ${t} address`});return e}var vn={[O.P2PKH]:(e,t)=>{let{address:r,script:n}=Ze(xn(e,t),O.P2PKH);return{address:r,script:n}},[O.P2SH_P2WPKH]:(e,t)=>{let r=Nt(e,t),{address:n,script:o}=Ze(bn(r,t),O.P2SH_P2WPKH);return{address:n,redeemScript:r.script,script:o}},[O.P2WPKH]:(e,t)=>{let{address:r,script:n}=Ze(Nt(e,t),O.P2WPKH);return{address:r,script:n}},[O.P2TR]:(e,t)=>{let r=_n(e),{address:n,script:o}=Ze(wn(r,void 0,t),O.P2TR);return{address:n,script:o,tapInternalKey:r}}};function Ve(e,t,r){return vn[e](t,r)}function ut(e,t){if(e!==oe.BitcoinCash)return t.address;let r=Zt.decode(t.script);if(r.type!=="pkh")throw new Xe("toolbox_utxo_invalid_address",{chain:e,error:`Cannot encode ${r.type} as CashAddr`});return gn({hash:r.hash,prefix:mn.MAINNET,type:yn.P2PKH}).replace(/^bitcoincash:/,"")}var An=Object.freeze({pkh:O.P2PKH,sh:O.P2SH_P2WPKH,tr:O.P2TR,wpkh:O.P2WPKH}),at=Object.freeze({pkh:me[O.P2PKH].outputSize,sh:me[O.P2SH_P2WPKH].outputSize,tr:me[O.P2TR].outputSize,wpkh:me[O.P2WPKH].outputSize,wsh:43});function $t(e){return e in at}function Lt(e){if(e==="tex")return at.pkh;return $t(e)?at[e]:void 0}function Be(e){return An[e]}function pt(e){try{let{type:t}=Zt.decode(e);return $t(t)?Be(t):void 0}catch{return}}import{UTXOScriptType as ie}from"@swapkit/helpers";var ws=1000,ht=10,Cn=2,Xn=10;function M(e){let t=new Uint8Array(Buffer.from(e,"utf8"));return Sn.encode(["RETURN",t])}function qt(e){return Object.fromEntries(On.map((t)=>[t,Vt[t][e]]))}var Yt=qt("inputSize"),lt=qt("outputSize"),ft=(e)=>Vt[e].witness,Ge=(e,t)=>{let r=j({address:e,chain:t});if(!r)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let n=Be(r);if(!n||!ye(t,n))throw new qe("toolbox_utxo_unsupported_script_type",{address:e,addressType:r,chain:t,error:"Address is valid but its script type is not one the SDK spends from"});return n},Bn=(e,t)=>{let r=j({address:e,chain:t});if(!r)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let n=Lt(r);if(!n)throw new qe("toolbox_utxo_unsupported_script_type",{address:e,addressType:r,chain:t,error:"Address is valid but a transparent transaction cannot pay to it"});return n},ge=({chain:e,inputs:t,outputs:r,feeRate:n})=>{let o=t[0]?ke(t[0],e):Ye.P2PKH,i=n?t.filter((u)=>u.value>=Yt["type"in u&&u.type?u.type:Ye.P2PKH]*Math.ceil(n)):t,d=0,s=0;for(let u of i)if(d+=se(u,e),!ft(ke(u,e)))s++;let p=r?.reduce((u,a)=>u+je(a,e),0)||lt[o],c=s<i.length;return ht+d+p+Tt(c,s)},ke=(e,t)=>{if("type"in e&&e.type)return e.type;if("address"in e&&e.address)return Ge(e.address,t);return Ye.P2PKH},se=(e,t)=>Yt[ke(e,t)],Tt=(e,t)=>e?Math.ceil((Cn+t)/4):0,je=(e,t,r)=>{if(e?.script)return Xn+e.script.length+(e.script.length>=74?2:1);if(r)return lt[r];if("address"in e&&e.address)return Bn(e.address,t);return lt[Ye.P2PKH]};function Ke(e){switch(e){case ae.Bitcoin:case ae.BitcoinCash:return 550;case ae.Dash:case ae.Litecoin:return 5500;case ae.Dogecoin:return 1e5;case ae.Zcash:return 546;default:throw new mt("toolbox_utxo_not_supported",{chain:e})}}function E({inputs:e,outputs:t,feeRate:r=1,chain:n=ae.Bitcoin,changeAddress:o="",sweep:i=!1}){let d=Ke(n),s=e.filter((f)=>{let y=se(f,n)*r;return i?f.value>Math.max(y,d):y<=f.value});if(i){let f=Math.ceil(r*ge({chain:n,inputs:s,outputs:t})),y=s.reduce((X,q)=>X+q.value,0),x=y-f;if(x<=d)throw new mt("toolbox_sweep_amount_too_low",{available:y,dustThreshold:d,fee:f});let S=t.findIndex((X)=>("address"in X)&&X.address);if(S===-1)throw new mt("toolbox_utxo_invalid_params",{error:"Sweep requires a recipient output"});return{fee:f,inputs:s,outputs:t.map((X,q)=>q===S?{...X,value:x}:X)}}let p=ht+t.reduce((f,y)=>f+je(y,n),0),c=t.reduce((f,y)=>f+y.value,0),u=0,a=0,l=!1,h=0,m=[];for(let f of s){if(u+=se(f,n),ft(ke(f,n)))l=!0;else a++;h+=f.value,m.push(f);let y=(p+u+Tt(l,a))*r,x=y+c;if(h<x)continue;let S=h-x,X=r*je({address:o,value:0},n);if(S>X){let q=X+y,Ue=h-(c+Math.ceil(q));if(Ue>Math.max(se({value:0},n)*r,Ke(n)))return{fee:Math.ceil(q),inputs:m,outputs:t.concat({address:o,value:Ue})}}return{fee:Math.ceil(y),inputs:m,outputs:t}}return{fee:Math.ceil(r*ge({chain:n,inputs:e,outputs:t}))}}import{secp256k1 as kn}from"@noble/curves/secp256k1.js";import{base64 as Kn,utf8 as Gt}from"@scure/base";import{SwapKitError as Fn,UTXOScriptType as yt}from"@swapkit/helpers";import{CompactSize as Dn,utils as In}from"@swapkit/utxo-signer";var Hn=Gt.decode(`\x18Bitcoin Signed Message:
|
|
2
|
-
`),jt={[yt.P2PKH]:31,[yt.P2SH_P2WPKH]:35,[yt.P2WPKH]:39};function Rn(e){return jt[e]!==void 0}function Mn(e){let t=Gt.decode(e);return In.sha256x2(Hn,Dn.encode(BigInt(t.length)),t)}function Jt({message:e,privateKey:t,scriptType:r}){let n=jt[r];if(n===void 0)throw new Fn("toolbox_utxo_unsupported_script_type",{error:`BIP-137 message signatures cannot express a ${r} address`,scriptType:r});let o=kn.sign(Mn(e),t,{format:"recovered",prehash:!1}),[i=0]=o,d=new Uint8Array(65);return d[0]=n+i,d.set(o.subarray(1),1),Kn.encode(d)}import{Chain as Pe,SwapKitError as Eo}from"@swapkit/helpers";import{hex as hr}from"@scure/base";import{Chain as io,derivationPathToString as ao,FeeOption as co,resolveDerivationPath as uo,SwapKitError as L}from"@swapkit/helpers";import{BCHSigHash as po,CashAddrPrefix as fr,CashAddrType as Tr,encodeCashAddr as mr,NETWORKS as lo,p2pkh as yr,Transaction as gr}from"@swapkit/utxo-signer";import{secp256k1 as En}from"@noble/curves/secp256k1.js";import{hex as J}from"@scure/base";import{HDKey as rr}from"@scure/bip32";import{mnemonicToSeedSync as bt}from"@scure/bip39";import{AssetValue as gt,applyFeeMultiplier as Qt,Chain as be,derivationPathToString as Fe,FeeOption as N,NetworkDerivationPath as Nn,SwapKitError as P,SwapKitNumber as Wn,UTXO_SCRIPT_TYPES as Zn,warnOnce as zn}from"@swapkit/helpers";import{BCHSigHash as nr,RBF_SEQUENCE as $n,SigHash as er,Transaction as Je,utils as Ln,WIF as or}from"@swapkit/utxo-signer";var Qe=[be.Bitcoin];function sr({address:e,chain:t}){return j({address:e,chain:t})!==null}function Vn({phrase:e,derivationPath:t,network:r,seed:n}){let o=n??bt(e),d=rr.fromMasterSeed(o,r.bip32).derive(t);if(!d.privateKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive private key from phrase"});return d.privateKey}function xt(e){return En.getPublicKey(e,!0)}function De({publicKey:e,chain:t,network:r,scriptType:n}){return ut(t,Ve(n,e,r))}function xe({phrase:e,derivationPath:t,chain:r,wif:n,seed:o}){let i=U(r);if(n){let c=or(i).decode(n),u=xt(c);return{privateKey:c,publicKey:u}}if(!e)throw new P("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let d=t||Fe(Nn[r]),s=Vn({derivationPath:d,network:i,phrase:e,seed:o}),p=xt(s);return{privateKey:s,publicKey:p}}function qn(e,t){return or(U(t)).encode(e)}function Yn({phrase:e,derivationPath:t,chain:r,seed:n}){let o=t.split("/");if(o.length<4)throw new P("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${o.length}): ${t}`});let i=U(r),d=n??bt(e),s=rr.fromMasterSeed(d,i.bip32),p=o.slice(0,4).join("/");return s.derive(p)}function Gn(e,t){if(!e||!Zn[e].witness)return!1;return e!==ie.P2SH_P2WPKH||!!t}function ir({chain:e,script:t,publicKey:r,network:n}){let o=pt(t);if(o!==ie.P2SH_P2WPKH&&o!==ie.P2TR)return{};if(!ye(e,o))return{};let i=Ve(o,r,n);if(Ln.compareBytes(i.script,t)!==0)return{};return o===ie.P2TR?{tapInternalKey:i.tapInternalKey}:{redeemScript:i.redeemScript}}function jn(e,t,r){if(!r)return!1;let n=j({address:e,chain:t}),o=n?Be(n):void 0;if(!o||!ye(t,o))return!1;let i=ut(t,Ve(o,r,U(t)));return t===be.BitcoinCash?z(i)===z(e):i===e}function Jn(e){return e.witnessUtxo?.script??e.nonWitnessUtxo?.outputs[e.index??0]?.script}function wt({chain:e,tx:t,publicKey:r,network:n,indexes:o}){let i=o??Array.from({length:t.inputsLength},(s,p)=>p),d=[];for(let s of i){let p=t.getInput(s),c=Jn(p);if(!c)continue;let{redeemScript:u,tapInternalKey:a}=ir({chain:e,network:n,publicKey:r,script:c}),l={index:s};if(u&&!p.redeemScript)l.redeemScript=u;if(a&&!p.tapInternalKey)l.tapInternalKey=a;if(l.redeemScript||l.tapInternalKey)d.push(l)}return d}function ce({inputs:e,outputs:t,chain:r,tx:n,sender:o,compiledMemo:i,enableRBF:d=!1}){let s=U(r),p=ct(r),c=d?$n:void 0,u=new Set;for(let a of e){let l=`${a.hash}:${a.index}`;if(u.has(l))throw new P("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});u.add(l);let h=typeof a.hash==="string"?J.decode(a.hash):a.hash,m=a.witnessUtxo?pt(a.witnessUtxo.script):void 0,f=a.publicKey&&a.witnessUtxo?ir({chain:r,network:s,publicKey:a.publicKey,script:a.witnessUtxo.script}):{};if(p&&a.witnessUtxo&&Gn(m,f.redeemScript))n.addInput({...f,index:a.index,sequence:c,txid:h,witnessUtxo:{amount:BigInt(a.witnessUtxo.value),script:a.witnessUtxo.script}});else if(a.txHex)n.addInput({...f,index:a.index,nonWitnessUtxo:J.decode(a.txHex),sequence:c,txid:h,...r===be.BitcoinCash?{sighashType:nr.ALL}:{}});else throw new P("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 a of t){let l="address"in a&&a.address?a.address:o;if(r===be.BitcoinCash)l=G(l);if(a.script)if(i)n.addOutput({amount:0n,script:i});else throw new P("toolbox_utxo_invalid_params",{error:"An output carrying a script needs the compiled memo it carries"});else n.addOutputAddress(l,BigInt(a.value),s)}return{inputs:e,tx:n}}async function we(e){let t=await A(e).getSuggestedTxFee();return{[N.Average]:t,[N.Fast]:Qt(t,N.Fast),[N.Fastest]:Qt(t,N.Fastest)}}async function ar({assetValue:e,recipient:t,memo:r,sender:n,sweep:o,fetchTxHex:i=!1,publicKey:d},s,{forEstimateOnly:p=!1}={}){let c=e.chain,u=Ge(n,c),a=u===ie.P2PKH||u===ie.P2SH_P2WPKH&&!jn(n,c,d),l=i||!p&&a,h=e.getBaseValue("number"),m=o?void 0:s??(await we(c))[N.Fastest],f=o||m===void 0?void 0:Math.ceil(h+m*5000);return{inputs:await A(c).getUtxos({address:n,fetchTxHex:l,targetValue:f}),outputs:[{address:t,value:o?0:h},...r?[{address:"",script:M(r),value:0}]:[]]}}async function cr({assetValue:e,recipient:t,memo:r,feeRate:n,sender:o,fetchTxHex:i=!1,enableRBF:d=!1,sweep:s,publicKey:p}){let c=e.chain,u=r?M(r):null,a=await ar({assetValue:e,fetchTxHex:i,memo:r,publicKey:p,recipient:t,sender:o,sweep:s},n),{inputs:l,outputs:h}=E({...a,chain:c,changeAddress:o,feeRate:n,sweep:s});if(!(l&&h))throw new P("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let m=p?l.map((S)=>({...S,publicKey:p})):l,f=new Je({allowUnknownOutputs:!!u,version:1}),{inputs:y,tx:x}=ce({chain:c,compiledMemo:u,enableRBF:d,inputs:m,outputs:h,sender:o,tx:f});return{inputs:y,tx:x,utxos:a.inputs}}async function dr({assetValue:e,feeOptionKey:t=N.Fast,feeRate:r,memo:n,sender:o,recipient:i,sweep:d}){let s=e.chain,p,c;if(r!==void 0)p=r,c=Math.floor(r);else{let a=await we(s);p=a[N.Fastest],c=a[t]}let u=await ar({assetValue:e,memo:n,recipient:i,sender:o,sweep:d},p,{forEstimateOnly:!0});return E({...u,chain:s,changeAddress:o,feeRate:c,sweep:d})}function Qn(e){return async function({from:r,memo:n,feeRate:o,feeOptionKey:i=N.Fast,recipient:d=r,recipients:s=1}){let p=o??(await we(e))[i],u=(await A(e).getUtxos({address:r,fetchTxHex:!1})).filter((f)=>f.value>Math.max(Ke(e),se(f,e)*p));if(!u.length)return gt.from({chain:e});let a=typeof s==="number"?Math.max(s,1):s.length,l=typeof s==="number"||a===0?Array.from({length:a||1},()=>({address:d,value:0})):[...s];if(n)l.push({address:r,script:M(n),value:0});let{outputs:h}=E({chain:e,feeRate:p,inputs:u,outputs:l,sweep:!0}),m=h?.[0]?.value??0;return gt.from({chain:e,value:BigInt(m)})}}function eo(e){return async function(r){let{fee:n}=await dr(r);return gt.from({chain:e,value:Wn.fromBigInt(BigInt(n),8).getValue("string")})}}function to({chain:e,phrase:t,derivationPath:r,scriptType:n,seed:o}){let i=U(e),{privateKey:d,publicKey:s}=xe({chain:e,derivationPath:r,phrase:t,seed:o}),p=ur(e);return{getAddress:()=>De({chain:e,network:i,publicKey:s,scriptType:n}),privateKey:d,publicKey:s,signTransaction:(c)=>{for(let{index:u,...a}of wt({chain:e,network:i,publicKey:s,tx:c}))c.updateInput(u,a);return c.sign(d,p),c}}}function ur(e){return e===be.BitcoinCash?[nr.ALL]:[er.ALL,er.DEFAULT]}function ro(e,t,r){return async function({memo:o,recipient:i,feeOptionKey:d,feeRate:s,assetValue:p,enableRBF:c=!1,sweep:u}){let a=await t?.getAddress();if(!(t&&a))throw new P("toolbox_utxo_no_signer");if(!i)throw new P("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});zn({condition:c&&!Qe.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 l=c&&Qe.includes(e),h=s||(await we(e))[d||N.Fast],{tx:m}=await cr({assetValue:p,enableRBF:l,feeRate:h,memo:o,publicKey:r,recipient:i,sender:a,sweep:u}),f=await t.signTransaction(m);return f.finalize(),A(e).broadcastTx(J.encode(f.extract()))}}function pr(e){return(t)=>sr({address:t,chain:e})}function lr(e,{scriptType:t}){let r=U(e);return function(o){if(!o)throw new P("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return De({chain:e,network:r,publicKey:o.publicKey,scriptType:t})}}function no(e){let t=e?.publicKey;if(t===void 0)return;if(t instanceof Uint8Array&&t.length===33)return t;throw new P("toolbox_utxo_invalid_params",{error:"signer.publicKey must be a 33-byte compressed public key (Uint8Array)"})}function de(e){let{chain:t}=e,r=e.phrase?e:void 0;if(!r&&"derivationPath"in e&&e.derivationPath!==void 0)throw new P("toolbox_utxo_invalid_params",{error:"derivationPath needs a phrase; a toolbox built around a signer uses the signer's addresses"});let n=r?.phrase,o=r?.index??0,i=n?bt(n):void 0,{derivationPath:d,scriptType:s}=Le({chain:t,derivationPath:r?.derivationPath,index:o,scriptType:e.scriptType}),p=Fe(d),c=n?to({chain:t,derivationPath:p,phrase:n,scriptType:s,seed:i}):void 0,u=r?void 0:e.signer,a=c||u,l=n?xe({chain:t,derivationPath:p,phrase:n,seed:i}):void 0,h=l?.publicKey??no(u);function m(){if(a)return a.getAddress();return Promise.resolve(void 0)}function f(T){if(!n)return;let g=re({accountIndex:T,chain:t,derivationPath:d});return Yn({chain:t,derivationPath:Fe(g),phrase:n,seed:i})}let y=f();function x(){if(!y)return;return y.publicExtendedKey}function S({accountIndex:T}={}){let g=T===void 0?y:f(T);if(!g)return;let w=re({accountIndex:T,chain:t,derivationPath:d});return{accountIndex:pe(w),path:Fe(w),xpub:g.publicExtendedKey}}function X({accountIndex:T,index:g,change:w=!1}){let v=T===void 0?y:f(T);if(!v)return;let b=Oe({accountIndex:T,chain:t,change:w,derivationPath:d,index:g}),K=U(t),I=v.deriveChild(Number(w)).deriveChild(g);if(!I.publicKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let B=De({chain:t,network:K,publicKey:I.publicKey,scriptType:s}),F=J.encode(I.publicKey);return{accountIndex:pe(b),address:B,change:w,index:g,path:Fe(b),pubkey:F}}async function q(T){if(!Qe.includes(t))return{reason:`RBF is not supported on ${t}`,supported:!1};let g=await A(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 Ue({txid:T,newFeeRate:g,recipient:w,memo:v}){if(!Qe.includes(t))throw new P("toolbox_utxo_rbf_not_supported",{chain:t});let b=await A(t).getTransactionDetails(T);if(!b.isRBF)throw new P("toolbox_utxo_tx_not_replaceable",{txid:T});if(b.confirmed)throw new P("toolbox_utxo_tx_already_confirmed",{blockId:b.blockId,txid:T});let K=b.inputs.reduce((_,D)=>_+D.value,0),B=b.outputs.find((_)=>_.recipient===w)?.value||0;if(B===0)throw new P("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let F=await Promise.all(b.inputs.map(async(_)=>{let D=await A(t).getRawTx(_.transaction_hash),k=Je.fromRaw(J.decode(D),{allowUnknownOutputs:!0,disableScriptCheck:!0}).getOutput(_.index);return{address:_.recipient,hash:_.transaction_hash,index:_.index,publicKey:h,txHex:D,value:_.value,witnessUtxo:k.script&&k.amount!==void 0?{script:Buffer.from(k.script),value:Number(k.amount)}:void 0}})),H=v?M(v):null,ee=K-B-b.fee,_e=await m(),ue=[];if(H)ue.push({address:"",script:H,value:0});if(ee>Ke(t)&&_e)ue.push({address:_e,value:ee});let He=ge({chain:t,inputs:F.map((_)=>({..._,type:Ge(_.address,t)})),outputs:[{address:w,value:B},...ue]}),Y=Math.ceil(He*g);if(Y<=b.fee)throw new P("toolbox_utxo_rbf_fee_too_low",{newFee:Y,originalFee:b.fee});let ve=Y-b.fee,te=B-ve;if(te<=0)throw new P("toolbox_utxo_rbf_insufficient_change");let Ae=new Je({allowUnknownOutputs:!!H,version:1}),rt=[{address:w,value:te},...ue];return ce({chain:t,compiledMemo:H,inputs:F,outputs:rt,sender:_e||w,tx:Ae}),{feeDelta:ve,newFee:Y,originalFee:b.fee,tx:Ae}}async function Or({txid:T,newFeeRate:g,recipient:w,memo:v}){let{tx:b,originalFee:K,newFee:I}=await Ue({memo:v,newFeeRate:g,recipient:w,txid:T}),B=await tt(b);B.finalize();let F=await A(t).broadcastTx(J.encode(B.extract()));return{newFee:I,originalFee:K,txid:F}}function _t({accountIndex:T,index:g,change:w=!1}){Z("index",g);let v=T===void 0?y:f(T);if(!v)return;return v.deriveChild(Number(w)).deriveChild(g).privateKey||void 0}function vt({tx:T,inputDerivations:g}){if(!y)throw new P("toolbox_utxo_no_signer");let w=ur(t),v=U(t);for(let b=0;b<g.length;b++){let K=g[b];if(!K)continue;let{derivationIndex:I,isChange:B}=K,F=_t({change:B,index:I});if(!F)throw new P("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${b} at index ${I}`});for(let{index:H,...ee}of wt({chain:t,indexes:[b],network:v,publicKey:xt(F),tx:T}))T.updateInput(H,ee);T.signIdx(F,b,w)}return T}async function Sr({utxos:T,recipient:g,assetValue:w,memo:v,feeRate:b,feeOptionKey:K,changeAddress:I,sweep:B}){if(B)throw new P("toolbox_utxo_invalid_params",{error:"Sweep is not supported for transfers from multiple addresses"});if(!y)throw new P("toolbox_utxo_no_signer");let F=b||(await we(t))[K||N.Fast],H=v?M(v):null,ee=[{address:g,value:w.getBaseValue("number")}];if(H)ee.push({address:"",script:H,value:0});let _e=T.map(({address:_,hash:D,index:k,value:nt,txHex:kr,witnessUtxo:ot})=>({address:_,hash:D,index:k,txHex:kr,value:nt,witnessUtxo:ot?{script:ot.script,value:ot.value}:void 0})),ue=T[0]?.address,He=I||await m()||ue||g,{inputs:Y,outputs:ve}=E({chain:t,changeAddress:He,feeRate:F,inputs:_e,outputs:ee});if(!(Y&&ve))throw new P("toolbox_utxo_insufficient_balance",{assetValue:w,sender:"multiple addresses"});let te=new Je({allowUnknownOutputs:!!H,version:1}),Ae=Y.map((_)=>{let D=T.find((k)=>k.hash===_.hash&&k.index===_.index);return D?{derivationIndex:D.derivationIndex,isChange:D.isChange}:{derivationIndex:0,isChange:!1}}),rt=Y.map((_,D)=>{let k=Ae[D],nt=k?y.deriveChild(Number(k.isChange)).deriveChild(k.derivationIndex).publicKey:null;return{..._,publicKey:nt??void 0}});return ce({chain:t,compiledMemo:H,inputs:rt,outputs:ve,sender:He,tx:te}),vt({inputDerivations:Ae,tx:te}),te.finalize(),A(t).broadcastTx(J.encode(te.extract()))}function Cr({address:T,gapLimit:g=20}){if(!y)return;for(let w=0;w<g;w++){let v=X({change:!1,index:w}),b=X({change:!0,index:w}),K=v?.address===T?!1:b?.address===T;if(v?.address===T||b?.address===T)return{change:K,index:w}}return}function tt(T){if(!a)throw new P("toolbox_utxo_no_signer");return a.signTransaction(T)}let Xr=t===be.Bitcoin&&l?async(T)=>Jt({message:T,privateKey:l.privateKey,scriptType:s}):void 0;async function Br(T){let g=await tt(T);return g.finalize(),await A(t).broadcastTx(J.encode(g.extract()))}return{accumulative:E,broadcastTx:(T)=>A(t).broadcastTx(T),bumpFee:Or,calculateTxSize:(T)=>ge({...T,chain:t}),createKeysForPath:(T)=>xe({...T,chain:t}),createReplacementTransaction:Ue,createTransaction:(T)=>cr({publicKey:h,...T}),deriveAddressAtIndex:X,derivePrivateKeyAtIndex:_t,estimateMaxSendableAmount:Qn(t),estimateTransactionFee:eo(t),getAddress:m,getAddressFromKeys:lr(t,{scriptType:s}),getAddressType:(T)=>j({address:T,chain:t}),getBalance:tr(t),getExtendedPublicKey:x,getExtendedPublicKeyInfo:S,getFeeRates:()=>we(t),getInputsOutputsFee:dr,getNetworkForChain:()=>U(t),getPrivateKeyFromMnemonic:(T)=>qn(xe({...T,chain:t}).privateKey,t),isRBFEnabled:q,keys:l,resolveDerivationIndex:Cr,scriptType:s,signAndBroadcastTransaction:Br,signMessage:Xr,signTransaction:tt,signTransactionWithMultipleKeys:vt,transfer:ro(t,a,h),transferFromMultipleAddresses:Sr,validateAddress:pr(t)}}import{getZcashAddressType as oo,toTransparentZcashAddress as so,validateZcashAddress as Pt}from"@swapkit/utxo-signer";function Ie(e){return Ce(e)!==null}var W=io.BitcoinCash;function et(e){return z(Ee(e))}function ho(e){let t=U(W);function r(o){return o.sign(e.privateKey,[po.ALL]),o}function n(){let o=yr(e.publicKey,t);if(!o.hash)throw new L("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let i=mr({hash:o.hash,prefix:fr.MAINNET,type:Tr.P2PKH});return Promise.resolve(i.replace(/^bitcoincash:/,""))}return{getAddress:n,signTransaction:r}}function xr(e={}){let t="phrase"in e?e.phrase:void 0,r="index"in e?e.index||0:0,n="derivationPath"in e?e.derivationPath:void 0,o=uo({chain:W,derivationPath:n,index:r}),i=ao(o),d=t?xe({chain:W,derivationPath:i,phrase:t}):void 0,s=d?ho(d):("signer"in e)?e.signer:void 0;function p(){return Promise.resolve(s?.getAddress())}let c="scriptType"in e?e.scriptType:void 0,{getBalance:u,getFeeRates:a,broadcastTx:l,...h}=de(t?{chain:W,index:r,phrase:t,...n?{derivationPath:n,scriptType:c}:{scriptType:c}}:{chain:W,scriptType:c});function m(x,S=!0){return u(z(Ee(x)))}function f(x){if(!s)throw new L("toolbox_utxo_no_signer");return s.signTransaction(x)}async function y(x){let S=await f(x);return S.finalize(),await l(hr.encode(S.extract()))}return{...h,broadcastTx:l,buildTx:To,createTransaction:br,getAddress:p,getAddressFromKeys:mo,getBalance:m,getFeeRates:a,signAndBroadcastTransaction:y,signTransaction:f,stripPrefix:z,stripToCashAddress:et,transfer:fo({broadcastTx:l,getFeeRates:a,signer:s}),validateAddress:Ie}}async function br({assetValue:e,recipient:t,memo:r,feeRate:n,sender:o,sweep:i}){if(!Ie(t))throw new L("toolbox_utxo_invalid_address",{address:t});let d=Math.ceil(e.getBaseValue("number")+n*7500),s=await A(W).getUtxos({address:et(o),fetchTxHex:!0,targetValue:i?void 0:d}),p=r?M(r):null,c=[],u=G(t);if(c.push({address:u,value:i?0:e.getBaseValue("number")}),p)c.push({script:p,value:0});let{inputs:a,outputs:l}=E({chain:W,feeRate:n,inputs:s,outputs:c,sweep:i});if(!(a&&l))throw new L("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let h=new gr({allowUnknownOutputs:!!p,version:1}),m=G(o),{inputs:f,tx:y}=ce({chain:W,compiledMemo:p,inputs:a,outputs:l.map((x)=>("address"in x)&&x.address?{...x,address:G(x.address)}:x),sender:m,tx:h});return{inputs:f,tx:y,utxos:a}}function fo({broadcastTx:e,getFeeRates:t,signer:r}){return async function({recipient:o,assetValue:i,feeOptionKey:d=co.Fast,sweep:s,...p}){let c=await r?.getAddress();if(!(r&&c))throw new L("toolbox_utxo_no_signer");if(!o)throw new L("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let u=p.feeRate||(await t())[d],{tx:a}=await br({...p,assetValue:i,feeRate:u,recipient:o,sender:c,sweep:s}),l=await r.signTransaction(a);return l.finalize(),e(hr.encode(l.extract()))}}async function To({assetValue:e,recipient:t,memo:r,feeRate:n,sender:o}){let i=Ee(t);if(!Ie(i))throw new L("toolbox_utxo_invalid_address",{address:i});let d=Math.ceil(e.getBaseValue("number")+n*7500),s=await A(W).getUtxos({address:et(o),fetchTxHex:!0,targetValue:d}),p=Number(n.toFixed(0)),c=r?M(r):null,u=[];if(u.push({address:G(t),value:e.getBaseValue("number")}),c)u.push({script:c,value:0});let{inputs:a,outputs:l}=E({chain:W,feeRate:p,inputs:s,outputs:u});if(!(a&&l))throw new L("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let h=new gr({allowUnknownOutputs:!!c,version:1}),{inputs:m,tx:f}=ce({chain:W,compiledMemo:c,inputs:a,outputs:l,sender:G(o),tx:h});return{inputs:m,tx:f,utxos:s}}function mo(e){let t=lo.bitcoinCash,r=yr(e.publicKey,t);if(!r.hash)throw new L("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return mr({hash:r.hash,prefix:fr.MAINNET,type:Tr.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as yo,hex as go}from"@scure/base";import{HDKey as Ur}from"@scure/bip32";import{mnemonicToSeedSync as _r}from"@scure/bip39";import{Chain as V,derivationPathToString as xo,FeeOption as bo,SwapKitError as Q}from"@swapkit/helpers";import{Address as wo,createZcashTransaction as Po,getZcashTransactionFormat as Uo,isTransparentZcashAddress as wr,OutScript as _o,toTransparentZcashAddress as vo,utils as vr,WIF as Ao,ZcashSigHash as Oo}from"@swapkit/utxo-signer";import{match as So,P as Ut}from"ts-pattern";var Co=yo(vr.sha256);function Xo(e){return Co.encode(e)}function Bo({phrase:e,derivationPath:t}){let r=_r(e),o=Ur.fromMasterSeed(r).derive(t);if(!o.privateKey||!o.publicKey)throw new Q("toolbox_utxo_invalid_params");let{privateKey:i,publicKey:d}=o,s=vr.hash160(d),p=new Uint8Array([28,184]),c=new Uint8Array(p.length+s.length);c.set(p,0),c.set(s,p.length);let u=Xo(c);return{getAddress:()=>Promise.resolve(u),signTransaction:(a)=>{if(a.signAllInputs(i,d,Oo.ALL),"extract"in a)return a.finalizeAllInputs(),Promise.resolve(a.extract());return Promise.resolve(a)}}}function ko({inputs:e,outputs:t,tx:r,sender:n,compiledMemo:o}){let i=U(V.Zcash);for(let d of e){let s=wo(i).decode(n),p=_o.encode(s);r.addInput({index:d.index,script:p,sequence:4294967295,txid:go.decode(d.hash),value:BigInt(d.value)})}for(let d of t){let s="address"in d&&d.address?d.address:n,p=d.script;if(p&&!o)continue;if(p&&o)r.addOutput({amount:0n,script:o});else r.addOutputAddress(s,BigInt(d.value),i)}return{inputs:e,tx:r}}async function Ko(){try{let e=await A(V.Zcash).getBlockHeight();return Uo(e+1)}catch(e){throw new Q({errorKey:"toolbox_utxo_api_error",info:{chain:V.Zcash,reason:"Block height is required to choose the Zcash transaction format"}},e)}}async function Pr(e){let{assetValue:t,recipient:r,memo:n,feeRate:o,sender:i,fetchTxHex:d,sweep:s}=e,p=U(V.Zcash);if(!wr(i,p))throw new Q("toolbox_utxo_invalid_address",{address:i});let c=vo(r);if(!wr(c,p))throw new Q("toolbox_utxo_invalid_address",{address:r,error:"Zcash transaction creation currently supports transparent addresses only"});let u=n?M(n):null,a=await A(V.Zcash).getUtxos({address:i,fetchTxHex:d!==!1}),l=[{address:c,value:s?0:Number(t.getBaseValue("string"))},...u?[{script:u,value:0}]:[]],{inputs:h,outputs:m}=E({chain:V.Zcash,changeAddress:i,feeRate:o,inputs:a,outputs:l,sweep:s});if(!(h&&m))throw new Q("toolbox_utxo_insufficient_balance",{assetValue:t,sender:i});let f=Po({...await Ko(),expiryHeight:0,lockTime:0}),{tx:y,inputs:x}=ko({compiledMemo:u,inputs:h,outputs:m,sender:i,tx:f});return{inputs:x,outputs:m,tx:y}}function Ar(e={}){let t="scriptType"in e?e.scriptType:void 0,r=So(e).with({signer:Ut.not(Ut.nullish)},({signer:c})=>c).with({phrase:Ut.string},({phrase:c,derivationPath:u,index:a=0})=>{let{derivationPath:l}=Le({chain:V.Zcash,derivationPath:u,index:a,scriptType:t}),h=xo(l);return Bo({derivationPath:h,phrase:c})}).otherwise(()=>{return}),n=de({chain:V.Zcash,scriptType:t,signer:r});async function o(c){if(!r)throw new Q("toolbox_utxo_no_signer");return await r.signTransaction(c)}async function i(c){let u=await o(c);return n.broadcastTx(u.toHex())}async function d({recipient:c,assetValue:u,feeOptionKey:a=bo.Fast,sweep:l,...h}){let m=await r?.getAddress();if(!(r&&m))throw new Q("toolbox_utxo_no_signer");let f=h.feeRate||(await n.getFeeRates())[a],{tx:y}=await Pr({...h,assetValue:u,feeRate:f,recipient:c,sender:m,sweep:l}),S=(await r.signTransaction(y)).toHex();return n.broadcastTx(S)}function s({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let a=_r(c),h=Ur.fromMasterSeed(a).derive(u);if(!h.privateKey||!h.publicKey)throw new Q("toolbox_utxo_invalid_params");return{privateKey:h.privateKey,publicKey:h.publicKey}}function p({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let a=s({derivationPath:u,phrase:c}),l=U(V.Zcash);return Ao(l).encode(a.privateKey)}return{...n,createKeysForPath:s,createTransaction:Pr,getPrivateKeyFromMnemonic:p,signAndBroadcastTransaction:i,signTransaction:o,transfer:d,validateAddress:Pt}}import{hex as Fo}from"@scure/base";import{HDKey as Do}from"@scure/bip32";import{derivationPathToString as Io,NetworkDerivationPath as Ho,updateDerivationPath as Ro}from"@swapkit/helpers";function Mo({xpub:e,chain:t,count:r,startIndex:n=0,accountIndex:o,purpose:i,scriptType:d}){if(Z("count",r),r<1)throw RangeError("count must be at least 1");Z("startIndex",n),$e(t,d),dt({chain:t,purpose:i,scriptType:d});let s=U(t),p=Do.fromExtendedKey(e,s.bip32),c=i===void 0?void 0:Ro(Ho[t],{purpose:i}),u=re({accountIndex:o,chain:t,derivationPath:c}),a=pe(u),l=[];for(let h of[!1,!0]){let m=p.deriveChild(Number(h));for(let f=0;f<r;f++){let y=n+f,x=m.deriveChild(y);if(!x.publicKey)continue;let S=Oe({accountIndex:o,chain:t,change:h,derivationPath:c,index:y});l.push({accountIndex:a,address:De({chain:t,network:s,publicKey:x.publicKey,scriptType:d}),change:h,index:y,pubkey:Fo.encode(x.publicKey),...i===void 0?{}:{path:Io(S)}})}}return l}function Ki(e,t){switch(e){case Pe.BitcoinCash:return xr(t||{});case Pe.Zcash:return Ar(t);case Pe.Bitcoin:case Pe.Dogecoin:case Pe.Litecoin:case Pe.Dash:return de({chain:e,...t});default:throw new Eo("toolbox_utxo_not_supported",{chain:e})}}export{Yt as InputSizes,ws as MIN_TX_FEE,Xn as OP_RETURN_OVERHEAD,lt as OutputSizes,Cn as SEGWIT_MARKER_FLAG_WEIGHT,ht as TX_OVERHEAD,ie as UTXOScriptType,It as UtxoNetwork,E as accumulative,ce as addInputsAndOutputs,lr as addressFromKeysGetter,Z as assertDerivationIndex,he as baseUrl,ge as calculateTxSize,Rn as canSignBitcoinMessage,M as compileMemo,xr as createBCHToolbox,Lo as createCustomUtxoApi,Fr as createHDWalletHelpers,de as createUTXOToolbox,Ar as createZcashToolbox,Mo as deriveAddressesFromXpub,rs as detectAddressNetwork,Ce as getBchAddressType,Ke as getDustThreshold,ke as getInputScriptType,se as getInputSize,wt as getMissingSpendingMetadata,U as getNetworkForChain,je as getOutputSize,Bn as getOutputSizeForAddress,Ge as getScriptTypeForAddress,pe as getUTXOAccountIndexFromPath,re as getUTXOAccountPath,Oe as getUTXOAddressPath,pr as getUTXOAddressValidator,j as getUtxoAddressType,A as getUtxoApi,Vo as getUtxoNetwork,Ki as getUtxoToolbox,Tt as getWitnessOverhead,oo as getZcashAddressType,ft as isSegwitScriptType,ts as isValidAddress,zt as nonSegwitChains,z as stripPrefix,et as stripToCashAddress,Ee as toCashAddress,G as toLegacyAddress,so as toTransparentZcashAddress,Ne as tryDecodeAddress,Ie as validateBchAddress,sr as validateUtxoAddress,Pt as validateZcashAddress};
|
|
1
|
+
import{ia as Ft,ja as fn}from"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.js";import{NetworkDerivationPath as $n}from"@swapkit/helpers";function W(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`${e} must be a non-negative integer, got: ${t}`)}function se({accountIndex:e,chain:t,derivationPath:n}){if(e!==void 0)W("accountIndex",e);let[r,o,a]=n??$n[t];return[r,o,e??a]}function Be({accountIndex:e,change:t=!1,chain:n,derivationPath:r,index:o}){return W("index",o),[...se({accountIndex:e,chain:n,derivationPath:r}),Number(t),o]}function he(e){return e[2]??0}function Ln({deriveAddress:e,getBalance:t,getUtxos:n}){async function r(s){let{accountIndex:d,count:p,startIndex:c=0,change:i=!1}=s;if(W("count",p),p<1)throw RangeError("count must be at least 1");W("startIndex",c);let l=[];for(let f=0;f<p;f++){let g=await e({accountIndex:d,change:i,index:c+f});if(g)l.push(g)}return l}async function o(s){let{gapLimit:d=20,change:p=!1}=s??{},c=[],i=0,l=0;while(i<d){let f=await e({change:p,index:l});if(!f)break;if((await t(f.address)).some((h)=>h.getValue("number")>0))c.push(f),i=0;else i++;l++}return c}async function a(s=20){let[d,p]=await Promise.all([o({change:!1,gapLimit:s}),o({change:!0,gapLimit:s})]),c=[...d,...p],i=await Promise.all(c.map(async(f)=>{let T=(await t(f.address)).reduce((h,y)=>h+y.getValue("number"),0);return{...f,balance:T}})),l=i.reduce((f,g)=>f+g.balance,0);return{addresses:i,total:l}}async function u(s=20){let[d,p]=await Promise.all([o({change:!1,gapLimit:s}),o({change:!0,gapLimit:s})]),c=[...d,...p];return(await Promise.all(c.map(async(l)=>(await n(l.address)).map((g)=>({...g,address:l.address,derivationIndex:l.index,isChange:l.change}))))).flat()}return{deriveAddresses:r,getAggregatedBalance:a,getAggregatedUtxos:u,scanForAddresses:o}}import{Chain as S,getRPCUrl as Vn,RequestClient as Ne,SKConfig as It,SwapKitError as R,warnOnce as qn}from"@swapkit/helpers";import{NETWORKS as fe}from"@swapkit/utxo-signer";async function Gn({chain:e,txHash:t}){let n=`${Te(e)}/push/transaction`,r=JSON.stringify({data:t});try{let o=await Ne.post(n,{body:r,headers:{"Content-Type":"application/json"}});if(o.context.code!==200)throw new R("toolbox_utxo_broadcast_failed",{error:o.context.error||"Transaction broadcast failed"});return o.data?.transaction_hash||t}catch(o){let a=await Vn(e);if(a){let u=JSON.stringify({id:Ft(),jsonrpc:"2.0",method:"sendrawtransaction",params:[t]}),s=await Ne.post(a,{body:u,headers:{"Content-Type":"application/json"}});if(s.error)throw new R("toolbox_utxo_broadcast_failed",{error:s.error?.message});if(s.result.includes('"code":-26'))throw new R("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return s.result}throw o}}function Te(e){return`${(It.get("blockchairApiUrl")||"https://api.blockchair.com").replace(/\/+$/,"")}/${Yn(e)}`}function pt(e){switch(e){case S.Bitcoin:return 5;case S.Dogecoin:return 1e4;case S.Litecoin:return 1;case S.Zcash:return 1;default:return 2}}function Yn(e){switch(e){case S.BitcoinCash:return"bitcoin-cash";case S.Litecoin:return"litecoin";case S.Dash:return"dash";case S.Dogecoin:return"dogecoin";case S.Zcash:return"zcash";case S.Polkadot:return"polkadot";default:return"bitcoin"}}async function jn(e){if(e===S.Zcash)return pt(e);try{let{feePerKb:t}=await Ne.get(`https://app.bitgo.com/api/v2/${e.toLowerCase()}/tx/fee`),n=t/1000;return Math.max(n,pt(e))}catch{return pt(e)}}async function Ke(e,t){let n=await Ne.get(`${e}${t?`${e.includes("?")?"&":"?"}key=${t}`:""}`);if(!n||n.context.code!==200)throw new R("toolbox_utxo_api_error",{error:`Failed to query ${e}`});return n.data}async function Jn({chain:e,apiKey:t}){let n=await Ke(`${Te(e)}/stats`,t);if(typeof n.best_block_height!=="number")throw new R("toolbox_utxo_api_error",{error:"Missing best_block_height in stats response"});return n.best_block_height}async function Dt({address:e,chain:t,apiKey:n}){if(!e)throw new R("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await Ke(`${Te(t)}/dashboards/address/${e}?transaction_details=true`,n))[e]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function Qn({address:e,chain:t,apiKey:n}){return(await Dt({address:e,apiKey:n,chain:t}))?.address.balance||0}async function Ht({chain:e,apiKey:t,txHash:n}){if(!n)throw new R("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await Ke(`${Te(e)}/raw/transaction/${n}`,t))?.[n]?.raw_transaction||""}catch(r){let o=r instanceof Error?r.message:String(r);return console.error(`Failed to fetch raw transaction: ${o}`),""}}var er=4294967294;async function tr({chain:e,apiKey:t,txHash:n}){if(!n)throw new R("toolbox_utxo_invalid_params",{error:"TxHash is required"});let o=(await Ke(`${Te(e)}/dashboards/transaction/${n}`,t))?.[n];if(!o)throw new R("toolbox_utxo_tx_not_found",{txHash:n});let{transaction:a,inputs:u,outputs:s}=o,d=u.map((c)=>c.spending_sequence),p=a.is_rbf===!0||d.some((c)=>c<er);return{blockId:a.block_id,confirmed:a.block_id!==-1,fee:a.fee,inputs:u,isRBF:p,outputs:s,sequences:d,size:a.size,txid:a.hash,weight:a.weight}}async function nr({chain:e,address:t,apiKey:n,offset:r=0,limit:o=30}){return(await Ke(`${Te(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=${o}&offset=${r}`,n)).map(({is_spent:d,script_hex:p,block_id:c,transaction_hash:i,index:l,value:f,spending_signature_hex:g})=>({hash:i,index:l,is_confirmed:c!==-1,is_spent:d,script_hex:p,txHex:g,value:f}))}function rr(e){return e.reduce((t,n)=>t+n.value,0)}function kt(e,t){let n=[...e].sort((r,o)=>o.value-r.value);if(t){let r=[],o=0;for(let a of n)if(r.push(a),o+=a.value,o>=t)break;return r}return n}async function Rt({chain:e,address:t,apiKey:n,targetValue:r,accumulativeValue:o=0,offset:a=0,limit:u=30}){if(!t)throw new R("toolbox_utxo_invalid_params",{error:"Address is required"});try{let s=await nr({address:t,apiKey:n,chain:e,limit:u,offset:a,targetValue:r}),p=s.length<u,c=s.filter(({is_spent:h})=>!h),i=rr(c),l=o+i,f=r&&l>=r;if(p||f)return kt(c,r);let g=await Rt({accumulativeValue:l,address:t,apiKey:n,chain:e,limit:u,offset:a+u,targetValue:r}),T=[...c,...g];return kt(T,r)}catch(s){let d=s instanceof Error?s.message:String(s);return console.error(`Failed to fetch unspent UTXOs: ${d}`),[]}}async function or({address:e,chain:t,apiKey:n,fetchTxHex:r=!0,targetValue:o}){let a=await Rt({address:e,apiKey:n,chain:t,targetValue:o}),u=r?await Promise.all(a.map(({hash:s})=>Ht({apiKey:n,chain:t,txHash:s}))):[];return a.map(({hash:s,index:d,script_hex:p,value:c},i)=>({address:e,hash:s,index:d,txHex:r?u[i]:void 0,value:c,witnessUtxo:{script:Buffer.from(p,"hex"),value:c}}))}function A(e){let t=It.get("apiKeys").blockchair||"";return qn({condition:!t,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(n)=>Gn({chain:e,txHash:n}),getAddressData:(n)=>Dt({address:n,apiKey:t,chain:e}),getBalance:(n)=>Qn({address:n,apiKey:t,chain:e}),getBlockHeight:()=>Jn({apiKey:t,chain:e}),getRawTx:(n)=>Ht({apiKey:t,chain:e,txHash:n}),getSuggestedTxFee:()=>jn(e),getTransactionDetails:(n)=>tr({apiKey:t,chain:e,txHash:n}),getUtxos:(n)=>or({...n,apiKey:t,chain:e})}}function ls(e){return e}function hs(){return function(t){switch(t){case S.Bitcoin:return fe.bitcoin;case S.BitcoinCash:return fe.bitcoinCash;case S.Dash:return fe.dash;case S.Litecoin:return fe.litecoin;case S.Dogecoin:return fe.dogecoin;case S.Zcash:return fe.zcash;default:throw new R("toolbox_utxo_not_supported",{chain:t})}}}import{sha256 as pr}from"@noble/hashes/sha2.js";import{createBase58check as lr}from"@scure/base";import{SwapKitError as Mt}from"@swapkit/helpers";import{CashAddrType as ze,decodeCashAddr as sr,encodeCashAddr as ar}from"@swapkit/utxo-signer";var ir={P2PKH:ze.P2PKH,P2SH:ze.P2SH},cr={[ze.P2PKH]:"P2PKH",[ze.P2SH]:"P2SH"};function ur(e,t,n){return ar({hash:n,prefix:e,type:ir[t]})}function dr(e){let t=sr(e),n=cr[t.type];if(!n)throw Error(`Unknown CashAddr type: ${t.type}`);return{hash:t.hash,prefix:t.prefix,type:n}}var lt={decode:dr,encode:ur};var Zt=lr(pr);var Nt;((n)=>{n.Mainnet="mainnet";n.Testnet="testnet"})(Nt||={});var ae={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}},hr={["p2pkh"]:"pkh",["p2sh"]:"sh"};function ws(e){return $e(e)!==void 0}function Ps(e){return ht(e).network}function j(e){let t=ht(e);if(t.format==="legacy")return e;return mr(t)}function We(e){let t=ht(e);return gr(t)}function $e(e){if(typeof e!=="string")return;let t=fr(e)??Tr(e);return t&&{...t,scriptType:hr[t.type]}}function ht(e){let t=$e(e);if(!t)throw new Mt("toolbox_utxo_invalid_address",{address:e});return t}function fr(e){try{let t=Zt.decode(e);if(t.length!==21)throw new Mt("toolbox_utxo_invalid_address",{address:e});let n=t[0],r=Array.prototype.slice.call(t,1);switch(n){case ae.legacy.mainnet.p2pkh:return{format:"legacy",hash:r,network:"mainnet",type:"p2pkh"};case ae.legacy.mainnet.p2sh:return{format:"legacy",hash:r,network:"mainnet",type:"p2sh"};case ae.legacy.testnet.p2pkh:return{format:"legacy",hash:r,network:"testnet",type:"p2pkh"};case ae.legacy.testnet.p2sh:return{format:"legacy",hash:r,network:"testnet",type:"p2sh"};case ae.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2pkh"};case ae.bitpay.mainnet.p2sh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function Tr(e){if(e.indexOf(":")!==-1)try{return Et(e)}catch{}else{let t=["bitcoincash","bchtest","bchreg"];for(let n of t)try{return Et(`${n}:${e}`)}catch{}}return}function Et(e){try{let{hash:t,prefix:n,type:r}=lt.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 mr(e){let t=ae.legacy[e.network][e.type],n=Buffer.alloc(1+e.hash.length);return n[0]=t,n.set(e.hash,1),Zt.encode(n)}function gr(e){let t=e.network==="mainnet"?"bitcoincash":"bchtest",n=e.type==="p2pkh"?"P2PKH":"P2SH",r=new Uint8Array(e.hash);return lt.encode(t,n,r)}import{Chain as cn}from"@swapkit/helpers";import{Chain as be,SwapKitError as ce,UTXO_SCRIPT_TYPE_LIST as Rr,UTXO_SCRIPT_TYPES as Qt,UTXOScriptType as Je}from"@swapkit/helpers";import{Script as Er}from"@swapkit/utxo-signer";import{Chain as zt}from"@swapkit/helpers";import{getAddressScriptType as xr,getZcashAddressType as br}from"@swapkit/utxo-signer";import{match as wr}from"ts-pattern";import{Chain as me}from"@swapkit/helpers";import{NETWORKS as ge}from"@swapkit/utxo-signer";import{match as yr}from"ts-pattern";function U(e){return yr(e).with(me.Bitcoin,()=>ge.bitcoin).with(me.BitcoinCash,()=>ge.bitcoinCash).with(me.Dash,()=>ge.dash).with(me.Dogecoin,()=>ge.dogecoin).with(me.Litecoin,()=>ge.litecoin).with(me.Zcash,()=>ge.zcash).exhaustive()}function L(e){return e.replace(/(bchtest:|bitcoincash:)/,"")}function ke(e){if(typeof e!=="string")return null;let t=$e(L(e));if(!t||t.network!=="mainnet")return null;return t.scriptType}function J({address:e,chain:t}){return wr(t).with(zt.BitcoinCash,()=>ke(e)).with(zt.Zcash,()=>br(e)).otherwise(()=>xr(e,U(t)))}import{Chain as ie,derivationPathToString as Wt,getPurposeFromPath as Pr,getUTXOScriptTypeForPath as $t,getUTXOScriptTypeForPurpose as qt,resolveDerivationPath as Ur,SwapKitError as Fe,UTXO_SCRIPT_TYPE_LIST as Lt,UTXO_SCRIPT_TYPES as ye,UTXOChains as _r,UTXOScriptType as C,updateDerivationPath as vr,warnOnce as Ar}from"@swapkit/helpers";import{CashAddrPrefix as Or,CashAddrType as Sr,encodeCashAddr as Cr,OutScript as Gt,p2pkh as Xr,p2sh as Br,p2tr as Kr,p2wpkh as Vt}from"@swapkit/utxo-signer";var Le=Object.freeze([C.P2PKH]),kr=Object.freeze({[ie.Bitcoin]:Lt,[ie.BitcoinCash]:Le,[ie.Dash]:Le,[ie.Dogecoin]:Le,[ie.Litecoin]:Lt,[ie.Zcash]:Le});function qe(e){return kr[e]}function Tt(e){return qe(e).some((t)=>ye[t].witness)}function xe(e,t){return qe(e).includes(t)}function Ge(e,t){if(xe(e,t))return t;throw new Fe("toolbox_utxo_unsupported_script_type",{chain:e,error:`${e} cannot encode ${t}; supported: ${qe(e).join(", ")}`,scriptType:t,supported:qe(e)})}var Yt=_r.filter((e)=>!Tt(e));function Fr({purpose:e,scriptType:t}){let n=qt(e);return n===void 0||n===t}function mt({chain:e,purpose:t,scriptType:n}){Ar({condition:!Fr({purpose:t,scriptType:n}),id:`utxo_off_standard_encoding_${e}_${t}_${n}`,warning:`${e}: encoding m/${t}' keys as ${n}, not the ${qt(t)} the path implies. No other wallet derives these addresses: move funds out of them, never receive into them.`})}function Ye({chain:e,derivationPath:t,index:n=0,scriptType:r}){if(t){if(!r){let s=$t(t);throw new Fe("toolbox_utxo_invalid_params",{chain:e,derivationPath:Wt(t),error:`scriptType is required alongside derivationPath: getUTXOScriptTypeForPath gives the standard one${s?` (${s})`:""}, or state another deliberately.`})}return Ge(e,r),mt({chain:e,purpose:Pr(t),scriptType:r}),{derivationPath:t,scriptType:r}}let o=Ur({chain:e,index:n}),a=r?vr(o,{purpose:ye[r].purpose}):o,u=r??$t(a);if(!u)throw new Fe("toolbox_utxo_invalid_params",{chain:e,derivationPath:Wt(a),error:`${e}: the default derivation path has no standard script type`});return Ge(e,u),{derivationPath:a,scriptType:u}}function Ir(e){return e.length===32?e:e.slice(1)}function Ve(e,t){if(!e.address)throw new Fe("toolbox_utxo_invalid_address",{error:`Could not derive a ${t} address`});return e}var Dr={[C.P2PKH]:(e,t)=>{let{address:n,script:r}=Ve(Xr(e,t),C.P2PKH);return{address:n,script:r}},[C.P2SH_P2WPKH]:(e,t)=>{let n=Vt(e,t),{address:r,script:o}=Ve(Br(n,t),C.P2SH_P2WPKH);return{address:r,redeemScript:n.script,script:o}},[C.P2WPKH]:(e,t)=>{let{address:n,script:r}=Ve(Vt(e,t),C.P2WPKH);return{address:n,script:r}},[C.P2TR]:(e,t)=>{let n=Ir(e),{address:r,script:o}=Ve(Kr(n,void 0,t),C.P2TR);return{address:r,script:o,tapInternalKey:n}}};function je(e,t,n){return Dr[e](t,n)}function gt(e,t){if(e!==ie.BitcoinCash)return t.address;let n=Gt.decode(t.script);if(n.type!=="pkh")throw new Fe("toolbox_utxo_invalid_address",{chain:e,error:`Cannot encode ${n.type} as CashAddr`});return Cr({hash:n.hash,prefix:Or.MAINNET,type:Sr.P2PKH}).replace(/^bitcoincash:/,"")}var Hr=Object.freeze({pkh:C.P2PKH,sh:C.P2SH_P2WPKH,tr:C.P2TR,wpkh:C.P2WPKH}),ft=Object.freeze({pkh:ye[C.P2PKH].outputSize,sh:ye[C.P2SH_P2WPKH].outputSize,tr:ye[C.P2TR].outputSize,wpkh:ye[C.P2WPKH].outputSize,wsh:43});function jt(e){return e in ft}function Jt(e){if(e==="tex")return ft.pkh;return jt(e)?ft[e]:void 0}function Ie(e){return Hr[e]}function yt(e){try{let{type:t}=Gt.decode(e);return jt(t)?Ie(t):void 0}catch{return}}import{UTXOScriptType as ue}from"@swapkit/helpers";var Zs=1000,bt=10,Mr=2,Zr=10;function Q(e){switch(e){case be.Bitcoin:case be.BitcoinCash:return 550;case be.Dash:case be.Litecoin:return 5500;case be.Dogecoin:return 1e5;case be.Zcash:return 546;default:throw new ce("toolbox_utxo_not_supported",{chain:e})}}function Qe({inputs:e,outputs:t,fee:n,dustThreshold:r}){let o=e.reduce((s,d)=>s+d.value,0),a=o-n;if(a<=r)throw new ce("toolbox_sweep_amount_too_low",{available:o,dustThreshold:r,fee:n});let u=t.findIndex((s)=>("address"in s)&&s.address);if(u===-1)throw new ce("toolbox_utxo_invalid_params",{error:"Sweep requires a recipient output"});return{fee:n,inputs:e,outputs:t.map((s,d)=>d===u?{...s,value:a}:s)}}function E(e){let t=new Uint8Array(Buffer.from(e,"utf8"));return Er.encode(["RETURN",t])}function en(e){return Object.fromEntries(Rr.map((t)=>[t,Qt[t][e]]))}var tn=en("inputSize"),xt=en("outputSize"),wt=(e)=>Qt[e].witness,et=(e,t)=>{let n=J({address:e,chain:t});if(!n)throw new ce("toolbox_utxo_invalid_address",{address:e,chain:t});let r=Ie(n);if(!r||!xe(t,r))throw new ce("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},Nr=(e,t)=>{let n=J({address:e,chain:t});if(!n)throw new ce("toolbox_utxo_invalid_address",{address:e,chain:t});let r=Jt(n);if(!r)throw new ce("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},we=({chain:e,inputs:t,outputs:n,feeRate:r})=>{let o=t[0]?De(t[0],e):Je.P2PKH,a=r?t.filter((c)=>c.value>=tn["type"in c&&c.type?c.type:Je.P2PKH]*Math.ceil(r)):t,u=0,s=0;for(let c of a)if(u+=I(c,e),!wt(De(c,e)))s++;let d=n?.reduce((c,i)=>c+Pe(i,e),0)||xt[o],p=s<a.length;return bt+u+d+Pt(p,s)},De=(e,t)=>{if("type"in e&&e.type)return e.type;if("address"in e&&e.address)return et(e.address,t);return Je.P2PKH},I=(e,t)=>tn[De(e,t)],Pt=(e,t)=>e?Math.ceil((Mr+t)/4):0,Pe=(e,t,n)=>{if(e?.script)return Zr+e.script.length+(e.script.length>=74?2:1);if(n)return xt[n];if("address"in e&&e.address)return Nr(e.address,t);return xt[Je.P2PKH]};import{Chain as tt}from"@swapkit/helpers";var nt=5000,zr=1000,Wr=3590000,$r=12,Lr=2,nn=150,Vr=34,qr=5000;function Ue(e){return e!==void 0&&e>=Wr+$r?zr:nt}function Ut({inputBytes:e,outputBytes:t,marginalFee:n=nt}){let r=Math.max(Math.ceil(e/nn),Math.ceil(t/Vr));return n*Math.max(Lr,r)}function rn(e){if(!e.script)return Pe(e,tt.Zcash);let t=e.script.length;return 8+Gr(t)+t}function Gr(e){if(e<253)return 1;return e<=65535?3:5}function on(e){return e.reduce((t,n)=>t+rn(n),0)}function Yr({inputs:e,outputs:t,marginalFee:n}){return Ut({inputBytes:e.reduce((r,o)=>r+I(o,tt.Zcash),0),marginalFee:n,outputBytes:on(t)})}function jr(e,t=nt){return t*Math.ceil(I(e,tt.Zcash)/nn)}function sn(e=nt){return Ut({inputBytes:qr,marginalFee:e,outputBytes:0})}function an({inputs:e,outputs:t,changeAddress:n="",sweep:r=!1,marginalFee:o=Ue()}){let a=tt.Zcash,u=Q(a),s=on(t),d=(T,h=0)=>Ut({inputBytes:T,marginalFee:o,outputBytes:s+h}),p=[...e].sort((T,h)=>h.value-T.value),c=0,i=0,l=[];if(r){for(let h of p){let y=I(h,a),_=d(c+y)-d(c);if(h.value<=Math.max(_,u))continue;c+=y,l.push(h)}let T=Qe({dustThreshold:u,fee:d(c),inputs:l,outputs:t});return{fee:T.fee,inputs:T.inputs,outputs:T.outputs}}let f=rn({address:n,value:0}),g=t.reduce((T,h)=>T+h.value,0);for(let T of p){let h=I(T,a),y=d(c+h)-d(c);if(T.value<=y)continue;c+=h,i+=T.value,l.push(T);let _=d(c);if(i<_+g)continue;let G=d(c,f),ne=i-g-G;if(ne>Math.max(jr({value:0},o),u))return{fee:G,inputs:l,outputs:t.concat({address:n,value:ne})};return{fee:i-g,inputs:l,outputs:t}}return{fee:Yr({inputs:e,marginalFee:o,outputs:t})}}function M({inputs:e,outputs:t,feeRate:n=1,chain:r=cn.Bitcoin,changeAddress:o="",sweep:a=!1,marginalFee:u}){if(r===cn.Zcash)return an({changeAddress:o,inputs:e,marginalFee:u,outputs:t,sweep:a});let s=Q(r),d=e.filter((h)=>{let y=I(h,r)*n;return a?h.value>Math.max(y,s):y<=h.value});if(a){let h=Math.ceil(n*we({chain:r,inputs:d,outputs:t})),y=Qe({dustThreshold:s,fee:h,inputs:d,outputs:t});return{fee:y.fee,inputs:y.inputs,outputs:y.outputs}}let p=bt+t.reduce((h,y)=>h+Pe(y,r),0),c=t.reduce((h,y)=>h+y.value,0),i=0,l=0,f=!1,g=0,T=[];for(let h of d){if(i+=I(h,r),wt(De(h,r)))f=!0;else l++;g+=h.value,T.push(h);let y=(p+i+Pt(f,l))*n,_=y+c;if(g<_)continue;let G=g-_,ne=n*Pe({address:o,value:0},r);if(G>ne){let Oe=ne+y,Me=g-(c+Math.ceil(Oe));if(Me>Math.max(I({value:0},r)*n,Q(r)))return{fee:Math.ceil(Oe),inputs:T,outputs:t.concat({address:o,value:Me})}}return{fee:Math.ceil(y),inputs:T,outputs:t}}return{fee:Math.ceil(n*we({chain:r,inputs:e,outputs:t}))}}import{secp256k1 as Jr}from"@noble/curves/secp256k1.js";import{base64 as Qr,utf8 as un}from"@scure/base";import{SwapKitError as eo,UTXOScriptType as _t}from"@swapkit/helpers";import{CompactSize as to,utils as no}from"@swapkit/utxo-signer";var ro=un.decode(`\x18Bitcoin Signed Message:
|
|
2
|
+
`),dn={[_t.P2PKH]:31,[_t.P2SH_P2WPKH]:35,[_t.P2WPKH]:39};function oo(e){return dn[e]!==void 0}function so(e){let t=un.decode(e);return no.sha256x2(ro,to.encode(BigInt(t.length)),t)}function pn({message:e,privateKey:t,scriptType:n}){let r=dn[n];if(r===void 0)throw new eo("toolbox_utxo_unsupported_script_type",{error:`BIP-137 message signatures cannot express a ${n} address`,scriptType:n});let o=Jr.sign(so(e),t,{format:"recovered",prehash:!1}),[a=0]=o,u=new Uint8Array(65);return u[0]=r+a,u.set(o.subarray(1),1),Qr.encode(u)}import{Chain as Ae,SwapKitError as as}from"@swapkit/helpers";import{hex as An}from"@scure/base";import{Chain as Oo,derivationPathToString as So,FeeOption as Co,resolveDerivationPath as Xo,SwapKitError as q}from"@swapkit/helpers";import{BCHSigHash as Bo,CashAddrPrefix as On,CashAddrType as Sn,encodeCashAddr as Cn,NETWORKS as Ko,p2pkh as Xn,Transaction as Bn}from"@swapkit/utxo-signer";import{secp256k1 as ao}from"@noble/curves/secp256k1.js";import{hex as ee}from"@scure/base";import{HDKey as Tn}from"@scure/bip32";import{mnemonicToSeedSync as At}from"@scure/bip39";import{AssetValue as rt,applyFeeMultiplier as ln,Chain as N,derivationPathToString as He,FeeOption as Z,NetworkDerivationPath as io,SwapKitError as P,SwapKitNumber as co,UTXO_SCRIPT_TYPES as uo,warnOnce as po}from"@swapkit/helpers";import{BCHSigHash as mn,RBF_SEQUENCE as lo,SigHash as hn,Transaction as ot,utils as ho,WIF as gn}from"@swapkit/utxo-signer";var st=[N.Bitcoin];function yn({address:e,chain:t}){return J({address:e,chain:t})!==null}function fo({phrase:e,derivationPath:t,network:n,seed:r}){let o=r??At(e),u=Tn.fromMasterSeed(o,n.bip32).derive(t);if(!u.privateKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive private key from phrase"});return u.privateKey}function vt(e){return ao.getPublicKey(e,!0)}function Re({publicKey:e,chain:t,network:n,scriptType:r}){return gt(t,je(r,e,n))}function _e({phrase:e,derivationPath:t,chain:n,wif:r,seed:o}){let a=U(n);if(r){let p=gn(a).decode(r),c=vt(p);return{privateKey:p,publicKey:c}}if(!e)throw new P("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let u=t||He(io[n]),s=fo({derivationPath:u,network:a,phrase:e,seed:o}),d=vt(s);return{privateKey:s,publicKey:d}}function To(e,t){return gn(U(t)).encode(e)}function mo({phrase:e,derivationPath:t,chain:n,seed:r}){let o=t.split("/");if(o.length<4)throw new P("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${o.length}): ${t}`});let a=U(n),u=r??At(e),s=Tn.fromMasterSeed(u,a.bip32),d=o.slice(0,4).join("/");return s.derive(d)}function go(e,t){if(!e||!uo[e].witness)return!1;return e!==ue.P2SH_P2WPKH||!!t}function xn({chain:e,script:t,publicKey:n,network:r}){let o=yt(t);if(o!==ue.P2SH_P2WPKH&&o!==ue.P2TR)return{};if(!xe(e,o))return{};let a=je(o,n,r);if(ho.compareBytes(a.script,t)!==0)return{};return o===ue.P2TR?{tapInternalKey:a.tapInternalKey}:{redeemScript:a.redeemScript}}function yo(e,t,n){if(!n)return!1;let r=J({address:e,chain:t}),o=r?Ie(r):void 0;if(!o||!xe(t,o))return!1;let a=gt(t,je(o,n,U(t)));return t===N.BitcoinCash?L(a)===L(e):a===e}function xo(e){return e.witnessUtxo?.script??e.nonWitnessUtxo?.outputs[e.index??0]?.script}function Ot({chain:e,tx:t,publicKey:n,network:r,indexes:o}){let a=o??Array.from({length:t.inputsLength},(s,d)=>d),u=[];for(let s of a){let d=t.getInput(s),p=xo(d);if(!p)continue;let{redeemScript:c,tapInternalKey:i}=xn({chain:e,network:r,publicKey:n,script:p}),l={index:s};if(c&&!d.redeemScript)l.redeemScript=c;if(i&&!d.tapInternalKey)l.tapInternalKey=i;if(l.redeemScript||l.tapInternalKey)u.push(l)}return u}function de({inputs:e,outputs:t,chain:n,tx:r,sender:o,compiledMemo:a,enableRBF:u=!1}){let s=U(n),d=Tt(n),p=u?lo:void 0,c=new Set;for(let i of e){let l=`${i.hash}:${i.index}`;if(c.has(l))throw new P("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});c.add(l);let f=typeof i.hash==="string"?ee.decode(i.hash):i.hash,g=i.witnessUtxo?yt(i.witnessUtxo.script):void 0,T=i.publicKey&&i.witnessUtxo?xn({chain:n,network:s,publicKey:i.publicKey,script:i.witnessUtxo.script}):{};if(d&&i.witnessUtxo&&go(g,T.redeemScript))r.addInput({...T,index:i.index,sequence:p,txid:f,witnessUtxo:{amount:BigInt(i.witnessUtxo.value),script:i.witnessUtxo.script}});else if(i.txHex)r.addInput({...T,index:i.index,nonWitnessUtxo:ee.decode(i.txHex),sequence:p,txid:f,...n===N.BitcoinCash?{sighashType:mn.ALL}:{}});else throw new P("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:o;if(n===N.BitcoinCash)l=j(l);if(i.script)if(a)r.addOutput({amount:0n,script:a});else throw new P("toolbox_utxo_invalid_params",{error:"An output carrying a script needs the compiled memo it carries"});else r.addOutputAddress(l,BigInt(i.value),s)}return{inputs:e,tx:r}}async function ve(e){let t=await A(e).getSuggestedTxFee();return{[Z.Average]:t,[Z.Fast]:ln(t,Z.Fast),[Z.Fastest]:ln(t,Z.Fastest)}}async function St(e){if(e!==N.Zcash)return;try{return Ue(await A(N.Zcash).getBlockHeight()+1)}catch{return Ue()}}async function bn({assetValue:e,recipient:t,memo:n,sender:r,sweep:o,fetchTxHex:a=!1,publicKey:u},s,{forEstimateOnly:d=!1,marginalFee:p}={}){let c=e.chain,i=et(r,c),l=i===ue.P2PKH||i===ue.P2SH_P2WPKH&&!yo(r,c,u),f=a||!d&&l,g=e.getBaseValue("number"),T=o?void 0:s??(await ve(c))[Z.Fastest],h=c===N.Zcash?sn(p):(T??0)*5000,y=o||T===void 0?void 0:Math.ceil(g+h);return{inputs:await A(c).getUtxos({address:r,fetchTxHex:f,targetValue:y}),outputs:[{address:t,value:o?0:g},...n?[{address:"",script:E(n),value:0}]:[]]}}async function wn({assetValue:e,recipient:t,memo:n,feeRate:r,sender:o,fetchTxHex:a=!1,enableRBF:u=!1,sweep:s,publicKey:d}){let p=e.chain,c=n?E(n):null,i=await bn({assetValue:e,fetchTxHex:a,memo:n,publicKey:d,recipient:t,sender:o,sweep:s},r),{inputs:l,outputs:f}=M({...i,chain:p,changeAddress:o,feeRate:r,sweep:s});if(!(l&&f))throw new P("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let g=d?l.map((_)=>({..._,publicKey:d})):l,T=new ot({allowUnknownOutputs:!!c,version:1}),{inputs:h,tx:y}=de({chain:p,compiledMemo:c,enableRBF:u,inputs:g,outputs:f,sender:o,tx:T});return{inputs:h,tx:y,utxos:i.inputs}}async function Pn({assetValue:e,feeOptionKey:t=Z.Fast,feeRate:n,memo:r,sender:o,recipient:a,sweep:u}){let s=e.chain,d,p;if(n!==void 0)d=n,p=Math.floor(n);else{let l=await ve(s);d=l[Z.Fastest],p=l[t]}let c=await St(s),i=await bn({assetValue:e,memo:r,recipient:a,sender:o,sweep:u},d,{forEstimateOnly:!0,marginalFee:c});return M({...i,chain:s,changeAddress:o,feeRate:p,marginalFee:c,sweep:u})}function bo(e){return async function({from:n,memo:r,feeRate:o,feeOptionKey:a=Z.Fast,recipient:u=n,recipients:s=1}){let d=o??(await ve(e))[a],p=await St(e),c=await A(e).getUtxos({address:n,fetchTxHex:!1}),i=e===N.Zcash?c:c.filter((h)=>h.value>Math.max(Q(e),I(h,e)*d));if(!i.length)return rt.from({chain:e});let l=typeof s==="number"?Math.max(s,1):s.length,f=typeof s==="number"||l===0?Array.from({length:l||1},()=>({address:u,value:0})):[...s];if(r)f.push({address:n,script:E(r),value:0});let g;try{({outputs:g}=M({chain:e,feeRate:d,inputs:i,marginalFee:p,outputs:f,sweep:!0}))}catch(h){let y=h instanceof P&&h.errorKey==="toolbox_sweep_amount_too_low";if(e===N.Zcash&&y)return rt.from({chain:e});throw h}let T=g?.[0]?.value??0;return rt.from({chain:e,value:BigInt(T)})}}function wo(e){return async function(n){let{fee:r}=await Pn(n);return rt.from({chain:e,value:co.fromBigInt(BigInt(r),8).getValue("string")})}}function Po({chain:e,phrase:t,derivationPath:n,scriptType:r,seed:o}){let a=U(e),{privateKey:u,publicKey:s}=_e({chain:e,derivationPath:n,phrase:t,seed:o}),d=Un(e);return{getAddress:()=>Re({chain:e,network:a,publicKey:s,scriptType:r}),privateKey:u,publicKey:s,signTransaction:(p)=>{for(let{index:c,...i}of Ot({chain:e,network:a,publicKey:s,tx:p}))p.updateInput(c,i);return p.sign(u,d),p}}}function Un(e){return e===N.BitcoinCash?[mn.ALL]:[hn.ALL,hn.DEFAULT]}function Uo(e,t,n){return async function({memo:o,recipient:a,feeOptionKey:u,feeRate:s,assetValue:d,enableRBF:p=!1,sweep:c}){let i=await t?.getAddress();if(!(t&&i))throw new P("toolbox_utxo_no_signer");if(!a)throw new P("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});po({condition:p&&!st.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 l=p&&st.includes(e),f=s||(await ve(e))[u||Z.Fast],{tx:g}=await wn({assetValue:d,enableRBF:l,feeRate:f,memo:o,publicKey:n,recipient:a,sender:i,sweep:c}),T=await t.signTransaction(g);return T.finalize(),A(e).broadcastTx(ee.encode(T.extract()))}}function _n(e){return(t)=>yn({address:t,chain:e})}function vn(e,{scriptType:t}){let n=U(e);return function(o){if(!o)throw new P("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return Re({chain:e,network:n,publicKey:o.publicKey,scriptType:t})}}function _o(e){let t=e?.publicKey;if(t===void 0)return;if(t instanceof Uint8Array&&t.length===33)return t;throw new P("toolbox_utxo_invalid_params",{error:"signer.publicKey must be a 33-byte compressed public key (Uint8Array)"})}function pe(e){let{chain:t}=e,n=e.phrase?e:void 0;if(!n&&"derivationPath"in e&&e.derivationPath!==void 0)throw new P("toolbox_utxo_invalid_params",{error:"derivationPath needs a phrase; a toolbox built around a signer uses the signer's addresses"});let r=n?.phrase,o=n?.index??0,a=r?At(r):void 0,{derivationPath:u,scriptType:s}=Ye({chain:t,derivationPath:n?.derivationPath,index:o,scriptType:e.scriptType}),d=He(u),p=r?Po({chain:t,derivationPath:d,phrase:r,scriptType:s,seed:a}):void 0,c=n?void 0:e.signer,i=p||c,l=r?_e({chain:t,derivationPath:d,phrase:r,seed:a}):void 0,f=l?.publicKey??_o(c);function g(){if(i)return i.getAddress();return Promise.resolve(void 0)}function T(m){if(!r)return;let x=se({accountIndex:m,chain:t,derivationPath:u});return mo({chain:t,derivationPath:He(x),phrase:r,seed:a})}let h=T();function y(){if(!h)return;return h.publicExtendedKey}function _({accountIndex:m}={}){let x=m===void 0?h:T(m);if(!x)return;let w=se({accountIndex:m,chain:t,derivationPath:u});return{accountIndex:he(w),path:He(w),xpub:x.publicExtendedKey}}function G({accountIndex:m,index:x,change:w=!1}){let O=m===void 0?h:T(m);if(!O)return;let b=Be({accountIndex:m,chain:t,change:w,derivationPath:u,index:x}),K=U(t),D=O.deriveChild(Number(w)).deriveChild(x);if(!D.publicKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let X=Re({chain:t,network:K,publicKey:D.publicKey,scriptType:s}),k=ee.encode(D.publicKey);return{accountIndex:he(b),address:X,change:w,index:x,path:He(b),pubkey:k}}async function ne(m){if(!st.includes(t))return{reason:`RBF is not supported on ${t}`,supported:!1};let x=await A(t).getTransactionDetails(m);return{canReplace:x.isRBF&&!x.confirmed,confirmed:x.confirmed,enabled:x.isRBF,fee:x.fee,sequences:x.sequences,supported:!0}}async function Oe({txid:m,newFeeRate:x,recipient:w,memo:O}){if(!st.includes(t))throw new P("toolbox_utxo_rbf_not_supported",{chain:t});let b=await A(t).getTransactionDetails(m);if(!b.isRBF)throw new P("toolbox_utxo_tx_not_replaceable",{txid:m});if(b.confirmed)throw new P("toolbox_utxo_tx_already_confirmed",{blockId:b.blockId,txid:m});let K=b.inputs.reduce((v,F)=>v+F.value,0),X=b.outputs.find((v)=>v.recipient===w)?.value||0;if(X===0)throw new P("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let k=await Promise.all(b.inputs.map(async(v)=>{let F=await A(t).getRawTx(v.transaction_hash),B=ot.fromRaw(ee.decode(F),{allowUnknownOutputs:!0,disableScriptCheck:!0}).getOutput(v.index);return{address:v.recipient,hash:v.transaction_hash,index:v.index,publicKey:f,txHex:F,value:v.value,witnessUtxo:B.script&&B.amount!==void 0?{script:Buffer.from(B.script),value:Number(B.amount)}:void 0}})),H=O?E(O):null,re=K-X-b.fee,Se=await g(),le=[];if(H)le.push({address:"",script:H,value:0});if(re>Q(t)&&Se)le.push({address:Se,value:re});let Ze=we({chain:t,inputs:k.map((v)=>({...v,type:et(v.address,t)})),outputs:[{address:w,value:X},...le]}),Y=Math.ceil(Ze*x);if(Y<=b.fee)throw new P("toolbox_utxo_rbf_fee_too_low",{newFee:Y,originalFee:b.fee});let Ce=Y-b.fee,oe=X-Ce;if(oe<=0)throw new P("toolbox_utxo_rbf_insufficient_change");let Xe=new ot({allowUnknownOutputs:!!H,version:1}),ct=[{address:w,value:oe},...le];return de({chain:t,compiledMemo:H,inputs:k,outputs:ct,sender:Se||w,tx:Xe}),{feeDelta:Ce,newFee:Y,originalFee:b.fee,tx:Xe}}async function Me({txid:m,newFeeRate:x,recipient:w,memo:O}){let{tx:b,originalFee:K,newFee:D}=await Oe({memo:O,newFeeRate:x,recipient:w,txid:m}),X=await it(b);X.finalize();let k=await A(t).broadcastTx(ee.encode(X.extract()));return{newFee:D,originalFee:K,txid:k}}function Bt({accountIndex:m,index:x,change:w=!1}){W("index",x);let O=m===void 0?h:T(m);if(!O)return;return O.deriveChild(Number(w)).deriveChild(x).privateKey||void 0}function Kt({tx:m,inputDerivations:x}){if(!h)throw new P("toolbox_utxo_no_signer");let w=Un(t),O=U(t);for(let b=0;b<x.length;b++){let K=x[b];if(!K)continue;let{derivationIndex:D,isChange:X}=K,k=Bt({change:X,index:D});if(!k)throw new P("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${b} at index ${D}`});for(let{index:H,...re}of Ot({chain:t,indexes:[b],network:O,publicKey:vt(k),tx:m}))m.updateInput(H,re);m.signIdx(k,b,w)}return m}async function Mn({utxos:m,recipient:x,assetValue:w,memo:O,feeRate:b,feeOptionKey:K,changeAddress:D,sweep:X}){if(X)throw new P("toolbox_utxo_invalid_params",{error:"Sweep is not supported for transfers from multiple addresses"});if(!h)throw new P("toolbox_utxo_no_signer");let k=b||(await ve(t))[K||Z.Fast],H=O?E(O):null,re=[{address:x,value:w.getBaseValue("number")}];if(H)re.push({address:"",script:H,value:0});let Se=m.map(({address:v,hash:F,index:B,value:ut,txHex:Wn,witnessUtxo:dt})=>({address:v,hash:F,index:B,txHex:Wn,value:ut,witnessUtxo:dt?{script:dt.script,value:dt.value}:void 0})),le=m[0]?.address,Ze=D||await g()||le||x,{inputs:Y,outputs:Ce}=M({chain:t,changeAddress:Ze,feeRate:k,inputs:Se,marginalFee:await St(t),outputs:re});if(!(Y&&Ce))throw new P("toolbox_utxo_insufficient_balance",{assetValue:w,sender:"multiple addresses"});let oe=new ot({allowUnknownOutputs:!!H,version:1}),Xe=Y.map((v)=>{let F=m.find((B)=>B.hash===v.hash&&B.index===v.index);return F?{derivationIndex:F.derivationIndex,isChange:F.isChange}:{derivationIndex:0,isChange:!1}}),ct=Y.map((v,F)=>{let B=Xe[F],ut=B?h.deriveChild(Number(B.isChange)).deriveChild(B.derivationIndex).publicKey:null;return{...v,publicKey:ut??void 0}});return de({chain:t,compiledMemo:H,inputs:ct,outputs:Ce,sender:Ze,tx:oe}),Kt({inputDerivations:Xe,tx:oe}),oe.finalize(),A(t).broadcastTx(ee.encode(oe.extract()))}function Zn({address:m,gapLimit:x=20}){if(!h)return;for(let w=0;w<x;w++){let O=G({change:!1,index:w}),b=G({change:!0,index:w}),K=O?.address===m?!1:b?.address===m;if(O?.address===m||b?.address===m)return{change:K,index:w}}return}function it(m){if(!i)throw new P("toolbox_utxo_no_signer");return i.signTransaction(m)}let Nn=t===N.Bitcoin&&l?async(m)=>pn({message:m,privateKey:l.privateKey,scriptType:s}):void 0;async function zn(m){let x=await it(m);return x.finalize(),await A(t).broadcastTx(ee.encode(x.extract()))}return{accumulative:M,broadcastTx:(m)=>A(t).broadcastTx(m),bumpFee:Me,calculateTxSize:(m)=>we({...m,chain:t}),createKeysForPath:(m)=>_e({...m,chain:t}),createReplacementTransaction:Oe,createTransaction:(m)=>wn({publicKey:f,...m}),deriveAddressAtIndex:G,derivePrivateKeyAtIndex:Bt,estimateMaxSendableAmount:bo(t),estimateTransactionFee:wo(t),getAddress:g,getAddressFromKeys:vn(t,{scriptType:s}),getAddressType:(m)=>J({address:m,chain:t}),getBalance:fn(t),getExtendedPublicKey:y,getExtendedPublicKeyInfo:_,getFeeRates:()=>ve(t),getInputsOutputsFee:Pn,getNetworkForChain:()=>U(t),getPrivateKeyFromMnemonic:(m)=>To(_e({...m,chain:t}).privateKey,t),isRBFEnabled:ne,keys:l,resolveDerivationIndex:Zn,scriptType:s,signAndBroadcastTransaction:zn,signMessage:Nn,signTransaction:it,signTransactionWithMultipleKeys:Kt,transfer:Uo(t,i,f),transferFromMultipleAddresses:Mn,validateAddress:_n(t)}}import{getZcashAddressType as vo,toTransparentZcashAddress as Ao,validateZcashAddress as Ct}from"@swapkit/utxo-signer";function Ee(e){return ke(e)!==null}var z=Oo.BitcoinCash;function at(e){return L(We(e))}function ko(e){let t=U(z);function n(o){return o.sign(e.privateKey,[Bo.ALL]),o}function r(){let o=Xn(e.publicKey,t);if(!o.hash)throw new q("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let a=Cn({hash:o.hash,prefix:On.MAINNET,type:Sn.P2PKH});return Promise.resolve(a.replace(/^bitcoincash:/,""))}return{getAddress:r,signTransaction:n}}function Kn(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,o=Xo({chain:z,derivationPath:r,index:n}),a=So(o),u=t?_e({chain:z,derivationPath:a,phrase:t}):void 0,s=u?ko(u):("signer"in e)?e.signer:void 0;function d(){return Promise.resolve(s?.getAddress())}let p="scriptType"in e?e.scriptType:void 0,{getBalance:c,getFeeRates:i,broadcastTx:l,...f}=pe(t?{chain:z,index:n,phrase:t,...r?{derivationPath:r,scriptType:p}:{scriptType:p}}:{chain:z,scriptType:p});function g(y,_=!0){return c(L(We(y)))}function T(y){if(!s)throw new q("toolbox_utxo_no_signer");return s.signTransaction(y)}async function h(y){let _=await T(y);return _.finalize(),await l(An.encode(_.extract()))}return{...f,broadcastTx:l,buildTx:Io,createTransaction:kn,getAddress:d,getAddressFromKeys:Do,getBalance:g,getFeeRates:i,signAndBroadcastTransaction:h,signTransaction:T,stripPrefix:L,stripToCashAddress:at,transfer:Fo({broadcastTx:l,getFeeRates:i,signer:s}),validateAddress:Ee}}async function kn({assetValue:e,recipient:t,memo:n,feeRate:r,sender:o,sweep:a}){if(!Ee(t))throw new q("toolbox_utxo_invalid_address",{address:t});let u=Math.ceil(e.getBaseValue("number")+r*7500),s=await A(z).getUtxos({address:at(o),fetchTxHex:!0,targetValue:a?void 0:u}),d=n?E(n):null,p=[],c=j(t);if(p.push({address:c,value:a?0:e.getBaseValue("number")}),d)p.push({script:d,value:0});let{inputs:i,outputs:l}=M({chain:z,feeRate:r,inputs:s,outputs:p,sweep:a});if(!(i&&l))throw new q("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let f=new Bn({allowUnknownOutputs:!!d,version:1}),g=j(o),{inputs:T,tx:h}=de({chain:z,compiledMemo:d,inputs:i,outputs:l.map((y)=>("address"in y)&&y.address?{...y,address:j(y.address)}:y),sender:g,tx:f});return{inputs:T,tx:h,utxos:i}}function Fo({broadcastTx:e,getFeeRates:t,signer:n}){return async function({recipient:o,assetValue:a,feeOptionKey:u=Co.Fast,sweep:s,...d}){let p=await n?.getAddress();if(!(n&&p))throw new q("toolbox_utxo_no_signer");if(!o)throw new q("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let c=d.feeRate||(await t())[u],{tx:i}=await kn({...d,assetValue:a,feeRate:c,recipient:o,sender:p,sweep:s}),l=await n.signTransaction(i);return l.finalize(),e(An.encode(l.extract()))}}async function Io({assetValue:e,recipient:t,memo:n,feeRate:r,sender:o}){let a=We(t);if(!Ee(a))throw new q("toolbox_utxo_invalid_address",{address:a});let u=Math.ceil(e.getBaseValue("number")+r*7500),s=await A(z).getUtxos({address:at(o),fetchTxHex:!0,targetValue:u}),d=Number(r.toFixed(0)),p=n?E(n):null,c=[];if(c.push({address:j(t),value:e.getBaseValue("number")}),p)c.push({script:p,value:0});let{inputs:i,outputs:l}=M({chain:z,feeRate:d,inputs:s,outputs:c});if(!(i&&l))throw new q("toolbox_utxo_insufficient_balance",{assetValue:e,sender:o});let f=new Bn({allowUnknownOutputs:!!p,version:1}),{inputs:g,tx:T}=de({chain:z,compiledMemo:p,inputs:i,outputs:l,sender:j(o),tx:f});return{inputs:g,tx:T,utxos:s}}function Do(e){let t=Ko.bitcoinCash,n=Xn(e.publicKey,t);if(!n.hash)throw new q("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return Cn({hash:n.hash,prefix:On.MAINNET,type:Sn.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as Ho,hex as Ro}from"@scure/base";import{HDKey as Dn}from"@scure/bip32";import{mnemonicToSeedSync as Hn}from"@scure/bip39";import{Chain as V,derivationPathToString as Eo,FeeOption as Mo,SwapKitError as te}from"@swapkit/helpers";import{Address as Zo,createZcashTransaction as No,getZcashTransactionFormat as zo,isTransparentZcashAddress as Fn,OutScript as Wo,toTransparentZcashAddress as $o,utils as Rn,WIF as Lo,ZcashSigHash as Vo}from"@swapkit/utxo-signer";import{match as qo,P as Xt}from"ts-pattern";var Go=Ho(Rn.sha256);function Yo(e){return Go.encode(e)}function jo({phrase:e,derivationPath:t}){let n=Hn(e),o=Dn.fromMasterSeed(n).derive(t);if(!o.privateKey||!o.publicKey)throw new te("toolbox_utxo_invalid_params");let{privateKey:a,publicKey:u}=o,s=Rn.hash160(u),d=new Uint8Array([28,184]),p=new Uint8Array(d.length+s.length);p.set(d,0),p.set(s,d.length);let c=Yo(p);return{getAddress:()=>Promise.resolve(c),signTransaction:(i)=>{if(i.signAllInputs(a,u,Vo.ALL),"extract"in i)return i.finalizeAllInputs(),Promise.resolve(i.extract());return Promise.resolve(i)}}}function Jo({inputs:e,outputs:t,tx:n,sender:r,compiledMemo:o}){let a=U(V.Zcash);for(let u of e){let s=Zo(a).decode(r),d=Wo.encode(s);n.addInput({index:u.index,script:d,sequence:4294967295,txid:Ro.decode(u.hash),value:BigInt(u.value)})}for(let u of t){let s="address"in u&&u.address?u.address:r,d=u.script;if(d&&!o)continue;if(d&&o)n.addOutput({amount:0n,script:o});else n.addOutputAddress(s,BigInt(u.value),a)}return{inputs:e,tx:n}}async function Qo(){try{return await A(V.Zcash).getBlockHeight()+1}catch(e){throw new te({errorKey:"toolbox_utxo_api_error",info:{chain:V.Zcash,reason:"Block height is required to choose the Zcash transaction format"}},e)}}async function In(e){let{assetValue:t,recipient:n,memo:r,feeRate:o,sender:a,fetchTxHex:u,sweep:s}=e,d=U(V.Zcash);if(!Fn(a,d))throw new te("toolbox_utxo_invalid_address",{address:a});let p=$o(n);if(!Fn(p,d))throw new te("toolbox_utxo_invalid_address",{address:n,error:"Zcash transaction creation currently supports transparent addresses only"});let c=r?E(r):null,i=await A(V.Zcash).getUtxos({address:a,fetchTxHex:u!==!1}),l=[{address:p,value:s?0:Number(t.getBaseValue("string"))},...c?[{script:c,value:0}]:[]],f=await Qo(),{inputs:g,outputs:T}=M({chain:V.Zcash,changeAddress:a,feeRate:o,inputs:i,marginalFee:Ue(f),outputs:l,sweep:s});if(!(g&&T))throw new te("toolbox_utxo_insufficient_balance",{assetValue:t,sender:a});let h=No({...zo(f),expiryHeight:0,lockTime:0}),{tx:y,inputs:_}=Jo({compiledMemo:c,inputs:g,outputs:T,sender:a,tx:h});return{inputs:_,outputs:T,tx:y}}function En(e={}){let t="scriptType"in e?e.scriptType:void 0,n=qo(e).with({signer:Xt.not(Xt.nullish)},({signer:p})=>p).with({phrase:Xt.string},({phrase:p,derivationPath:c,index:i=0})=>{let{derivationPath:l}=Ye({chain:V.Zcash,derivationPath:c,index:i,scriptType:t}),f=Eo(l);return jo({derivationPath:f,phrase:p})}).otherwise(()=>{return}),r=pe({chain:V.Zcash,scriptType:t,signer:n});async function o(p){if(!n)throw new te("toolbox_utxo_no_signer");return await n.signTransaction(p)}async function a(p){let c=await o(p);return r.broadcastTx(c.toHex())}async function u({recipient:p,assetValue:c,feeOptionKey:i=Mo.Fast,sweep:l,...f}){let g=await n?.getAddress();if(!(n&&g))throw new te("toolbox_utxo_no_signer");let T=f.feeRate||(await r.getFeeRates())[i],{tx:h}=await In({...f,assetValue:c,feeRate:T,recipient:p,sender:g,sweep:l}),_=(await n.signTransaction(h)).toHex();return r.broadcastTx(_)}function s({phrase:p,derivationPath:c="m/44'/133'/0'/0/0"}){let i=Hn(p),f=Dn.fromMasterSeed(i).derive(c);if(!f.privateKey||!f.publicKey)throw new te("toolbox_utxo_invalid_params");return{privateKey:f.privateKey,publicKey:f.publicKey}}function d({phrase:p,derivationPath:c="m/44'/133'/0'/0/0"}){let i=s({derivationPath:c,phrase:p}),l=U(V.Zcash);return Lo(l).encode(i.privateKey)}return{...r,createKeysForPath:s,createTransaction:In,getPrivateKeyFromMnemonic:d,signAndBroadcastTransaction:a,signTransaction:o,transfer:u,validateAddress:Ct}}import{hex as es}from"@scure/base";import{HDKey as ts}from"@scure/bip32";import{derivationPathToString as ns,NetworkDerivationPath as rs,updateDerivationPath as os}from"@swapkit/helpers";function ss({xpub:e,chain:t,count:n,startIndex:r=0,accountIndex:o,purpose:a,scriptType:u}){if(W("count",n),n<1)throw RangeError("count must be at least 1");W("startIndex",r),Ge(t,u),mt({chain:t,purpose:a,scriptType:u});let s=U(t),d=ts.fromExtendedKey(e,s.bip32),p=a===void 0?void 0:os(rs[t],{purpose:a}),c=se({accountIndex:o,chain:t,derivationPath:p}),i=he(c),l=[];for(let f of[!1,!0]){let g=d.deriveChild(Number(f));for(let T=0;T<n;T++){let h=r+T,y=g.deriveChild(h);if(!y.publicKey)continue;let _=Be({accountIndex:o,chain:t,change:f,derivationPath:p,index:h});l.push({accountIndex:i,address:Re({chain:t,network:s,publicKey:y.publicKey,scriptType:u}),change:f,index:h,pubkey:es.encode(y.publicKey),...a===void 0?{}:{path:ns(_)}})}}return l}function oi(e,t){switch(e){case Ae.BitcoinCash:return Kn(t||{});case Ae.Zcash:return En(t);case Ae.Bitcoin:case Ae.Dogecoin:case Ae.Litecoin:case Ae.Dash:return pe({chain:e,...t});default:throw new as("toolbox_utxo_not_supported",{chain:e})}}export{tn as InputSizes,Zs as MIN_TX_FEE,Zr as OP_RETURN_OVERHEAD,xt as OutputSizes,Mr as SEGWIT_MARKER_FLAG_WEIGHT,bt as TX_OVERHEAD,ue as UTXOScriptType,Nt as UtxoNetwork,Wr as ZCASH_FEE_REDUCTION_HEIGHT,$r as ZCASH_FEE_REDUCTION_MARGIN_BLOCKS,Lr as ZIP317_GRACE_ACTIONS,nt as ZIP317_MARGINAL_FEE,nn as ZIP317_P2PKH_STANDARD_INPUT_SIZE,Vr as ZIP317_P2PKH_STANDARD_OUTPUT_SIZE,zr as ZIP317_REDUCED_MARGINAL_FEE,M as accumulative,an as accumulativeZcash,de as addInputsAndOutputs,vn as addressFromKeysGetter,W as assertDerivationIndex,Te as baseUrl,Qe as buildSweep,we as calculateTxSize,Yr as calculateZcashFee,Ut as calculateZip317Fee,oo as canSignBitcoinMessage,E as compileMemo,Kn as createBCHToolbox,ls as createCustomUtxoApi,Ln as createHDWalletHelpers,pe as createUTXOToolbox,En as createZcashToolbox,ss as deriveAddressesFromXpub,Ps as detectAddressNetwork,ke as getBchAddressType,Q as getDustThreshold,De as getInputScriptType,I as getInputSize,Ot as getMissingSpendingMetadata,U as getNetworkForChain,Pe as getOutputSize,Nr as getOutputSizeForAddress,et as getScriptTypeForAddress,he as getUTXOAccountIndexFromPath,se as getUTXOAccountPath,Be as getUTXOAddressPath,_n as getUTXOAddressValidator,J as getUtxoAddressType,A as getUtxoApi,hs as getUtxoNetwork,oi as getUtxoToolbox,Pt as getWitnessOverhead,vo as getZcashAddressType,sn as getZcashFeeBuffer,Ue as getZcashMarginalFee,wt as isSegwitScriptType,ws as isValidAddress,Yt as nonSegwitChains,L as stripPrefix,at as stripToCashAddress,We as toCashAddress,j as toLegacyAddress,Ao as toTransparentZcashAddress,$e as tryDecodeAddress,Ee as validateBchAddress,yn as validateUtxoAddress,Ct as validateZcashAddress};
|
|
@@ -7,9 +7,9 @@ type AccumulativeParams<T extends UTXOSizeInput> = {
|
|
|
7
7
|
chain: UTXOChain;
|
|
8
8
|
changeAddress?: string;
|
|
9
9
|
sweep?: boolean;
|
|
10
|
+
marginalFee?: number;
|
|
10
11
|
};
|
|
11
|
-
export declare function
|
|
12
|
-
export declare function accumulative<T extends UTXOSizeInput>({ inputs, outputs, feeRate, chain, changeAddress, sweep, }: AccumulativeParams<T>): {
|
|
12
|
+
export declare function accumulative<T extends UTXOSizeInput>({ inputs, outputs, feeRate, chain, changeAddress, sweep, marginalFee, }: AccumulativeParams<T>): {
|
|
13
13
|
fee: number;
|
|
14
14
|
inputs: T[];
|
|
15
15
|
outputs: TargetOutput[];
|
|
@@ -9,6 +9,17 @@ export declare const MIN_TX_FEE = 1000;
|
|
|
9
9
|
export declare const TX_OVERHEAD: number;
|
|
10
10
|
export declare const SEGWIT_MARKER_FLAG_WEIGHT = 2;
|
|
11
11
|
export declare const OP_RETURN_OVERHEAD: number;
|
|
12
|
+
export declare function getDustThreshold(chain: UTXOChain): 100000 | 550 | 5500 | 546;
|
|
13
|
+
export declare function buildSweep<T extends UTXOSizeInput>({ inputs, outputs, fee, dustThreshold, }: {
|
|
14
|
+
inputs: T[];
|
|
15
|
+
outputs: TargetOutput[];
|
|
16
|
+
fee: number;
|
|
17
|
+
dustThreshold: number;
|
|
18
|
+
}): {
|
|
19
|
+
fee: number;
|
|
20
|
+
inputs: T[];
|
|
21
|
+
outputs: TargetOutput[];
|
|
22
|
+
};
|
|
12
23
|
export declare function compileMemo(memo: string): Uint8Array;
|
|
13
24
|
export { UTXOScriptType } from "@swapkit/helpers";
|
|
14
25
|
export declare const InputSizes: Record<UTXOScriptType, number>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { TargetOutput, UTXOSizeInput } from "../types";
|
|
2
|
+
export declare const ZIP317_MARGINAL_FEE = 5000;
|
|
3
|
+
export declare const ZIP317_REDUCED_MARGINAL_FEE = 1000;
|
|
4
|
+
export declare const ZCASH_FEE_REDUCTION_HEIGHT = 3590000;
|
|
5
|
+
export declare const ZCASH_FEE_REDUCTION_MARGIN_BLOCKS = 12;
|
|
6
|
+
export declare const ZIP317_GRACE_ACTIONS = 2;
|
|
7
|
+
export declare const ZIP317_P2PKH_STANDARD_INPUT_SIZE = 150;
|
|
8
|
+
export declare const ZIP317_P2PKH_STANDARD_OUTPUT_SIZE = 34;
|
|
9
|
+
type ZcashFeeParams = {
|
|
10
|
+
inputs: UTXOSizeInput[];
|
|
11
|
+
outputs: TargetOutput[];
|
|
12
|
+
marginalFee?: number;
|
|
13
|
+
};
|
|
14
|
+
type ZcashSelectionParams<T extends UTXOSizeInput> = {
|
|
15
|
+
inputs: T[];
|
|
16
|
+
outputs: TargetOutput[];
|
|
17
|
+
changeAddress?: string;
|
|
18
|
+
sweep?: boolean;
|
|
19
|
+
marginalFee?: number;
|
|
20
|
+
};
|
|
21
|
+
export declare function getZcashMarginalFee(targetHeight?: number): 5000 | 1000;
|
|
22
|
+
export declare function calculateZip317Fee({ inputBytes, outputBytes, marginalFee, }: {
|
|
23
|
+
inputBytes: number;
|
|
24
|
+
outputBytes: number;
|
|
25
|
+
marginalFee?: number;
|
|
26
|
+
}): number;
|
|
27
|
+
export declare function calculateZcashFee({ inputs, outputs, marginalFee }: ZcashFeeParams): number;
|
|
28
|
+
export declare function getZcashFeeBuffer(marginalFee?: number): number;
|
|
29
|
+
export declare function accumulativeZcash<T extends UTXOSizeInput>({ inputs, outputs, changeAddress, sweep, marginalFee, }: ZcashSelectionParams<T>): {
|
|
30
|
+
fee: number;
|
|
31
|
+
inputs: T[];
|
|
32
|
+
outputs: TargetOutput[];
|
|
33
|
+
} | {
|
|
34
|
+
fee: number;
|
|
35
|
+
inputs?: undefined;
|
|
36
|
+
outputs?: undefined;
|
|
37
|
+
};
|
|
38
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"dependencies": { "@swapkit/helpers": "6.4.
|
|
2
|
+
"dependencies": { "@swapkit/helpers": "6.4.3", "@swapkit/utxo-signer": "3.3.0" },
|
|
3
3
|
"description": "SwapKit - Toolboxes",
|
|
4
4
|
"devDependencies": {
|
|
5
5
|
"@aptos-labs/ts-sdk": "7.0.1",
|
|
@@ -133,5 +133,5 @@
|
|
|
133
133
|
"type-check:go": "tsgo"
|
|
134
134
|
},
|
|
135
135
|
"type": "module",
|
|
136
|
-
"version": "6.6.
|
|
136
|
+
"version": "6.6.1"
|
|
137
137
|
}
|