@swapkit/toolboxes 5.1.2 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{ea as j2,fa as M2}from"../../chunk-nvfkjbyq.js";import"../../chunk-xbdjxeqd.js";import{NetworkDerivationPath as p2}from"@swapkit/helpers";function m(X,$){if(!Number.isInteger($)||$<0)throw RangeError(`${X} must be a non-negative integer, got: ${$}`)}function n({accountIndex:X,chain:$,derivationPath:J}){if(X!==void 0)m("accountIndex",X);let j=[...J?.slice(0,3)??p2[$].slice(0,3)];if(X!==void 0)j[2]=X;return j}function MX({accountIndex:X,change:$=!1,chain:J,derivationPath:j,index:Q}){return m("index",Q),[...n({accountIndex:X,chain:J,derivationPath:j}),Number($),Q]}function ZX(X){return X[2]??0}function d2({deriveAddress:X,getBalance:$,getUtxos:J}){async function j(Y){let{accountIndex:q,count:G,startIndex:W=0,change:U=!1}=Y;if(m("count",G),G<1)throw RangeError("count must be at least 1");m("startIndex",W);let L=[];for(let _=0;_<G;_++){let N=await X({accountIndex:q,change:U,index:W+_});if(N)L.push(N)}return L}async function Q(Y){let{gapLimit:q=20,change:G=!1}=Y??{},W=[],U=0,L=0;while(U<q){let _=await X({change:G,index:L});if(!_)break;if((await $(_.address)).some((D)=>D.getValue("number")>0))W.push(_),U=0;else U++;L++}return W}async function Z(Y=20){let[q,G]=await Promise.all([Q({change:!1,gapLimit:Y}),Q({change:!0,gapLimit:Y})]),W=[...q,...G],U=await Promise.all(W.map(async(_)=>{let H=(await $(_.address)).reduce((D,b)=>D+b.getValue("number"),0);return{..._,balance:H}})),L=U.reduce((_,N)=>_+N.balance,0);return{addresses:U,total:L}}async function z(Y=20){let[q,G]=await Promise.all([Q({change:!1,gapLimit:Y}),Q({change:!0,gapLimit:Y})]),W=[...q,...G];return(await Promise.all(W.map(async(L)=>{return(await J(L.address)).map((N)=>({...N,address:L.address,derivationIndex:L.index,isChange:L.change}))}))).flat()}return{deriveAddresses:j,getAggregatedBalance:Z,getAggregatedUtxos:z,scanForAddresses:Q}}import{Chain as T,getRPCUrl as r2,RequestClient as AX,SKConfig as n2,SwapKitError as v,warnOnce as i2}from"@swapkit/helpers";import{NETWORKS as GX}from"@swapkit/utxo-signer";async function s2({chain:X,txHash:$}){let J=`${YX(X)}/push/transaction`,j=JSON.stringify({data:$});try{let Q=await AX.post(J,{body:j,headers:{"Content-Type":"application/json"}});if(Q.context.code!==200)throw new v("toolbox_utxo_broadcast_failed",{error:Q.context.error||"Transaction broadcast failed"});return Q.data?.transaction_hash||$}catch(Q){let Z=await r2(X);if(Z){let z=JSON.stringify({id:j2(),jsonrpc:"2.0",method:"sendrawtransaction",params:[$]}),Y=await AX.post(Z,{body:z,headers:{"Content-Type":"application/json"}});if(Y.error)throw new v("toolbox_utxo_broadcast_failed",{error:Y.error?.message});if(Y.result.includes('"code":-26'))throw new v("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return Y.result}throw Q}}function YX(X){return`https://api.blockchair.com/${a2(X)}`}function $2(X){switch(X){case T.Bitcoin:return 5;case T.Dogecoin:return 1e4;case T.Litecoin:return 1;case T.Zcash:return 1;default:return 2}}function a2(X){switch(X){case T.BitcoinCash:return"bitcoin-cash";case T.Litecoin:return"litecoin";case T.Dash:return"dash";case T.Dogecoin:return"dogecoin";case T.Zcash:return"zcash";case T.Polkadot:return"polkadot";default:return"bitcoin"}}async function t2(X){try{let{feePerKb:$}=await AX.get(`https://app.bitgo.com/api/v2/${X.toLowerCase()}/tx/fee`),J=$/1000;return Math.max(J,$2(X))}catch{return $2(X)}}async function DX(X,$){let J=await AX.get(`${X}${$?`${X.includes("?")?"&":"?"}key=${$}`:""}`);if(!J||J.context.code!==200)throw new v("toolbox_utxo_api_error",{error:`Failed to query ${X}`});return J.data}async function e2({chain:X,apiKey:$}){let J=await DX(`${YX(X)}/stats`,$);if(typeof J.best_block_height!=="number")throw new v("toolbox_utxo_api_error",{error:"Missing best_block_height in stats response"});return J.best_block_height}async function Q2({address:X,chain:$,apiKey:J}){if(!X)throw new v("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await DX(`${YX($)}/dashboards/address/${X}?transaction_details=true`,J))[X]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function X0({address:X,chain:$,apiKey:J}){return(await Q2({address:X,apiKey:J,chain:$}))?.address.balance||0}async function Z2({chain:X,apiKey:$,txHash:J}){if(!J)throw new v("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await DX(`${YX(X)}/raw/transaction/${J}`,$))?.[J]?.raw_transaction||""}catch(j){let Q=j instanceof Error?j.message:String(j);return console.error(`Failed to fetch raw transaction: ${Q}`),""}}var $0=4294967294;async function J0({chain:X,apiKey:$,txHash:J}){if(!J)throw new v("toolbox_utxo_invalid_params",{error:"TxHash is required"});let Q=(await DX(`${YX(X)}/dashboards/transaction/${J}`,$))?.[J];if(!Q)throw new v("toolbox_utxo_tx_not_found",{txHash:J});let{transaction:Z,inputs:z,outputs:Y}=Q,q=z.map((W)=>W.spending_sequence),G=Z.is_rbf===!0||q.some((W)=>W<$0);return{blockId:Z.block_id,confirmed:Z.block_id!==-1,fee:Z.fee,inputs:z,isRBF:G,outputs:Y,sequences:q,size:Z.size,txid:Z.hash,weight:Z.weight}}async function j0({chain:X,address:$,apiKey:J,offset:j=0,limit:Q=30}){return(await DX(`${YX(X)}/outputs?q=recipient(${$}),is_spent(false)&s=value(desc)&fields=is_spent,transaction_hash,index,value,script_hex,block_id,spending_signature_hex&limit=${Q}&offset=${j}`,J)).map(({is_spent:q,script_hex:G,block_id:W,transaction_hash:U,index:L,value:_,spending_signature_hex:N})=>({hash:U,index:L,is_confirmed:W!==-1,is_spent:q,script_hex:G,txHex:N,value:_}))}function Q0(X){return X.reduce(($,J)=>$+J.value,0)}function J2(X,$){let J=[...X].sort((j,Q)=>Q.value-j.value);if($){let j=[],Q=0;for(let Z of J)if(j.push(Z),Q+=Z.value,Q>=$)break;return j}return J}async function G2({chain:X,address:$,apiKey:J,targetValue:j,accumulativeValue:Q=0,offset:Z=0,limit:z=30}){if(!$)throw new v("toolbox_utxo_invalid_params",{error:"Address is required"});try{let Y=await j0({address:$,apiKey:J,chain:X,limit:z,offset:Z,targetValue:j}),G=Y.length<z,W=Y.filter(({is_spent:D})=>!D),U=Q0(W),L=Q+U,_=j&&L>=j;if(G||_)return J2(W,j);let N=await G2({accumulativeValue:L,address:$,apiKey:J,chain:X,limit:z,offset:Z+z,targetValue:j}),H=[...W,...N];return J2(H,j)}catch(Y){let q=Y instanceof Error?Y.message:String(Y);return console.error(`Failed to fetch unspent UTXOs: ${q}`),[]}}async function Z0({address:X,chain:$,apiKey:J,fetchTxHex:j=!0,targetValue:Q}){let Z=await G2({address:X,apiKey:J,chain:$,targetValue:Q}),z=j?await Promise.all(Z.map(({hash:Y})=>Z2({apiKey:J,chain:$,txHash:Y}))):[];return Z.map(({hash:Y,index:q,script_hex:G,value:W},U)=>({address:X,hash:Y,index:q,txHex:j?z[U]:void 0,value:W,witnessUtxo:{script:Buffer.from(G,"hex"),value:W}}))}function I(X){let $=n2.get("apiKeys").blockchair||"";return i2({condition:!$,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(J)=>s2({chain:X,txHash:J}),getAddressData:(J)=>Q2({address:J,apiKey:$,chain:X}),getBalance:(J)=>X0({address:J,apiKey:$,chain:X}),getBlockHeight:()=>e2({apiKey:$,chain:X}),getRawTx:(J)=>Z2({apiKey:$,chain:X,txHash:J}),getSuggestedTxFee:()=>t2(X),getTransactionDetails:(J)=>J0({apiKey:$,chain:X,txHash:J}),getUtxos:(J)=>Z0({...J,apiKey:$,chain:X})}}function f1(X){return X}function A1(){return function($){switch($){case T.Bitcoin:return GX.bitcoin;case T.BitcoinCash:return GX.bitcoinCash;case T.Dash:return GX.dash;case T.Litecoin:return GX.litecoin;case T.Dogecoin:return GX.dogecoin;case T.Zcash:return GX.zcash;default:throw new v("toolbox_utxo_not_supported",{chain:$})}}}import{sha256 as U0}from"@noble/hashes/sha2.js";import{createBase58check as _0}from"@scure/base";import{SwapKitError as q2}from"@swapkit/helpers";import{CashAddrType as yX,decodeCashAddr as G0,encodeCashAddr as Y0}from"@swapkit/utxo-signer";var q0={P2PKH:yX.P2PKH,P2SH:yX.P2SH},L0={[yX.P2PKH]:"P2PKH",[yX.P2SH]:"P2SH"};function z0(X,$,J){return Y0({hash:J,prefix:X,type:q0[$]})}function W0(X){let $=G0(X),J=L0[$.type];if(!J)throw Error(`Unknown CashAddr type: ${$.type}`);return{hash:$.hash,prefix:$.prefix,type:J}}var hX={decode:W0,encode:z0};var L2=_0(U0);var z2;((J)=>{J.Mainnet="mainnet";J.Testnet="testnet"})(z2||={});var i={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}};function W2(X){try{return vX(X),!0}catch{return!1}}function U2(X){return vX(X)?.network}function o(X){let $=vX(X);if($?.format==="legacy")return X;return M0($)}function RX(X){let $=vX(X);return D0($)}function vX(X){try{let $=N0(X);if($)return $}catch{}try{let $=B0(X);if($)return $}catch{}throw new q2("toolbox_utxo_invalid_address",{address:X})}function N0(X){try{let $=L2.decode(X);if($.length!==21)throw new q2("toolbox_utxo_invalid_address",{address:X});let J=$[0],j=Array.prototype.slice.call($,1);switch(J){case i.legacy.mainnet.p2pkh:return{format:"legacy",hash:j,network:"mainnet",type:"p2pkh"};case i.legacy.mainnet.p2sh:return{format:"legacy",hash:j,network:"mainnet",type:"p2sh"};case i.legacy.testnet.p2pkh:return{format:"legacy",hash:j,network:"testnet",type:"p2pkh"};case i.legacy.testnet.p2sh:return{format:"legacy",hash:j,network:"testnet",type:"p2sh"};case i.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:j,network:"mainnet",type:"p2pkh"};case i.bitpay.mainnet.p2sh:return{format:"bitpay",hash:j,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function B0(X){if(X.indexOf(":")!==-1)try{return Y2(X)}catch{}else{let $=["bitcoincash","bchtest","bchreg"];for(let J of $)try{return Y2(`${J}:${X}`)}catch{}}return}function Y2(X){try{let{hash:$,prefix:J,type:j}=hX.decode(X);return{format:"cashaddr",hash:Array.prototype.slice.call($,0),network:J==="bitcoincash"?"mainnet":"testnet",type:j==="P2PKH"?"p2pkh":"p2sh"}}catch{return}}function M0(X){let $=i.legacy[X.network][X.type],J=Buffer.alloc(1+X.hash.length);return J[0]=$,J.set(X.hash,1),L2.encode(J)}function D0(X){let $=X.network==="mainnet"?"bitcoincash":"bchtest",J=X.type==="p2pkh"?"P2PKH":"P2SH",j=new Uint8Array(X.hash);return hX.encode($,J,j)}import{Chain as a,SwapKitError as dX}from"@swapkit/helpers";import{SwapKitError as H0}from"@swapkit/helpers";import{Script as C0}from"@swapkit/utxo-signer";var h1=1000,oX=10,uX=2,O0=10,k0=41,V0=107;function R(X){let $=new Uint8Array(Buffer.from(X,"utf8"));return C0.encode(["RETURN",$])}var pX;((J)=>{J.P2PKH="P2PKH";J.P2WPKH="P2WPKH"})(pX||={});var cX={["P2PKH"]:148,["P2WPKH"]:68},SX={["P2PKH"]:34,["P2WPKH"]:31},HX=(X)=>{if(X.startsWith("bc1")||X.startsWith("tb1")||X.startsWith("ltc1")||X.startsWith("tltc1"))return"P2WPKH";if(X.startsWith("1")||X.startsWith("m")||X.startsWith("n")||X.startsWith("bitcoincash:q")||X.startsWith("bitcoincash:p")||X.startsWith("q")||X.startsWith("p")||X.startsWith("L")||X.startsWith("M")||X.startsWith("3")||X.startsWith("D")||X.startsWith("A")||X.startsWith("9")||X.startsWith("X")||X.startsWith("7")||X.startsWith("y")||X.startsWith("t1")||X.startsWith("t3")||X.startsWith("tm"))return"P2PKH";throw new H0("toolbox_utxo_invalid_address",{address:X})},qX=({inputs:X,outputs:$,feeRate:J})=>{let j=X[0]&&"address"in X[0]&&X[0].address?HX(X[0].address):"P2PKH",Z=(J?X.filter((G)=>G.value>=cX["type"in G&&G.type?G.type:"P2PKH"]*Math.ceil(J)):X).reduce((G,W)=>G+s(W),0),z=$?.reduce((G,W)=>G+wX(W),0)||SX[j],Y=oX+Z+z;return j==="P2WPKH"?Math.ceil(Y+uX/4):Y},s=(X)=>{if("type"in X&&X.type)return cX[X.type];if("address"in X&&X.address)return cX[HX(X.address)];return k0+V0},wX=(X,$)=>{if(X?.script)return O0+X.script.length+(X.script.length>=74?2:1);if($)return SX[$];if("address"in X&&X.address)return SX[HX(X.address)];return SX.P2PKH};function CX(X){switch(X){case a.Bitcoin:case a.BitcoinCash:return 550;case a.Dash:case a.Litecoin:return 5500;case a.Dogecoin:return 1e5;case a.Zcash:return 546;default:throw new dX("toolbox_utxo_not_supported",{chain:X})}}function S({inputs:X,outputs:$,feeRate:J=1,chain:j=a.Bitcoin,changeAddress:Q="",sweep:Z=!1}){let z=CX(j),Y=X.filter((D)=>{let b=s(D)*J;return Z?D.value>Math.max(b,z):b<=D.value});if(Z){let D=Math.ceil(J*qX({inputs:Y,outputs:$})),b=Y.reduce((A,l)=>A+l.value,0),u=b-D;if(u<=z)throw new dX("toolbox_sweep_amount_too_low",{available:b,dustThreshold:z,fee:D});let p=$.findIndex((A)=>("address"in A)&&A.address);if(p===-1)throw new dX("toolbox_utxo_invalid_params",{error:"Sweep requires a recipient output"});return{fee:D,inputs:Y,outputs:$.map((A,l)=>l===p?{...A,value:u}:A)}}let W=(X[0]&&"address"in X[0]&&X[0].address?HX(X[0].address):"P2PKH")==="P2WPKH"?Math.ceil(uX/4):0,U=oX+W+$.reduce((D,b)=>D+wX(b),0),L=$.reduce((D,b)=>D+b.value,0),_=U*J,N=0,H=[];for(let D of Y){let b=s(D),u=J*b;_+=u,N+=D.value,H.push(D);let p=_+L;if(N<p)continue;let A=N-p,l=J*wX({address:Q,value:0});if(A>l){let IX=l+_,PX=N-(L+Math.ceil(IX));if(PX>Math.max(s({value:0})*J,CX(j)))return{fee:Math.ceil(IX),inputs:H,outputs:$.concat({address:Q,value:PX})}}return{fee:Math.ceil(_),inputs:H,outputs:$}}return{fee:Math.ceil(J*qX({inputs:X,outputs:$}))}}import{Chain as _X,SwapKitError as b1}from"@swapkit/helpers";import{hex as E2}from"@scure/base";import{Chain as x0,derivationPathToString as h0,FeeOption as c0,NetworkDerivationPath as o0,SwapKitError as h,updateDerivationPath as u0}from"@swapkit/helpers";import{BCHSigHash as p0,CashAddrPrefix as f2,CashAddrType as A2,encodeCashAddr as y2,NETWORKS as d0,p2pkh as R2,Transaction as v2}from"@swapkit/utxo-signer";import{secp256k1 as b0}from"@noble/curves/secp256k1.js";import{hex as e}from"@scure/base";import{HDKey as D2}from"@scure/bip32";import{mnemonicToSeedSync as iX}from"@scure/bip39";import{AssetValue as rX,applyFeeMultiplier as _2,Chain as P,derivationPathToString as kX,FeeOption as w,NetworkDerivationPath as H2,SwapKitError as V,SwapKitNumber as I0,updateDerivationPath as P0,warnOnce as T0}from"@swapkit/helpers";import{Address as F0,BCHSigHash as sX,CashAddrPrefix as E0,CashAddrType as f0,encodeCashAddr as A0,NETWORKS as zX,p2pkh as N2,p2wpkh as y0,RBF_SEQUENCE as R0,SigHash as C2,Transaction as nX,WIF as O2}from"@swapkit/utxo-signer";import{match as k2}from"ts-pattern";import{validateZcashAddress as OX}from"@swapkit/utxo-signer";function LX(X){return X.replace(/(bchtest:|bitcoincash:)/,"")}function t(X){let $=LX(X);return W2($)&&U2($)==="mainnet"}var mX=[P.Dash,P.Dogecoin,P.Zcash,P.BitcoinCash],KX=[P.Bitcoin];function V2({address:X,chain:$}){return k2($).with(P.BitcoinCash,()=>t(X)).with(P.Zcash,()=>OX(X)).otherwise(()=>{try{return F0(E($)).decode(X),!0}catch{return!1}})}function E(X){return k2(X).with(P.Bitcoin,()=>zX.bitcoin).with(P.BitcoinCash,()=>zX.bitcoinCash).with(P.Dash,()=>zX.dash).with(P.Dogecoin,()=>zX.dogecoin).with(P.Litecoin,()=>zX.litecoin).with(P.Zcash,()=>zX.zcash).exhaustive()}function v0({phrase:X,derivationPath:$,network:J,seed:j}){let Q=j??iX(X),z=D2.fromMasterSeed(Q,J.bip32).derive($);if(!z.privateKey)throw new V("toolbox_utxo_invalid_params",{error:"Could not derive private key from phrase"});return z.privateKey}function B2(X){return b0.getPublicKey(X,!0)}function VX({publicKey:X,chain:$,network:J}){if($===P.BitcoinCash){let Z=N2(X,J);if(!Z.hash)throw new V("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return A0({hash:Z.hash,prefix:E0.MAINNET,type:f0.P2PKH}).replace(/^bitcoincash:/,"")}let Q=!mX.includes($)?y0(X,J):N2(X,J);if(!Q.address)throw new V("toolbox_utxo_invalid_address",{error:"Could not derive address"});return Q.address}function WX({phrase:X,derivationPath:$,chain:J,wif:j,seed:Q}){let Z=E(J);if(j){let G=O2(Z).decode(j),W=B2(G);return{privateKey:G,publicKey:W}}if(!X)throw new V("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let z=$||kX(H2[J]),Y=v0({derivationPath:z,network:Z,phrase:X,seed:Q}),q=B2(Y);return{privateKey:Y,publicKey:q}}function S0(X,$){return O2(E($)).encode(X)}function w0({phrase:X,derivationPath:$,chain:J,seed:j}){let Q=$.split("/");if(Q.length<4)throw new V("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${Q.length}): ${$}`});let Z=E(J),z=j??iX(X),Y=D2.fromMasterSeed(z,Z.bip32),q=Q.slice(0,4).join("/");return Y.derive(q)}function XX({inputs:X,outputs:$,chain:J,tx:j,sender:Q,compiledMemo:Z,enableRBF:z=!1}){let Y=E(J),q=!mX.includes(J),G=z?R0:void 0,W=new Set;for(let U of X){let L=`${U.hash}:${U.index}`;if(W.has(L))throw new V("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});W.add(L);let _=typeof U.hash==="string"?e.decode(U.hash):U.hash;if(q&&U.witnessUtxo)j.addInput({index:U.index,sequence:G,txid:_,witnessUtxo:{amount:BigInt(U.witnessUtxo.value),script:U.witnessUtxo.script}});else if(U.txHex)j.addInput({index:U.index,nonWitnessUtxo:e.decode(U.txHex),sequence:G,txid:_,...J===P.BitcoinCash?{sighashType:sX.ALL}:{}});else throw new V("toolbox_utxo_invalid_params",{error:"Input requires either witnessUtxo or txHex for non-segwit chains"})}for(let U of $){let L="address"in U&&U.address?U.address:Q;if(J===P.BitcoinCash)L=o(L);if(U.script){if(Z)j.addOutput({amount:0n,script:Z})}else j.addOutputAddress(L,BigInt(U.value),Y)}return{inputs:X,tx:j}}async function UX(X){let $=await I(X).getSuggestedTxFee();return{[w.Average]:$,[w.Fast]:_2($,w.Fast),[w.Fastest]:_2($,w.Fastest)}}async function b2({assetValue:X,recipient:$,memo:J,sender:j,sweep:Q,fetchTxHex:Z=!1},z){let Y=X.chain,q=Z||mX.includes(Y),G=X.getBaseValue("number"),W=Q?void 0:z??(await UX(Y))[w.Fastest],U=Q||W===void 0?void 0:Math.ceil(G+W*5000);return{inputs:await I(Y).getUtxos({address:j,fetchTxHex:q,targetValue:U}),outputs:[{address:$,value:Q?0:G},...J?[{address:"",script:R(J),value:0}]:[]]}}async function I2({assetValue:X,recipient:$,memo:J,feeRate:j,sender:Q,fetchTxHex:Z=!1,enableRBF:z=!1,sweep:Y}){let q=X.chain,G=J?R(J):null,W=await b2({assetValue:X,fetchTxHex:Z,memo:J,recipient:$,sender:Q,sweep:Y},j),{inputs:U,outputs:L}=S({...W,chain:q,feeRate:j,sweep:Y});if(!(U&&L))throw new V("toolbox_utxo_insufficient_balance",{assetValue:X,sender:Q});let _=new nX({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!G,version:1}),{inputs:N,tx:H}=XX({chain:q,compiledMemo:G,enableRBF:z,inputs:U,outputs:L,sender:Q,tx:_});return{inputs:N,tx:H,utxos:W.inputs}}async function P2({assetValue:X,feeOptionKey:$=w.Fast,feeRate:J,memo:j,sender:Q,recipient:Z,sweep:z}){let Y=X.chain,q,G;if(J!==void 0)q=J,G=Math.floor(J);else{let U=await UX(Y);q=U[w.Fastest],G=U[$]}let W=await b2({assetValue:X,memo:j,recipient:Z,sender:Q,sweep:z},q);return S({...W,chain:Y,feeRate:G,sweep:z})}function K0(X){return async function({from:J,memo:j,feeRate:Q,feeOptionKey:Z=w.Fast,recipient:z=J,recipients:Y=1}){let q=Q??(await UX(X))[Z],W=(await I(X).getUtxos({address:J,fetchTxHex:!1})).filter((H)=>H.value>Math.max(CX(X),s(H)*q));if(!W.length)return rX.from({chain:X});let U=typeof Y==="number"?Math.max(Y,1):Y.length,L=typeof Y==="number"||U===0?Array.from({length:U||1},()=>({address:z,value:0})):[...Y];if(j)L.push({address:J,script:R(j),value:0});let{outputs:_}=S({chain:X,feeRate:q,inputs:W,outputs:L,sweep:!0}),N=_?.[0]?.value??0;return rX.from({chain:X,value:BigInt(N)})}}function m0(X){return async function(J){let{fee:j}=await P2(J);return rX.from({chain:X,value:I0.fromBigInt(BigInt(j),8).getValue("string")})}}function g0({chain:X,phrase:$,derivationPath:J,seed:j}){let Q=E(X),{privateKey:Z,publicKey:z}=WX({chain:X,derivationPath:J,phrase:$,seed:j}),Y=X===P.BitcoinCash?[sX.ALL]:[C2.ALL];return{getAddress:()=>VX({chain:X,network:Q,publicKey:z}),privateKey:Z,publicKey:z,signTransaction:(q)=>{return q.sign(Z,Y),q}}}function l0(X,$){return async function({memo:j,recipient:Q,feeOptionKey:Z,feeRate:z,assetValue:Y,enableRBF:q=!1,sweep:G}){let W=await $?.getAddress();if(!($&&W))throw new V("toolbox_utxo_no_signer");if(!Q)throw new V("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});T0({condition:q&&!KX.includes(X),id:`rbf_not_supported_${X}`,warning:`RBF (Replace-by-Fee) is not reliably supported on ${X}. Transaction will be created without RBF signaling.`});let U=q&&KX.includes(X),L=z||(await UX(X))[Z||w.Fast],{tx:_}=await I2({assetValue:Y,enableRBF:U,feeRate:L,memo:j,recipient:Q,sender:W,sweep:G}),N=await $.signTransaction(_);return N.finalize(),I(X).broadcastTx(e.encode(N.extract()))}}function T2(X){return($)=>V2({address:$,chain:X})}function F2(X){let $=E(X);return function(j){if(!j)throw new V("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return VX({chain:X,network:$,publicKey:j.publicKey})}}function $X({chain:X,...$}){let J="phrase"in $?$.phrase:void 0,j="index"in $?$.index||0:0,Q=J?iX(J):void 0,Z="derivationPath"in $&&$.derivationPath?$.derivationPath:P0(H2[X],{index:j}),z=kX(Z),Y=J?g0({chain:X,derivationPath:z,phrase:J,seed:Q}):void 0,q="signer"in $?$.signer:void 0,G=Y||q,W=J?WX({chain:X,derivationPath:z,phrase:J,seed:Q}):void 0;function U(){if(G)return G.getAddress();return Promise.resolve(void 0)}function L(B){if(!J)return;let M=n({accountIndex:B,chain:X,derivationPath:Z});return w0({chain:X,derivationPath:kX(M),phrase:J,seed:Q})}let _=L();function N(){if(!_)return;return _.publicExtendedKey}function H({accountIndex:B}={}){let M=B===void 0?_:L(B);if(!M)return;let C=n({accountIndex:B,chain:X,derivationPath:Z});return{accountIndex:ZX(C),path:kX(C),xpub:M.publicExtendedKey}}function D({accountIndex:B,index:M,change:C=!1}){let O=B===void 0?_:L(B);if(!O)return;let k=MX({accountIndex:B,chain:X,change:C,derivationPath:Z,index:M}),y=E(X),K=O.deriveChild(Number(C)).deriveChild(M);if(!K.publicKey)throw new V("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let f=VX({chain:X,network:y,publicKey:K.publicKey}),c=e.encode(K.publicKey);return{accountIndex:ZX(k),address:f,change:C,index:M,path:kX(k),pubkey:c}}async function b(B){if(!KX.includes(X))return{reason:`RBF is not supported on ${X}`,supported:!1};let M=await I(X).getTransactionDetails(B);return{canReplace:M.isRBF&&!M.confirmed,confirmed:M.confirmed,enabled:M.isRBF,fee:M.fee,sequences:M.sequences,supported:!0}}async function u({txid:B,newFeeRate:M,recipient:C,memo:O}){if(!KX.includes(X))throw new V("toolbox_utxo_rbf_not_supported",{chain:X});let k=await I(X).getTransactionDetails(B);if(!k.isRBF)throw new V("toolbox_utxo_tx_not_replaceable",{txid:B});if(k.confirmed)throw new V("toolbox_utxo_tx_already_confirmed",{blockId:k.blockId,txid:B});let y=k.inputs.reduce((F,x)=>F+x.value,0),f=k.outputs.find((F)=>F.recipient===C)?.value||0;if(f===0)throw new V("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let c=await Promise.all(k.inputs.map(async(F)=>{let x=await I(X).getRawTx(F.transaction_hash);return{hash:F.transaction_hash,index:F.index,txHex:x,value:F.value,witnessUtxo:void 0}})),NX=O?R(O):null,TX=qX({feeRate:M,inputs:c.map((F)=>({...F,type:"P2WPKH"})),outputs:[{address:C,value:f}]}),d=Math.ceil(TX*M);if(d<=k.fee)throw new V("toolbox_utxo_rbf_fee_too_low",{newFee:d,originalFee:k.fee});let jX=d-k.fee,QX=f-jX;if(QX<=0)throw new V("toolbox_utxo_rbf_insufficient_change");let r=new nX({allowLegacyWitnessUtxo:!0,version:1}),FX=[{address:C,value:QX},...O?[{address:"",script:R(O),value:0}]:[]],EX=y-QX-d,BX=await U();if(EX>CX(X)&&BX)FX.push({address:BX,value:EX});return XX({chain:X,compiledMemo:NX,inputs:c,outputs:FX,sender:BX||C,tx:r}),{feeDelta:jX,newFee:d,originalFee:k.fee,tx:r}}async function p({txid:B,newFeeRate:M,recipient:C,memo:O}){let{tx:k,originalFee:y,newFee:K}=await u({memo:O,newFeeRate:M,recipient:C,txid:B}),f=await lX(k);f.finalize();let c=await I(X).broadcastTx(e.encode(f.extract()));return{newFee:K,originalFee:y,txid:c}}function A({accountIndex:B,index:M,change:C=!1}){m("index",M);let O=B===void 0?_:L(B);if(!O)return;return O.deriveChild(Number(C)).deriveChild(M).privateKey||void 0}function l({tx:B,inputDerivations:M}){if(!_)throw new V("toolbox_utxo_no_signer");let C=X===P.BitcoinCash?[sX.ALL]:[C2.ALL];for(let O=0;O<M.length;O++){let k=M[O];if(!k)continue;let{derivationIndex:y,isChange:K}=k,f=A({change:K,index:y});if(!f)throw new V("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${O} at index ${y}`});B.signIdx(f,O,C)}return B}async function IX({utxos:B,recipient:M,assetValue:C,memo:O,feeRate:k,feeOptionKey:y,changeAddress:K,sweep:f}){if(f)throw new V("toolbox_utxo_invalid_params",{error:"Sweep is not supported for transfers from multiple addresses"});if(!_)throw new V("toolbox_utxo_no_signer");let c=k||(await UX(X))[y||w.Fast],NX=O?R(O):null,TX=[{address:M,value:C.getBaseValue("number")}];if(NX)TX.push({address:"",script:NX,value:0});let d=B.map(({hash:F,index:x,value:fX,txHex:u2,witnessUtxo:xX})=>({hash:F,index:x,txHex:u2,value:fX,witnessUtxo:xX?{script:xX.script,value:xX.value}:void 0})),{inputs:jX,outputs:QX}=S({chain:X,feeRate:c,inputs:d,outputs:TX});if(!(jX&&QX))throw new V("toolbox_utxo_insufficient_balance",{assetValue:C,sender:"multiple addresses"});let r=new nX({allowLegacyWitnessUtxo:!0,version:1}),FX=B[0]?.address,EX=K||await U()||FX||M;XX({chain:X,compiledMemo:NX,inputs:jX,outputs:QX,sender:EX,tx:r});let BX=jX.map((F)=>{let x=B.find((fX)=>fX.hash===F.hash&&fX.index===F.index);return x?{derivationIndex:x.derivationIndex,isChange:x.isChange}:{derivationIndex:0,isChange:!1}});return l({inputDerivations:BX,tx:r}),r.finalize(),I(X).broadcastTx(e.encode(r.extract()))}function PX({address:B,gapLimit:M=20}){if(!_)return;for(let C=0;C<M;C++){let O=D({change:!1,index:C}),k=D({change:!0,index:C}),y=O?.address===B?!1:k?.address===B;if(O?.address===B||k?.address===B)return{change:y,index:C}}return}function lX(B){if(!G)throw new V("toolbox_utxo_no_signer");return G.signTransaction(B)}async function o2(B){let M=await lX(B);return M.finalize(),await I(X).broadcastTx(e.encode(M.extract()))}return{accumulative:S,broadcastTx:(B)=>I(X).broadcastTx(B),bumpFee:p,calculateTxSize:qX,createKeysForPath:(B)=>WX({...B,chain:X}),createReplacementTransaction:u,createTransaction:I2,deriveAddressAtIndex:D,derivePrivateKeyAtIndex:A,estimateMaxSendableAmount:K0(X),estimateTransactionFee:m0(X),getAddress:U,getAddressFromKeys:F2(X),getBalance:M2(X),getExtendedPublicKey:N,getExtendedPublicKeyInfo:H,getFeeRates:()=>UX(X),getInputsOutputsFee:P2,getNetworkForChain:()=>E(X),getPrivateKeyFromMnemonic:(B)=>S0(WX({...B,chain:X}).privateKey,X),isRBFEnabled:b,keys:W,resolveDerivationIndex:PX,signAndBroadcastTransaction:o2,signTransaction:lX,signTransactionWithMultipleKeys:l,transfer:l0(X,G),transferFromMultipleAddresses:IX,validateAddress:T2(X)}}var g=x0.BitcoinCash;function gX(X){return LX(RX(X))}function r0(X){let $=E(g);function J(Q){return Q.sign(X.privateKey,[p0.ALL]),Q}function j(){let Q=R2(X.publicKey,$);if(!Q.hash)throw new h("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let Z=y2({hash:Q.hash,prefix:f2.MAINNET,type:A2.P2PKH});return Promise.resolve(Z.replace(/^bitcoincash:/,""))}return{getAddress:j,signTransaction:J}}function S2(X){let $="phrase"in X?X.phrase:void 0,J="index"in X?X.index||0:0,j=h0("derivationPath"in X&&X.derivationPath?X.derivationPath:u0(o0[g],{index:J})),Q=$?WX({chain:g,derivationPath:j,phrase:$}):void 0,Z=Q?r0(Q):("signer"in X)?X.signer:void 0;function z(){return Promise.resolve(Z?.getAddress())}let{getBalance:Y,getFeeRates:q,broadcastTx:G,...W}=$X({chain:g});function U(N,H=!0){return Y(LX(RX(N)))}function L(N){if(!Z)throw new h("toolbox_utxo_no_signer");return Z.signTransaction(N)}async function _(N){let H=await L(N);return H.finalize(),await G(E2.encode(H.extract()))}return{...W,broadcastTx:G,buildTx:i0,createTransaction:w2,getAddress:z,getAddressFromKeys:s0,getBalance:U,getFeeRates:q,signAndBroadcastTransaction:_,signTransaction:L,stripPrefix:LX,stripToCashAddress:gX,transfer:n0({broadcastTx:G,getFeeRates:q,signer:Z}),validateAddress:t}}async function w2({assetValue:X,recipient:$,memo:J,feeRate:j,sender:Q,sweep:Z}){if(!t($))throw new h("toolbox_utxo_invalid_address",{address:$});let z=Math.ceil(X.getBaseValue("number")+j*7500),Y=await I(g).getUtxos({address:gX(Q),fetchTxHex:!0,targetValue:Z?void 0:z}),q=J?R(J):null,G=[],W=o($);if(G.push({address:W,value:Z?0:X.getBaseValue("number")}),q)G.push({script:q,value:0});let{inputs:U,outputs:L}=S({chain:g,feeRate:j,inputs:Y,outputs:G,sweep:Z});if(!(U&&L))throw new h("toolbox_utxo_insufficient_balance",{assetValue:X,sender:Q});let _=new v2({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!q,version:1}),N=o(Q),{inputs:H,tx:D}=XX({chain:g,compiledMemo:q,inputs:U,outputs:L.map((b)=>("address"in b)&&b.address?{...b,address:o(b.address)}:b),sender:N,tx:_});return{inputs:H,tx:D,utxos:U}}function n0({broadcastTx:X,getFeeRates:$,signer:J}){return async function({recipient:Q,assetValue:Z,feeOptionKey:z=c0.Fast,sweep:Y,...q}){let G=await J?.getAddress();if(!(J&&G))throw new h("toolbox_utxo_no_signer");if(!Q)throw new h("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let W=q.feeRate||(await $())[z],{tx:U}=await w2({...q,assetValue:Z,feeRate:W,recipient:Q,sender:G,sweep:Y}),L=await J.signTransaction(U);return L.finalize(),X(E2.encode(L.extract()))}}async function i0({assetValue:X,recipient:$,memo:J,feeRate:j,sender:Q}){let Z=RX($);if(!t(Z))throw new h("toolbox_utxo_invalid_address",{address:Z});let z=Math.ceil(X.getBaseValue("number")+j*7500),Y=await I(g).getUtxos({address:gX(Q),fetchTxHex:!0,targetValue:z}),q=Number(j.toFixed(0)),G=J?R(J):null,W=[];if(W.push({address:o($),value:X.getBaseValue("number")}),G)W.push({script:G,value:0});let{inputs:U,outputs:L}=S({chain:g,feeRate:q,inputs:Y,outputs:W});if(!(U&&L))throw new h("toolbox_utxo_insufficient_balance",{assetValue:X,sender:Q});let _=new v2({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!G,version:1}),{inputs:N,tx:H}=XX({chain:g,compiledMemo:G,inputs:U,outputs:L,sender:o(Q),tx:_});return{inputs:N,tx:H,utxos:Y}}function s0(X){let $=d0.bitcoinCash,J=R2(X.publicKey,$);if(!J.hash)throw new h("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return y2({hash:J.hash,prefix:f2.MAINNET,type:A2.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as a0,hex as t0}from"@scure/base";import{HDKey as l2}from"@scure/bip32";import{mnemonicToSeedSync as x2}from"@scure/bip39";import{Chain as bX,derivationPathToString as e0,FeeOption as X1,NetworkDerivationPath as $1,SKConfig as eX,SwapKitError as JX,updateDerivationPath as J1}from"@swapkit/helpers";import{Address as j1,createZcashTransaction as Q1,getZcashConsensusBranchId as Z1,isTransparentZcashAddress as K2,OutScript as G1,PCZT as Y1,utils as h2,WIF as q1,ZCASH_NETWORK as L1,ZCASH_TEST_NETWORK as z1,ZcashConsensusBranchId as m2,ZcashPSBT as W1,ZcashSigHash as aX,ZcashVersionGroupId as U1}from"@swapkit/utxo-signer";import{match as _1,P as tX}from"ts-pattern";function X2(){let{isStagenet:X}=eX.get("envs");return X?z1:L1}var N1=a0(h2.sha256);function B1(X){return N1.encode(X)}function M1({phrase:X,derivationPath:$}){let J=x2(X),Q=l2.fromMasterSeed(J).derive($);if(!Q.privateKey||!Q.publicKey)throw new JX("toolbox_utxo_invalid_params");let{privateKey:Z,publicKey:z}=Q,Y=h2.hash160(z),{isStagenet:q}=eX.get("envs"),G=q?new Uint8Array([29,37]):new Uint8Array([28,184]),W=new Uint8Array(G.length+Y.length);W.set(G,0),W.set(Y,G.length);let U=B1(W);return{getAddress:()=>Promise.resolve(U),signTransaction:(L)=>{if(L instanceof W1){let _=L.toPCZT();return _.signAllInputs(Z,z,aX.ALL),_.finalizeAllInputs(),Promise.resolve(_.extract())}if(L instanceof Y1)return L.signAllInputs(Z,z,aX.ALL),L.finalizeAllInputs(),Promise.resolve(L.extract());return L.signAllInputs(Z,z,aX.ALL),Promise.resolve(L)}}}function D1({inputs:X,outputs:$,tx:J,sender:j,compiledMemo:Q}){let Z=X2();for(let z of X){let Y=j1(Z).decode(j),q=G1.encode(Y);J.addInput({index:z.index,script:q,sequence:4294967295,txid:t0.decode(z.hash),value:BigInt(z.value)})}for(let z of $){let Y="address"in z&&z.address?z.address:j,q=z.script;if(q&&!Q)continue;if(q&&Q)J.addOutput({amount:0n,script:Q});else J.addOutputAddress(Y,BigInt(z.value),Z)}return{inputs:X,tx:J}}async function H1(){let{isStagenet:X}=eX.get("envs");if(X)return m2.IRONWOOD;try{let $=await I(bX.Zcash).getBlockHeight();return Z1($+1)}catch{return m2.IRONWOOD}}async function g2(X){let{assetValue:$,recipient:J,memo:j,feeRate:Q,sender:Z,fetchTxHex:z,sweep:Y}=X,q=X2();if(!K2(Z,q))throw new JX("toolbox_utxo_invalid_address",{address:Z});if(!K2(J,q))throw new JX("toolbox_utxo_invalid_address",{address:J,error:"Zcash transaction creation currently supports transparent addresses only"});let G=j?R(j):null,W=await I(bX.Zcash).getUtxos({address:Z,fetchTxHex:z!==!1}),U=[{address:J,value:Y?0:Number($.getBaseValue("string"))},...G?[{script:G,value:0}]:[]],{inputs:L,outputs:_}=S({chain:bX.Zcash,changeAddress:Z,feeRate:Q,inputs:W,outputs:U,sweep:Y});if(!(L&&_))throw new JX("toolbox_utxo_insufficient_balance",{assetValue:$,sender:Z});let N=Q1({consensusBranchId:await H1(),expiryHeight:0,lockTime:0,version:4,versionGroupId:U1.SAPLING}),{tx:H,inputs:D}=D1({compiledMemo:G,inputs:L,outputs:_,sender:Z,tx:N});return{inputs:D,outputs:_,tx:H}}function c2(X){let $=_1(X).with({signer:tX.not(tX.nullish)},({signer:q})=>q).with({phrase:tX.string},({phrase:q,derivationPath:G,index:W=0})=>{let U=G||$1[bX.Zcash]||[44,133,0,0,0],L=J1(U,{index:W}),_=e0(L);return M1({derivationPath:_,phrase:q})}).otherwise(()=>{return}),J=$X({chain:bX.Zcash,signer:$});async function j(q){if(!$)throw new JX("toolbox_utxo_no_signer");return await $.signTransaction(q)}async function Q(q){let G=await j(q);return J.broadcastTx(G.toHex())}async function Z({recipient:q,assetValue:G,feeOptionKey:W=X1.Fast,sweep:U,...L}){let _=await $?.getAddress();if(!($&&_))throw new JX("toolbox_utxo_no_signer");let N=L.feeRate||(await J.getFeeRates())[W],{tx:H}=await g2({...L,assetValue:G,feeRate:N,recipient:q,sender:_,sweep:U}),b=(await $.signTransaction(H)).toHex();return J.broadcastTx(b)}function z({phrase:q,derivationPath:G="m/44'/133'/0'/0/0"}){let W=x2(q),L=l2.fromMasterSeed(W).derive(G);if(!L.privateKey||!L.publicKey)throw new JX("toolbox_utxo_invalid_params");return{privateKey:L.privateKey,publicKey:L.publicKey}}function Y({phrase:q,derivationPath:G="m/44'/133'/0'/0/0"}){let W=z({derivationPath:G,phrase:q}),U=X2();return q1(U).encode(W.privateKey)}return{...J,createKeysForPath:z,createTransaction:g2,getPrivateKeyFromMnemonic:Y,signAndBroadcastTransaction:Q,signTransaction:j,transfer:Z,validateAddress:OX}}import{hex as C1}from"@scure/base";import{HDKey as O1}from"@scure/bip32";import{derivationPathToString as k1}from"@swapkit/helpers";function V1({xpub:X,chain:$,count:J,startIndex:j=0,accountIndex:Q}){if(m("count",J),J<1)throw RangeError("count must be at least 1");m("startIndex",j);let Z=E($),z=O1.fromExtendedKey(X,Z.bip32),Y=n({accountIndex:Q,chain:$}),q=ZX(Y),G=[];for(let W of[!1,!0]){let U=z.deriveChild(Number(W));for(let L=0;L<J;L++){let _=j+L,N=U.deriveChild(_);if(!N.publicKey)continue;let H=MX({accountIndex:Q,chain:$,change:W,index:_});G.push({accountIndex:q,address:VX({chain:$,network:Z,publicKey:N.publicKey}),change:W,index:_,path:k1(H),pubkey:C1.encode(N.publicKey)})}}return G}function l8(X,$){switch(X){case _X.BitcoinCash:return S2($||{});case _X.Zcash:return c2($);case _X.Bitcoin:case _X.Dogecoin:case _X.Litecoin:case _X.Dash:return $X({chain:X,...$});default:throw new b1("toolbox_utxo_not_supported",{chain:X})}}export{OX as validateZcashAddress,V2 as validateUtxoAddress,t as validateBchAddress,o as toLegacyAddress,RX as toCashAddress,gX as stripToCashAddress,LX as stripPrefix,mX as nonSegwitChains,W2 as isValidAddress,l8 as getUtxoToolbox,A1 as getUtxoNetwork,I as getUtxoApi,T2 as getUTXOAddressValidator,MX as getUTXOAddressPath,n as getUTXOAccountPath,ZX as getUTXOAccountIndexFromPath,HX as getScriptTypeForAddress,wX as getOutputSize,E as getNetworkForChain,s as getInputSize,CX as getDustThreshold,U2 as detectAddressNetwork,V1 as deriveAddressesFromXpub,c2 as createZcashToolbox,$X as createUTXOToolbox,d2 as createHDWalletHelpers,f1 as createCustomUtxoApi,S2 as createBCHToolbox,R as compileMemo,qX as calculateTxSize,m as assertDerivationIndex,F2 as addressFromKeysGetter,XX as addInputsAndOutputs,S as accumulative,z2 as UtxoNetwork,pX as UTXOScriptType,oX as TX_OVERHEAD,uX as SEGWIT_MARKER_FLAG_WEIGHT,SX as OutputSizes,O0 as OP_RETURN_OVERHEAD,h1 as MIN_TX_FEE,cX as InputSizes};
1
+ import{ea as j2,fa as M2}from"../../chunk-nvfkjbyq.js";import"../../chunk-xbdjxeqd.js";import{NetworkDerivationPath as p2}from"@swapkit/helpers";function g(X,$){if(!Number.isInteger($)||$<0)throw RangeError(`${X} must be a non-negative integer, got: ${$}`)}function n({accountIndex:X,chain:$,derivationPath:J}){if(X!==void 0)g("accountIndex",X);let[j,Q,Z]=J??p2[$];return[j,Q,X??Z]}function MX({accountIndex:X,change:$=!1,chain:J,derivationPath:j,index:Q}){return g("index",Q),[...n({accountIndex:X,chain:J,derivationPath:j}),Number($),Q]}function ZX(X){return X[2]??0}function d2({deriveAddress:X,getBalance:$,getUtxos:J}){async function j(G){let{accountIndex:q,count:Y,startIndex:W=0,change:L=!1}=G;if(g("count",Y),Y<1)throw RangeError("count must be at least 1");g("startIndex",W);let U=[];for(let _=0;_<Y;_++){let B=await X({accountIndex:q,change:L,index:W+_});if(B)U.push(B)}return U}async function Q(G){let{gapLimit:q=20,change:Y=!1}=G??{},W=[],L=0,U=0;while(L<q){let _=await X({change:Y,index:U});if(!_)break;if((await $(_.address)).some((M)=>M.getValue("number")>0))W.push(_),L=0;else L++;U++}return W}async function Z(G=20){let[q,Y]=await Promise.all([Q({change:!1,gapLimit:G}),Q({change:!0,gapLimit:G})]),W=[...q,...Y],L=await Promise.all(W.map(async(_)=>{let H=(await $(_.address)).reduce((M,C)=>M+C.getValue("number"),0);return{..._,balance:H}})),U=L.reduce((_,B)=>_+B.balance,0);return{addresses:L,total:U}}async function z(G=20){let[q,Y]=await Promise.all([Q({change:!1,gapLimit:G}),Q({change:!0,gapLimit:G})]),W=[...q,...Y];return(await Promise.all(W.map(async(U)=>{return(await J(U.address)).map((B)=>({...B,address:U.address,derivationIndex:U.index,isChange:U.change}))}))).flat()}return{deriveAddresses:j,getAggregatedBalance:Z,getAggregatedUtxos:z,scanForAddresses:Q}}import{Chain as T,getRPCUrl as r2,RequestClient as AX,SKConfig as n2,SwapKitError as v,warnOnce as i2}from"@swapkit/helpers";import{NETWORKS as GX}from"@swapkit/utxo-signer";async function s2({chain:X,txHash:$}){let J=`${YX(X)}/push/transaction`,j=JSON.stringify({data:$});try{let Q=await AX.post(J,{body:j,headers:{"Content-Type":"application/json"}});if(Q.context.code!==200)throw new v("toolbox_utxo_broadcast_failed",{error:Q.context.error||"Transaction broadcast failed"});return Q.data?.transaction_hash||$}catch(Q){let Z=await r2(X);if(Z){let z=JSON.stringify({id:j2(),jsonrpc:"2.0",method:"sendrawtransaction",params:[$]}),G=await AX.post(Z,{body:z,headers:{"Content-Type":"application/json"}});if(G.error)throw new v("toolbox_utxo_broadcast_failed",{error:G.error?.message});if(G.result.includes('"code":-26'))throw new v("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return G.result}throw Q}}function YX(X){return`https://api.blockchair.com/${a2(X)}`}function $2(X){switch(X){case T.Bitcoin:return 5;case T.Dogecoin:return 1e4;case T.Litecoin:return 1;case T.Zcash:return 1;default:return 2}}function a2(X){switch(X){case T.BitcoinCash:return"bitcoin-cash";case T.Litecoin:return"litecoin";case T.Dash:return"dash";case T.Dogecoin:return"dogecoin";case T.Zcash:return"zcash";case T.Polkadot:return"polkadot";default:return"bitcoin"}}async function t2(X){try{let{feePerKb:$}=await AX.get(`https://app.bitgo.com/api/v2/${X.toLowerCase()}/tx/fee`),J=$/1000;return Math.max(J,$2(X))}catch{return $2(X)}}async function DX(X,$){let J=await AX.get(`${X}${$?`${X.includes("?")?"&":"?"}key=${$}`:""}`);if(!J||J.context.code!==200)throw new v("toolbox_utxo_api_error",{error:`Failed to query ${X}`});return J.data}async function e2({chain:X,apiKey:$}){let J=await DX(`${YX(X)}/stats`,$);if(typeof J.best_block_height!=="number")throw new v("toolbox_utxo_api_error",{error:"Missing best_block_height in stats response"});return J.best_block_height}async function Q2({address:X,chain:$,apiKey:J}){if(!X)throw new v("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await DX(`${YX($)}/dashboards/address/${X}?transaction_details=true`,J))[X]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function X0({address:X,chain:$,apiKey:J}){return(await Q2({address:X,apiKey:J,chain:$}))?.address.balance||0}async function Z2({chain:X,apiKey:$,txHash:J}){if(!J)throw new v("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await DX(`${YX(X)}/raw/transaction/${J}`,$))?.[J]?.raw_transaction||""}catch(j){let Q=j instanceof Error?j.message:String(j);return console.error(`Failed to fetch raw transaction: ${Q}`),""}}var $0=4294967294;async function J0({chain:X,apiKey:$,txHash:J}){if(!J)throw new v("toolbox_utxo_invalid_params",{error:"TxHash is required"});let Q=(await DX(`${YX(X)}/dashboards/transaction/${J}`,$))?.[J];if(!Q)throw new v("toolbox_utxo_tx_not_found",{txHash:J});let{transaction:Z,inputs:z,outputs:G}=Q,q=z.map((W)=>W.spending_sequence),Y=Z.is_rbf===!0||q.some((W)=>W<$0);return{blockId:Z.block_id,confirmed:Z.block_id!==-1,fee:Z.fee,inputs:z,isRBF:Y,outputs:G,sequences:q,size:Z.size,txid:Z.hash,weight:Z.weight}}async function j0({chain:X,address:$,apiKey:J,offset:j=0,limit:Q=30}){return(await DX(`${YX(X)}/outputs?q=recipient(${$}),is_spent(false)&s=value(desc)&fields=is_spent,transaction_hash,index,value,script_hex,block_id,spending_signature_hex&limit=${Q}&offset=${j}`,J)).map(({is_spent:q,script_hex:Y,block_id:W,transaction_hash:L,index:U,value:_,spending_signature_hex:B})=>({hash:L,index:U,is_confirmed:W!==-1,is_spent:q,script_hex:Y,txHex:B,value:_}))}function Q0(X){return X.reduce(($,J)=>$+J.value,0)}function J2(X,$){let J=[...X].sort((j,Q)=>Q.value-j.value);if($){let j=[],Q=0;for(let Z of J)if(j.push(Z),Q+=Z.value,Q>=$)break;return j}return J}async function G2({chain:X,address:$,apiKey:J,targetValue:j,accumulativeValue:Q=0,offset:Z=0,limit:z=30}){if(!$)throw new v("toolbox_utxo_invalid_params",{error:"Address is required"});try{let G=await j0({address:$,apiKey:J,chain:X,limit:z,offset:Z,targetValue:j}),Y=G.length<z,W=G.filter(({is_spent:M})=>!M),L=Q0(W),U=Q+L,_=j&&U>=j;if(Y||_)return J2(W,j);let B=await G2({accumulativeValue:U,address:$,apiKey:J,chain:X,limit:z,offset:Z+z,targetValue:j}),H=[...W,...B];return J2(H,j)}catch(G){let q=G instanceof Error?G.message:String(G);return console.error(`Failed to fetch unspent UTXOs: ${q}`),[]}}async function Z0({address:X,chain:$,apiKey:J,fetchTxHex:j=!0,targetValue:Q}){let Z=await G2({address:X,apiKey:J,chain:$,targetValue:Q}),z=j?await Promise.all(Z.map(({hash:G})=>Z2({apiKey:J,chain:$,txHash:G}))):[];return Z.map(({hash:G,index:q,script_hex:Y,value:W},L)=>({address:X,hash:G,index:q,txHex:j?z[L]:void 0,value:W,witnessUtxo:{script:Buffer.from(Y,"hex"),value:W}}))}function I(X){let $=n2.get("apiKeys").blockchair||"";return i2({condition:!$,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(J)=>s2({chain:X,txHash:J}),getAddressData:(J)=>Q2({address:J,apiKey:$,chain:X}),getBalance:(J)=>X0({address:J,apiKey:$,chain:X}),getBlockHeight:()=>e2({apiKey:$,chain:X}),getRawTx:(J)=>Z2({apiKey:$,chain:X,txHash:J}),getSuggestedTxFee:()=>t2(X),getTransactionDetails:(J)=>J0({apiKey:$,chain:X,txHash:J}),getUtxos:(J)=>Z0({...J,apiKey:$,chain:X})}}function F1(X){return X}function E1(){return function($){switch($){case T.Bitcoin:return GX.bitcoin;case T.BitcoinCash:return GX.bitcoinCash;case T.Dash:return GX.dash;case T.Litecoin:return GX.litecoin;case T.Dogecoin:return GX.dogecoin;case T.Zcash:return GX.zcash;default:throw new v("toolbox_utxo_not_supported",{chain:$})}}}import{sha256 as U0}from"@noble/hashes/sha2.js";import{createBase58check as _0}from"@scure/base";import{SwapKitError as q2}from"@swapkit/helpers";import{CashAddrType as yX,decodeCashAddr as G0,encodeCashAddr as Y0}from"@swapkit/utxo-signer";var q0={P2PKH:yX.P2PKH,P2SH:yX.P2SH},L0={[yX.P2PKH]:"P2PKH",[yX.P2SH]:"P2SH"};function z0(X,$,J){return Y0({hash:J,prefix:X,type:q0[$]})}function W0(X){let $=G0(X),J=L0[$.type];if(!J)throw Error(`Unknown CashAddr type: ${$.type}`);return{hash:$.hash,prefix:$.prefix,type:J}}var hX={decode:W0,encode:z0};var L2=_0(U0);var z2;((J)=>{J.Mainnet="mainnet";J.Testnet="testnet"})(z2||={});var i={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}};function W2(X){try{return vX(X),!0}catch{return!1}}function U2(X){return vX(X)?.network}function c(X){let $=vX(X);if($?.format==="legacy")return X;return M0($)}function RX(X){let $=vX(X);return D0($)}function vX(X){try{let $=N0(X);if($)return $}catch{}try{let $=B0(X);if($)return $}catch{}throw new q2("toolbox_utxo_invalid_address",{address:X})}function N0(X){try{let $=L2.decode(X);if($.length!==21)throw new q2("toolbox_utxo_invalid_address",{address:X});let J=$[0],j=Array.prototype.slice.call($,1);switch(J){case i.legacy.mainnet.p2pkh:return{format:"legacy",hash:j,network:"mainnet",type:"p2pkh"};case i.legacy.mainnet.p2sh:return{format:"legacy",hash:j,network:"mainnet",type:"p2sh"};case i.legacy.testnet.p2pkh:return{format:"legacy",hash:j,network:"testnet",type:"p2pkh"};case i.legacy.testnet.p2sh:return{format:"legacy",hash:j,network:"testnet",type:"p2sh"};case i.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:j,network:"mainnet",type:"p2pkh"};case i.bitpay.mainnet.p2sh:return{format:"bitpay",hash:j,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function B0(X){if(X.indexOf(":")!==-1)try{return Y2(X)}catch{}else{let $=["bitcoincash","bchtest","bchreg"];for(let J of $)try{return Y2(`${J}:${X}`)}catch{}}return}function Y2(X){try{let{hash:$,prefix:J,type:j}=hX.decode(X);return{format:"cashaddr",hash:Array.prototype.slice.call($,0),network:J==="bitcoincash"?"mainnet":"testnet",type:j==="P2PKH"?"p2pkh":"p2sh"}}catch{return}}function M0(X){let $=i.legacy[X.network][X.type],J=Buffer.alloc(1+X.hash.length);return J[0]=$,J.set(X.hash,1),L2.encode(J)}function D0(X){let $=X.network==="mainnet"?"bitcoincash":"bchtest",J=X.type==="p2pkh"?"P2PKH":"P2SH",j=new Uint8Array(X.hash);return hX.encode($,J,j)}import{Chain as a,SwapKitError as dX}from"@swapkit/helpers";import{SwapKitError as H0}from"@swapkit/helpers";import{Script as C0}from"@swapkit/utxo-signer";var l1=1000,cX=10,uX=2,O0=10,k0=41,b0=107;function R(X){let $=new Uint8Array(Buffer.from(X,"utf8"));return C0.encode(["RETURN",$])}var pX;((J)=>{J.P2PKH="P2PKH";J.P2WPKH="P2WPKH"})(pX||={});var oX={["P2PKH"]:148,["P2WPKH"]:68},SX={["P2PKH"]:34,["P2WPKH"]:31},HX=(X)=>{if(X.startsWith("bc1")||X.startsWith("tb1")||X.startsWith("ltc1")||X.startsWith("tltc1"))return"P2WPKH";if(X.startsWith("1")||X.startsWith("m")||X.startsWith("n")||X.startsWith("bitcoincash:q")||X.startsWith("bitcoincash:p")||X.startsWith("q")||X.startsWith("p")||X.startsWith("L")||X.startsWith("M")||X.startsWith("3")||X.startsWith("D")||X.startsWith("A")||X.startsWith("9")||X.startsWith("X")||X.startsWith("7")||X.startsWith("y")||X.startsWith("t1")||X.startsWith("t3")||X.startsWith("tm"))return"P2PKH";throw new H0("toolbox_utxo_invalid_address",{address:X})},qX=({inputs:X,outputs:$,feeRate:J})=>{let j=X[0]&&"address"in X[0]&&X[0].address?HX(X[0].address):"P2PKH",Z=(J?X.filter((Y)=>Y.value>=oX["type"in Y&&Y.type?Y.type:"P2PKH"]*Math.ceil(J)):X).reduce((Y,W)=>Y+s(W),0),z=$?.reduce((Y,W)=>Y+wX(W),0)||SX[j],G=cX+Z+z;return j==="P2WPKH"?Math.ceil(G+uX/4):G},s=(X)=>{if("type"in X&&X.type)return oX[X.type];if("address"in X&&X.address)return oX[HX(X.address)];return k0+b0},wX=(X,$)=>{if(X?.script)return O0+X.script.length+(X.script.length>=74?2:1);if($)return SX[$];if("address"in X&&X.address)return SX[HX(X.address)];return SX.P2PKH};function CX(X){switch(X){case a.Bitcoin:case a.BitcoinCash:return 550;case a.Dash:case a.Litecoin:return 5500;case a.Dogecoin:return 1e5;case a.Zcash:return 546;default:throw new dX("toolbox_utxo_not_supported",{chain:X})}}function S({inputs:X,outputs:$,feeRate:J=1,chain:j=a.Bitcoin,changeAddress:Q="",sweep:Z=!1}){let z=CX(j),G=X.filter((M)=>{let C=s(M)*J;return Z?M.value>Math.max(C,z):C<=M.value});if(Z){let M=Math.ceil(J*qX({inputs:G,outputs:$})),C=G.reduce((A,l)=>A+l.value,0),u=C-M;if(u<=z)throw new dX("toolbox_sweep_amount_too_low",{available:C,dustThreshold:z,fee:M});let p=$.findIndex((A)=>("address"in A)&&A.address);if(p===-1)throw new dX("toolbox_utxo_invalid_params",{error:"Sweep requires a recipient output"});return{fee:M,inputs:G,outputs:$.map((A,l)=>l===p?{...A,value:u}:A)}}let W=(X[0]&&"address"in X[0]&&X[0].address?HX(X[0].address):"P2PKH")==="P2WPKH"?Math.ceil(uX/4):0,L=cX+W+$.reduce((M,C)=>M+wX(C),0),U=$.reduce((M,C)=>M+C.value,0),_=L*J,B=0,H=[];for(let M of G){let C=s(M),u=J*C;_+=u,B+=M.value,H.push(M);let p=_+U;if(B<p)continue;let A=B-p,l=J*wX({address:Q,value:0});if(A>l){let IX=l+_,PX=B-(U+Math.ceil(IX));if(PX>Math.max(s({value:0})*J,CX(j)))return{fee:Math.ceil(IX),inputs:H,outputs:$.concat({address:Q,value:PX})}}return{fee:Math.ceil(_),inputs:H,outputs:$}}return{fee:Math.ceil(J*qX({inputs:X,outputs:$}))}}import{Chain as _X,SwapKitError as k1}from"@swapkit/helpers";import{hex as E2}from"@scure/base";import{Chain as x0,derivationPathToString as h0,FeeOption as o0,resolveDerivationPath as c0,SwapKitError as h}from"@swapkit/helpers";import{BCHSigHash as u0,CashAddrPrefix as f2,CashAddrType as A2,encodeCashAddr as y2,NETWORKS as p0,p2pkh as R2,Transaction as v2}from"@swapkit/utxo-signer";import{secp256k1 as V0}from"@noble/curves/secp256k1.js";import{hex as e}from"@scure/base";import{HDKey as D2}from"@scure/bip32";import{mnemonicToSeedSync as iX}from"@scure/bip39";import{AssetValue as rX,applyFeeMultiplier as _2,Chain as P,derivationPathToString as kX,FeeOption as w,NetworkDerivationPath as H2,SwapKitError as V,SwapKitNumber as I0,updateDerivationPath as P0,warnOnce as T0}from"@swapkit/helpers";import{Address as F0,BCHSigHash as sX,CashAddrPrefix as E0,CashAddrType as f0,encodeCashAddr as A0,NETWORKS as zX,p2pkh as N2,p2wpkh as y0,RBF_SEQUENCE as R0,SigHash as C2,Transaction as nX,WIF as O2}from"@swapkit/utxo-signer";import{match as k2}from"ts-pattern";import{validateZcashAddress as OX}from"@swapkit/utxo-signer";function LX(X){return X.replace(/(bchtest:|bitcoincash:)/,"")}function t(X){let $=LX(X);return W2($)&&U2($)==="mainnet"}var mX=[P.Dash,P.Dogecoin,P.Zcash,P.BitcoinCash],KX=[P.Bitcoin];function b2({address:X,chain:$}){return k2($).with(P.BitcoinCash,()=>t(X)).with(P.Zcash,()=>OX(X)).otherwise(()=>{try{return F0(E($)).decode(X),!0}catch{return!1}})}function E(X){return k2(X).with(P.Bitcoin,()=>zX.bitcoin).with(P.BitcoinCash,()=>zX.bitcoinCash).with(P.Dash,()=>zX.dash).with(P.Dogecoin,()=>zX.dogecoin).with(P.Litecoin,()=>zX.litecoin).with(P.Zcash,()=>zX.zcash).exhaustive()}function v0({phrase:X,derivationPath:$,network:J,seed:j}){let Q=j??iX(X),z=D2.fromMasterSeed(Q,J.bip32).derive($);if(!z.privateKey)throw new V("toolbox_utxo_invalid_params",{error:"Could not derive private key from phrase"});return z.privateKey}function B2(X){return V0.getPublicKey(X,!0)}function bX({publicKey:X,chain:$,network:J}){if($===P.BitcoinCash){let Z=N2(X,J);if(!Z.hash)throw new V("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return A0({hash:Z.hash,prefix:E0.MAINNET,type:f0.P2PKH}).replace(/^bitcoincash:/,"")}let Q=!mX.includes($)?y0(X,J):N2(X,J);if(!Q.address)throw new V("toolbox_utxo_invalid_address",{error:"Could not derive address"});return Q.address}function WX({phrase:X,derivationPath:$,chain:J,wif:j,seed:Q}){let Z=E(J);if(j){let Y=O2(Z).decode(j),W=B2(Y);return{privateKey:Y,publicKey:W}}if(!X)throw new V("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let z=$||kX(H2[J]),G=v0({derivationPath:z,network:Z,phrase:X,seed:Q}),q=B2(G);return{privateKey:G,publicKey:q}}function S0(X,$){return O2(E($)).encode(X)}function w0({phrase:X,derivationPath:$,chain:J,seed:j}){let Q=$.split("/");if(Q.length<4)throw new V("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${Q.length}): ${$}`});let Z=E(J),z=j??iX(X),G=D2.fromMasterSeed(z,Z.bip32),q=Q.slice(0,4).join("/");return G.derive(q)}function XX({inputs:X,outputs:$,chain:J,tx:j,sender:Q,compiledMemo:Z,enableRBF:z=!1}){let G=E(J),q=!mX.includes(J),Y=z?R0:void 0,W=new Set;for(let L of X){let U=`${L.hash}:${L.index}`;if(W.has(U))throw new V("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});W.add(U);let _=typeof L.hash==="string"?e.decode(L.hash):L.hash;if(q&&L.witnessUtxo)j.addInput({index:L.index,sequence:Y,txid:_,witnessUtxo:{amount:BigInt(L.witnessUtxo.value),script:L.witnessUtxo.script}});else if(L.txHex)j.addInput({index:L.index,nonWitnessUtxo:e.decode(L.txHex),sequence:Y,txid:_,...J===P.BitcoinCash?{sighashType:sX.ALL}:{}});else throw new V("toolbox_utxo_invalid_params",{error:"Input requires either witnessUtxo or txHex for non-segwit chains"})}for(let L of $){let U="address"in L&&L.address?L.address:Q;if(J===P.BitcoinCash)U=c(U);if(L.script){if(Z)j.addOutput({amount:0n,script:Z})}else j.addOutputAddress(U,BigInt(L.value),G)}return{inputs:X,tx:j}}async function UX(X){let $=await I(X).getSuggestedTxFee();return{[w.Average]:$,[w.Fast]:_2($,w.Fast),[w.Fastest]:_2($,w.Fastest)}}async function V2({assetValue:X,recipient:$,memo:J,sender:j,sweep:Q,fetchTxHex:Z=!1},z){let G=X.chain,q=Z||mX.includes(G),Y=X.getBaseValue("number"),W=Q?void 0:z??(await UX(G))[w.Fastest],L=Q||W===void 0?void 0:Math.ceil(Y+W*5000);return{inputs:await I(G).getUtxos({address:j,fetchTxHex:q,targetValue:L}),outputs:[{address:$,value:Q?0:Y},...J?[{address:"",script:R(J),value:0}]:[]]}}async function I2({assetValue:X,recipient:$,memo:J,feeRate:j,sender:Q,fetchTxHex:Z=!1,enableRBF:z=!1,sweep:G}){let q=X.chain,Y=J?R(J):null,W=await V2({assetValue:X,fetchTxHex:Z,memo:J,recipient:$,sender:Q,sweep:G},j),{inputs:L,outputs:U}=S({...W,chain:q,feeRate:j,sweep:G});if(!(L&&U))throw new V("toolbox_utxo_insufficient_balance",{assetValue:X,sender:Q});let _=new nX({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!Y,version:1}),{inputs:B,tx:H}=XX({chain:q,compiledMemo:Y,enableRBF:z,inputs:L,outputs:U,sender:Q,tx:_});return{inputs:B,tx:H,utxos:W.inputs}}async function P2({assetValue:X,feeOptionKey:$=w.Fast,feeRate:J,memo:j,sender:Q,recipient:Z,sweep:z}){let G=X.chain,q,Y;if(J!==void 0)q=J,Y=Math.floor(J);else{let L=await UX(G);q=L[w.Fastest],Y=L[$]}let W=await V2({assetValue:X,memo:j,recipient:Z,sender:Q,sweep:z},q);return S({...W,chain:G,feeRate:Y,sweep:z})}function K0(X){return async function({from:J,memo:j,feeRate:Q,feeOptionKey:Z=w.Fast,recipient:z=J,recipients:G=1}){let q=Q??(await UX(X))[Z],W=(await I(X).getUtxos({address:J,fetchTxHex:!1})).filter((H)=>H.value>Math.max(CX(X),s(H)*q));if(!W.length)return rX.from({chain:X});let L=typeof G==="number"?Math.max(G,1):G.length,U=typeof G==="number"||L===0?Array.from({length:L||1},()=>({address:z,value:0})):[...G];if(j)U.push({address:J,script:R(j),value:0});let{outputs:_}=S({chain:X,feeRate:q,inputs:W,outputs:U,sweep:!0}),B=_?.[0]?.value??0;return rX.from({chain:X,value:BigInt(B)})}}function m0(X){return async function(J){let{fee:j}=await P2(J);return rX.from({chain:X,value:I0.fromBigInt(BigInt(j),8).getValue("string")})}}function g0({chain:X,phrase:$,derivationPath:J,seed:j}){let Q=E(X),{privateKey:Z,publicKey:z}=WX({chain:X,derivationPath:J,phrase:$,seed:j}),G=X===P.BitcoinCash?[sX.ALL]:[C2.ALL];return{getAddress:()=>bX({chain:X,network:Q,publicKey:z}),privateKey:Z,publicKey:z,signTransaction:(q)=>{return q.sign(Z,G),q}}}function l0(X,$){return async function({memo:j,recipient:Q,feeOptionKey:Z,feeRate:z,assetValue:G,enableRBF:q=!1,sweep:Y}){let W=await $?.getAddress();if(!($&&W))throw new V("toolbox_utxo_no_signer");if(!Q)throw new V("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});T0({condition:q&&!KX.includes(X),id:`rbf_not_supported_${X}`,warning:`RBF (Replace-by-Fee) is not reliably supported on ${X}. Transaction will be created without RBF signaling.`});let L=q&&KX.includes(X),U=z||(await UX(X))[Z||w.Fast],{tx:_}=await I2({assetValue:G,enableRBF:L,feeRate:U,memo:j,recipient:Q,sender:W,sweep:Y}),B=await $.signTransaction(_);return B.finalize(),I(X).broadcastTx(e.encode(B.extract()))}}function T2(X){return($)=>b2({address:$,chain:X})}function F2(X){let $=E(X);return function(j){if(!j)throw new V("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return bX({chain:X,network:$,publicKey:j.publicKey})}}function $X({chain:X,...$}){let J="phrase"in $?$.phrase:void 0,j="index"in $?$.index||0:0,Q=J?iX(J):void 0,Z="derivationPath"in $&&$.derivationPath?$.derivationPath:P0(H2[X],{index:j}),z=kX(Z),G=J?g0({chain:X,derivationPath:z,phrase:J,seed:Q}):void 0,q="signer"in $?$.signer:void 0,Y=G||q,W=J?WX({chain:X,derivationPath:z,phrase:J,seed:Q}):void 0;function L(){if(Y)return Y.getAddress();return Promise.resolve(void 0)}function U(N){if(!J)return;let D=n({accountIndex:N,chain:X,derivationPath:Z});return w0({chain:X,derivationPath:kX(D),phrase:J,seed:Q})}let _=U();function B(){if(!_)return;return _.publicExtendedKey}function H({accountIndex:N}={}){let D=N===void 0?_:U(N);if(!D)return;let O=n({accountIndex:N,chain:X,derivationPath:Z});return{accountIndex:ZX(O),path:kX(O),xpub:D.publicExtendedKey}}function M({accountIndex:N,index:D,change:O=!1}){let k=N===void 0?_:U(N);if(!k)return;let b=MX({accountIndex:N,chain:X,change:O,derivationPath:Z,index:D}),y=E(X),m=k.deriveChild(Number(O)).deriveChild(D);if(!m.publicKey)throw new V("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let f=bX({chain:X,network:y,publicKey:m.publicKey}),o=e.encode(m.publicKey);return{accountIndex:ZX(b),address:f,change:O,index:D,path:kX(b),pubkey:o}}async function C(N){if(!KX.includes(X))return{reason:`RBF is not supported on ${X}`,supported:!1};let D=await I(X).getTransactionDetails(N);return{canReplace:D.isRBF&&!D.confirmed,confirmed:D.confirmed,enabled:D.isRBF,fee:D.fee,sequences:D.sequences,supported:!0}}async function u({txid:N,newFeeRate:D,recipient:O,memo:k}){if(!KX.includes(X))throw new V("toolbox_utxo_rbf_not_supported",{chain:X});let b=await I(X).getTransactionDetails(N);if(!b.isRBF)throw new V("toolbox_utxo_tx_not_replaceable",{txid:N});if(b.confirmed)throw new V("toolbox_utxo_tx_already_confirmed",{blockId:b.blockId,txid:N});let y=b.inputs.reduce((F,x)=>F+x.value,0),f=b.outputs.find((F)=>F.recipient===O)?.value||0;if(f===0)throw new V("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let o=await Promise.all(b.inputs.map(async(F)=>{let x=await I(X).getRawTx(F.transaction_hash);return{hash:F.transaction_hash,index:F.index,txHex:x,value:F.value,witnessUtxo:void 0}})),NX=k?R(k):null,TX=qX({feeRate:D,inputs:o.map((F)=>({...F,type:"P2WPKH"})),outputs:[{address:O,value:f}]}),d=Math.ceil(TX*D);if(d<=b.fee)throw new V("toolbox_utxo_rbf_fee_too_low",{newFee:d,originalFee:b.fee});let jX=d-b.fee,QX=f-jX;if(QX<=0)throw new V("toolbox_utxo_rbf_insufficient_change");let r=new nX({allowLegacyWitnessUtxo:!0,version:1}),FX=[{address:O,value:QX},...k?[{address:"",script:R(k),value:0}]:[]],EX=y-QX-d,BX=await L();if(EX>CX(X)&&BX)FX.push({address:BX,value:EX});return XX({chain:X,compiledMemo:NX,inputs:o,outputs:FX,sender:BX||O,tx:r}),{feeDelta:jX,newFee:d,originalFee:b.fee,tx:r}}async function p({txid:N,newFeeRate:D,recipient:O,memo:k}){let{tx:b,originalFee:y,newFee:m}=await u({memo:k,newFeeRate:D,recipient:O,txid:N}),f=await lX(b);f.finalize();let o=await I(X).broadcastTx(e.encode(f.extract()));return{newFee:m,originalFee:y,txid:o}}function A({accountIndex:N,index:D,change:O=!1}){g("index",D);let k=N===void 0?_:U(N);if(!k)return;return k.deriveChild(Number(O)).deriveChild(D).privateKey||void 0}function l({tx:N,inputDerivations:D}){if(!_)throw new V("toolbox_utxo_no_signer");let O=X===P.BitcoinCash?[sX.ALL]:[C2.ALL];for(let k=0;k<D.length;k++){let b=D[k];if(!b)continue;let{derivationIndex:y,isChange:m}=b,f=A({change:m,index:y});if(!f)throw new V("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${k} at index ${y}`});N.signIdx(f,k,O)}return N}async function IX({utxos:N,recipient:D,assetValue:O,memo:k,feeRate:b,feeOptionKey:y,changeAddress:m,sweep:f}){if(f)throw new V("toolbox_utxo_invalid_params",{error:"Sweep is not supported for transfers from multiple addresses"});if(!_)throw new V("toolbox_utxo_no_signer");let o=b||(await UX(X))[y||w.Fast],NX=k?R(k):null,TX=[{address:D,value:O.getBaseValue("number")}];if(NX)TX.push({address:"",script:NX,value:0});let d=N.map(({hash:F,index:x,value:fX,txHex:u2,witnessUtxo:xX})=>({hash:F,index:x,txHex:u2,value:fX,witnessUtxo:xX?{script:xX.script,value:xX.value}:void 0})),{inputs:jX,outputs:QX}=S({chain:X,feeRate:o,inputs:d,outputs:TX});if(!(jX&&QX))throw new V("toolbox_utxo_insufficient_balance",{assetValue:O,sender:"multiple addresses"});let r=new nX({allowLegacyWitnessUtxo:!0,version:1}),FX=N[0]?.address,EX=m||await L()||FX||D;XX({chain:X,compiledMemo:NX,inputs:jX,outputs:QX,sender:EX,tx:r});let BX=jX.map((F)=>{let x=N.find((fX)=>fX.hash===F.hash&&fX.index===F.index);return x?{derivationIndex:x.derivationIndex,isChange:x.isChange}:{derivationIndex:0,isChange:!1}});return l({inputDerivations:BX,tx:r}),r.finalize(),I(X).broadcastTx(e.encode(r.extract()))}function PX({address:N,gapLimit:D=20}){if(!_)return;for(let O=0;O<D;O++){let k=M({change:!1,index:O}),b=M({change:!0,index:O}),y=k?.address===N?!1:b?.address===N;if(k?.address===N||b?.address===N)return{change:y,index:O}}return}function lX(N){if(!Y)throw new V("toolbox_utxo_no_signer");return Y.signTransaction(N)}async function c2(N){let D=await lX(N);return D.finalize(),await I(X).broadcastTx(e.encode(D.extract()))}return{accumulative:S,broadcastTx:(N)=>I(X).broadcastTx(N),bumpFee:p,calculateTxSize:qX,createKeysForPath:(N)=>WX({...N,chain:X}),createReplacementTransaction:u,createTransaction:I2,deriveAddressAtIndex:M,derivePrivateKeyAtIndex:A,estimateMaxSendableAmount:K0(X),estimateTransactionFee:m0(X),getAddress:L,getAddressFromKeys:F2(X),getBalance:M2(X),getExtendedPublicKey:B,getExtendedPublicKeyInfo:H,getFeeRates:()=>UX(X),getInputsOutputsFee:P2,getNetworkForChain:()=>E(X),getPrivateKeyFromMnemonic:(N)=>S0(WX({...N,chain:X}).privateKey,X),isRBFEnabled:C,keys:W,resolveDerivationIndex:PX,signAndBroadcastTransaction:c2,signTransaction:lX,signTransactionWithMultipleKeys:l,transfer:l0(X,Y),transferFromMultipleAddresses:IX,validateAddress:T2(X)}}var K=x0.BitcoinCash;function gX(X){return LX(RX(X))}function d0(X){let $=E(K);function J(Q){return Q.sign(X.privateKey,[u0.ALL]),Q}function j(){let Q=R2(X.publicKey,$);if(!Q.hash)throw new h("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let Z=y2({hash:Q.hash,prefix:f2.MAINNET,type:A2.P2PKH});return Promise.resolve(Z.replace(/^bitcoincash:/,""))}return{getAddress:j,signTransaction:J}}function S2(X){let $="phrase"in X?X.phrase:void 0,J="index"in X?X.index||0:0,j="derivationPath"in X?X.derivationPath:void 0,Q=c0({chain:K,derivationPath:j,index:J}),Z=h0(Q),z=$?WX({chain:K,derivationPath:Z,phrase:$}):void 0,G=z?d0(z):("signer"in X)?X.signer:void 0;function q(){return Promise.resolve(G?.getAddress())}let{getBalance:Y,getFeeRates:W,broadcastTx:L,...U}=$X($?{chain:K,derivationPath:Q,phrase:$}:{chain:K});function _(M,C=!0){return Y(LX(RX(M)))}function B(M){if(!G)throw new h("toolbox_utxo_no_signer");return G.signTransaction(M)}async function H(M){let C=await B(M);return C.finalize(),await L(E2.encode(C.extract()))}return{...U,broadcastTx:L,buildTx:n0,createTransaction:w2,getAddress:q,getAddressFromKeys:i0,getBalance:_,getFeeRates:W,signAndBroadcastTransaction:H,signTransaction:B,stripPrefix:LX,stripToCashAddress:gX,transfer:r0({broadcastTx:L,getFeeRates:W,signer:G}),validateAddress:t}}async function w2({assetValue:X,recipient:$,memo:J,feeRate:j,sender:Q,sweep:Z}){if(!t($))throw new h("toolbox_utxo_invalid_address",{address:$});let z=Math.ceil(X.getBaseValue("number")+j*7500),G=await I(K).getUtxos({address:gX(Q),fetchTxHex:!0,targetValue:Z?void 0:z}),q=J?R(J):null,Y=[],W=c($);if(Y.push({address:W,value:Z?0:X.getBaseValue("number")}),q)Y.push({script:q,value:0});let{inputs:L,outputs:U}=S({chain:K,feeRate:j,inputs:G,outputs:Y,sweep:Z});if(!(L&&U))throw new h("toolbox_utxo_insufficient_balance",{assetValue:X,sender:Q});let _=new v2({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!q,version:1}),B=c(Q),{inputs:H,tx:M}=XX({chain:K,compiledMemo:q,inputs:L,outputs:U.map((C)=>("address"in C)&&C.address?{...C,address:c(C.address)}:C),sender:B,tx:_});return{inputs:H,tx:M,utxos:L}}function r0({broadcastTx:X,getFeeRates:$,signer:J}){return async function({recipient:Q,assetValue:Z,feeOptionKey:z=o0.Fast,sweep:G,...q}){let Y=await J?.getAddress();if(!(J&&Y))throw new h("toolbox_utxo_no_signer");if(!Q)throw new h("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let W=q.feeRate||(await $())[z],{tx:L}=await w2({...q,assetValue:Z,feeRate:W,recipient:Q,sender:Y,sweep:G}),U=await J.signTransaction(L);return U.finalize(),X(E2.encode(U.extract()))}}async function n0({assetValue:X,recipient:$,memo:J,feeRate:j,sender:Q}){let Z=RX($);if(!t(Z))throw new h("toolbox_utxo_invalid_address",{address:Z});let z=Math.ceil(X.getBaseValue("number")+j*7500),G=await I(K).getUtxos({address:gX(Q),fetchTxHex:!0,targetValue:z}),q=Number(j.toFixed(0)),Y=J?R(J):null,W=[];if(W.push({address:c($),value:X.getBaseValue("number")}),Y)W.push({script:Y,value:0});let{inputs:L,outputs:U}=S({chain:K,feeRate:q,inputs:G,outputs:W});if(!(L&&U))throw new h("toolbox_utxo_insufficient_balance",{assetValue:X,sender:Q});let _=new v2({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!Y,version:1}),{inputs:B,tx:H}=XX({chain:K,compiledMemo:Y,inputs:L,outputs:U,sender:c(Q),tx:_});return{inputs:B,tx:H,utxos:G}}function i0(X){let $=p0.bitcoinCash,J=R2(X.publicKey,$);if(!J.hash)throw new h("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return y2({hash:J.hash,prefix:f2.MAINNET,type:A2.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as s0,hex as a0}from"@scure/base";import{HDKey as l2}from"@scure/bip32";import{mnemonicToSeedSync as x2}from"@scure/bip39";import{Chain as VX,derivationPathToString as t0,FeeOption as e0,resolveDerivationPath as X1,SKConfig as eX,SwapKitError as JX}from"@swapkit/helpers";import{Address as $1,createZcashTransaction as J1,getZcashConsensusBranchId as j1,isTransparentZcashAddress as K2,OutScript as Q1,PCZT as Z1,utils as h2,WIF as G1,ZCASH_NETWORK as Y1,ZCASH_TEST_NETWORK as q1,ZcashConsensusBranchId as m2,ZcashPSBT as L1,ZcashSigHash as aX,ZcashVersionGroupId as z1}from"@swapkit/utxo-signer";import{match as W1,P as tX}from"ts-pattern";function X2(){let{isStagenet:X}=eX.get("envs");return X?q1:Y1}var U1=s0(h2.sha256);function _1(X){return U1.encode(X)}function N1({phrase:X,derivationPath:$}){let J=x2(X),Q=l2.fromMasterSeed(J).derive($);if(!Q.privateKey||!Q.publicKey)throw new JX("toolbox_utxo_invalid_params");let{privateKey:Z,publicKey:z}=Q,G=h2.hash160(z),{isStagenet:q}=eX.get("envs"),Y=q?new Uint8Array([29,37]):new Uint8Array([28,184]),W=new Uint8Array(Y.length+G.length);W.set(Y,0),W.set(G,Y.length);let L=_1(W);return{getAddress:()=>Promise.resolve(L),signTransaction:(U)=>{if(U instanceof L1){let _=U.toPCZT();return _.signAllInputs(Z,z,aX.ALL),_.finalizeAllInputs(),Promise.resolve(_.extract())}if(U instanceof Z1)return U.signAllInputs(Z,z,aX.ALL),U.finalizeAllInputs(),Promise.resolve(U.extract());return U.signAllInputs(Z,z,aX.ALL),Promise.resolve(U)}}}function B1({inputs:X,outputs:$,tx:J,sender:j,compiledMemo:Q}){let Z=X2();for(let z of X){let G=$1(Z).decode(j),q=Q1.encode(G);J.addInput({index:z.index,script:q,sequence:4294967295,txid:a0.decode(z.hash),value:BigInt(z.value)})}for(let z of $){let G="address"in z&&z.address?z.address:j,q=z.script;if(q&&!Q)continue;if(q&&Q)J.addOutput({amount:0n,script:Q});else J.addOutputAddress(G,BigInt(z.value),Z)}return{inputs:X,tx:J}}async function M1(){let{isStagenet:X}=eX.get("envs");if(X)return m2.IRONWOOD;try{let $=await I(VX.Zcash).getBlockHeight();return j1($+1)}catch{return m2.IRONWOOD}}async function g2(X){let{assetValue:$,recipient:J,memo:j,feeRate:Q,sender:Z,fetchTxHex:z,sweep:G}=X,q=X2();if(!K2(Z,q))throw new JX("toolbox_utxo_invalid_address",{address:Z});if(!K2(J,q))throw new JX("toolbox_utxo_invalid_address",{address:J,error:"Zcash transaction creation currently supports transparent addresses only"});let Y=j?R(j):null,W=await I(VX.Zcash).getUtxos({address:Z,fetchTxHex:z!==!1}),L=[{address:J,value:G?0:Number($.getBaseValue("string"))},...Y?[{script:Y,value:0}]:[]],{inputs:U,outputs:_}=S({chain:VX.Zcash,changeAddress:Z,feeRate:Q,inputs:W,outputs:L,sweep:G});if(!(U&&_))throw new JX("toolbox_utxo_insufficient_balance",{assetValue:$,sender:Z});let B=J1({consensusBranchId:await M1(),expiryHeight:0,lockTime:0,version:4,versionGroupId:z1.SAPLING}),{tx:H,inputs:M}=B1({compiledMemo:Y,inputs:U,outputs:_,sender:Z,tx:B});return{inputs:M,outputs:_,tx:H}}function o2(X){let $=W1(X).with({signer:tX.not(tX.nullish)},({signer:q})=>q).with({phrase:tX.string},({phrase:q,derivationPath:Y,index:W=0})=>{let L=X1({chain:VX.Zcash,derivationPath:Y,index:W}),U=t0(L);return N1({derivationPath:U,phrase:q})}).otherwise(()=>{return}),J=$X({chain:VX.Zcash,signer:$});async function j(q){if(!$)throw new JX("toolbox_utxo_no_signer");return await $.signTransaction(q)}async function Q(q){let Y=await j(q);return J.broadcastTx(Y.toHex())}async function Z({recipient:q,assetValue:Y,feeOptionKey:W=e0.Fast,sweep:L,...U}){let _=await $?.getAddress();if(!($&&_))throw new JX("toolbox_utxo_no_signer");let B=U.feeRate||(await J.getFeeRates())[W],{tx:H}=await g2({...U,assetValue:Y,feeRate:B,recipient:q,sender:_,sweep:L}),C=(await $.signTransaction(H)).toHex();return J.broadcastTx(C)}function z({phrase:q,derivationPath:Y="m/44'/133'/0'/0/0"}){let W=x2(q),U=l2.fromMasterSeed(W).derive(Y);if(!U.privateKey||!U.publicKey)throw new JX("toolbox_utxo_invalid_params");return{privateKey:U.privateKey,publicKey:U.publicKey}}function G({phrase:q,derivationPath:Y="m/44'/133'/0'/0/0"}){let W=z({derivationPath:Y,phrase:q}),L=X2();return G1(L).encode(W.privateKey)}return{...J,createKeysForPath:z,createTransaction:g2,getPrivateKeyFromMnemonic:G,signAndBroadcastTransaction:Q,signTransaction:j,transfer:Z,validateAddress:OX}}import{hex as D1}from"@scure/base";import{HDKey as H1}from"@scure/bip32";import{derivationPathToString as C1}from"@swapkit/helpers";function O1({xpub:X,chain:$,count:J,startIndex:j=0,accountIndex:Q}){if(g("count",J),J<1)throw RangeError("count must be at least 1");g("startIndex",j);let Z=E($),z=H1.fromExtendedKey(X,Z.bip32),G=n({accountIndex:Q,chain:$}),q=ZX(G),Y=[];for(let W of[!1,!0]){let L=z.deriveChild(Number(W));for(let U=0;U<J;U++){let _=j+U,B=L.deriveChild(_);if(!B.publicKey)continue;let H=MX({accountIndex:Q,chain:$,change:W,index:_});Y.push({accountIndex:q,address:bX({chain:$,network:Z,publicKey:B.publicKey}),change:W,index:_,path:C1(H),pubkey:D1.encode(B.publicKey)})}}return Y}function m8(X,$){switch(X){case _X.BitcoinCash:return S2($||{});case _X.Zcash:return o2($);case _X.Bitcoin:case _X.Dogecoin:case _X.Litecoin:case _X.Dash:return $X({chain:X,...$});default:throw new k1("toolbox_utxo_not_supported",{chain:X})}}export{OX as validateZcashAddress,b2 as validateUtxoAddress,t as validateBchAddress,c as toLegacyAddress,RX as toCashAddress,gX as stripToCashAddress,LX as stripPrefix,mX as nonSegwitChains,W2 as isValidAddress,m8 as getUtxoToolbox,E1 as getUtxoNetwork,I as getUtxoApi,T2 as getUTXOAddressValidator,MX as getUTXOAddressPath,n as getUTXOAccountPath,ZX as getUTXOAccountIndexFromPath,HX as getScriptTypeForAddress,wX as getOutputSize,E as getNetworkForChain,s as getInputSize,CX as getDustThreshold,U2 as detectAddressNetwork,O1 as deriveAddressesFromXpub,o2 as createZcashToolbox,$X as createUTXOToolbox,d2 as createHDWalletHelpers,F1 as createCustomUtxoApi,S2 as createBCHToolbox,R as compileMemo,qX as calculateTxSize,g as assertDerivationIndex,F2 as addressFromKeysGetter,XX as addInputsAndOutputs,S as accumulative,z2 as UtxoNetwork,pX as UTXOScriptType,cX as TX_OVERHEAD,uX as SEGWIT_MARKER_FLAG_WEIGHT,SX as OutputSizes,O0 as OP_RETURN_OVERHEAD,l1 as MIN_TX_FEE,oX as InputSizes};
@@ -47,7 +47,7 @@ export type Toolboxes = {
47
47
  export type ToolboxParams = {
48
48
  [key in EVMChain]: Parameters<typeof getEvmToolbox>[1];
49
49
  } & {
50
- [key in UTXOChain]: undefined;
50
+ [key in UTXOChain]: Parameters<typeof getUtxoToolbox>[1];
51
51
  } & {
52
52
  [key in CosmosChain]: Parameters<typeof getCosmosToolbox>[1];
53
53
  } & {
@@ -1,4 +1,4 @@
1
- import { AssetValue, type ChainSigner, type GenericTransferParams } from "@swapkit/helpers";
1
+ import { AssetValue, type ChainSigner, type DerivationPathArray, type GenericTransferParams } from "@swapkit/helpers";
2
2
  import type { Payment, Transaction as RippleTransaction } from "xrpl";
3
3
  export * from "./currency";
4
4
  export * from "./tokens";
@@ -38,13 +38,15 @@ export interface TrustLineInfo {
38
38
  authorized: boolean;
39
39
  peerAuthorized: boolean;
40
40
  }
41
- declare function createSigner(phrase: string): ChainSigner<RippleTransaction, {
41
+ declare function createSigner(phrase: string, derivationPath?: string): ChainSigner<RippleTransaction, {
42
42
  tx_blob: string;
43
43
  hash: string;
44
44
  }>;
45
45
  export declare function validateRippleAddress(address: string): boolean;
46
46
  type RippleToolboxParams = {
47
47
  phrase?: string;
48
+ derivationPath?: DerivationPathArray;
49
+ index?: number;
48
50
  } | {
49
51
  signer?: ChainSigner<RippleTransaction, {
50
52
  tx_blob: string;
@@ -13,4 +13,5 @@ export type StellarCreateTrustlineTransactionParams = StellarTrustlineParams & {
13
13
  export type StellarToolboxParams = {
14
14
  phrase?: string;
15
15
  derivationPath?: DerivationPathArray;
16
+ index?: number;
16
17
  };
@@ -1,5 +1,5 @@
1
1
  import type { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
2
- import type { ChainSigner, GenericCreateTransactionParams, GenericTransferParams } from "@swapkit/helpers";
2
+ import type { ChainSigner, DerivationPathArray, GenericCreateTransactionParams, GenericTransferParams } from "@swapkit/helpers";
3
3
  import type { getSuiToolbox } from "./toolbox";
4
4
  export type SuiChainSigner = ChainSigner<Uint8Array, {
5
5
  bytes: string;
@@ -19,5 +19,7 @@ export type SuiSigner = Ed25519Keypair | SuiChainSigner;
19
19
  export type SuiToolboxParams = {
20
20
  provider?: string;
21
21
  phrase?: string;
22
+ derivationPath?: DerivationPathArray;
23
+ index?: number;
22
24
  signer?: SuiSigner;
23
25
  };
@@ -15,7 +15,7 @@ export declare function assertDerivationIndex(name: string, value: number): void
15
15
  export declare function getUTXOAccountPath({ accountIndex, chain, derivationPath, }: HDWalletAccountParams & {
16
16
  chain: UTXOChain;
17
17
  derivationPath?: DerivationPathArray;
18
- }): [44, 118, 0, 0, 0] | [44, 931, 0, 0, 0] | [number, number, number, number, number] | [44, 683, 0, 0] | [44, 637, 0, 0, 0] | [44, 60, 0, 0, 0] | [44, 397, 0, 0, 0] | [0, 0, 0, 0, 0] | [44, 144, 0, 0, 0] | [44, 501, 0, 0, 0] | [8797555, 1, 0, 0, 0] | [44, 607, 0, 0, 0] | [44, 195, 0, 0, 0] | [44, 148, 0, 0, 0] | [44, 784, 0, 0, 0] | [1852, 1815, 0, 0, 0] | [44, 9004, 0, 0, 0] | [number, number, number, number, (number | undefined)?] | [44, 145, 0, 0, 0] | [84, 2, 0, 0, 0] | [44, 3, 0, 0, 0] | [44, 5, 0, 0, 0] | [44, 133, 0, 0, 0];
18
+ }): DerivationPathArray;
19
19
  export declare function getUTXOAddressPath({ accountIndex, change, chain, derivationPath, index, }: HDWalletAccountParams & {
20
20
  change?: boolean;
21
21
  chain: UTXOChain;
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "dependencies": { "@swapkit/helpers": "5.1.0", "@swapkit/utxo-signer": "3.0.0" },
2
+ "dependencies": { "@swapkit/helpers": "5.2.0", "@swapkit/utxo-signer": "3.0.0" },
3
3
  "description": "SwapKit - Toolboxes",
4
4
  "devDependencies": {
5
5
  "@aptos-labs/ts-sdk": "7.0.1",
@@ -131,5 +131,5 @@
131
131
  "type-check:go": "tsgo"
132
132
  },
133
133
  "type": "module",
134
- "version": "5.1.2"
134
+ "version": "5.2.0"
135
135
  }
@@ -1,2 +0,0 @@
1
- import{fa as Ny}from"./chunk-nvfkjbyq.js";import{ga as Uy}from"./chunk-xbdjxeqd.js";import{Chain as H}from"@swapkit/helpers";import{match as b5}from"ts-pattern";import{Chain as $,getChainConfig as p,getRPCUrl as Wu,SKConfig as Qu,SwapKitError as c}from"@swapkit/helpers";import{FallbackProvider as Xu,getAddress as Hy,Interface as Yu,JsonRpcProvider as ty,Network as Zu}from"ethers";import{match as Ry}from"ts-pattern";function $u(y){return new ty(y)}async function X5(y,u){return $u(u||await Wu(y))}function ky(y){let u=Qu.get("rpcUrls")[y]?.filter(Boolean)??[];if(u.length===0)throw new c("helpers_chain_no_public_or_set_rpc_url",{chain:y});let{chainId:n}=p(y),t=Zu.from(Number(n)),[T]=u;if(u.length===1)return new ty(T,t,{staticNetwork:t});return new Xu(u.map((M,b)=>({priority:b+1,provider:new ty(M,t,{staticNetwork:t}),stallTimeout:2000})),t,{quorum:1})}function l(y){return y>0n?`0x${y.toString(16)}`:"0x0"}function Dy(y){let{explorerUrl:u,chainIdHex:n,rpcUrls:t}=p(y);return function(){return y!==$.Ethereum?{...Bu({chain:y}),blockExplorerUrls:[u],chainId:n,rpcUrls:t}:void 0}}function Ly(y){return![$.Adi,$.Arbitrum,$.BinanceSmartChain,$.Robinhood].includes(y)}function Bu({chain:y}){let{name:u,nativeCurrency:n,baseDecimal:t}=p(y);return Ry(y).with($.Arbitrum,()=>({chainName:"Arbitrum One",nativeCurrency:{decimals:t,name:"Ethereum",symbol:$.Ethereum}})).with($.Aurora,()=>({chainName:"Aurora Mainnet",nativeCurrency:{decimals:t,name:"Ethereum",symbol:$.Ethereum}})).with($.Avalanche,()=>({chainName:"Avalanche Network",nativeCurrency:{decimals:t,name:"Avalanche",symbol:y}})).with($.Base,()=>({chainName:"Base Mainnet",nativeCurrency:{decimals:t,name:"Ethereum",symbol:$.Ethereum}})).with($.Berachain,()=>({chainName:"Berachain",nativeCurrency:{decimals:t,name:"Berachain",symbol:"BERA"}})).with($.XLayer,()=>({chainName:"X Layer",nativeCurrency:{decimals:t,name:"OKB",symbol:"OKB"}})).with($.BinanceSmartChain,()=>({chainName:"BNB Smart Chain Mainnet",nativeCurrency:{decimals:t,name:"Binance Coin",symbol:"BNB"}})).with($.Gnosis,()=>({chainName:"Gnosis",nativeCurrency:{decimals:t,name:"xDAI",symbol:"XDAI"}})).with($.Optimism,()=>({chainName:"OP Mainnet",nativeCurrency:{decimals:t,name:"Ethereum",symbol:$.Ethereum}})).with($.Polygon,()=>({chainName:"Polygon Mainnet",nativeCurrency:{decimals:t,name:"Polygon",symbol:$.Polygon}})).with($.Robinhood,()=>({chainName:"Robinhood Chain",nativeCurrency:{decimals:t,name:"Ethereum",symbol:$.Ethereum}})).otherwise(()=>({chainName:u,nativeCurrency:{decimals:t,name:n,symbol:n}}))}async function zy(y,u){if(!("authorize"in y))throw Error("Signer does not support EIP-7702 authorization. Requires ethers.js v6.14+");let n={...u,nonce:u.nonce!==void 0?BigInt(u.nonce):void 0};return await y.authorize(n)}var Jy=(y)=>typeof y==="string"&&/^0x[a-fA-F0-9]{64}$/.test(y),Ju=(y)=>{try{return typeof y==="string"&&!!Hy(y)}catch{return!1}};function Hu(y,u){let n=u!==void 0?`index ${u}: `:"",t=(T,M)=>{throw new c({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:T,message:`${n}${M}`}})};Ry(y).when(({chainId:T})=>typeof T!=="bigint",()=>t("chainId","chainId must be a bigint")).when(({address:T})=>!Ju(T),()=>t("address","address must be a valid checksummed address")).when(({nonce:T})=>typeof T!=="bigint"||T<0n,()=>t("nonce","nonce must be a non-negative bigint")).when(({signature:T})=>!T,()=>t("signature","signature is required")).when(({signature:T})=>typeof T?.yParity!=="number"||![0,1].includes(T.yParity),()=>t("signature.yParity","yParity must be 0 or 1")).when(({signature:T})=>!Jy(T?.r),()=>t("signature.r","r must be a 32-byte hex string")).when(({signature:T})=>!Jy(T?.s),()=>t("signature.s","s must be a 32-byte hex string")).otherwise(()=>{})}function Ru(y){return[{key:"name",type:"string"},{key:"version",type:"string"},{key:"chainId",type:"uint256"},{key:"verifyingContract",type:"address"},{key:"salt",type:"bytes32"}].filter(({key:u})=>y[u]!=null).map(({key:u,type:n})=>({name:u,type:n}))}function Ty(y){return y.charAt(0).toUpperCase()+y.slice(1)}function My(y,u){if(y.isTuple()&&y.components){let n=Ty(y.name);return u[n]=y.components.map((t)=>({name:t.name,type:My(t,u)})),n}if(y.isArray()){let n=y.arrayChildren;if(n?.isTuple()&&n.components){let t=Ty(y.name.replace(/s$/,""));return u[t]=n.components.map((T)=>({name:T.name,type:My(T,u)})),`${t}[]`}return`${n?.type??"bytes"}[]`}return y.type}function by(y,u){if(typeof y==="bigint")return y;if(u?.isTuple()&&typeof y?.toObject==="function"){let n=y.toObject(),t={};for(let[T,M]of(u.components??[]).entries())t[M.name]=by(n[M.name]??y[T],M);return t}if(Array.isArray(y)){let n=u?.arrayChildren;return y.map((t)=>by(t,n??void 0))}return y}function Y5({chain:y,abi:u,data:n,to:t}){let M=new Yu(u).parseTransaction({data:n});if(!M)throw new c({errorKey:"toolbox_evm_invalid_params",info:{error:"Could not decode calldata"}});let b={},q=Ty(M.name);b[q]=M.fragment.inputs.map((X)=>({name:X.name,type:My(X,b)}));let W={};for(let[X,B]of M.fragment.inputs.entries())W[B.name]=by(M.args[X],B);let{chainId:Q}=p(y),U={chainId:Number(Q),verifyingContract:Hy(t)},k=Ru(U);return{domain:U,message:W,primaryType:q,types:{EIP712Domain:k,...b}}}function jy(y,u){if(!Array.isArray(y)||y.length===0)throw new c({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{message:"EIP-7702 transactions require at least one authorization"}});for(let[n,t]of y.entries())if(Hu(t,n),u!==void 0&&t.chainId!==u)throw new c({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:"chainId",message:`index ${n}: authorization chainId (${t.chainId}) does not match transaction chainId (${u})`}})}import{Chain as R,FeeOption as n5}from"@swapkit/helpers";import{HDNodeWallet as t5}from"ethers";import{match as T5,P as oy}from"ts-pattern";var Gy=[{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"aggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes[]",name:"returnData",type:"bytes[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"blockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"getBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getBlockNumber",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockCoinbase",outputs:[{internalType:"address",name:"coinbase",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockDifficulty",outputs:[{internalType:"uint256",name:"difficulty",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockGasLimit",outputs:[{internalType:"uint256",name:"gaslimit",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"addr",type:"address"}],name:"getEthBalance",outputs:[{internalType:"uint256",name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLastBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryAggregate",outputs:[{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryBlockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"}];import{AssetValue as ku,applyFeeMultiplierToBigInt as j,Chain as K,EVMChains as Du,FeeOption as Y,isGasAsset as Lu,SwapKitError as Z,SwapKitNumber as s}from"@swapkit/helpers";import{erc20ABI as C}from"@swapkit/helpers/contracts";import{BrowserProvider as zu,Contract as _y,getAddress as i,getBytes as ju,Interface as Vy}from"ethers";import{match as wy}from"ts-pattern";function d(y){return{getBalance:Ny(y)}}function J5(y){return y}var Wy=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function a({chain:y=K.Ethereum,provider:u,signer:n,isEIP1559Compatible:t=!0,estimateGasPrices:T,estimateAdditionalFee:M}){let b=T??m({chain:y,isEIP1559Compatible:t,provider:u}),q=fy({chain:y,estimateAdditionalFee:M,estimateGasPrices:b,isEIP1559Compatible:t,provider:u,signer:n});return{approve:Ou({chain:y,isEIP1559Compatible:t,provider:u,signer:n}),approvedAmount:ly({chain:y,provider:u}),broadcastTransaction:u.broadcastTransaction,call:yy({chain:y,isEIP1559Compatible:t,provider:u,signer:n}),createApprovalTx:hu({chain:y,provider:u,signer:n}),createContract:Nu({chain:y,provider:u}),createContractTxObject:h({chain:y,provider:u}),createTransaction:q,createTransferTx:q,EIP1193SendTransaction:r(u),estimateCall:Sy({provider:u,signer:n}),estimateGasLimit:xu({chain:y,provider:u,signer:n}),estimateGasPrices:b,estimateTransactionFee:mu({chain:y,isEIP1559Compatible:t,provider:u}),getAddress:()=>{return n?n.getAddress():void 0},getBalance:d(y).getBalance,getNetworkParams:Dy(y),isApproved:Ku({chain:y,provider:u}),sendTransaction:Oy({chain:y,estimateGasPrices:b,isEIP1559Compatible:t,provider:u,signer:n}),signAuthorization:Fu({signer:n}),signMessage:n?(W)=>n.signMessage(W):void 0,signTypedData:n?({domain:W,types:Q,value:U})=>n.signTypedData(W,Q,U):void 0,transfer:fu({chain:y,estimateAdditionalFee:M,estimateGasPrices:b,isEIP1559Compatible:t,provider:u,signer:n}),validateAddress:Gu}}function Gu(y){try{return i(y),!0}catch{return!1}}function e(y){return y instanceof zu}function Qy(y,u,n){return new _y(y,Vy.from(u),n)}function Nu({provider:y}){return function(n,t){return new _y(n,Vy.from(t),y)}}var _u=["payable","nonpayable"];function Vu({abi:y,funcName:u}){let n=y.find((t)=>t.name===u);if(!n)throw new Z("toolbox_evm_no_abi_fragment",{funcName:u});return n.stateMutability&&_u.includes(n.stateMutability)}function G5(y){return i(y)}function r(y,u=!1){return function({value:t,...T}){if(!e(y))throw new Z("toolbox_evm_provider_not_eip1193_compatible");let M={...T,gasPrice:"gasPrice"in T?T.gasPrice:void 0,maxFeePerGas:"maxFeePerGas"in T?T.maxFeePerGas:void 0,maxPriorityFeePerGas:"maxPriorityFeePerGas"in T?T.maxPriorityFeePerGas:void 0},{gasLimit:b,gasPrice:q,maxFeePerGas:W,maxPriorityFeePerGas:Q,...U}=M,k={...U,...u&&b!==void 0&&{gas:l(BigInt(b))},...u&&q!==void 0&&{gasPrice:l(BigInt(q))},...u&&W!==void 0&&{maxFeePerGas:l(BigInt(W))},...u&&Q!==void 0&&{maxPriorityFeePerGas:l(BigInt(Q))},value:l(BigInt(t||0))};return y.send("eth_sendTransaction",[k])}}function N5(y,u){let n=Xy(y,u);if(n)return i(n.toLowerCase());throw new Z("toolbox_evm_invalid_gas_asset_address")}var wu=Du.reduce((y,u)=>{return y[u]="0x0000000000000000000000000000000000000000",y},{}),lu={...wu,[K.Optimism]:"0x4200000000000000000000000000000000000042",[K.Polygon]:"0x0000000000000000000000000000000000001010"},Su=[K.Arbitrum,K.Aurora,K.Base,K.Optimism,K.Robinhood];function Xy({chain:y,symbol:u,ticker:n},t){try{let T=y===K.BinanceSmartChain&&u==="BNB"&&n==="BNB",M=y===K.Hyperevm&&u==="HYPE"&&n==="HYPE",b=y===t&&u===t&&n===t,q=Su.includes(y)&&u==="ETH"&&n==="ETH";if(b||T||M||q)return lu[t];return i(u.slice(n.length+1).replace(/^0X/,""))}catch{return null}}function h({provider:y}){return async({contractAddress:u,abi:n,funcName:t,funcParams:T=[],txOverrides:M})=>{let b=await Qy(u,n,y).getFunction(t).populateTransaction(...T.concat(M).filter((q)=>typeof q<"u"));return{...b,value:l(BigInt(b.value||0))}}}function m({chain:y,provider:u,isEIP1559Compatible:n=!0}){return wy(y).with(K.Gnosis,()=>{return async function(){try{let{gasPrice:T,maxPriorityFeePerGas:M}=await u.getFeeData();if(!T||M===null)throw new Z("toolbox_evm_no_fee_data");return{[Y.Average]:{maxFeePerGas:j(T,Y.Average),maxPriorityFeePerGas:j(M,Y.Average)},[Y.Fast]:{maxFeePerGas:j(T,Y.Fast),maxPriorityFeePerGas:j(M,Y.Fast)},[Y.Fastest]:{maxFeePerGas:j(T,Y.Fastest),maxPriorityFeePerGas:j(M,Y.Fastest)}}}catch(T){throw new Z("toolbox_evm_gas_estimation_error",{error:T.msg??T.toString()})}}}).with(K.Arbitrum,()=>{return async function(){try{let{gasPrice:T}=await u.getFeeData();if(!T)throw new Z("toolbox_evm_no_fee_data");let M=T*12n/10n;return{[Y.Average]:{gasPrice:M},[Y.Fast]:{gasPrice:j(M,Y.Fast)},[Y.Fastest]:{gasPrice:j(M,Y.Fastest)}}}catch(T){throw new Z("toolbox_evm_gas_estimation_error",{error:T.msg??T.toString()})}}}).otherwise(()=>{return async function(){try{let{maxFeePerGas:T,maxPriorityFeePerGas:M,gasPrice:b}=await u.getFeeData();if(n){if(T===null||M===null)throw new Z("toolbox_evm_no_fee_data");return{[Y.Average]:{maxFeePerGas:T,maxPriorityFeePerGas:M},[Y.Fast]:{maxFeePerGas:j(T,Y.Fast),maxPriorityFeePerGas:j(M,Y.Fast)},[Y.Fastest]:{maxFeePerGas:j(T,Y.Fastest),maxPriorityFeePerGas:j(M,Y.Fastest)}}}if(!b)throw new Z("toolbox_evm_no_gas_price");return{[Y.Average]:{gasPrice:b},[Y.Fast]:{gasPrice:j(b,Y.Fast)},[Y.Fastest]:{gasPrice:j(b,Y.Fastest)}}}catch(T){throw new Z("toolbox_evm_gas_estimation_error",{error:T.msg??T.toString()})}}})}function yy({provider:y,isEIP1559Compatible:u,signer:n,chain:t}){return async function({callProvider:M,contractAddress:b,abi:q,funcName:W,funcParams:Q=[],txOverrides:U={},feeOption:k=Y.Fast}){let X=M||y;if(!b)throw new Z("toolbox_evm_invalid_params",{error:"contractAddress must be provided"});let B=Vu({abi:q,funcName:W});if(B&&e(X)&&n){let z=h({chain:t,provider:X}),O=U?.from||await n?.getAddress(),G=await z({abi:q,contractAddress:b,funcName:W,funcParams:Q,txOverrides:{...U,from:O}});return r(X)(G)}let J=Qy(b,q,X);if(B){if(!n)throw new Z("toolbox_evm_no_signer");let z=U?.from||await n.getAddress();if(!z)throw new Z("toolbox_evm_no_signer_address");let O=J.connect(n),G=m({chain:t,isEIP1559Compatible:u,provider:y}),[{maxFeePerGas:N,maxPriorityFeePerGas:I,gasPrice:x},_,F]=await Promise.all([G().then((V)=>V[k]),J.getFunction(W).estimateGas(...Q,U),U?.nonce!==void 0?Promise.resolve(U.nonce):X.getTransactionCount(z)]),S=await O[W](...Q,{...U,gasLimit:_,gasPrice:x,maxFeePerGas:N,maxPriorityFeePerGas:I,nonce:F});return typeof S?.hash==="string"?S?.hash:S}let D=await J[W]?.(...Q);return typeof D?.hash==="string"?D?.hash:D}}function ly({provider:y,chain:u}){return function({assetAddress:t,spenderAddress:T,from:M}){return yy({chain:u,isEIP1559Compatible:!0,provider:y})({abi:C,contractAddress:t,funcName:"allowance",funcParams:[M,T]})}}function Ku({provider:y,chain:u}){return async function({assetAddress:t,spenderAddress:T,from:M,amount:b=Wy}){let q=await ly({chain:u,provider:y})({assetAddress:t,from:M,spenderAddress:T});return s.fromBigInt(q).gte(s.fromBigInt(BigInt(b)))}}function Ou({signer:y,isEIP1559Compatible:u=!0,provider:n,chain:t}){return async function({assetAddress:M,spenderAddress:b,feeOptionKey:q=Y.Fast,amount:W,gasLimitFallback:Q,from:U,nonce:k}){let X=[b,BigInt(W||Wy)],B=await y?.getAddress()||U,J={abi:C,contractAddress:M,funcName:"approve",funcParams:X,signer:y,txOverrides:{from:B}};if(e(n)){let z=h({chain:t,provider:n}),O=r(n),G=await z(J);return O(G)}return yy({chain:t,isEIP1559Compatible:u,provider:n,signer:y})({...J,feeOption:q,funcParams:X,txOverrides:{from:B,gasLimit:Q?BigInt(Q.toString()):void 0,nonce:k}})}}function fu({chain:y,estimateGasPrices:u,estimateAdditionalFee:n,signer:t,isEIP1559Compatible:T=!0,provider:M}){return async function({assetValue:q,memo:W,recipient:Q,feeOptionKey:U=Y.Fast,sender:k,sweep:X,...B}){let J=k||await t?.getAddress(),D=Oy({chain:y,estimateGasPrices:u,isEIP1559Compatible:T,provider:M,signer:t});if(!J)throw new Z("toolbox_evm_no_from_address");let z=await fy({chain:y,estimateAdditionalFee:n,estimateGasPrices:u,isEIP1559Compatible:T,provider:M,signer:t})({assetValue:q,feeOptionKey:U,memo:W,recipient:Q,sender:J,sweep:X,...B});return D({...z,feeOptionKey:U,sweep:X})}}function Sy({provider:y,signer:u}){return function({contractAddress:t,abi:T,funcName:M,funcParams:b=[],txOverrides:q}){if(!t)throw new Z("toolbox_evm_no_contract_address");let W=Qy(t,T,y);return u?W.connect(u).getFunction(M).estimateGas(...b,q):W.getFunction(M).estimateGas(...b,q)}}function xu({provider:y,signer:u}){return async function({assetValue:t,recipient:T,memo:M,data:b,sender:q,funcName:W,funcParams:Q,txOverrides:U}){let k=t.bigIntValue,X=t.isGasAsset?null:Xy(t,t.chain);if(X&&W)return Sy({provider:y,signer:u})({abi:C,contractAddress:X,funcName:W,funcParams:Q,txOverrides:U});let{hexlify:B,toUtf8Bytes:J}=await import("ethers");return y.estimateGas({data:b?b:M?B(J(M)):void 0,from:q,to:T,value:k})}}function Fu({signer:y}){if(!y)return;return(u)=>zy(y,u)}var Ky=(y)=>y.type===4||(y.authorizations?.length??0)>0,Iu=(y)=>!Ky(y)&&(y.type===2||!!y.maxFeePerGas||!!y.maxPriorityFeePerGas),Eu=(y,u=!0)=>{if(Ky(y))return"eip7702";if(Iu(y)||u)return"eip1559";return"legacy"};function Au(y,u){if(y==="legacy"){if(u.gasPrice===void 0)throw new Z("toolbox_evm_no_fee_data");return{gasPrice:l(u.gasPrice)}}if(u.maxFeePerGas===void 0||u.maxPriorityFeePerGas===void 0)throw new Z("toolbox_evm_no_fee_data");return{maxFeePerGas:l(u.maxFeePerGas),maxPriorityFeePerGas:l(u.maxPriorityFeePerGas)}}function Oy({chain:y,estimateGasPrices:u,provider:n,signer:t,isEIP1559Compatible:T=!0}){return async function({feeOptionKey:b=Y.Fast,sweep:q,...W}){let{from:Q,to:U,data:k,value:X,...B}=W;if(!t)throw new Z("toolbox_evm_no_signer");if(!U)throw new Z("toolbox_evm_no_to_address");let J={...B,data:k||"0x",from:Q,to:U,value:BigInt(X||0)};if(e(n))return r(n,q)(J);let D=Q||await t.getAddress(),[z,O]=await Promise.all([W.nonce!==void 0?Promise.resolve(W.nonce):n.getTransactionCount(D),n.getNetwork()]),G=O.chainId,N=Eu(J,T);if(N==="eip7702")jy(J.authorizations||[],G);let I=wy(N).with("eip7702",()=>4).with("eip1559",()=>2).otherwise(()=>0),x={...J,chainId:G,nonce:z,type:I,...N==="eip7702"&&{authorizationList:J.authorizations}},_=u??m({chain:y,isEIP1559Compatible:T,provider:n}),S=(N==="legacy"?J.gasPrice!==void 0:J.maxFeePerGas!==void 0&&J.maxPriorityFeePerGas!==void 0)?{}:Au(N,(await _())[b]),V;try{V=l(J.gasLimit?BigInt(J.gasLimit):await n.estimateGas(x)*11n/10n)}catch(w){throw new Z("toolbox_evm_error_estimating_gas_limit",{error:w})}try{let w={...x,gasLimit:V,...S};try{return(await t.sendTransaction(w)).hash}catch{let E=await t.signTransaction({...w,from:D});return(await n.broadcastTransaction(E)).hash}}catch(w){throw new Z("toolbox_evm_error_sending_transaction",{error:w})}}}function A(y,u){throw new Z({errorKey:"toolbox_sweep_amount_too_low",info:{balance:y.toString(),fee:u.toString()}})}function Pu(y,u){if(u){if(y.maxFeePerGas===void 0||y.maxPriorityFeePerGas===void 0)throw new Z("toolbox_evm_no_fee_data");return{feeFields:{maxFeePerGas:y.maxFeePerGas,maxPriorityFeePerGas:y.maxPriorityFeePerGas},feePerGas:y.maxFeePerGas}}if(y.gasPrice===void 0)throw new Z("toolbox_evm_no_fee_data");return{feeFields:{gasPrice:y.gasPrice},feePerGas:y.gasPrice}}function Cu(y,u){if(y>u)return y;return u}function ou(y){return ju(y).reduce((u,n)=>u+(n===0?4n:16n),21000n)}function qy(y){let n=(y instanceof Error?y.message:String(y)).toLowerCase();return n.includes("insufficient funds")||n.includes("insufficient balance")||n.includes("gas required exceeds allowance")}async function gu({balance:y,estimateAdditionalFee:u,feeOptionKey:n,l2Reserve:t,sweepTx:T,valueBeforeL1Fee:M}){if(!u)return 0n;let b=await u({...T,value:M})??0n,q=j(b,n),W=M-q;if(W<=0n)A(y,t+q);let Q=await u({...T,value:W})??b;return j(Cu(b,Q),n)}async function vu({chain:y,data:u,estimateGasPrices:n,estimateAdditionalFee:t,feeOptionKey:T,from:M,isEIP1559Compatible:b,provider:q,recipient:W,transaction:Q}){let U=await q.getBalance(M),k=n??m({chain:y,isEIP1559Compatible:b,provider:q}),{feeFields:X,feePerGas:B}=Pu((await k())[T],b),D={...t&&Q.nonce===void 0?{...Q,nonce:await q.getTransactionCount(M)}:Q,...X,data:u,from:M,to:W},z=ou(u)*B;if(U-z<=0n)A(U,z);let O=(U-z)/2n,G;try{G=await q.estimateGas({...D,value:O})}catch(v){if(!qy(v))throw v;try{G=await q.estimateGas({...D,value:0n})}catch(By){if(qy(By))A(U,z);throw By}}let N=G*B;if(U-N<=0n)A(U,N);let _=G*11n/10n*B,F=U>_?U-_:0n,S;try{S=await q.estimateGas({...D,value:F})}catch(v){if(!qy(v))throw v;A(U,_)}let V=S*B,w=U-V;if(w<=0n)A(U,V);let E=await gu({balance:U,estimateAdditionalFee:t,feeOptionKey:T,l2Reserve:V,sweepTx:{...D,gasLimit:S},valueBeforeL1Fee:w}),P=w-E;if(P<=0n)A(U,V+E);return{...D,gasLimit:S,value:l(P)}}async function cu({chain:y,contractAddress:u,from:n,provider:t}){let T=await yy({chain:y,provider:t})({abi:C,contractAddress:u,funcName:"balanceOf",funcParams:[n]});if(typeof T!=="bigint")throw new Z({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid ERC20 balance"}});return T}function fy({chain:y,estimateAdditionalFee:u,estimateGasPrices:n,isEIP1559Compatible:t=!0,provider:T,signer:M}){return async function({assetValue:q,authorizations:W,memo:Q,recipient:U,data:k,feeOptionKey:X=Y.Fast,gasLimit:B,sender:J,sweep:D,type:z,maxFeePerGas:O,maxPriorityFeePerGas:G,gasPrice:N,...I}){let x=q.getBaseValue("bigint"),_=J||await M?.getAddress();if(!_)throw new Z("toolbox_evm_no_from_address");if(D&&(z===4||(W?.length??0)>0))throw new Z({errorKey:"toolbox_not_supported",info:{chain:y,reason:"EIP-7702 sweep transactions are not supported"}});if(Lu(q)){let{hexlify:w,toUtf8Bytes:E}=await import("ethers"),P=k||w(E(Q||""));if(!D)return{...I,...W!==void 0&&{authorizations:W},data:P,from:_,...B!==void 0&&{gasLimit:B},to:U,...z!==void 0&&{type:z},value:l(x)};return vu({chain:y,data:P,estimateAdditionalFee:u,estimateGasPrices:n,feeOptionKey:X,from:_,isEIP1559Compatible:t,provider:T,recipient:U,transaction:{nonce:I.nonce,type:z}})}let F=Xy(q,y);if(!F)throw new Z("toolbox_evm_no_contract_address");let S=h({chain:y,provider:T}),V=D?await cu({chain:y,contractAddress:F,from:_,provider:T}):x;if(D&&V<=0n)throw new Z({errorKey:"toolbox_sweep_amount_too_low",info:{asset:q.toString(),balance:V.toString()}});return S({abi:C,contractAddress:F,funcName:"transfer",funcParams:[U,V],txOverrides:{from:_,gasLimit:B,gasPrice:N,maxFeePerGas:O,maxPriorityFeePerGas:G}})}}function hu({provider:y,signer:u,chain:n}){return async function({assetAddress:T,spenderAddress:M,amount:b,from:q}){let W=await u?.getAddress()||q,Q=h({chain:n,provider:y}),U=["bigint","number"].includes(typeof b)?b:b||Wy;return await Q({abi:C,contractAddress:T,funcName:"approve",funcParams:[M,BigInt(U)],txOverrides:{from:W}})}}function mu({provider:y,isEIP1559Compatible:u=!0,chain:n}){return async function({feeOption:T=Y.Fast,...M}){let q=await m({chain:n,isEIP1559Compatible:u,provider:y})(),W=await y.estimateGas(M),Q=ku.from({chain:n}),{gasPrice:U,maxFeePerGas:k,maxPriorityFeePerGas:X}=q[T];if(!u&&U)return Q.set(s.fromBigInt(U*W,Q.decimal));if(k&&X){let B=(k+X)*W;return Q.set(s.fromBigInt(B,Q.decimal))}throw new Z("toolbox_evm_no_gas_price")}}import{applyFeeMultiplierToBigInt as o,Chain as Iy,FeeOption as f,getChainConfig as pu,SwapKitError as g}from"@swapkit/helpers";import{Contract as du,HDNodeWallet as su}from"ethers";import{match as iu,P as Fy}from"ts-pattern";var xy=[{inputs:[{internalType:"address",name:"_owner",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"DecimalsUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"GasPriceUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"L1BaseFeeUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"OverheadUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"ScalarUpdated",type:"event"},{inputs:[],name:"decimals",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"gasPrice",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1Fee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1GasUsed",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_gasUsed",type:"uint256"}],name:"getOperatorFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"l1BaseFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"overhead",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"scalar",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_decimals",type:"uint256"}],name:"setDecimals",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_gasPrice",type:"uint256"}],name:"setGasPrice",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_baseFee",type:"uint256"}],name:"setL1BaseFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_overhead",type:"uint256"}],name:"setOverhead",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_scalar",type:"uint256"}],name:"setScalar",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"}];var au="0x420000000000000000000000000000000000000f";function uy(y){return new du(au,xy,y)}function Ey(y){return async function(){let n=uy(y);if(n&&"l1BaseFee"in n)return await n?.l1BaseFee();return}}function Ay(y){return async function({from:n,to:t,nonce:T,...M}){let{Transaction:b}=await import("ethers");if(!t)throw new g("toolbox_evm_invalid_transaction",{error:"Missing to address"});return b.from({...M,authorizationList:M.authorizationList,nonce:T??(n?await y.getTransactionCount(n):0),to:t}).unsignedSerialized}}function Yy(y,u){return async function(t){let T=uy(y),M=t.chainId??u??(await y.getNetwork()).chainId,b=await Ay(y)({...t,chainId:M});if(T&&"getL1Fee"in T){let q=await T.getL1Fee(b);if(typeof q!=="bigint")throw new g({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack L1 fee"}});return q}return}}function Zy(y){return async function(n){let t=uy(y);if(t&&"getOperatorFee"in t){let T=await t.getOperatorFee(n);if(typeof T!=="bigint")throw new g({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack operator fee"}});return T}return 0n}}function eu(y,u){let n=Yy(y,u),t=Zy(y);return async function(M){if(M.gasLimit===void 0||M.gasLimit===null)throw new g({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Missing gas limit for OP-stack fee estimation"}});let[b,q]=await Promise.all([n(M),t(BigInt(M.gasLimit.toString()))]);return(b??0n)+q}}function Py(y){return async function(n){let T=(await y.getFeeData()).gasPrice??0n,M=await y.estimateGas(n);return T*M}}function ru(y){return async function(n){let t=await Yy(y)(n)??0n,T=await Py(y)(n),M=n.gasLimit??await y.estimateGas(n),b=await Zy(y)(BigInt(M.toString()));return t+T+b}}function y5(y){return async function(n){let t=uy(y),T=await Ay(y)(n);if(t&&"getL1GasUsed"in t)return t.getL1GasUsed(T)}}function u5(y){return async function(){try{let{maxFeePerGas:n,maxPriorityFeePerGas:t,gasPrice:T}=await y.getFeeData(),M=await Ey(y)(),b=T;if(!(n&&t))throw new g("toolbox_evm_no_fee_data");return{[f.Average]:{gasPrice:b,l1GasPrice:M,maxFeePerGas:n,maxPriorityFeePerGas:t},[f.Fast]:{gasPrice:o(b,f.Fast),l1GasPrice:o(M||0n,f.Fast),maxFeePerGas:n,maxPriorityFeePerGas:o(t,f.Fast)},[f.Fastest]:{gasPrice:o(b,f.Fastest),l1GasPrice:o(M||0n,f.Fastest),maxFeePerGas:n,maxPriorityFeePerGas:o(t,f.Fastest)}}}catch(n){throw new g("toolbox_evm_gas_estimation_error",{error:n.msg??n.toString()})}}}function ny(y){return function({provider:n,...t}){let T=iu(t).with({phrase:Fy.string},({phrase:X})=>su.fromPhrase(X).connect(n)).with({signer:Fy.any},({signer:X})=>X).otherwise(()=>{return}),M=Ey(n),b=BigInt(pu(y).chainId),q=Yy(n,b),W=eu(n,b),Q=Zy(n),U=y===Iy.Optimism?u5(n):void 0;return{...a({chain:y,estimateAdditionalFee:W,estimateGasPrices:U,provider:n,signer:T}),estimateL1Gas:y5(n),estimateL1GasCost:q,estimateL2GasCost:Py(n),estimateOperatorFee:Q,estimateTotalGasCost:ru(n),getBalance:d(y).getBalance,getL1GasPrice:M}}}var Cy=ny(Iy.Optimism);function gy(y){let u=L(R.Ethereum)(y);async function n(t,T="0x5ba1e12693dc8f9c48aad8770482f4739beed696",M="aggregate",b=n5.Fast){let q=await u.createContractTxObject({abi:Gy,contractAddress:T,funcName:M,funcParams:[t]});return u.sendTransaction({...q,feeOptionKey:b})}return{...u,multicall:n}}var vy=L(R.Adi),cy=L(R.Arbitrum),hy=L(R.Aurora),my=L(R.Avalanche),py=ny(R.Base),dy=L(R.Berachain),sy=L(R.BinanceSmartChain),g5=L(R.Botanix),iy=L(R.Core),ay=L(R.Corn),ey=L(R.Cronos),ry=L(R.Gnosis),yu=L(R.Robinhood),uu=L(R.Hyperevm),nu=L(R.Linea),tu=L(R.Polygon),Tu=L(R.MegaETH),Mu=L(R.Monad),bu=L(R.Plasma),$y=L(R.Sonic),qu=ny(R.Unichain),Uu=L(R.XLayer);function L(y){return function({provider:n,...t}){let T=Ly(y),M=T5(t).with({phrase:oy.string},({phrase:q})=>t5.fromPhrase(q).connect(n)).with({signer:oy.any},({signer:q})=>q).otherwise(()=>{return});return a({chain:y,isEIP1559Compatible:T,provider:n,signer:M})}}function q5(y,u){return b5(y).with(H.Adi,()=>vy(u)).with(H.Arbitrum,()=>cy(u)).with(H.Aurora,()=>hy(u)).with(H.Avalanche,()=>my(u)).with(H.Base,()=>py(u)).with(H.Berachain,()=>dy(u)).with(H.BinanceSmartChain,()=>sy(u)).with(H.Botanix,()=>$y(u)).with(H.Core,()=>iy(u)).with(H.Corn,()=>ay(u)).with(H.Cronos,()=>ey(u)).with(H.Ethereum,()=>gy(u)).with(H.Gnosis,()=>ry(u)).with(H.Hyperevm,()=>uu(u)).with(H.Linea,()=>nu(u)).with(H.MegaETH,()=>Tu(u)).with(H.Monad,()=>Mu(u)).with(H.Optimism,()=>Cy(u)).with(H.Plasma,()=>bu(u)).with(H.Polygon,()=>tu(u)).with(H.Robinhood,()=>yu(u)).with(H.Sonic,()=>$y(u)).with(H.Unichain,()=>qu(u)).with(H.XLayer,()=>Uu(u)).exhaustive()}async function p5(y,u){let n={...u,provider:u?.provider||ky(y)};return q5(y,n)}
2
- export{d as b,J5 as c,$u as d,X5 as e,ky as f,l as g,Dy as h,Ly as i,zy as j,Hu as k,Ru as l,Y5 as m,jy as n,Wy as o,a as p,Gu as q,e as r,Qy as s,Nu as t,Vu as u,G5 as v,r as w,N5 as x,lu as y,Xy as z,h as A,m as B,Ky as C,Iu as D,Eu as E,ny as F,Cy as G,gy as H,vy as I,cy as J,hy as K,my as L,py as M,dy as N,sy as O,g5 as P,iy as Q,ay as R,ey as S,ry as T,yu as U,uu as V,nu as W,tu as X,Tu as Y,Mu as Z,bu as _,$y as $,qu as aa,Uu as ba,q5 as ca,p5 as da};