@swapkit/toolboxes 4.21.0 → 4.23.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{ca as tX,da as U2}from"../../chunk-54gntgt1.js";import"../../chunk-ntbvmmch.js";import{NetworkDerivationPath as p2}from"@swapkit/helpers";function y(X,$){if(!Number.isInteger($)||$<0)throw RangeError(`${X} must be a non-negative integer, got: ${$}`)}function o({accountIndex:X,chain:$,derivationPath:J}){if(X!==void 0)y("accountIndex",X);let j=[...J?.slice(0,3)??p2[$].slice(0,3)];if(X!==void 0)j[2]=X;return j}function UX({accountIndex:X,change:$=!1,chain:J,derivationPath:j,index:Q}){return y("index",Q),[...o({accountIndex:X,chain:J,derivationPath:j}),Number($),Q]}function XX(X){return X[2]??0}function u2({deriveAddress:X,getBalance:$,getUtxos:J}){async function j(q){let{accountIndex:G,count:Y,startIndex:W=0,change:z=!1}=q;if(y("count",Y),Y<1)throw RangeError("count must be at least 1");y("startIndex",W);let U=[];for(let _=0;_<Y;_++){let B=await X({accountIndex:G,change:z,index:W+_});if(B)U.push(B)}return U}async function Q(q){let{gapLimit:G=20,change:Y=!1}=q??{},W=[],z=0,U=0;while(z<G){let _=await X({change:Y,index:U});if(!_)break;if((await $(_.address)).some((V)=>V.getValue("number")>0))W.push(_),z=0;else z++;U++}return W}async function Z(q=20){let[G,Y]=await Promise.all([Q({change:!1,gapLimit:q}),Q({change:!0,gapLimit:q})]),W=[...G,...Y],z=await Promise.all(W.map(async(_)=>{let D=(await $(_.address)).reduce((V,e)=>V+e.getValue("number"),0);return{..._,balance:D}})),U=z.reduce((_,B)=>_+B.balance,0);return{addresses:z,total:U}}async function L(q=20){let[G,Y]=await Promise.all([Q({change:!1,gapLimit:q}),Q({change:!0,gapLimit:q})]),W=[...G,...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:L,scanForAddresses:Q}}import{Chain as F,getRPCUrl as o2,RequestClient as bX,SKConfig as c2,SwapKitError as w,warnOnce as d2}from"@swapkit/helpers";import{NETWORKS as $X}from"@swapkit/utxo-signer";async function r2({chain:X,txHash:$}){let J=`${WX(X)}/push/transaction`,j=JSON.stringify({data:$});try{let Q=await bX.post(J,{body:j,headers:{"Content-Type":"application/json"}});if(Q.context.code!==200)throw new w("toolbox_utxo_broadcast_failed",{error:Q.context.error||"Transaction broadcast failed"});return Q.data?.transaction_hash||$}catch(Q){let Z=await o2(X);if(Z){let L=JSON.stringify({id:tX(),jsonrpc:"2.0",method:"sendrawtransaction",params:[$]}),q=await bX.post(Z,{body:L,headers:{"Content-Type":"application/json"}});if(q.error)throw new w("toolbox_utxo_broadcast_failed",{error:q.error?.message});if(q.result.includes('"code":-26'))throw new w("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return q.result}throw Q}}function WX(X){return`https://api.blockchair.com/${n2(X)}`}function sX(X){switch(X){case F.Bitcoin:return 5;case F.Dogecoin:return 1e4;case F.Litecoin:return 1;case F.Zcash:return 1;default:return 2}}function n2(X){switch(X){case F.BitcoinCash:return"bitcoin-cash";case F.Litecoin:return"litecoin";case F.Dash:return"dash";case F.Dogecoin:return"dogecoin";case F.Zcash:return"zcash";case F.Polkadot:return"polkadot";default:return"bitcoin"}}async function i2(X){try{let{feePerKb:$}=await bX.get(`https://app.bitgo.com/api/v2/${X.toLowerCase()}/tx/fee`),J=$/1000;return Math.max(J,sX(X))}catch{return sX(X)}}async function IX(X,$){let J=await bX.get(`${X}${$?`${X.includes("?")?"&":"?"}key=${$}`:""}`);if(!J||J.context.code!==200)throw new w("toolbox_utxo_api_error",{error:`Failed to query ${X}`});return J.data}async function eX({address:X,chain:$,apiKey:J}){if(!X)throw new w("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await IX(`${WX($)}/dashboards/address/${X}?transaction_details=true`,J))[X]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function s2({address:X,chain:$,apiKey:J}){return(await eX({address:X,apiKey:J,chain:$}))?.address.balance||0}async function X2({chain:X,apiKey:$,txHash:J}){if(!J)throw new w("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await IX(`${WX(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 a2=4294967294;async function t2({chain:X,apiKey:$,txHash:J}){if(!J)throw new w("toolbox_utxo_invalid_params",{error:"TxHash is required"});let Q=(await IX(`${WX(X)}/dashboards/transaction/${J}`,$))?.[J];if(!Q)throw new w("toolbox_utxo_tx_not_found",{txHash:J});let{transaction:Z,inputs:L,outputs:q}=Q,G=L.map((W)=>W.spending_sequence),Y=Z.is_rbf===!0||G.some((W)=>W<a2);return{blockId:Z.block_id,confirmed:Z.block_id!==-1,fee:Z.fee,inputs:L,isRBF:Y,outputs:q,sequences:G,size:Z.size,txid:Z.hash,weight:Z.weight}}async function e2({chain:X,address:$,apiKey:J,offset:j=0,limit:Q=30}){return(await IX(`${WX(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:G,script_hex:Y,block_id:W,transaction_hash:z,index:U,value:_,spending_signature_hex:B})=>({hash:z,index:U,is_confirmed:W!==-1,is_spent:G,script_hex:Y,txHex:B,value:_}))}function X0(X){return X.reduce(($,J)=>$+J.value,0)}function aX(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 $2({chain:X,address:$,apiKey:J,targetValue:j,accumulativeValue:Q=0,offset:Z=0,limit:L=30}){if(!$)throw new w("toolbox_utxo_invalid_params",{error:"Address is required"});try{let q=await e2({address:$,apiKey:J,chain:X,limit:L,offset:Z,targetValue:j}),Y=q.length<L,W=q.filter(({is_spent:V})=>!V),z=X0(W),U=Q+z,_=j&&U>=j;if(Y||_)return aX(W,j);let B=await $2({accumulativeValue:U,address:$,apiKey:J,chain:X,limit:L,offset:Z+L,targetValue:j}),D=[...W,...B];return aX(D,j)}catch(q){let G=q instanceof Error?q.message:String(q);return console.error(`Failed to fetch unspent UTXOs: ${G}`),[]}}async function $0({address:X,chain:$,apiKey:J,fetchTxHex:j=!0,targetValue:Q}){let Z=await $2({address:X,apiKey:J,chain:$,targetValue:Q}),L=[];for(let{hash:q,index:G,script_hex:Y,value:W}of Z){let z;if(j)z=await X2({apiKey:J,chain:$,txHash:q});L.push({address:X,hash:q,index:G,txHex:z,value:W,witnessUtxo:{script:Buffer.from(Y,"hex"),value:W}})}return L}function I(X){let $=c2.get("apiKeys").blockchair||"";return d2({condition:!$,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(J)=>r2({chain:X,txHash:J}),getAddressData:(J)=>eX({address:J,apiKey:$,chain:X}),getBalance:(J)=>s2({address:J,apiKey:$,chain:X}),getRawTx:(J)=>X2({apiKey:$,chain:X,txHash:J}),getSuggestedTxFee:()=>i2(X),getTransactionDetails:(J)=>t2({apiKey:$,chain:X,txHash:J}),getUtxos:(J)=>$0({...J,apiKey:$,chain:X})}}function f1(X){return X}function F1(){return function($){switch($){case F.Bitcoin:return $X.bitcoin;case F.BitcoinCash:return $X.bitcoinCash;case F.Dash:return $X.dash;case F.Litecoin:return $X.litecoin;case F.Dogecoin:return $X.dogecoin;case F.Zcash:return $X.zcash;default:throw new w("toolbox_utxo_not_supported",{chain:$})}}}import{sha256 as q0}from"@noble/hashes/sha2.js";import{createBase58check as L0}from"@scure/base";import{SwapKitError as j2}from"@swapkit/helpers";import{CashAddrType as fX,decodeCashAddr as J0,encodeCashAddr as j0}from"@swapkit/utxo-signer";var Q0={P2PKH:fX.P2PKH,P2SH:fX.P2SH},Z0={[fX.P2PKH]:"P2PKH",[fX.P2SH]:"P2SH"};function G0(X,$,J){return j0({hash:J,prefix:X,type:Q0[$]})}function Y0(X){let $=J0(X),J=Z0[$.type];if(!J)throw Error(`Unknown CashAddr type: ${$.type}`);return{hash:$.hash,prefix:$.prefix,type:J}}var lX={decode:Y0,encode:G0};var Q2=L0(q0);var Z2;((J)=>{J.Mainnet="mainnet";J.Testnet="testnet"})(Z2||={});var c={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}};function G2(X){try{return PX(X),!0}catch{return!1}}function Y2(X){return PX(X)?.network}function u(X){let $=PX(X);if($?.format==="legacy")return X;return W0($)}function FX(X){let $=PX(X);return _0($)}function PX(X){try{let $=z0(X);if($)return $}catch{}try{let $=U0(X);if($)return $}catch{}throw new j2("toolbox_utxo_invalid_address",{address:X})}function z0(X){try{let $=Q2.decode(X);if($.length!==21)throw new j2("toolbox_utxo_invalid_address",{address:X});let J=$[0],j=Array.prototype.slice.call($,1);switch(J){case c.legacy.mainnet.p2pkh:return{format:"legacy",hash:j,network:"mainnet",type:"p2pkh"};case c.legacy.mainnet.p2sh:return{format:"legacy",hash:j,network:"mainnet",type:"p2sh"};case c.legacy.testnet.p2pkh:return{format:"legacy",hash:j,network:"testnet",type:"p2pkh"};case c.legacy.testnet.p2sh:return{format:"legacy",hash:j,network:"testnet",type:"p2sh"};case c.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:j,network:"mainnet",type:"p2pkh"};case c.bitpay.mainnet.p2sh:return{format:"bitpay",hash:j,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function U0(X){if(X.indexOf(":")!==-1)try{return J2(X)}catch{}else{let $=["bitcoincash","bchtest","bchreg"];for(let J of $)try{return J2(`${J}:${X}`)}catch{}}return}function J2(X){try{let{hash:$,prefix:J,type:j}=lX.decode(X);return{format:"cashaddr",hash:Array.prototype.slice.call($,0),network:J==="bitcoincash"?"mainnet":"testnet",type:j==="P2PKH"?"p2pkh":"p2sh"}}catch{return}}function W0(X){let $=c.legacy[X.network][X.type],J=Buffer.alloc(1+X.hash.length);return J[0]=$,J.set(X.hash,1),Q2.encode(J)}function _0(X){let $=X.network==="mainnet"?"bitcoincash":"bchtest",J=X.type==="p2pkh"?"P2PKH":"P2SH",j=new Uint8Array(X.hash);return lX.encode($,J,j)}import{Chain as r,SwapKitError as H0}from"@swapkit/helpers";import{SwapKitError as B0}from"@swapkit/helpers";import{Script as N0}from"@swapkit/utxo-signer";var m1=1000,hX=10,pX=2,M0=10,D0=41,C0=107;function R(X){let $=new Uint8Array(Buffer.from(X,"utf8"));return N0.encode(["RETURN",$])}var uX;((J)=>{J.P2PKH="P2PKH";J.P2WPKH="P2WPKH"})(uX||={});var xX={["P2PKH"]:148,["P2WPKH"]:68},TX={["P2PKH"]:34,["P2WPKH"]:31},_X=(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 B0("toolbox_utxo_invalid_address",{address:X})},JX=({inputs:X,outputs:$,feeRate:J})=>{let j=X[0]&&"address"in X[0]&&X[0].address?_X(X[0].address):"P2PKH",Z=(J?X.filter((Y)=>Y.value>=xX["type"in Y&&Y.type?Y.type:"P2PKH"]*Math.ceil(J)):X).reduce((Y,W)=>Y+d(W),0),L=$?.reduce((Y,W)=>Y+EX(W),0)||TX[j],q=hX+Z+L;return j==="P2WPKH"?Math.ceil(q+pX/4):q},d=(X)=>{if("type"in X&&X.type)return xX[X.type];if("address"in X&&X.address)return xX[_X(X.address)];return D0+C0},EX=(X,$)=>{if(X?.script)return M0+X.script.length+(X.script.length>=74?2:1);if($)return TX[$];if("address"in X&&X.address)return TX[_X(X.address)];return TX.P2PKH};function RX(X){switch(X){case r.Bitcoin:case r.BitcoinCash:return 550;case r.Dash:case r.Litecoin:return 5500;case r.Dogecoin:return 1e5;case r.Zcash:return 546;default:throw new H0("toolbox_utxo_not_supported",{chain:X})}}function S({inputs:X,outputs:$,feeRate:J=1,chain:j=r.Bitcoin,changeAddress:Q=""}){let Z=X[0]&&"address"in X[0]&&X[0].address?_X(X[0].address):"P2PKH",L=X.filter((B)=>d(B)*J<=B.value),G=Z==="P2WPKH"?Math.ceil(pX/4):0,Y=hX+G+$.reduce((B,D)=>B+EX(D),0),W=$.reduce((B,D)=>B+D.value,0),z=Y*J,U=0,_=[];for(let B of L){let D=d(B),V=J*D;z+=V,U+=B.value,_.push(B);let e=z+W;if(U<e)continue;let DX=U-e,CX=J*EX({address:Q,value:0});if(DX>CX){let qX=CX+z,LX=U-(W+Math.ceil(qX));if(LX>Math.max(d({value:0})*J,RX(j)))return{fee:Math.ceil(qX),inputs:_,outputs:$.concat({address:Q,value:LX})}}return{fee:Math.ceil(z),inputs:_,outputs:$}}return{fee:Math.ceil(J*JX({inputs:X,outputs:$}))}}import{Chain as YX,SwapKitError as H1}from"@swapkit/helpers";import{hex as b2}from"@scure/base";import{Chain as m0,derivationPathToString as g0,FeeOption as l0,NetworkDerivationPath as x0,SwapKitError as l,updateDerivationPath as h0}from"@swapkit/helpers";import{BCHSigHash as p0,CashAddrPrefix as I2,CashAddrType as f2,encodeCashAddr as F2,NETWORKS as u0,p2pkh as P2,Transaction as T2}from"@swapkit/utxo-signer";import{secp256k1 as O0}from"@noble/curves/secp256k1.js";import{hex as i}from"@scure/base";import{HDKey as W2}from"@scure/bip32";import{mnemonicToSeedSync as cX}from"@scure/bip39";import{AssetValue as AX,applyFeeMultiplier as q2,Chain as b,derivationPathToString as NX,FeeOption as K,NetworkDerivationPath as _2,SwapKitError as k,SwapKitNumber as k0,updateDerivationPath as V0,warnOnce as b0}from"@swapkit/helpers";import{Address as I0,BCHSigHash as dX,CashAddrPrefix as f0,CashAddrType as F0,encodeCashAddr as P0,NETWORKS as QX,p2pkh as L2,p2wpkh as T0,RBF_SEQUENCE as E0,SigHash as B2,Transaction as oX,WIF as N2}from"@swapkit/utxo-signer";import{match as M2}from"ts-pattern";import{validateZcashAddress as BX}from"@swapkit/utxo-signer";function jX(X){return X.replace(/(bchtest:|bitcoincash:)/,"")}function n(X){let $=jX(X);return G2($)&&Y2($)==="mainnet"}var yX=[b.Dash,b.Dogecoin,b.Zcash,b.BitcoinCash],vX=[b.Bitcoin];function D2({address:X,chain:$}){return M2($).with(b.BitcoinCash,()=>n(X)).with(b.Zcash,()=>BX(X)).otherwise(()=>{try{return I0(P($)).decode(X),!0}catch{return!1}})}function P(X){return M2(X).with(b.Bitcoin,()=>QX.bitcoin).with(b.BitcoinCash,()=>QX.bitcoinCash).with(b.Dash,()=>QX.dash).with(b.Dogecoin,()=>QX.dogecoin).with(b.Litecoin,()=>QX.litecoin).with(b.Zcash,()=>QX.zcash).exhaustive()}function R0({phrase:X,derivationPath:$,network:J,seed:j}){let Q=j??cX(X),L=W2.fromMasterSeed(Q,J.bip32).derive($);if(!L.privateKey)throw new k("toolbox_utxo_invalid_params",{error:"Could not derive private key from phrase"});return L.privateKey}function z2(X){return O0.getPublicKey(X,!0)}function MX({publicKey:X,chain:$,network:J}){if($===b.BitcoinCash){let Z=L2(X,J);if(!Z.hash)throw new k("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return P0({hash:Z.hash,prefix:f0.MAINNET,type:F0.P2PKH}).replace(/^bitcoincash:/,"")}let Q=!yX.includes($)?T0(X,J):L2(X,J);if(!Q.address)throw new k("toolbox_utxo_invalid_address",{error:"Could not derive address"});return Q.address}function ZX({phrase:X,derivationPath:$,chain:J,wif:j,seed:Q}){let Z=P(J);if(j){let Y=N2(Z).decode(j),W=z2(Y);return{privateKey:Y,publicKey:W}}if(!X)throw new k("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let L=$||NX(_2[J]),q=R0({derivationPath:L,network:Z,phrase:X,seed:Q}),G=z2(q);return{privateKey:q,publicKey:G}}function A0(X,$){return N2(P($)).encode(X)}function v0({phrase:X,derivationPath:$,chain:J,seed:j}){let Q=$.split("/");if(Q.length<4)throw new k("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${Q.length}): ${$}`});let Z=P(J),L=j??cX(X),q=W2.fromMasterSeed(L,Z.bip32),G=Q.slice(0,4).join("/");return q.derive(G)}function s({inputs:X,outputs:$,chain:J,tx:j,sender:Q,compiledMemo:Z,enableRBF:L=!1}){let q=P(J),G=!yX.includes(J),Y=L?E0:void 0,W=new Set;for(let z of X){let U=`${z.hash}:${z.index}`;if(W.has(U))throw new k("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});W.add(U);let _=typeof z.hash==="string"?i.decode(z.hash):z.hash;if(G&&z.witnessUtxo)j.addInput({index:z.index,sequence:Y,txid:_,witnessUtxo:{amount:BigInt(z.witnessUtxo.value),script:z.witnessUtxo.script}});else if(z.txHex)j.addInput({index:z.index,nonWitnessUtxo:i.decode(z.txHex),sequence:Y,txid:_,...J===b.BitcoinCash?{sighashType:dX.ALL}:{}});else throw new k("toolbox_utxo_invalid_params",{error:"Input requires either witnessUtxo or txHex for non-segwit chains"})}for(let z of $){let U="address"in z&&z.address?z.address:Q;if(J===b.BitcoinCash)U=u(U);if(z.script){if(Z)j.addOutput({amount:0n,script:Z})}else j.addOutputAddress(U,BigInt(z.value),q)}return{inputs:X,tx:j}}async function GX(X){let $=await I(X).getSuggestedTxFee();return{[K.Average]:$,[K.Fast]:q2($,K.Fast),[K.Fastest]:q2($,K.Fastest)}}async function C2({assetValue:X,recipient:$,memo:J,sender:j,fetchTxHex:Q=!1}){let Z=X.chain,L=(await GX(Z))[K.Fastest],q=Q||yX.includes(Z),G=X.getBaseValue("number"),Y=Math.ceil(G+L*5000);return{inputs:await I(Z).getUtxos({address:j,fetchTxHex:q,targetValue:Y}),outputs:[{address:$,value:G},...J?[{address:"",script:R(J),value:0}]:[]]}}async function H2({assetValue:X,recipient:$,memo:J,feeRate:j,sender:Q,fetchTxHex:Z=!1,enableRBF:L=!1}){let q=X.chain,G=J?R(J):null,Y=await C2({assetValue:X,fetchTxHex:Z,memo:J,recipient:$,sender:Q}),{inputs:W,outputs:z}=S({...Y,chain:q,feeRate:j});if(!(W&&z))throw new k("toolbox_utxo_insufficient_balance",{assetValue:X,sender:Q});let U=new oX({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!G,version:1}),{inputs:_,tx:B}=s({chain:q,compiledMemo:G,enableRBF:L,inputs:W,outputs:z,sender:Q,tx:U});return{inputs:_,tx:B,utxos:Y.inputs}}async function O2({assetValue:X,feeOptionKey:$=K.Fast,feeRate:J,memo:j,sender:Q,recipient:Z}){let L=X.chain,q=await C2({assetValue:X,memo:j,recipient:Z,sender:Q}),G=J?Math.floor(J):(await GX(L))[$];return S({...q,chain:L,feeRate:G})}function y0(X){return async function({from:J,memo:j,feeRate:Q,feeOptionKey:Z=K.Fast,recipients:L=1}){let q=await I(X).getAddressData(J),G=Q?Math.ceil(Q):(await GX(X))[Z],Y=q?.utxo.map((D)=>({...D,hash:"",type:"P2PKH"})).filter((D)=>D.value>Math.max(RX(X),d(D)*G));if(!Y?.length)return AX.from({chain:X});let W=BigInt(Y.reduce((D,V)=>D+V.value,0)),z=AX.from({chain:X,value:W}),U=typeof L==="number"?Array.from({length:L},()=>({address:J,value:0})):L;if(j)U.push({address:J,script:R(j),value:0});let _=JX({inputs:Y,outputs:U}),B=AX.from({chain:X,value:BigInt(_*G)});return z.sub(B)}}function w0(X){return async function(J){let{fee:j}=await O2(J);return AX.from({chain:X,value:k0.fromBigInt(BigInt(j),8).getValue("string")})}}function S0({chain:X,phrase:$,derivationPath:J,seed:j}){let Q=P(X),{privateKey:Z,publicKey:L}=ZX({chain:X,derivationPath:J,phrase:$,seed:j}),q=X===b.BitcoinCash?[dX.ALL]:[B2.ALL];return{getAddress:()=>MX({chain:X,network:Q,publicKey:L}),privateKey:Z,publicKey:L,signTransaction:(G)=>{return G.sign(Z,q),G}}}function K0(X,$){return async function({memo:j,recipient:Q,feeOptionKey:Z,feeRate:L,assetValue:q,enableRBF:G=!1}){let Y=await $?.getAddress();if(!($&&Y))throw new k("toolbox_utxo_no_signer");if(!Q)throw new k("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});b0({condition:G&&!vX.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 W=G&&vX.includes(X),z=L||(await GX(X))[Z||K.Fast],{tx:U}=await H2({assetValue:q,enableRBF:W,feeRate:z,memo:j,recipient:Q,sender:Y}),_=await $.signTransaction(U);return _.finalize(),I(X).broadcastTx(i.encode(_.extract()))}}function k2(X){return($)=>D2({address:$,chain:X})}function V2(X){let $=P(X);return function(j){if(!j)throw new k("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return MX({chain:X,network:$,publicKey:j.publicKey})}}function a({chain:X,...$}){let J="phrase"in $?$.phrase:void 0,j="index"in $?$.index||0:0,Q=J?cX(J):void 0,Z="derivationPath"in $&&$.derivationPath?$.derivationPath:V0(_2[X],{index:j}),L=NX(Z),q=J?S0({chain:X,derivationPath:L,phrase:J,seed:Q}):void 0,G="signer"in $?$.signer:void 0,Y=q||G,W=J?ZX({chain:X,derivationPath:L,phrase:J,seed:Q}):void 0;function z(){if(Y)return Y.getAddress();return Promise.resolve(void 0)}function U(N){if(!J)return;let M=o({accountIndex:N,chain:X,derivationPath:Z});return v0({chain:X,derivationPath:NX(M),phrase:J,seed:Q})}let _=U();function B(){if(!_)return;return _.publicExtendedKey}function D({accountIndex:N}={}){let M=N===void 0?_:U(N);if(!M)return;let C=o({accountIndex:N,chain:X,derivationPath:Z});return{accountIndex:XX(C),path:NX(C),xpub:M.publicExtendedKey}}function V({accountIndex:N,index:M,change:C=!1}){let H=N===void 0?_:U(N);if(!H)return;let O=UX({accountIndex:N,chain:X,change:C,derivationPath:Z,index:M}),E=P(X),A=H.deriveChild(Number(C)).deriveChild(M);if(!A.publicKey)throw new k("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let T=MX({chain:X,network:E,publicKey:A.publicKey}),v=i.encode(A.publicKey);return{accountIndex:XX(O),address:T,change:C,index:M,path:NX(O),pubkey:v}}async function e(N){if(!vX.includes(X))return{reason:`RBF is not supported on ${X}`,supported:!1};let M=await I(X).getTransactionDetails(N);return{canReplace:M.isRBF&&!M.confirmed,confirmed:M.confirmed,enabled:M.isRBF,fee:M.fee,sequences:M.sequences,supported:!0}}async function DX({txid:N,newFeeRate:M,recipient:C,memo:H}){if(!vX.includes(X))throw new k("toolbox_utxo_rbf_not_supported",{chain:X});let O=await I(X).getTransactionDetails(N);if(!O.isRBF)throw new k("toolbox_utxo_tx_not_replaceable",{txid:N});if(O.confirmed)throw new k("toolbox_utxo_tx_already_confirmed",{blockId:O.blockId,txid:N});let E=O.inputs.reduce((f,p)=>f+p.value,0),T=O.outputs.find((f)=>f.recipient===C)?.value||0;if(T===0)throw new k("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let v=await Promise.all(O.inputs.map(async(f)=>{let p=await I(X).getRawTx(f.transaction_hash);return{hash:f.transaction_hash,index:f.index,txHex:p,value:f.value,witnessUtxo:void 0}})),HX=H?R(H):null,mX=JX({feeRate:M,inputs:v.map((f)=>({...f,type:"P2WPKH"})),outputs:[{address:C,value:T}]}),g=Math.ceil(mX*M);if(g<=O.fee)throw new k("toolbox_utxo_rbf_fee_too_low",{newFee:g,originalFee:O.fee});let zX=g-O.fee,x=T-zX;if(x<=0)throw new k("toolbox_utxo_rbf_insufficient_change");let OX=new oX({allowLegacyWitnessUtxo:!0,version:1}),kX=[{address:C,value:x},...H?[{address:"",script:R(H),value:0}]:[]],VX=E-x-g,h=await z();if(VX>RX(X)&&h)kX.push({address:h,value:VX});return s({chain:X,compiledMemo:HX,inputs:v,outputs:kX,sender:h||C,tx:OX}),{feeDelta:zX,newFee:g,originalFee:O.fee,tx:OX}}async function CX({txid:N,newFeeRate:M,recipient:C,memo:H}){let{tx:O,originalFee:E,newFee:A}=await DX({memo:H,newFeeRate:M,recipient:C,txid:N}),T=await KX(O);T.finalize();let v=await I(X).broadcastTx(i.encode(T.extract()));return{newFee:A,originalFee:E,txid:v}}function qX({accountIndex:N,index:M,change:C=!1}){y("index",M);let H=N===void 0?_:U(N);if(!H)return;return H.deriveChild(Number(C)).deriveChild(M).privateKey||void 0}function LX({tx:N,inputDerivations:M}){if(!_)throw new k("toolbox_utxo_no_signer");let C=X===b.BitcoinCash?[dX.ALL]:[B2.ALL];for(let H=0;H<M.length;H++){let O=M[H];if(!O)continue;let{derivationIndex:E,isChange:A}=O,T=qX({change:A,index:E});if(!T)throw new k("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${H} at index ${E}`});N.signIdx(T,H,C)}return N}async function g2({utxos:N,recipient:M,assetValue:C,memo:H,feeRate:O,feeOptionKey:E,changeAddress:A}){if(!_)throw new k("toolbox_utxo_no_signer");let T=O||(await GX(X))[E||K.Fast],v=H?R(H):null,HX=[{address:M,value:C.getBaseValue("number")}];if(v)HX.push({address:"",script:v,value:0});let mX=N.map(({hash:h,index:f,value:p,txHex:h2,witnessUtxo:gX})=>({hash:h,index:f,txHex:h2,value:p,witnessUtxo:gX?{script:gX.script,value:gX.value}:void 0})),{inputs:g,outputs:zX}=S({chain:X,feeRate:T,inputs:mX,outputs:HX});if(!(g&&zX))throw new k("toolbox_utxo_insufficient_balance",{assetValue:C,sender:"multiple addresses"});let x=new oX({allowLegacyWitnessUtxo:!0,version:1}),OX=N[0]?.address,kX=A||await z()||OX||M;s({chain:X,compiledMemo:v,inputs:g,outputs:zX,sender:kX,tx:x});let VX=g.map((h)=>{let f=N.find((p)=>p.hash===h.hash&&p.index===h.index);return f?{derivationIndex:f.derivationIndex,isChange:f.isChange}:{derivationIndex:0,isChange:!1}});return LX({inputDerivations:VX,tx:x}),x.finalize(),I(X).broadcastTx(i.encode(x.extract()))}function l2({address:N,gapLimit:M=20}){if(!_)return;for(let C=0;C<M;C++){let H=V({change:!1,index:C}),O=V({change:!0,index:C}),E=H?.address===N?!1:O?.address===N;if(H?.address===N||O?.address===N)return{change:E,index:C}}return}function KX(N){if(!Y)throw new k("toolbox_utxo_no_signer");return Y.signTransaction(N)}async function x2(N){let M=await KX(N);return M.finalize(),await I(X).broadcastTx(i.encode(M.extract()))}return{accumulative:S,broadcastTx:(N)=>I(X).broadcastTx(N),bumpFee:CX,calculateTxSize:JX,createKeysForPath:(N)=>ZX({...N,chain:X}),createReplacementTransaction:DX,createTransaction:H2,deriveAddressAtIndex:V,derivePrivateKeyAtIndex:qX,estimateMaxSendableAmount:y0(X),estimateTransactionFee:w0(X),getAddress:z,getAddressFromKeys:V2(X),getBalance:U2(X),getExtendedPublicKey:B,getExtendedPublicKeyInfo:D,getFeeRates:()=>GX(X),getInputsOutputsFee:O2,getNetworkForChain:()=>P(X),getPrivateKeyFromMnemonic:(N)=>A0(ZX({...N,chain:X}).privateKey,X),isRBFEnabled:e,keys:W,resolveDerivationIndex:l2,signAndBroadcastTransaction:x2,signTransaction:KX,signTransactionWithMultipleKeys:LX,transfer:K0(X,Y),transferFromMultipleAddresses:g2,validateAddress:k2(X)}}var m=m0.BitcoinCash;function wX(X){return jX(FX(X))}function o0(X){let $=P(m);function J(Q){return Q.sign(X.privateKey,[p0.ALL]),Q}function j(){let Q=P2(X.publicKey,$);if(!Q.hash)throw new l("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let Z=F2({hash:Q.hash,prefix:I2.MAINNET,type:f2.P2PKH});return Promise.resolve(Z.replace(/^bitcoincash:/,""))}return{getAddress:j,signTransaction:J}}function E2(X){let $="phrase"in X?X.phrase:void 0,J="index"in X?X.index||0:0,j=g0("derivationPath"in X&&X.derivationPath?X.derivationPath:h0(x0[m],{index:J})),Q=$?ZX({chain:m,derivationPath:j,phrase:$}):void 0,Z=Q?o0(Q):("signer"in X)?X.signer:void 0;function L(){return Promise.resolve(Z?.getAddress())}let{getBalance:q,getFeeRates:G,broadcastTx:Y,...W}=a({chain:m});function z(B,D=!0){return q(jX(FX(B)))}function U(B){if(!Z)throw new l("toolbox_utxo_no_signer");return Z.signTransaction(B)}async function _(B){let D=await U(B);return D.finalize(),await Y(b2.encode(D.extract()))}return{...W,broadcastTx:Y,buildTx:d0,createTransaction:R2,getAddress:L,getAddressFromKeys:r0,getBalance:z,getFeeRates:G,signAndBroadcastTransaction:_,signTransaction:U,stripPrefix:jX,stripToCashAddress:wX,transfer:c0({broadcastTx:Y,getFeeRates:G,signer:Z}),validateAddress:n}}async function R2({assetValue:X,recipient:$,memo:J,feeRate:j,sender:Q}){if(!n($))throw new l("toolbox_utxo_invalid_address",{address:$});let Z=Math.ceil(X.getBaseValue("number")+j*7500),L=await I(m).getUtxos({address:wX(Q),fetchTxHex:!0,targetValue:Z}),q=J?R(J):null,G=[],Y=u($);if(G.push({address:Y,value:X.getBaseValue("number")}),q)G.push({script:q,value:0});let{inputs:W,outputs:z}=S({chain:m,feeRate:j,inputs:L,outputs:G});if(!(W&&z))throw new l("toolbox_utxo_insufficient_balance",{assetValue:X,sender:Q});let U=new T2({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!q,version:1}),_=u(Q),{inputs:B,tx:D}=s({chain:m,compiledMemo:q,inputs:W,outputs:z.map((V)=>("address"in V)&&V.address?{...V,address:u(V.address)}:V),sender:_,tx:U});return{inputs:B,tx:D,utxos:W}}function c0({broadcastTx:X,getFeeRates:$,signer:J}){return async function({recipient:Q,assetValue:Z,feeOptionKey:L=l0.Fast,...q}){let G=await J?.getAddress();if(!(J&&G))throw new l("toolbox_utxo_no_signer");if(!Q)throw new l("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let Y=q.feeRate||(await $())[L],{tx:W}=await R2({...q,assetValue:Z,feeRate:Y,recipient:Q,sender:G}),z=await J.signTransaction(W);return z.finalize(),X(b2.encode(z.extract()))}}async function d0({assetValue:X,recipient:$,memo:J,feeRate:j,sender:Q}){let Z=FX($);if(!n(Z))throw new l("toolbox_utxo_invalid_address",{address:Z});let L=Math.ceil(X.getBaseValue("number")+j*7500),q=await I(m).getUtxos({address:wX(Q),fetchTxHex:!0,targetValue:L}),G=Number(j.toFixed(0)),Y=J?R(J):null,W=[];if(W.push({address:u($),value:X.getBaseValue("number")}),Y)W.push({script:Y,value:0});let{inputs:z,outputs:U}=S({chain:m,feeRate:G,inputs:q,outputs:W});if(!(z&&U))throw new l("toolbox_utxo_insufficient_balance",{assetValue:X,sender:Q});let _=new T2({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!Y,version:1}),{inputs:B,tx:D}=s({chain:m,compiledMemo:Y,inputs:z,outputs:U,sender:u(Q),tx:_});return{inputs:B,tx:D,utxos:q}}function r0(X){let $=u0.bitcoinCash,J=P2(X.publicKey,$);if(!J.hash)throw new l("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return F2({hash:J.hash,prefix:I2.MAINNET,type:f2.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as n0,hex as i0}from"@scure/base";import{HDKey as y2}from"@scure/bip32";import{mnemonicToSeedSync as w2}from"@scure/bip39";import{Chain as SX,derivationPathToString as s0,FeeOption as a0,NetworkDerivationPath as t0,SKConfig as S2,SwapKitError as t,updateDerivationPath as e0}from"@swapkit/helpers";import{Address as X1,createZcashTransaction as $1,isTransparentZcashAddress as A2,OutScript as J1,PCZT as j1,utils as K2,WIF as Q1,ZCASH_NETWORK as Z1,ZCASH_TEST_NETWORK as G1,ZcashConsensusBranchId as Y1,ZcashPSBT as q1,ZcashSigHash as rX,ZcashVersionGroupId as L1}from"@swapkit/utxo-signer";import{match as z1,P as nX}from"ts-pattern";function iX(){let{isStagenet:X}=S2.get("envs");return X?G1:Z1}var U1=n0(K2.sha256);function W1(X){return U1.encode(X)}function _1({phrase:X,derivationPath:$}){let J=w2(X),Q=y2.fromMasterSeed(J).derive($);if(!Q.privateKey||!Q.publicKey)throw new t("toolbox_utxo_invalid_params");let{privateKey:Z,publicKey:L}=Q,q=K2.hash160(L),{isStagenet:G}=S2.get("envs"),Y=G?new Uint8Array([29,37]):new Uint8Array([28,184]),W=new Uint8Array(Y.length+q.length);W.set(Y,0),W.set(q,Y.length);let z=W1(W);return{getAddress:()=>Promise.resolve(z),signTransaction:(U)=>{if(U instanceof q1){let _=U.toPCZT();return _.signAllInputs(Z,L,rX.ALL),_.finalizeAllInputs(),Promise.resolve(_.extract())}if(U instanceof j1)return U.signAllInputs(Z,L,rX.ALL),U.finalizeAllInputs(),Promise.resolve(U.extract());return U.signAllInputs(Z,L,rX.ALL),Promise.resolve(U)}}}function B1({inputs:X,outputs:$,tx:J,sender:j,compiledMemo:Q}){let Z=iX();for(let L of X){let q=X1(Z).decode(j),G=J1.encode(q);J.addInput({index:L.index,script:G,sequence:4294967295,txid:i0.decode(L.hash),value:BigInt(L.value)})}for(let L of $){let q="address"in L&&L.address?L.address:j,G=L.script;if(G&&!Q)continue;if(G&&Q)J.addOutput({amount:0n,script:Q});else J.addOutputAddress(q,BigInt(L.value),Z)}return{inputs:X,tx:J}}async function v2(X){let{assetValue:$,recipient:J,memo:j,feeRate:Q,sender:Z,fetchTxHex:L}=X,q=iX();if(!A2(Z,q))throw new t("toolbox_utxo_invalid_address",{address:Z});if(!A2(J,q))throw new t("toolbox_utxo_invalid_address",{address:J,error:"Zcash transaction creation currently supports transparent addresses only"});let G=j?R(j):null,Y=await I(SX.Zcash).getUtxos({address:Z,fetchTxHex:L!==!1}),W=[{address:J,value:Number($.getBaseValue("string"))},...G?[{script:G,value:0}]:[]],{inputs:z,outputs:U}=S({chain:SX.Zcash,changeAddress:Z,feeRate:Q,inputs:Y,outputs:W});if(!(z&&U))throw new t("toolbox_utxo_insufficient_balance",{assetValue:$,sender:Z});let _=$1({consensusBranchId:Y1.NU6_2,expiryHeight:0,lockTime:0,version:4,versionGroupId:L1.SAPLING}),{tx:B,inputs:D}=B1({compiledMemo:G,inputs:z,outputs:U,sender:Z,tx:_});return{inputs:D,outputs:U,tx:B}}function m2(X){let $=z1(X).with({signer:nX.not(nX.nullish)},({signer:G})=>G).with({phrase:nX.string},({phrase:G,derivationPath:Y,index:W=0})=>{let z=Y||t0[SX.Zcash]||[44,133,0,0,0],U=e0(z,{index:W}),_=s0(U);return _1({derivationPath:_,phrase:G})}).otherwise(()=>{return}),J=a({chain:SX.Zcash,signer:$});async function j(G){if(!$)throw new t("toolbox_utxo_no_signer");return await $.signTransaction(G)}async function Q(G){let Y=await j(G);return J.broadcastTx(Y.toHex())}async function Z({recipient:G,assetValue:Y,feeOptionKey:W=a0.Fast,...z}){let U=await $?.getAddress();if(!($&&U))throw new t("toolbox_utxo_no_signer");let _=z.feeRate||(await J.getFeeRates())[W],{tx:B}=await v2({...z,assetValue:Y,feeRate:_,recipient:G,sender:U}),V=(await $.signTransaction(B)).toHex();return J.broadcastTx(V)}function L({phrase:G,derivationPath:Y="m/44'/133'/0'/0/0"}){let W=w2(G),U=y2.fromMasterSeed(W).derive(Y);if(!U.privateKey||!U.publicKey)throw new t("toolbox_utxo_invalid_params");return{privateKey:U.privateKey,publicKey:U.publicKey}}function q({phrase:G,derivationPath:Y="m/44'/133'/0'/0/0"}){let W=L({derivationPath:Y,phrase:G}),z=iX();return Q1(z).encode(W.privateKey)}return{...J,createKeysForPath:L,createTransaction:v2,getPrivateKeyFromMnemonic:q,signAndBroadcastTransaction:Q,signTransaction:j,transfer:Z,validateAddress:BX}}import{hex as N1}from"@scure/base";import{HDKey as M1}from"@scure/bip32";import{derivationPathToString as D1}from"@swapkit/helpers";function C1({xpub:X,chain:$,count:J,startIndex:j=0,accountIndex:Q}){if(y("count",J),J<1)throw RangeError("count must be at least 1");y("startIndex",j);let Z=P($),L=M1.fromExtendedKey(X,Z.bip32),q=o({accountIndex:Q,chain:$}),G=XX(q),Y=[];for(let W of[!1,!0]){let z=L.deriveChild(Number(W));for(let U=0;U<J;U++){let _=j+U,B=z.deriveChild(_);if(!B.publicKey)continue;let D=UX({accountIndex:Q,chain:$,change:W,index:_});Y.push({accountIndex:G,address:MX({chain:$,network:Z,publicKey:B.publicKey}),change:W,index:_,path:D1(D),pubkey:N1.encode(B.publicKey)})}}return Y}function S8(X,$){switch(X){case YX.BitcoinCash:return E2($||{});case YX.Zcash:return m2($);case YX.Bitcoin:case YX.Dogecoin:case YX.Litecoin:case YX.Dash:return a({chain:X,...$});default:throw new H1("toolbox_utxo_not_supported",{chain:X})}}export{BX as validateZcashAddress,D2 as validateUtxoAddress,n as validateBchAddress,u as toLegacyAddress,FX as toCashAddress,wX as stripToCashAddress,jX as stripPrefix,yX as nonSegwitChains,G2 as isValidAddress,S8 as getUtxoToolbox,F1 as getUtxoNetwork,I as getUtxoApi,k2 as getUTXOAddressValidator,UX as getUTXOAddressPath,o as getUTXOAccountPath,XX as getUTXOAccountIndexFromPath,_X as getScriptTypeForAddress,EX as getOutputSize,P as getNetworkForChain,d as getInputSize,RX as getDustThreshold,Y2 as detectAddressNetwork,C1 as deriveAddressesFromXpub,m2 as createZcashToolbox,a as createUTXOToolbox,u2 as createHDWalletHelpers,f1 as createCustomUtxoApi,E2 as createBCHToolbox,R as compileMemo,JX as calculateTxSize,y as assertDerivationIndex,V2 as addressFromKeysGetter,s as addInputsAndOutputs,S as accumulative,Z2 as UtxoNetwork,uX as UTXOScriptType,hX as TX_OVERHEAD,pX as SEGWIT_MARKER_FLAG_WEIGHT,TX as OutputSizes,M0 as OP_RETURN_OVERHEAD,m1 as MIN_TX_FEE,xX as InputSizes};
1
+ import{da as tX,ea as U2}from"../../chunk-jdh5asaw.js";import"../../chunk-fjyc6m34.js";import{NetworkDerivationPath as p2}from"@swapkit/helpers";function y(X,$){if(!Number.isInteger($)||$<0)throw RangeError(`${X} must be a non-negative integer, got: ${$}`)}function o({accountIndex:X,chain:$,derivationPath:J}){if(X!==void 0)y("accountIndex",X);let j=[...J?.slice(0,3)??p2[$].slice(0,3)];if(X!==void 0)j[2]=X;return j}function UX({accountIndex:X,change:$=!1,chain:J,derivationPath:j,index:Q}){return y("index",Q),[...o({accountIndex:X,chain:J,derivationPath:j}),Number($),Q]}function XX(X){return X[2]??0}function u2({deriveAddress:X,getBalance:$,getUtxos:J}){async function j(q){let{accountIndex:G,count:Y,startIndex:W=0,change:z=!1}=q;if(y("count",Y),Y<1)throw RangeError("count must be at least 1");y("startIndex",W);let U=[];for(let _=0;_<Y;_++){let B=await X({accountIndex:G,change:z,index:W+_});if(B)U.push(B)}return U}async function Q(q){let{gapLimit:G=20,change:Y=!1}=q??{},W=[],z=0,U=0;while(z<G){let _=await X({change:Y,index:U});if(!_)break;if((await $(_.address)).some((V)=>V.getValue("number")>0))W.push(_),z=0;else z++;U++}return W}async function Z(q=20){let[G,Y]=await Promise.all([Q({change:!1,gapLimit:q}),Q({change:!0,gapLimit:q})]),W=[...G,...Y],z=await Promise.all(W.map(async(_)=>{let D=(await $(_.address)).reduce((V,e)=>V+e.getValue("number"),0);return{..._,balance:D}})),U=z.reduce((_,B)=>_+B.balance,0);return{addresses:z,total:U}}async function L(q=20){let[G,Y]=await Promise.all([Q({change:!1,gapLimit:q}),Q({change:!0,gapLimit:q})]),W=[...G,...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:L,scanForAddresses:Q}}import{Chain as F,getRPCUrl as o2,RequestClient as bX,SKConfig as c2,SwapKitError as w,warnOnce as d2}from"@swapkit/helpers";import{NETWORKS as $X}from"@swapkit/utxo-signer";async function r2({chain:X,txHash:$}){let J=`${WX(X)}/push/transaction`,j=JSON.stringify({data:$});try{let Q=await bX.post(J,{body:j,headers:{"Content-Type":"application/json"}});if(Q.context.code!==200)throw new w("toolbox_utxo_broadcast_failed",{error:Q.context.error||"Transaction broadcast failed"});return Q.data?.transaction_hash||$}catch(Q){let Z=await o2(X);if(Z){let L=JSON.stringify({id:tX(),jsonrpc:"2.0",method:"sendrawtransaction",params:[$]}),q=await bX.post(Z,{body:L,headers:{"Content-Type":"application/json"}});if(q.error)throw new w("toolbox_utxo_broadcast_failed",{error:q.error?.message});if(q.result.includes('"code":-26'))throw new w("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return q.result}throw Q}}function WX(X){return`https://api.blockchair.com/${n2(X)}`}function sX(X){switch(X){case F.Bitcoin:return 5;case F.Dogecoin:return 1e4;case F.Litecoin:return 1;case F.Zcash:return 1;default:return 2}}function n2(X){switch(X){case F.BitcoinCash:return"bitcoin-cash";case F.Litecoin:return"litecoin";case F.Dash:return"dash";case F.Dogecoin:return"dogecoin";case F.Zcash:return"zcash";case F.Polkadot:return"polkadot";default:return"bitcoin"}}async function i2(X){try{let{feePerKb:$}=await bX.get(`https://app.bitgo.com/api/v2/${X.toLowerCase()}/tx/fee`),J=$/1000;return Math.max(J,sX(X))}catch{return sX(X)}}async function IX(X,$){let J=await bX.get(`${X}${$?`${X.includes("?")?"&":"?"}key=${$}`:""}`);if(!J||J.context.code!==200)throw new w("toolbox_utxo_api_error",{error:`Failed to query ${X}`});return J.data}async function eX({address:X,chain:$,apiKey:J}){if(!X)throw new w("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await IX(`${WX($)}/dashboards/address/${X}?transaction_details=true`,J))[X]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function s2({address:X,chain:$,apiKey:J}){return(await eX({address:X,apiKey:J,chain:$}))?.address.balance||0}async function X2({chain:X,apiKey:$,txHash:J}){if(!J)throw new w("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await IX(`${WX(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 a2=4294967294;async function t2({chain:X,apiKey:$,txHash:J}){if(!J)throw new w("toolbox_utxo_invalid_params",{error:"TxHash is required"});let Q=(await IX(`${WX(X)}/dashboards/transaction/${J}`,$))?.[J];if(!Q)throw new w("toolbox_utxo_tx_not_found",{txHash:J});let{transaction:Z,inputs:L,outputs:q}=Q,G=L.map((W)=>W.spending_sequence),Y=Z.is_rbf===!0||G.some((W)=>W<a2);return{blockId:Z.block_id,confirmed:Z.block_id!==-1,fee:Z.fee,inputs:L,isRBF:Y,outputs:q,sequences:G,size:Z.size,txid:Z.hash,weight:Z.weight}}async function e2({chain:X,address:$,apiKey:J,offset:j=0,limit:Q=30}){return(await IX(`${WX(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:G,script_hex:Y,block_id:W,transaction_hash:z,index:U,value:_,spending_signature_hex:B})=>({hash:z,index:U,is_confirmed:W!==-1,is_spent:G,script_hex:Y,txHex:B,value:_}))}function X0(X){return X.reduce(($,J)=>$+J.value,0)}function aX(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 $2({chain:X,address:$,apiKey:J,targetValue:j,accumulativeValue:Q=0,offset:Z=0,limit:L=30}){if(!$)throw new w("toolbox_utxo_invalid_params",{error:"Address is required"});try{let q=await e2({address:$,apiKey:J,chain:X,limit:L,offset:Z,targetValue:j}),Y=q.length<L,W=q.filter(({is_spent:V})=>!V),z=X0(W),U=Q+z,_=j&&U>=j;if(Y||_)return aX(W,j);let B=await $2({accumulativeValue:U,address:$,apiKey:J,chain:X,limit:L,offset:Z+L,targetValue:j}),D=[...W,...B];return aX(D,j)}catch(q){let G=q instanceof Error?q.message:String(q);return console.error(`Failed to fetch unspent UTXOs: ${G}`),[]}}async function $0({address:X,chain:$,apiKey:J,fetchTxHex:j=!0,targetValue:Q}){let Z=await $2({address:X,apiKey:J,chain:$,targetValue:Q}),L=[];for(let{hash:q,index:G,script_hex:Y,value:W}of Z){let z;if(j)z=await X2({apiKey:J,chain:$,txHash:q});L.push({address:X,hash:q,index:G,txHex:z,value:W,witnessUtxo:{script:Buffer.from(Y,"hex"),value:W}})}return L}function I(X){let $=c2.get("apiKeys").blockchair||"";return d2({condition:!$,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(J)=>r2({chain:X,txHash:J}),getAddressData:(J)=>eX({address:J,apiKey:$,chain:X}),getBalance:(J)=>s2({address:J,apiKey:$,chain:X}),getRawTx:(J)=>X2({apiKey:$,chain:X,txHash:J}),getSuggestedTxFee:()=>i2(X),getTransactionDetails:(J)=>t2({apiKey:$,chain:X,txHash:J}),getUtxos:(J)=>$0({...J,apiKey:$,chain:X})}}function f1(X){return X}function F1(){return function($){switch($){case F.Bitcoin:return $X.bitcoin;case F.BitcoinCash:return $X.bitcoinCash;case F.Dash:return $X.dash;case F.Litecoin:return $X.litecoin;case F.Dogecoin:return $X.dogecoin;case F.Zcash:return $X.zcash;default:throw new w("toolbox_utxo_not_supported",{chain:$})}}}import{sha256 as q0}from"@noble/hashes/sha2.js";import{createBase58check as L0}from"@scure/base";import{SwapKitError as j2}from"@swapkit/helpers";import{CashAddrType as fX,decodeCashAddr as J0,encodeCashAddr as j0}from"@swapkit/utxo-signer";var Q0={P2PKH:fX.P2PKH,P2SH:fX.P2SH},Z0={[fX.P2PKH]:"P2PKH",[fX.P2SH]:"P2SH"};function G0(X,$,J){return j0({hash:J,prefix:X,type:Q0[$]})}function Y0(X){let $=J0(X),J=Z0[$.type];if(!J)throw Error(`Unknown CashAddr type: ${$.type}`);return{hash:$.hash,prefix:$.prefix,type:J}}var lX={decode:Y0,encode:G0};var Q2=L0(q0);var Z2;((J)=>{J.Mainnet="mainnet";J.Testnet="testnet"})(Z2||={});var c={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}};function G2(X){try{return PX(X),!0}catch{return!1}}function Y2(X){return PX(X)?.network}function u(X){let $=PX(X);if($?.format==="legacy")return X;return W0($)}function FX(X){let $=PX(X);return _0($)}function PX(X){try{let $=z0(X);if($)return $}catch{}try{let $=U0(X);if($)return $}catch{}throw new j2("toolbox_utxo_invalid_address",{address:X})}function z0(X){try{let $=Q2.decode(X);if($.length!==21)throw new j2("toolbox_utxo_invalid_address",{address:X});let J=$[0],j=Array.prototype.slice.call($,1);switch(J){case c.legacy.mainnet.p2pkh:return{format:"legacy",hash:j,network:"mainnet",type:"p2pkh"};case c.legacy.mainnet.p2sh:return{format:"legacy",hash:j,network:"mainnet",type:"p2sh"};case c.legacy.testnet.p2pkh:return{format:"legacy",hash:j,network:"testnet",type:"p2pkh"};case c.legacy.testnet.p2sh:return{format:"legacy",hash:j,network:"testnet",type:"p2sh"};case c.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:j,network:"mainnet",type:"p2pkh"};case c.bitpay.mainnet.p2sh:return{format:"bitpay",hash:j,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function U0(X){if(X.indexOf(":")!==-1)try{return J2(X)}catch{}else{let $=["bitcoincash","bchtest","bchreg"];for(let J of $)try{return J2(`${J}:${X}`)}catch{}}return}function J2(X){try{let{hash:$,prefix:J,type:j}=lX.decode(X);return{format:"cashaddr",hash:Array.prototype.slice.call($,0),network:J==="bitcoincash"?"mainnet":"testnet",type:j==="P2PKH"?"p2pkh":"p2sh"}}catch{return}}function W0(X){let $=c.legacy[X.network][X.type],J=Buffer.alloc(1+X.hash.length);return J[0]=$,J.set(X.hash,1),Q2.encode(J)}function _0(X){let $=X.network==="mainnet"?"bitcoincash":"bchtest",J=X.type==="p2pkh"?"P2PKH":"P2SH",j=new Uint8Array(X.hash);return lX.encode($,J,j)}import{Chain as r,SwapKitError as H0}from"@swapkit/helpers";import{SwapKitError as B0}from"@swapkit/helpers";import{Script as N0}from"@swapkit/utxo-signer";var m1=1000,hX=10,pX=2,M0=10,D0=41,C0=107;function R(X){let $=new Uint8Array(Buffer.from(X,"utf8"));return N0.encode(["RETURN",$])}var uX;((J)=>{J.P2PKH="P2PKH";J.P2WPKH="P2WPKH"})(uX||={});var xX={["P2PKH"]:148,["P2WPKH"]:68},TX={["P2PKH"]:34,["P2WPKH"]:31},_X=(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 B0("toolbox_utxo_invalid_address",{address:X})},JX=({inputs:X,outputs:$,feeRate:J})=>{let j=X[0]&&"address"in X[0]&&X[0].address?_X(X[0].address):"P2PKH",Z=(J?X.filter((Y)=>Y.value>=xX["type"in Y&&Y.type?Y.type:"P2PKH"]*Math.ceil(J)):X).reduce((Y,W)=>Y+d(W),0),L=$?.reduce((Y,W)=>Y+EX(W),0)||TX[j],q=hX+Z+L;return j==="P2WPKH"?Math.ceil(q+pX/4):q},d=(X)=>{if("type"in X&&X.type)return xX[X.type];if("address"in X&&X.address)return xX[_X(X.address)];return D0+C0},EX=(X,$)=>{if(X?.script)return M0+X.script.length+(X.script.length>=74?2:1);if($)return TX[$];if("address"in X&&X.address)return TX[_X(X.address)];return TX.P2PKH};function RX(X){switch(X){case r.Bitcoin:case r.BitcoinCash:return 550;case r.Dash:case r.Litecoin:return 5500;case r.Dogecoin:return 1e5;case r.Zcash:return 546;default:throw new H0("toolbox_utxo_not_supported",{chain:X})}}function S({inputs:X,outputs:$,feeRate:J=1,chain:j=r.Bitcoin,changeAddress:Q=""}){let Z=X[0]&&"address"in X[0]&&X[0].address?_X(X[0].address):"P2PKH",L=X.filter((B)=>d(B)*J<=B.value),G=Z==="P2WPKH"?Math.ceil(pX/4):0,Y=hX+G+$.reduce((B,D)=>B+EX(D),0),W=$.reduce((B,D)=>B+D.value,0),z=Y*J,U=0,_=[];for(let B of L){let D=d(B),V=J*D;z+=V,U+=B.value,_.push(B);let e=z+W;if(U<e)continue;let DX=U-e,CX=J*EX({address:Q,value:0});if(DX>CX){let qX=CX+z,LX=U-(W+Math.ceil(qX));if(LX>Math.max(d({value:0})*J,RX(j)))return{fee:Math.ceil(qX),inputs:_,outputs:$.concat({address:Q,value:LX})}}return{fee:Math.ceil(z),inputs:_,outputs:$}}return{fee:Math.ceil(J*JX({inputs:X,outputs:$}))}}import{Chain as YX,SwapKitError as H1}from"@swapkit/helpers";import{hex as b2}from"@scure/base";import{Chain as m0,derivationPathToString as g0,FeeOption as l0,NetworkDerivationPath as x0,SwapKitError as l,updateDerivationPath as h0}from"@swapkit/helpers";import{BCHSigHash as p0,CashAddrPrefix as I2,CashAddrType as f2,encodeCashAddr as F2,NETWORKS as u0,p2pkh as P2,Transaction as T2}from"@swapkit/utxo-signer";import{secp256k1 as O0}from"@noble/curves/secp256k1.js";import{hex as i}from"@scure/base";import{HDKey as W2}from"@scure/bip32";import{mnemonicToSeedSync as cX}from"@scure/bip39";import{AssetValue as AX,applyFeeMultiplier as q2,Chain as b,derivationPathToString as NX,FeeOption as K,NetworkDerivationPath as _2,SwapKitError as k,SwapKitNumber as k0,updateDerivationPath as V0,warnOnce as b0}from"@swapkit/helpers";import{Address as I0,BCHSigHash as dX,CashAddrPrefix as f0,CashAddrType as F0,encodeCashAddr as P0,NETWORKS as QX,p2pkh as L2,p2wpkh as T0,RBF_SEQUENCE as E0,SigHash as B2,Transaction as oX,WIF as N2}from"@swapkit/utxo-signer";import{match as M2}from"ts-pattern";import{validateZcashAddress as BX}from"@swapkit/utxo-signer";function jX(X){return X.replace(/(bchtest:|bitcoincash:)/,"")}function n(X){let $=jX(X);return G2($)&&Y2($)==="mainnet"}var yX=[b.Dash,b.Dogecoin,b.Zcash,b.BitcoinCash],vX=[b.Bitcoin];function D2({address:X,chain:$}){return M2($).with(b.BitcoinCash,()=>n(X)).with(b.Zcash,()=>BX(X)).otherwise(()=>{try{return I0(P($)).decode(X),!0}catch{return!1}})}function P(X){return M2(X).with(b.Bitcoin,()=>QX.bitcoin).with(b.BitcoinCash,()=>QX.bitcoinCash).with(b.Dash,()=>QX.dash).with(b.Dogecoin,()=>QX.dogecoin).with(b.Litecoin,()=>QX.litecoin).with(b.Zcash,()=>QX.zcash).exhaustive()}function R0({phrase:X,derivationPath:$,network:J,seed:j}){let Q=j??cX(X),L=W2.fromMasterSeed(Q,J.bip32).derive($);if(!L.privateKey)throw new k("toolbox_utxo_invalid_params",{error:"Could not derive private key from phrase"});return L.privateKey}function z2(X){return O0.getPublicKey(X,!0)}function MX({publicKey:X,chain:$,network:J}){if($===b.BitcoinCash){let Z=L2(X,J);if(!Z.hash)throw new k("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return P0({hash:Z.hash,prefix:f0.MAINNET,type:F0.P2PKH}).replace(/^bitcoincash:/,"")}let Q=!yX.includes($)?T0(X,J):L2(X,J);if(!Q.address)throw new k("toolbox_utxo_invalid_address",{error:"Could not derive address"});return Q.address}function ZX({phrase:X,derivationPath:$,chain:J,wif:j,seed:Q}){let Z=P(J);if(j){let Y=N2(Z).decode(j),W=z2(Y);return{privateKey:Y,publicKey:W}}if(!X)throw new k("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let L=$||NX(_2[J]),q=R0({derivationPath:L,network:Z,phrase:X,seed:Q}),G=z2(q);return{privateKey:q,publicKey:G}}function A0(X,$){return N2(P($)).encode(X)}function v0({phrase:X,derivationPath:$,chain:J,seed:j}){let Q=$.split("/");if(Q.length<4)throw new k("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${Q.length}): ${$}`});let Z=P(J),L=j??cX(X),q=W2.fromMasterSeed(L,Z.bip32),G=Q.slice(0,4).join("/");return q.derive(G)}function s({inputs:X,outputs:$,chain:J,tx:j,sender:Q,compiledMemo:Z,enableRBF:L=!1}){let q=P(J),G=!yX.includes(J),Y=L?E0:void 0,W=new Set;for(let z of X){let U=`${z.hash}:${z.index}`;if(W.has(U))throw new k("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});W.add(U);let _=typeof z.hash==="string"?i.decode(z.hash):z.hash;if(G&&z.witnessUtxo)j.addInput({index:z.index,sequence:Y,txid:_,witnessUtxo:{amount:BigInt(z.witnessUtxo.value),script:z.witnessUtxo.script}});else if(z.txHex)j.addInput({index:z.index,nonWitnessUtxo:i.decode(z.txHex),sequence:Y,txid:_,...J===b.BitcoinCash?{sighashType:dX.ALL}:{}});else throw new k("toolbox_utxo_invalid_params",{error:"Input requires either witnessUtxo or txHex for non-segwit chains"})}for(let z of $){let U="address"in z&&z.address?z.address:Q;if(J===b.BitcoinCash)U=u(U);if(z.script){if(Z)j.addOutput({amount:0n,script:Z})}else j.addOutputAddress(U,BigInt(z.value),q)}return{inputs:X,tx:j}}async function GX(X){let $=await I(X).getSuggestedTxFee();return{[K.Average]:$,[K.Fast]:q2($,K.Fast),[K.Fastest]:q2($,K.Fastest)}}async function C2({assetValue:X,recipient:$,memo:J,sender:j,fetchTxHex:Q=!1}){let Z=X.chain,L=(await GX(Z))[K.Fastest],q=Q||yX.includes(Z),G=X.getBaseValue("number"),Y=Math.ceil(G+L*5000);return{inputs:await I(Z).getUtxos({address:j,fetchTxHex:q,targetValue:Y}),outputs:[{address:$,value:G},...J?[{address:"",script:R(J),value:0}]:[]]}}async function H2({assetValue:X,recipient:$,memo:J,feeRate:j,sender:Q,fetchTxHex:Z=!1,enableRBF:L=!1}){let q=X.chain,G=J?R(J):null,Y=await C2({assetValue:X,fetchTxHex:Z,memo:J,recipient:$,sender:Q}),{inputs:W,outputs:z}=S({...Y,chain:q,feeRate:j});if(!(W&&z))throw new k("toolbox_utxo_insufficient_balance",{assetValue:X,sender:Q});let U=new oX({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!G,version:1}),{inputs:_,tx:B}=s({chain:q,compiledMemo:G,enableRBF:L,inputs:W,outputs:z,sender:Q,tx:U});return{inputs:_,tx:B,utxos:Y.inputs}}async function O2({assetValue:X,feeOptionKey:$=K.Fast,feeRate:J,memo:j,sender:Q,recipient:Z}){let L=X.chain,q=await C2({assetValue:X,memo:j,recipient:Z,sender:Q}),G=J?Math.floor(J):(await GX(L))[$];return S({...q,chain:L,feeRate:G})}function y0(X){return async function({from:J,memo:j,feeRate:Q,feeOptionKey:Z=K.Fast,recipients:L=1}){let q=await I(X).getAddressData(J),G=Q?Math.ceil(Q):(await GX(X))[Z],Y=q?.utxo.map((D)=>({...D,hash:"",type:"P2PKH"})).filter((D)=>D.value>Math.max(RX(X),d(D)*G));if(!Y?.length)return AX.from({chain:X});let W=BigInt(Y.reduce((D,V)=>D+V.value,0)),z=AX.from({chain:X,value:W}),U=typeof L==="number"?Array.from({length:L},()=>({address:J,value:0})):L;if(j)U.push({address:J,script:R(j),value:0});let _=JX({inputs:Y,outputs:U}),B=AX.from({chain:X,value:BigInt(_*G)});return z.sub(B)}}function w0(X){return async function(J){let{fee:j}=await O2(J);return AX.from({chain:X,value:k0.fromBigInt(BigInt(j),8).getValue("string")})}}function S0({chain:X,phrase:$,derivationPath:J,seed:j}){let Q=P(X),{privateKey:Z,publicKey:L}=ZX({chain:X,derivationPath:J,phrase:$,seed:j}),q=X===b.BitcoinCash?[dX.ALL]:[B2.ALL];return{getAddress:()=>MX({chain:X,network:Q,publicKey:L}),privateKey:Z,publicKey:L,signTransaction:(G)=>{return G.sign(Z,q),G}}}function K0(X,$){return async function({memo:j,recipient:Q,feeOptionKey:Z,feeRate:L,assetValue:q,enableRBF:G=!1}){let Y=await $?.getAddress();if(!($&&Y))throw new k("toolbox_utxo_no_signer");if(!Q)throw new k("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});b0({condition:G&&!vX.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 W=G&&vX.includes(X),z=L||(await GX(X))[Z||K.Fast],{tx:U}=await H2({assetValue:q,enableRBF:W,feeRate:z,memo:j,recipient:Q,sender:Y}),_=await $.signTransaction(U);return _.finalize(),I(X).broadcastTx(i.encode(_.extract()))}}function k2(X){return($)=>D2({address:$,chain:X})}function V2(X){let $=P(X);return function(j){if(!j)throw new k("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return MX({chain:X,network:$,publicKey:j.publicKey})}}function a({chain:X,...$}){let J="phrase"in $?$.phrase:void 0,j="index"in $?$.index||0:0,Q=J?cX(J):void 0,Z="derivationPath"in $&&$.derivationPath?$.derivationPath:V0(_2[X],{index:j}),L=NX(Z),q=J?S0({chain:X,derivationPath:L,phrase:J,seed:Q}):void 0,G="signer"in $?$.signer:void 0,Y=q||G,W=J?ZX({chain:X,derivationPath:L,phrase:J,seed:Q}):void 0;function z(){if(Y)return Y.getAddress();return Promise.resolve(void 0)}function U(N){if(!J)return;let M=o({accountIndex:N,chain:X,derivationPath:Z});return v0({chain:X,derivationPath:NX(M),phrase:J,seed:Q})}let _=U();function B(){if(!_)return;return _.publicExtendedKey}function D({accountIndex:N}={}){let M=N===void 0?_:U(N);if(!M)return;let C=o({accountIndex:N,chain:X,derivationPath:Z});return{accountIndex:XX(C),path:NX(C),xpub:M.publicExtendedKey}}function V({accountIndex:N,index:M,change:C=!1}){let H=N===void 0?_:U(N);if(!H)return;let O=UX({accountIndex:N,chain:X,change:C,derivationPath:Z,index:M}),E=P(X),A=H.deriveChild(Number(C)).deriveChild(M);if(!A.publicKey)throw new k("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let T=MX({chain:X,network:E,publicKey:A.publicKey}),v=i.encode(A.publicKey);return{accountIndex:XX(O),address:T,change:C,index:M,path:NX(O),pubkey:v}}async function e(N){if(!vX.includes(X))return{reason:`RBF is not supported on ${X}`,supported:!1};let M=await I(X).getTransactionDetails(N);return{canReplace:M.isRBF&&!M.confirmed,confirmed:M.confirmed,enabled:M.isRBF,fee:M.fee,sequences:M.sequences,supported:!0}}async function DX({txid:N,newFeeRate:M,recipient:C,memo:H}){if(!vX.includes(X))throw new k("toolbox_utxo_rbf_not_supported",{chain:X});let O=await I(X).getTransactionDetails(N);if(!O.isRBF)throw new k("toolbox_utxo_tx_not_replaceable",{txid:N});if(O.confirmed)throw new k("toolbox_utxo_tx_already_confirmed",{blockId:O.blockId,txid:N});let E=O.inputs.reduce((f,p)=>f+p.value,0),T=O.outputs.find((f)=>f.recipient===C)?.value||0;if(T===0)throw new k("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let v=await Promise.all(O.inputs.map(async(f)=>{let p=await I(X).getRawTx(f.transaction_hash);return{hash:f.transaction_hash,index:f.index,txHex:p,value:f.value,witnessUtxo:void 0}})),HX=H?R(H):null,mX=JX({feeRate:M,inputs:v.map((f)=>({...f,type:"P2WPKH"})),outputs:[{address:C,value:T}]}),g=Math.ceil(mX*M);if(g<=O.fee)throw new k("toolbox_utxo_rbf_fee_too_low",{newFee:g,originalFee:O.fee});let zX=g-O.fee,x=T-zX;if(x<=0)throw new k("toolbox_utxo_rbf_insufficient_change");let OX=new oX({allowLegacyWitnessUtxo:!0,version:1}),kX=[{address:C,value:x},...H?[{address:"",script:R(H),value:0}]:[]],VX=E-x-g,h=await z();if(VX>RX(X)&&h)kX.push({address:h,value:VX});return s({chain:X,compiledMemo:HX,inputs:v,outputs:kX,sender:h||C,tx:OX}),{feeDelta:zX,newFee:g,originalFee:O.fee,tx:OX}}async function CX({txid:N,newFeeRate:M,recipient:C,memo:H}){let{tx:O,originalFee:E,newFee:A}=await DX({memo:H,newFeeRate:M,recipient:C,txid:N}),T=await KX(O);T.finalize();let v=await I(X).broadcastTx(i.encode(T.extract()));return{newFee:A,originalFee:E,txid:v}}function qX({accountIndex:N,index:M,change:C=!1}){y("index",M);let H=N===void 0?_:U(N);if(!H)return;return H.deriveChild(Number(C)).deriveChild(M).privateKey||void 0}function LX({tx:N,inputDerivations:M}){if(!_)throw new k("toolbox_utxo_no_signer");let C=X===b.BitcoinCash?[dX.ALL]:[B2.ALL];for(let H=0;H<M.length;H++){let O=M[H];if(!O)continue;let{derivationIndex:E,isChange:A}=O,T=qX({change:A,index:E});if(!T)throw new k("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${H} at index ${E}`});N.signIdx(T,H,C)}return N}async function g2({utxos:N,recipient:M,assetValue:C,memo:H,feeRate:O,feeOptionKey:E,changeAddress:A}){if(!_)throw new k("toolbox_utxo_no_signer");let T=O||(await GX(X))[E||K.Fast],v=H?R(H):null,HX=[{address:M,value:C.getBaseValue("number")}];if(v)HX.push({address:"",script:v,value:0});let mX=N.map(({hash:h,index:f,value:p,txHex:h2,witnessUtxo:gX})=>({hash:h,index:f,txHex:h2,value:p,witnessUtxo:gX?{script:gX.script,value:gX.value}:void 0})),{inputs:g,outputs:zX}=S({chain:X,feeRate:T,inputs:mX,outputs:HX});if(!(g&&zX))throw new k("toolbox_utxo_insufficient_balance",{assetValue:C,sender:"multiple addresses"});let x=new oX({allowLegacyWitnessUtxo:!0,version:1}),OX=N[0]?.address,kX=A||await z()||OX||M;s({chain:X,compiledMemo:v,inputs:g,outputs:zX,sender:kX,tx:x});let VX=g.map((h)=>{let f=N.find((p)=>p.hash===h.hash&&p.index===h.index);return f?{derivationIndex:f.derivationIndex,isChange:f.isChange}:{derivationIndex:0,isChange:!1}});return LX({inputDerivations:VX,tx:x}),x.finalize(),I(X).broadcastTx(i.encode(x.extract()))}function l2({address:N,gapLimit:M=20}){if(!_)return;for(let C=0;C<M;C++){let H=V({change:!1,index:C}),O=V({change:!0,index:C}),E=H?.address===N?!1:O?.address===N;if(H?.address===N||O?.address===N)return{change:E,index:C}}return}function KX(N){if(!Y)throw new k("toolbox_utxo_no_signer");return Y.signTransaction(N)}async function x2(N){let M=await KX(N);return M.finalize(),await I(X).broadcastTx(i.encode(M.extract()))}return{accumulative:S,broadcastTx:(N)=>I(X).broadcastTx(N),bumpFee:CX,calculateTxSize:JX,createKeysForPath:(N)=>ZX({...N,chain:X}),createReplacementTransaction:DX,createTransaction:H2,deriveAddressAtIndex:V,derivePrivateKeyAtIndex:qX,estimateMaxSendableAmount:y0(X),estimateTransactionFee:w0(X),getAddress:z,getAddressFromKeys:V2(X),getBalance:U2(X),getExtendedPublicKey:B,getExtendedPublicKeyInfo:D,getFeeRates:()=>GX(X),getInputsOutputsFee:O2,getNetworkForChain:()=>P(X),getPrivateKeyFromMnemonic:(N)=>A0(ZX({...N,chain:X}).privateKey,X),isRBFEnabled:e,keys:W,resolveDerivationIndex:l2,signAndBroadcastTransaction:x2,signTransaction:KX,signTransactionWithMultipleKeys:LX,transfer:K0(X,Y),transferFromMultipleAddresses:g2,validateAddress:k2(X)}}var m=m0.BitcoinCash;function wX(X){return jX(FX(X))}function o0(X){let $=P(m);function J(Q){return Q.sign(X.privateKey,[p0.ALL]),Q}function j(){let Q=P2(X.publicKey,$);if(!Q.hash)throw new l("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let Z=F2({hash:Q.hash,prefix:I2.MAINNET,type:f2.P2PKH});return Promise.resolve(Z.replace(/^bitcoincash:/,""))}return{getAddress:j,signTransaction:J}}function E2(X){let $="phrase"in X?X.phrase:void 0,J="index"in X?X.index||0:0,j=g0("derivationPath"in X&&X.derivationPath?X.derivationPath:h0(x0[m],{index:J})),Q=$?ZX({chain:m,derivationPath:j,phrase:$}):void 0,Z=Q?o0(Q):("signer"in X)?X.signer:void 0;function L(){return Promise.resolve(Z?.getAddress())}let{getBalance:q,getFeeRates:G,broadcastTx:Y,...W}=a({chain:m});function z(B,D=!0){return q(jX(FX(B)))}function U(B){if(!Z)throw new l("toolbox_utxo_no_signer");return Z.signTransaction(B)}async function _(B){let D=await U(B);return D.finalize(),await Y(b2.encode(D.extract()))}return{...W,broadcastTx:Y,buildTx:d0,createTransaction:R2,getAddress:L,getAddressFromKeys:r0,getBalance:z,getFeeRates:G,signAndBroadcastTransaction:_,signTransaction:U,stripPrefix:jX,stripToCashAddress:wX,transfer:c0({broadcastTx:Y,getFeeRates:G,signer:Z}),validateAddress:n}}async function R2({assetValue:X,recipient:$,memo:J,feeRate:j,sender:Q}){if(!n($))throw new l("toolbox_utxo_invalid_address",{address:$});let Z=Math.ceil(X.getBaseValue("number")+j*7500),L=await I(m).getUtxos({address:wX(Q),fetchTxHex:!0,targetValue:Z}),q=J?R(J):null,G=[],Y=u($);if(G.push({address:Y,value:X.getBaseValue("number")}),q)G.push({script:q,value:0});let{inputs:W,outputs:z}=S({chain:m,feeRate:j,inputs:L,outputs:G});if(!(W&&z))throw new l("toolbox_utxo_insufficient_balance",{assetValue:X,sender:Q});let U=new T2({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!q,version:1}),_=u(Q),{inputs:B,tx:D}=s({chain:m,compiledMemo:q,inputs:W,outputs:z.map((V)=>("address"in V)&&V.address?{...V,address:u(V.address)}:V),sender:_,tx:U});return{inputs:B,tx:D,utxos:W}}function c0({broadcastTx:X,getFeeRates:$,signer:J}){return async function({recipient:Q,assetValue:Z,feeOptionKey:L=l0.Fast,...q}){let G=await J?.getAddress();if(!(J&&G))throw new l("toolbox_utxo_no_signer");if(!Q)throw new l("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let Y=q.feeRate||(await $())[L],{tx:W}=await R2({...q,assetValue:Z,feeRate:Y,recipient:Q,sender:G}),z=await J.signTransaction(W);return z.finalize(),X(b2.encode(z.extract()))}}async function d0({assetValue:X,recipient:$,memo:J,feeRate:j,sender:Q}){let Z=FX($);if(!n(Z))throw new l("toolbox_utxo_invalid_address",{address:Z});let L=Math.ceil(X.getBaseValue("number")+j*7500),q=await I(m).getUtxos({address:wX(Q),fetchTxHex:!0,targetValue:L}),G=Number(j.toFixed(0)),Y=J?R(J):null,W=[];if(W.push({address:u($),value:X.getBaseValue("number")}),Y)W.push({script:Y,value:0});let{inputs:z,outputs:U}=S({chain:m,feeRate:G,inputs:q,outputs:W});if(!(z&&U))throw new l("toolbox_utxo_insufficient_balance",{assetValue:X,sender:Q});let _=new T2({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!Y,version:1}),{inputs:B,tx:D}=s({chain:m,compiledMemo:Y,inputs:z,outputs:U,sender:u(Q),tx:_});return{inputs:B,tx:D,utxos:q}}function r0(X){let $=u0.bitcoinCash,J=P2(X.publicKey,$);if(!J.hash)throw new l("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return F2({hash:J.hash,prefix:I2.MAINNET,type:f2.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as n0,hex as i0}from"@scure/base";import{HDKey as y2}from"@scure/bip32";import{mnemonicToSeedSync as w2}from"@scure/bip39";import{Chain as SX,derivationPathToString as s0,FeeOption as a0,NetworkDerivationPath as t0,SKConfig as S2,SwapKitError as t,updateDerivationPath as e0}from"@swapkit/helpers";import{Address as X1,createZcashTransaction as $1,isTransparentZcashAddress as A2,OutScript as J1,PCZT as j1,utils as K2,WIF as Q1,ZCASH_NETWORK as Z1,ZCASH_TEST_NETWORK as G1,ZcashConsensusBranchId as Y1,ZcashPSBT as q1,ZcashSigHash as rX,ZcashVersionGroupId as L1}from"@swapkit/utxo-signer";import{match as z1,P as nX}from"ts-pattern";function iX(){let{isStagenet:X}=S2.get("envs");return X?G1:Z1}var U1=n0(K2.sha256);function W1(X){return U1.encode(X)}function _1({phrase:X,derivationPath:$}){let J=w2(X),Q=y2.fromMasterSeed(J).derive($);if(!Q.privateKey||!Q.publicKey)throw new t("toolbox_utxo_invalid_params");let{privateKey:Z,publicKey:L}=Q,q=K2.hash160(L),{isStagenet:G}=S2.get("envs"),Y=G?new Uint8Array([29,37]):new Uint8Array([28,184]),W=new Uint8Array(Y.length+q.length);W.set(Y,0),W.set(q,Y.length);let z=W1(W);return{getAddress:()=>Promise.resolve(z),signTransaction:(U)=>{if(U instanceof q1){let _=U.toPCZT();return _.signAllInputs(Z,L,rX.ALL),_.finalizeAllInputs(),Promise.resolve(_.extract())}if(U instanceof j1)return U.signAllInputs(Z,L,rX.ALL),U.finalizeAllInputs(),Promise.resolve(U.extract());return U.signAllInputs(Z,L,rX.ALL),Promise.resolve(U)}}}function B1({inputs:X,outputs:$,tx:J,sender:j,compiledMemo:Q}){let Z=iX();for(let L of X){let q=X1(Z).decode(j),G=J1.encode(q);J.addInput({index:L.index,script:G,sequence:4294967295,txid:i0.decode(L.hash),value:BigInt(L.value)})}for(let L of $){let q="address"in L&&L.address?L.address:j,G=L.script;if(G&&!Q)continue;if(G&&Q)J.addOutput({amount:0n,script:Q});else J.addOutputAddress(q,BigInt(L.value),Z)}return{inputs:X,tx:J}}async function v2(X){let{assetValue:$,recipient:J,memo:j,feeRate:Q,sender:Z,fetchTxHex:L}=X,q=iX();if(!A2(Z,q))throw new t("toolbox_utxo_invalid_address",{address:Z});if(!A2(J,q))throw new t("toolbox_utxo_invalid_address",{address:J,error:"Zcash transaction creation currently supports transparent addresses only"});let G=j?R(j):null,Y=await I(SX.Zcash).getUtxos({address:Z,fetchTxHex:L!==!1}),W=[{address:J,value:Number($.getBaseValue("string"))},...G?[{script:G,value:0}]:[]],{inputs:z,outputs:U}=S({chain:SX.Zcash,changeAddress:Z,feeRate:Q,inputs:Y,outputs:W});if(!(z&&U))throw new t("toolbox_utxo_insufficient_balance",{assetValue:$,sender:Z});let _=$1({consensusBranchId:Y1.NU6_2,expiryHeight:0,lockTime:0,version:4,versionGroupId:L1.SAPLING}),{tx:B,inputs:D}=B1({compiledMemo:G,inputs:z,outputs:U,sender:Z,tx:_});return{inputs:D,outputs:U,tx:B}}function m2(X){let $=z1(X).with({signer:nX.not(nX.nullish)},({signer:G})=>G).with({phrase:nX.string},({phrase:G,derivationPath:Y,index:W=0})=>{let z=Y||t0[SX.Zcash]||[44,133,0,0,0],U=e0(z,{index:W}),_=s0(U);return _1({derivationPath:_,phrase:G})}).otherwise(()=>{return}),J=a({chain:SX.Zcash,signer:$});async function j(G){if(!$)throw new t("toolbox_utxo_no_signer");return await $.signTransaction(G)}async function Q(G){let Y=await j(G);return J.broadcastTx(Y.toHex())}async function Z({recipient:G,assetValue:Y,feeOptionKey:W=a0.Fast,...z}){let U=await $?.getAddress();if(!($&&U))throw new t("toolbox_utxo_no_signer");let _=z.feeRate||(await J.getFeeRates())[W],{tx:B}=await v2({...z,assetValue:Y,feeRate:_,recipient:G,sender:U}),V=(await $.signTransaction(B)).toHex();return J.broadcastTx(V)}function L({phrase:G,derivationPath:Y="m/44'/133'/0'/0/0"}){let W=w2(G),U=y2.fromMasterSeed(W).derive(Y);if(!U.privateKey||!U.publicKey)throw new t("toolbox_utxo_invalid_params");return{privateKey:U.privateKey,publicKey:U.publicKey}}function q({phrase:G,derivationPath:Y="m/44'/133'/0'/0/0"}){let W=L({derivationPath:Y,phrase:G}),z=iX();return Q1(z).encode(W.privateKey)}return{...J,createKeysForPath:L,createTransaction:v2,getPrivateKeyFromMnemonic:q,signAndBroadcastTransaction:Q,signTransaction:j,transfer:Z,validateAddress:BX}}import{hex as N1}from"@scure/base";import{HDKey as M1}from"@scure/bip32";import{derivationPathToString as D1}from"@swapkit/helpers";function C1({xpub:X,chain:$,count:J,startIndex:j=0,accountIndex:Q}){if(y("count",J),J<1)throw RangeError("count must be at least 1");y("startIndex",j);let Z=P($),L=M1.fromExtendedKey(X,Z.bip32),q=o({accountIndex:Q,chain:$}),G=XX(q),Y=[];for(let W of[!1,!0]){let z=L.deriveChild(Number(W));for(let U=0;U<J;U++){let _=j+U,B=z.deriveChild(_);if(!B.publicKey)continue;let D=UX({accountIndex:Q,chain:$,change:W,index:_});Y.push({accountIndex:G,address:MX({chain:$,network:Z,publicKey:B.publicKey}),change:W,index:_,path:D1(D),pubkey:N1.encode(B.publicKey)})}}return Y}function S8(X,$){switch(X){case YX.BitcoinCash:return E2($||{});case YX.Zcash:return m2($);case YX.Bitcoin:case YX.Dogecoin:case YX.Litecoin:case YX.Dash:return a({chain:X,...$});default:throw new H1("toolbox_utxo_not_supported",{chain:X})}}export{BX as validateZcashAddress,D2 as validateUtxoAddress,n as validateBchAddress,u as toLegacyAddress,FX as toCashAddress,wX as stripToCashAddress,jX as stripPrefix,yX as nonSegwitChains,G2 as isValidAddress,S8 as getUtxoToolbox,F1 as getUtxoNetwork,I as getUtxoApi,k2 as getUTXOAddressValidator,UX as getUTXOAddressPath,o as getUTXOAccountPath,XX as getUTXOAccountIndexFromPath,_X as getScriptTypeForAddress,EX as getOutputSize,P as getNetworkForChain,d as getInputSize,RX as getDustThreshold,Y2 as detectAddressNetwork,C1 as deriveAddressesFromXpub,m2 as createZcashToolbox,a as createUTXOToolbox,u2 as createHDWalletHelpers,f1 as createCustomUtxoApi,E2 as createBCHToolbox,R as compileMemo,JX as calculateTxSize,y as assertDerivationIndex,V2 as addressFromKeysGetter,s as addInputsAndOutputs,S as accumulative,Z2 as UtxoNetwork,uX as UTXOScriptType,hX as TX_OVERHEAD,pX as SEGWIT_MARKER_FLAG_WEIGHT,TX as OutputSizes,M0 as OP_RETURN_OVERHEAD,m1 as MIN_TX_FEE,xX as InputSizes};
@@ -1473,6 +1473,119 @@ export declare const GNOToolbox: ({ provider, ...toolboxParams }: EVMToolboxPara
1473
1473
  transfer: ({ assetValue, memo, recipient, feeOptionKey, sender, ...tx }: import("..").EVMTransferParams) => Promise<string>;
1474
1474
  validateAddress: typeof import("./baseEVMToolbox").validateEVMAddress;
1475
1475
  };
1476
+ export declare const HOODToolbox: ({ provider, ...toolboxParams }: EVMToolboxParams) => {
1477
+ approve: ({ assetAddress, spenderAddress, feeOptionKey, amount, gasLimitFallback, from: fromParam, nonce, }: import("..").ApproveParams) => Promise<string>;
1478
+ approvedAmount: ({ assetAddress, spenderAddress, from }: import("..").IsApprovedParams) => Promise<bigint>;
1479
+ broadcastTransaction: ((signedTx: string) => Promise<import("ethers").TransactionResponse>) | ((signedTx: string) => Promise<import("ethers").TransactionResponse>);
1480
+ call: <T>({ callProvider, contractAddress, abi, funcName, funcParams, txOverrides, feeOption, }: import("..").CallParams) => Promise<T>;
1481
+ createApprovalTx: ({ assetAddress, spenderAddress, amount, from: fromParam }: import("..").ApproveParams) => Promise<{
1482
+ value: string;
1483
+ to: string;
1484
+ data: string;
1485
+ from?: string;
1486
+ type?: number;
1487
+ nonce?: number;
1488
+ gasLimit?: bigint;
1489
+ gasPrice?: bigint;
1490
+ maxPriorityFeePerGas?: bigint;
1491
+ maxFeePerGas?: bigint;
1492
+ chainId?: bigint;
1493
+ accessList?: import("ethers").AccessList;
1494
+ authorizationList?: Array<import("ethers").Authorization>;
1495
+ customData?: any;
1496
+ blockTag?: import("ethers").BlockTag;
1497
+ enableCcipRead?: boolean;
1498
+ }>;
1499
+ createContract: (address: string, abi: readonly (import("ethers").JsonFragment | import("ethers").Fragment)[]) => import("ethers").Contract;
1500
+ createContractTxObject: ({ contractAddress, abi, funcName, funcParams, txOverrides }: import("..").CallParams) => Promise<{
1501
+ value: string;
1502
+ to: string;
1503
+ data: string;
1504
+ from?: string;
1505
+ type?: number;
1506
+ nonce?: number;
1507
+ gasLimit?: bigint;
1508
+ gasPrice?: bigint;
1509
+ maxPriorityFeePerGas?: bigint;
1510
+ maxFeePerGas?: bigint;
1511
+ chainId?: bigint;
1512
+ accessList?: import("ethers").AccessList;
1513
+ authorizationList?: Array<import("ethers").Authorization>;
1514
+ customData?: any;
1515
+ blockTag?: import("ethers").BlockTag;
1516
+ enableCcipRead?: boolean;
1517
+ }>;
1518
+ createTransaction: ({ assetValue, memo, recipient, data, sender: fromOverride, maxFeePerGas, maxPriorityFeePerGas, gasPrice, ...tx }: import("..").EVMCreateTransactionParams) => Promise<{
1519
+ value: string;
1520
+ to: string;
1521
+ data: string;
1522
+ from?: string;
1523
+ type?: number;
1524
+ nonce?: number;
1525
+ gasLimit?: bigint;
1526
+ gasPrice?: bigint;
1527
+ maxPriorityFeePerGas?: bigint;
1528
+ maxFeePerGas?: bigint;
1529
+ chainId?: bigint;
1530
+ accessList?: import("ethers").AccessList;
1531
+ authorizationList?: Array<import("ethers").Authorization>;
1532
+ customData?: any;
1533
+ blockTag?: import("ethers").BlockTag;
1534
+ enableCcipRead?: boolean;
1535
+ }>;
1536
+ createTransferTx: ({ assetValue, memo, recipient, data, sender: fromOverride, maxFeePerGas, maxPriorityFeePerGas, gasPrice, ...tx }: import("..").EVMCreateTransactionParams) => Promise<{
1537
+ value: string;
1538
+ to: string;
1539
+ data: string;
1540
+ from?: string;
1541
+ type?: number;
1542
+ nonce?: number;
1543
+ gasLimit?: bigint;
1544
+ gasPrice?: bigint;
1545
+ maxPriorityFeePerGas?: bigint;
1546
+ maxFeePerGas?: bigint;
1547
+ chainId?: bigint;
1548
+ accessList?: import("ethers").AccessList;
1549
+ authorizationList?: Array<import("ethers").Authorization>;
1550
+ customData?: any;
1551
+ blockTag?: import("ethers").BlockTag;
1552
+ enableCcipRead?: boolean;
1553
+ }>;
1554
+ EIP1193SendTransaction: ({ value, ...params }: import("..").EVMTxParams | import("ethers").ContractTransaction) => Promise<string>;
1555
+ estimateCall: ({ contractAddress, abi, funcName, funcParams, txOverrides }: import("..").EstimateCallParams) => Promise<bigint>;
1556
+ estimateGasLimit: ({ assetValue, recipient, memo, data, sender, funcName, funcParams, txOverrides, }: import("..").EVMTransferParams & {
1557
+ assetValue: import("@swapkit/helpers").AssetValue;
1558
+ funcName?: string;
1559
+ funcParams?: unknown[];
1560
+ txOverrides?: import("..").EVMTxParams;
1561
+ data?: string;
1562
+ }) => Promise<bigint>;
1563
+ estimateGasPrices: () => Promise<{ [key in FeeOption]: {
1564
+ l1GasPrice?: bigint;
1565
+ gasPrice?: bigint;
1566
+ maxFeePerGas?: bigint;
1567
+ maxPriorityFeePerGas?: bigint;
1568
+ }; }>;
1569
+ estimateTransactionFee: ({ feeOption, ...txObject }: import("..").EIP1559TxParams & {
1570
+ feeOption: FeeOption;
1571
+ }) => Promise<import("@swapkit/helpers").AssetValue>;
1572
+ getAddress: () => string | Promise<string> | undefined;
1573
+ getBalance: (address: string, scamFilter?: boolean) => Promise<import("@swapkit/helpers").AssetValue[]>;
1574
+ getNetworkParams: () => import("@swapkit/helpers").NetworkParams | undefined;
1575
+ isApproved: ({ assetAddress, spenderAddress, from, amount }: import("..").IsApprovedParams) => Promise<boolean>;
1576
+ sendTransaction: ({ feeOptionKey, ...tx }: import("..").EVMTxParams & {
1577
+ feeOptionKey?: FeeOption;
1578
+ }) => Promise<string>;
1579
+ signAuthorization: ((params: {
1580
+ address: string;
1581
+ nonce?: number | bigint;
1582
+ chainId?: bigint;
1583
+ }) => Promise<import("ethers").Authorization>) | undefined;
1584
+ signMessage: ((message: string | Uint8Array) => Promise<string>) | undefined;
1585
+ signTypedData: (({ domain, types, value }: import("..").SignTypedDataParams) => Promise<string>) | undefined;
1586
+ transfer: ({ assetValue, memo, recipient, feeOptionKey, sender, ...tx }: import("..").EVMTransferParams) => Promise<string>;
1587
+ validateAddress: typeof import("./baseEVMToolbox").validateEVMAddress;
1588
+ };
1476
1589
  export declare const HYPEREVMToolbox: ({ provider, ...toolboxParams }: EVMToolboxParams) => {
1477
1590
  approve: ({ assetAddress, spenderAddress, feeOptionKey, amount, gasLimitFallback, from: fromParam, nonce, }: import("..").ApproveParams) => Promise<string>;
1478
1591
  approvedAmount: ({ assetAddress, spenderAddress, from }: import("..").IsApprovedParams) => Promise<bigint>;
@@ -2,7 +2,7 @@ import type { AssetValue, ChainSigner, DerivationPathArray, FeeOption, GenericCr
2
2
  import { Chain } from "@swapkit/helpers";
3
3
  import type { BigNumberish, BrowserProvider, JsonFragment, JsonRpcSigner, Provider, Signer, TransactionRequest, TypedDataField } from "ethers";
4
4
  import type { getProvider } from "./index";
5
- import type { ADIToolbox, ARBToolbox, AURORAToolbox, AVAXToolbox, BASEToolbox, BERAToolbox, BSCToolbox, COREToolbox, CORNToolbox, CROToolbox, ETHToolbox, GNOToolbox, HYPEREVMToolbox, LINEAToolbox, MATICToolbox, MEGAETHToolbox, MONADToolbox, OPToolbox, PLASMAToolbox, SONICToolbox, UNIToolbox, XLayerToolbox } from "./toolbox";
5
+ import type { ADIToolbox, ARBToolbox, AURORAToolbox, AVAXToolbox, BASEToolbox, BERAToolbox, BSCToolbox, COREToolbox, CORNToolbox, CROToolbox, ETHToolbox, GNOToolbox, HOODToolbox, HYPEREVMToolbox, LINEAToolbox, MATICToolbox, MEGAETHToolbox, MONADToolbox, OPToolbox, PLASMAToolbox, SONICToolbox, UNIToolbox, XLayerToolbox } from "./toolbox";
6
6
  export declare enum EthNetwork {
7
7
  Test = "goerli",
8
8
  Main = "homestead"
@@ -125,6 +125,7 @@ export type EVMToolboxes = {
125
125
  [Chain.Optimism]: ReturnType<typeof OPToolbox>;
126
126
  [Chain.Plasma]: ReturnType<typeof PLASMAToolbox>;
127
127
  [Chain.Polygon]: ReturnType<typeof MATICToolbox>;
128
+ [Chain.Robinhood]: ReturnType<typeof HOODToolbox>;
128
129
  [Chain.Sonic]: ReturnType<typeof SONICToolbox>;
129
130
  [Chain.Unichain]: ReturnType<typeof UNIToolbox>;
130
131
  [Chain.XLayer]: ReturnType<typeof XLayerToolbox>;
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "dependencies": { "@swapkit/helpers": "4.15.4", "@swapkit/utxo-signer": "2.2.3" },
2
+ "dependencies": { "@swapkit/helpers": "4.16.1", "@swapkit/utxo-signer": "2.2.3" },
3
3
  "description": "SwapKit - Toolboxes",
4
4
  "devDependencies": {
5
5
  "@aptos-labs/ts-sdk": "7.0.1",
@@ -198,5 +198,5 @@
198
198
  "type-check:go": "tsgo"
199
199
  },
200
200
  "type": "module",
201
- "version": "4.21.0"
201
+ "version": "4.23.0"
202
202
  }
@@ -1 +0,0 @@
1
- import{$ as N,A as m,B as n,C as o,D as p,E as q,F as r,G as s,H as t,I as u,J as v,K as w,L as x,M as y,N as z,O as A,P as B,Q as C,R as D,S as E,T as F,U as G,V as H,W as I,X as J,Y as K,Z as L,_ as M,aa as O,ba as P,o as a,p as b,q as c,r as d,s as e,t as f,u as g,v as h,w as i,x as j,y as k,z as l}from"./chunk-xs0j1eze.js";import"./chunk-54gntgt1.js";import"./chunk-ntbvmmch.js";export{c as validateEVMAddress,h as toChecksumAddress,g as isStateChangingCall,o as isEIP7702Transaction,p as isEIP1559Transaction,d as isBrowserProvider,l as getTokenAddress,P as getEvmToolboxAsync,O as getEvmToolbox,n as getEstimateGasPrices,q as getEVMTxType,i as getEIP1193SendTransaction,m as getCreateContractTxObject,f as getCreateContract,j as getChecksumAddressFromAsset,e as createContract,M as XLayerToolbox,L as UNIToolbox,K as SONICToolbox,J as PLASMAToolbox,N as OPToolbox,I as MONADToolbox,H as MEGAETHToolbox,a as MAX_APPROVAL,G as MATICToolbox,F as LINEAToolbox,E as HYPEREVMToolbox,D as GNOToolbox,r as ETHToolbox,k as ContractAddress,C as CROToolbox,B as CORNToolbox,A as COREToolbox,z as BotanixToolbox,b as BaseEVMToolbox,y as BSCToolbox,x as BERAToolbox,w as BASEToolbox,v as AVAXToolbox,u as AURORAToolbox,t as ARBToolbox,s as ADIToolbox};
@@ -1,2 +0,0 @@
1
- import{da as Ht}from"./chunk-54gntgt1.js";import{ea as g}from"./chunk-ntbvmmch.js";import{Chain as w}from"@swapkit/helpers";import{match as Py}from"ts-pattern";import{Chain as H,getChainConfig as P,getRPCUrl as at,SKConfig as rt,SwapKitError as o}from"@swapkit/helpers";import{FallbackProvider as ty,getAddress as Dt,Interface as yy,JsonRpcProvider as s,Network as uy}from"ethers";import{match as Lt}from"ts-pattern";function ny(t){return new s(t)}async function cy(t,y){return ny(y||await at(t))}function Rt(t){let y=rt.get("rpcUrls")[t]?.filter(Boolean)??[];if(y.length===0)throw new o("helpers_chain_no_public_or_set_rpc_url",{chain:t});let{chainId:u}=P(t),n=uy.from(Number(u)),[T]=y;if(y.length===1)return new s(T,n,{staticNetwork:n});return new ty(y.map((l,b)=>({priority:b+1,provider:new s(l,n,{staticNetwork:n}),stallTimeout:2000})),n,{quorum:1})}function N(t){return t>0n?`0x${t.toString(16)}`:"0x0"}function qt(t){let{explorerUrl:y,chainIdHex:u,rpcUrls:n}=P(t);return function(){return t!==H.Ethereum?{...Ty({chain:t}),blockExplorerUrls:[y],chainId:u,rpcUrls:n}:void 0}}function Gt(t){return![H.Adi,H.Arbitrum,H.BinanceSmartChain].includes(t)}function Ty({chain:t}){let{name:y,nativeCurrency:u,baseDecimal:n}=P(t);return Lt(t).with(H.Arbitrum,()=>({chainName:"Arbitrum One",nativeCurrency:{decimals:n,name:"Ethereum",symbol:H.Ethereum}})).with(H.Aurora,()=>({chainName:"Aurora Mainnet",nativeCurrency:{decimals:n,name:"Ethereum",symbol:H.Ethereum}})).with(H.Avalanche,()=>({chainName:"Avalanche Network",nativeCurrency:{decimals:n,name:"Avalanche",symbol:t}})).with(H.Base,()=>({chainName:"Base Mainnet",nativeCurrency:{decimals:n,name:"Ethereum",symbol:H.Ethereum}})).with(H.Berachain,()=>({chainName:"Berachain",nativeCurrency:{decimals:n,name:"Berachain",symbol:"BERA"}})).with(H.XLayer,()=>({chainName:"X Layer",nativeCurrency:{decimals:n,name:"OKB",symbol:"OKB"}})).with(H.BinanceSmartChain,()=>({chainName:"BNB Smart Chain Mainnet",nativeCurrency:{decimals:n,name:"Binance Coin",symbol:"BNB"}})).with(H.Gnosis,()=>({chainName:"Gnosis",nativeCurrency:{decimals:n,name:"xDAI",symbol:"XDAI"}})).with(H.Optimism,()=>({chainName:"OP Mainnet",nativeCurrency:{decimals:n,name:"Ethereum",symbol:H.Ethereum}})).with(H.Polygon,()=>({chainName:"Polygon Mainnet",nativeCurrency:{decimals:n,name:"Polygon",symbol:H.Polygon}})).otherwise(()=>({chainName:y,nativeCurrency:{decimals:n,name:u,symbol:u}}))}async function Bt(t,y){if(!("authorize"in t))throw Error("Signer does not support EIP-7702 authorization. Requires ethers.js v6.14+");let u={...y,nonce:y.nonce!==void 0?BigInt(y.nonce):void 0};return await t.authorize(u)}var Mt=(t)=>typeof t==="string"&&/^0x[a-fA-F0-9]{64}$/.test(t),ly=(t)=>{try{return typeof t==="string"&&!!Dt(t)}catch{return!1}};function by(t,y){let u=y!==void 0?`index ${y}: `:"",n=(T,l)=>{throw new o({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:T,message:`${u}${l}`}})};Lt(t).when(({chainId:T})=>typeof T!=="bigint",()=>n("chainId","chainId must be a bigint")).when(({address:T})=>!ly(T),()=>n("address","address must be a valid checksummed address")).when(({nonce:T})=>typeof T!=="bigint"||T<0n,()=>n("nonce","nonce must be a non-negative bigint")).when(({signature:T})=>!T,()=>n("signature","signature is required")).when(({signature:T})=>typeof T?.yParity!=="number"||![0,1].includes(T.yParity),()=>n("signature.yParity","yParity must be 0 or 1")).when(({signature:T})=>!Mt(T?.r),()=>n("signature.r","r must be a 32-byte hex string")).when(({signature:T})=>!Mt(T?.s),()=>n("signature.s","s must be a 32-byte hex string")).otherwise(()=>{})}function My(t){return[{key:"name",type:"string"},{key:"version",type:"string"},{key:"chainId",type:"uint256"},{key:"verifyingContract",type:"address"},{key:"salt",type:"bytes32"}].filter(({key:y})=>t[y]!=null).map(({key:y,type:u})=>({name:y,type:u}))}function e(t){return t.charAt(0).toUpperCase()+t.slice(1)}function i(t,y){if(t.isTuple()&&t.components){let u=e(t.name);return y[u]=t.components.map((n)=>({name:n.name,type:i(n,y)})),u}if(t.isArray()){let u=t.arrayChildren;if(u?.isTuple()&&u.components){let n=e(t.name.replace(/s$/,""));return y[n]=u.components.map((T)=>({name:T.name,type:i(T,y)})),`${n}[]`}return`${u?.type??"bytes"}[]`}return t.type}function a(t,y){if(typeof t==="bigint")return t;if(y?.isTuple()&&typeof t?.toObject==="function"){let u=t.toObject(),n={};for(let[T,l]of(y.components??[]).entries())n[l.name]=a(u[l.name]??t[T],l);return n}if(Array.isArray(t)){let u=y?.arrayChildren;return t.map((n)=>a(n,u??void 0))}return t}function vy({chain:t,abi:y,data:u,to:n}){let l=new yy(y).parseTransaction({data:u});if(!l)throw new o({errorKey:"toolbox_evm_invalid_params",info:{error:"Could not decode calldata"}});let b={},M=e(l.name);b[M]=l.fragment.inputs.map((D)=>({name:D.name,type:i(D,b)}));let R={};for(let[D,W]of l.fragment.inputs.entries())R[W.name]=a(l.args[D],W);let{chainId:G}=P(t),q={chainId:Number(G),verifyingContract:Dt(n)},X=My(q);return{domain:q,message:R,primaryType:M,types:{EIP712Domain:X,...b}}}function wt(t,y){if(!Array.isArray(t)||t.length===0)throw new o({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{message:"EIP-7702 transactions require at least one authorization"}});for(let[u,n]of t.entries())if(by(n,u),y!==void 0&&n.chainId!==y)throw new o({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:"chainId",message:`index ${u}: authorization chainId (${n.chainId}) does not match transaction chainId (${y})`}})}import{Chain as U,FeeOption as jy}from"@swapkit/helpers";import{HDNodeWallet as Ny}from"ethers";import{match as Vy,P as Jt}from"ts-pattern";var Wt=[{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 Dy,applyFeeMultiplierToBigInt as $,Chain as _,EVMChains as Ly,FeeOption as L,isGasAsset as Ry,SwapKitError as B,SwapKitNumber as m}from"@swapkit/helpers";import{erc20ABI as F}from"@swapkit/helpers/contracts";import{BrowserProvider as qy,Contract as Ut,getAddress as p,Interface as Qt}from"ethers";import{match as Xt}from"ts-pattern";function C(t){return{getBalance:Ht(t)}}function ey(t){return t}var tt=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function c({chain:t=_.Ethereum,provider:y,signer:u,isEIP1559Compatible:n=!0}){return{approve:Yy({chain:t,isEIP1559Compatible:n,provider:y,signer:u}),approvedAmount:Yt({chain:t,provider:y}),broadcastTransaction:y.broadcastTransaction,call:ut({chain:t,isEIP1559Compatible:n,provider:y,signer:u}),createApprovalTx:ky({chain:t,provider:y,signer:u}),createContract:By({chain:t,provider:y}),createContractTxObject:x({chain:t,provider:y}),createTransaction:r({chain:t,provider:y,signer:u}),createTransferTx:r({chain:t,provider:y,signer:u}),EIP1193SendTransaction:h(y),estimateCall:Zt({provider:y,signer:u}),estimateGasLimit:$y({chain:t,provider:y,signer:u}),estimateGasPrices:A({chain:t,isEIP1559Compatible:n,provider:y}),estimateTransactionFee:_y({chain:t,isEIP1559Compatible:n,provider:y}),getAddress:()=>{return u?u.getAddress():void 0},getBalance:C(t).getBalance,getNetworkParams:qt(t),isApproved:Xy({chain:t,provider:y}),sendTransaction:zt({chain:t,isEIP1559Compatible:n,provider:y,signer:u}),signAuthorization:zy({signer:u}),signMessage:u?(T)=>u.signMessage(T):void 0,signTypedData:u?({domain:T,types:l,value:b})=>u.signTypedData(T,l,b):void 0,transfer:Zy({chain:t,isEIP1559Compatible:n,provider:y,signer:u}),validateAddress:Gy}}function Gy(t){try{return p(t),!0}catch{return!1}}function v(t){return t instanceof qy}function yt(t,y,u){return new Ut(t,Qt.from(y),u)}function By({provider:t}){return function(u,n){return new Ut(u,Qt.from(n),t)}}var wy=["payable","nonpayable"];function Wy({abi:t,funcName:y}){let u=t.find((n)=>n.name===y);if(!u)throw new B("toolbox_evm_no_abi_fragment",{funcName:y});return u.stateMutability&&wy.includes(u.stateMutability)}function Tu(t){return p(t)}function h(t){return function({value:u,...n}){if(!v(t))throw new B("toolbox_evm_provider_not_eip1193_compatible");let{gasLimit:T,gasPrice:l,maxFeePerGas:b,maxPriorityFeePerGas:M,...R}=n;return t.send("eth_sendTransaction",[{...R,value:N(BigInt(u||0))}])}}function lu(t,y){let u=d(t,y);if(u)return p(u.toLowerCase());throw new B("toolbox_evm_invalid_gas_asset_address")}var Hy=Ly.reduce((t,y)=>{return t[y]="0x0000000000000000000000000000000000000000",t},{}),Uy={...Hy,[_.Optimism]:"0x4200000000000000000000000000000000000042",[_.Polygon]:"0x0000000000000000000000000000000000001010"},Qy=[_.Arbitrum,_.Aurora,_.Base,_.Optimism];function d({chain:t,symbol:y,ticker:u},n){try{let T=t===_.BinanceSmartChain&&y==="BNB"&&u==="BNB",l=t===_.Hyperevm&&y==="HYPE"&&u==="HYPE",b=t===n&&y===n&&u===n,M=Qy.includes(t)&&y==="ETH"&&u==="ETH";if(b||T||l||M)return Uy[n];return p(y.slice(u.length+1).replace(/^0X/,""))}catch{return null}}function x({provider:t}){return async({contractAddress:y,abi:u,funcName:n,funcParams:T=[],txOverrides:l})=>{let b=await yt(y,u,t).getFunction(n).populateTransaction(...T.concat(l).filter((M)=>typeof M<"u"));return{...b,value:N(BigInt(b.value||0))}}}function A({chain:t,provider:y,isEIP1559Compatible:u=!0}){return Xt(t).with(_.Gnosis,()=>{return async function(){try{let{gasPrice:T,maxPriorityFeePerGas:l}=await y.getFeeData();if(!T||l===null)throw new B("toolbox_evm_no_fee_data");return{[L.Average]:{maxFeePerGas:$(T,L.Average),maxPriorityFeePerGas:$(l,L.Average)},[L.Fast]:{maxFeePerGas:$(T,L.Fast),maxPriorityFeePerGas:$(l,L.Fast)},[L.Fastest]:{maxFeePerGas:$(T,L.Fastest),maxPriorityFeePerGas:$(l,L.Fastest)}}}catch(T){throw new B("toolbox_evm_gas_estimation_error",{error:T.msg??T.toString()})}}}).with(_.Arbitrum,()=>{return async function(){try{let{gasPrice:T}=await y.getFeeData();if(!T)throw new B("toolbox_evm_no_fee_data");let l=T*12n/10n;return{[L.Average]:{gasPrice:l},[L.Fast]:{gasPrice:$(l,L.Fast)},[L.Fastest]:{gasPrice:$(l,L.Fastest)}}}catch(T){throw new B("toolbox_evm_gas_estimation_error",{error:T.msg??T.toString()})}}}).otherwise(()=>{return async function(){try{let{maxFeePerGas:T,maxPriorityFeePerGas:l,gasPrice:b}=await y.getFeeData();if(u){if(T===null||l===null)throw new B("toolbox_evm_no_fee_data");return{[L.Average]:{maxFeePerGas:T,maxPriorityFeePerGas:l},[L.Fast]:{maxFeePerGas:$(T,L.Fast),maxPriorityFeePerGas:$(l,L.Fast)},[L.Fastest]:{maxFeePerGas:$(T,L.Fastest),maxPriorityFeePerGas:$(l,L.Fastest)}}}if(!b)throw new B("toolbox_evm_no_gas_price");return{[L.Average]:{gasPrice:b},[L.Fast]:{gasPrice:$(b,L.Fast)},[L.Fastest]:{gasPrice:$(b,L.Fastest)}}}catch(T){throw new B("toolbox_evm_gas_estimation_error",{error:T.msg??T.toString()})}}})}function ut({provider:t,isEIP1559Compatible:y,signer:u,chain:n}){return async function({callProvider:l,contractAddress:b,abi:M,funcName:R,funcParams:G=[],txOverrides:q={},feeOption:X=L.Fast}){let D=l||t;if(!b)throw new B("toolbox_evm_invalid_params",{error:"contractAddress must be provided"});let W=Wy({abi:M,funcName:R});if(W&&v(D)&&u){let z=x({chain:n,provider:D}),k=q?.from||await u?.getAddress(),f=await z({abi:M,contractAddress:b,funcName:R,funcParams:G,txOverrides:{...q,from:k}});return h(D)(f)}let Y=yt(b,M,D);if(W){if(!u)throw new B("toolbox_evm_no_signer");let z=q?.from||await u.getAddress();if(!z)throw new B("toolbox_evm_no_signer_address");let k=Y.connect(u),f=A({chain:n,isEIP1559Compatible:y,provider:t}),{maxFeePerGas:V,maxPriorityFeePerGas:E,gasPrice:K}=(await f())[X],O=await Y.getFunction(R).estimateGas(...G,q),J=await k[R](...G,{...q,gasLimit:O,gasPrice:K,maxFeePerGas:V,maxPriorityFeePerGas:E,nonce:q?.nonce||await D.getTransactionCount(z)});return typeof J?.hash==="string"?J?.hash:J}let Z=await Y[R]?.(...G);return typeof Z?.hash==="string"?Z?.hash:Z}}function Yt({provider:t,chain:y}){return function({assetAddress:n,spenderAddress:T,from:l}){return ut({chain:y,isEIP1559Compatible:!0,provider:t})({abi:F,contractAddress:n,funcName:"allowance",funcParams:[l,T]})}}function Xy({provider:t,chain:y}){return async function({assetAddress:n,spenderAddress:T,from:l,amount:b=tt}){let M=await Yt({chain:y,provider:t})({assetAddress:n,from:l,spenderAddress:T});return m.fromBigInt(M).gte(m.fromBigInt(BigInt(b)))}}function Yy({signer:t,isEIP1559Compatible:y=!0,provider:u,chain:n}){return async function({assetAddress:l,spenderAddress:b,feeOptionKey:M=L.Fast,amount:R,gasLimitFallback:G,from:q,nonce:X}){let D=[b,BigInt(R||tt)],W=await t?.getAddress()||q,Y={abi:F,contractAddress:l,funcName:"approve",funcParams:D,signer:t,txOverrides:{from:W}};if(v(u)){let z=x({chain:n,provider:u}),k=h(u),f=await z(Y);return k(f)}return ut({chain:n,isEIP1559Compatible:y,provider:u,signer:t})({...Y,feeOption:M,funcParams:D,txOverrides:{from:W,gasLimit:G?BigInt(G.toString()):void 0,nonce:X}})}}function Zy({signer:t,isEIP1559Compatible:y=!0,provider:u}){return async function({assetValue:T,memo:l,recipient:b,feeOptionKey:M=L.Fast,sender:R,...G}){let{hexlify:q,toUtf8Bytes:X}=await import("ethers"),D=T.getBaseValue("bigint"),W=T.chain,Y=R||await t?.getAddress(),Z=zt({chain:W,isEIP1559Compatible:y,provider:u,signer:t});if(!Y)throw new B("toolbox_evm_no_from_address");if(T.isGasAsset){let K={...G,data:q(X(l||"")),feeOptionKey:M,from:Y,to:b,value:N(D)};return Z(K)}if(!d(T,W))throw new B("toolbox_evm_no_contract_address");let{maxFeePerGas:k,maxPriorityFeePerGas:f,gasPrice:V}=(await A({chain:W,isEIP1559Compatible:y,provider:u})())[M],E=await r({chain:W,provider:u,signer:t})({assetValue:T,data:q(X(l||"")),gasPrice:V,maxFeePerGas:k,maxPriorityFeePerGas:f,memo:l,recipient:b,sender:Y});return Z(E)}}function Zt({provider:t,signer:y}){return function({contractAddress:n,abi:T,funcName:l,funcParams:b=[],txOverrides:M}){if(!n)throw new B("toolbox_evm_no_contract_address");let R=yt(n,T,t);return y?R.connect(y).getFunction(l).estimateGas(...b,M):R.getFunction(l).estimateGas(...b,M)}}function $y({provider:t,signer:y}){return async function({assetValue:n,recipient:T,memo:l,data:b,sender:M,funcName:R,funcParams:G,txOverrides:q}){let X=n.bigIntValue,D=n.isGasAsset?null:d(n,n.chain);if(D&&R)return Zt({provider:t,signer:y})({abi:F,contractAddress:D,funcName:R,funcParams:G,txOverrides:q});let{hexlify:W,toUtf8Bytes:Y}=await import("ethers");return t.estimateGas({data:b?b:l?W(Y(l)):void 0,from:M,to:T,value:X})}}function zy({signer:t}){if(!t)return;return(y)=>Bt(t,y)}var $t=(t)=>t.type===4||(t.authorizations?.length??0)>0,Jy=(t)=>!$t(t)&&(t.type===2||!!t.maxFeePerGas||!!t.maxPriorityFeePerGas),fy=(t,y=!0)=>{if($t(t))return"eip7702";if(Jy(t)||y)return"eip1559";return"legacy"};function zt({provider:t,signer:y,isEIP1559Compatible:u=!0,chain:n}){return async function({feeOptionKey:l=L.Fast,...b}){let{from:M,to:R,data:G,value:q,...X}=b;if(!y)throw new B("toolbox_evm_no_signer");if(!R)throw new B("toolbox_evm_no_to_address");let D={...X,data:G||"0x",from:M,to:R,value:BigInt(q||0)};if(v(t))return h(t)(D);let W=M||await y.getAddress(),Y=b.nonce||await t.getTransactionCount(W),Z=(await t.getNetwork()).chainId,z=fy(D,u);if(z==="eip7702")wt(D.authorizations||[],Z);let k=Xt(z).with("eip7702",()=>4).with("eip1559",()=>2).otherwise(()=>0),f={...D,chainId:Z,nonce:Y,type:k,...z==="eip7702"&&{authorizationList:D.authorizations}},V=A({chain:n,isEIP1559Compatible:u,provider:t}),K=z!=="legacy"&&!(D.maxFeePerGas&&D.maxPriorityFeePerGas)||!D.gasPrice?Object.entries((await V())[l]).reduce((J,[I,bt])=>({...J,[I]:N(BigInt(bt))}),{}):{},O;try{O=N(D.gasLimit?BigInt(D.gasLimit):await t.estimateGas(f)*11n/10n)}catch(J){throw new B("toolbox_evm_error_estimating_gas_limit",{error:J})}try{let J={...f,gasLimit:O,...K};try{return(await y.sendTransaction(J)).hash}catch{let I=await y.signTransaction({...J,from:W});return(await t.broadcastTransaction(I)).hash}}catch(J){throw new B("toolbox_evm_error_sending_transaction",{error:J})}}}function r({provider:t,signer:y}){return async function({assetValue:n,memo:T,recipient:l,data:b,sender:M,maxFeePerGas:R,maxPriorityFeePerGas:G,gasPrice:q,...X}){let D=n.getBaseValue("bigint"),W=n.chain,Y=M||await y?.getAddress();if(!Y)throw new B("toolbox_evm_no_from_address");if(Ry(n)){let{hexlify:k,toUtf8Bytes:f}=await import("ethers");return{...X,data:b||k(f(T||"")),from:Y,to:l,value:N(D)}}let Z=d(n,W);if(!Z)throw new B("toolbox_evm_no_contract_address");return x({chain:n.chain,provider:t})({abi:F,contractAddress:Z,funcName:"transfer",funcParams:[l,D],txOverrides:{from:Y,gasPrice:q,maxFeePerGas:R,maxPriorityFeePerGas:G}})}}function ky({provider:t,signer:y,chain:u}){return async function({assetAddress:T,spenderAddress:l,amount:b,from:M}){let R=await y?.getAddress()||M,G=x({chain:u,provider:t}),q=["bigint","number"].includes(typeof b)?b:b||tt;return await G({abi:F,contractAddress:T,funcName:"approve",funcParams:[l,BigInt(q)],txOverrides:{from:R}})}}function _y({provider:t,isEIP1559Compatible:y=!0,chain:u}){return async function({feeOption:T=L.Fast,...l}){let M=await A({chain:u,isEIP1559Compatible:y,provider:t})(),R=await t.estimateGas(l),G=Dy.from({chain:u}),{gasPrice:q,maxFeePerGas:X,maxPriorityFeePerGas:D}=M[T];if(!y&&q)return G.set(m.fromBigInt(q*R,G.decimal));if(X&&D){let W=(X+D)*R;return G.set(m.fromBigInt(W,G.decimal))}throw new B("toolbox_evm_no_gas_price")}}function ft(t){let y=Q(U.Ethereum)(t);async function u(n,T="0x5ba1e12693dc8f9c48aad8770482f4739beed696",l="aggregate",b=jy.Fast){let M=await y.createContractTxObject({abi:Wt,contractAddress:T,funcName:l,funcParams:[n]});return y.sendTransaction({...M,feeOptionKey:b})}return{...y,multicall:u}}var kt=Q(U.Adi),_t=Q(U.Arbitrum),jt=Q(U.Aurora),Nt=Q(U.Avalanche),Vt=Q(U.Base),St=Q(U.Berachain),Kt=Q(U.BinanceSmartChain),Bu=Q(U.Botanix),ot=Q(U.Core),Ft=Q(U.Corn),xt=Q(U.Cronos),At=Q(U.Gnosis),Et=Q(U.Hyperevm),Ot=Q(U.Linea),It=Q(U.Polygon),Pt=Q(U.MegaETH),Ct=Q(U.Monad),mt=Q(U.Plasma),nt=Q(U.Sonic),gt=Q(U.Unichain),pt=Q(U.XLayer);function Q(t){return function({provider:u,...n}){let T=Gt(t),l=Vy(n).with({phrase:Jt.string},({phrase:M})=>Ny.fromPhrase(M).connect(u)).with({signer:Jt.any},({signer:M})=>M).otherwise(()=>{return});return c({chain:t,isEIP1559Compatible:T,provider:u,signer:l})}}import{applyFeeMultiplierToBigInt as S,Chain as Ky,FeeOption as j,SwapKitError as Tt}from"@swapkit/helpers";import{Contract as oy,HDNodeWallet as Fy}from"ethers";import{match as xy,P as vt}from"ts-pattern";var ct=[{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:[],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 Ay="0x420000000000000000000000000000000000000f";function lt(t){return new oy(Ay,ct,t)}function ht(t){return async function(){let u=lt(t);if(u&&"l1BaseFee"in u)return await u?.l1BaseFee();return}}function dt(t){return async function({from:u,to:n,nonce:T,...l}){let{Transaction:b}=await import("ethers");if(!n)throw new Tt("toolbox_evm_invalid_transaction",{error:"Missing to address"});return b.from({...l,authorizationList:l.authorizationList,nonce:T?T:u?await t.getTransactionCount(u):0,to:n}).serialized}}function st(t){return async function(u){let n=lt(t),T=await dt(t)(u);if(n&&"getL1Fee"in n)return n.getL1Fee(T)}}function et(t){return async function(u){let T=(await t.getFeeData()).gasPrice??0n,l=await t.estimateGas(u);return T*l}}function Ey(t){return async function(u){let n=await st(t)(u)??0n,T=await et(t)(u);return n+T}}function Oy(t){return async function(u){let n=lt(t),T=await dt(t)(u);if(n&&"getL1GasUsed"in n)return n.getL1GasUsed(T)}}function Iy(t){return async function(){try{let{maxFeePerGas:u,maxPriorityFeePerGas:n,gasPrice:T}=await t.getFeeData(),l=await ht(t)(),b=T;if(!(u&&n))throw new Tt("toolbox_evm_no_fee_data");return{[j.Average]:{gasPrice:b,l1GasPrice:l,maxFeePerGas:u,maxPriorityFeePerGas:n},[j.Fast]:{gasPrice:S(b,j.Fast),l1GasPrice:S(l||0n,j.Fast),maxFeePerGas:u,maxPriorityFeePerGas:S(n,j.Fast)},[j.Fastest]:{gasPrice:S(b,j.Fastest),l1GasPrice:S(l||0n,j.Fastest),maxFeePerGas:u,maxPriorityFeePerGas:S(n,j.Fastest)}}}catch(u){throw new Tt("toolbox_evm_gas_estimation_error",{error:u.msg??u.toString()})}}}function it({provider:t,...y}){let u=xy(y).with({phrase:vt.string},({phrase:l})=>Fy.fromPhrase(l).connect(t)).with({signer:vt.any},({signer:l})=>l).otherwise(()=>{return}),n=c({provider:t,signer:u}),T=ht(t);return{...n,estimateGasPrices:Iy(t),estimateL1Gas:Oy(t),estimateL1GasCost:st(t),estimateL2GasCost:et(t),estimateTotalGasCost:Ey(t),getBalance:C(Ky.Optimism).getBalance,getL1GasPrice:T}}function Cy(t,y){return Py(t).with(w.Adi,()=>kt(y)).with(w.Arbitrum,()=>_t(y)).with(w.Aurora,()=>jt(y)).with(w.Avalanche,()=>Nt(y)).with(w.Base,()=>Vt(y)).with(w.Berachain,()=>St(y)).with(w.BinanceSmartChain,()=>Kt(y)).with(w.Botanix,()=>nt(y)).with(w.Core,()=>ot(y)).with(w.Corn,()=>Ft(y)).with(w.Cronos,()=>xt(y)).with(w.Ethereum,()=>ft(y)).with(w.Gnosis,()=>At(y)).with(w.Hyperevm,()=>Et(y)).with(w.Linea,()=>Ot(y)).with(w.MegaETH,()=>Pt(y)).with(w.Monad,()=>Ct(y)).with(w.Optimism,()=>it(y)).with(w.Plasma,()=>mt(y)).with(w.Polygon,()=>It(y)).with(w.Sonic,()=>nt(y)).with(w.Unichain,()=>gt(y)).with(w.XLayer,()=>pt(y)).exhaustive()}async function ku(t,y){let u={...y,provider:y?.provider||Rt(t)};return Cy(t,u)}
2
- export{C as b,ey as c,ny as d,cy as e,Rt as f,N as g,qt as h,Gt as i,Bt as j,by as k,My as l,vy as m,wt as n,tt as o,c as p,Gy as q,v as r,yt as s,By as t,Wy as u,Tu as v,h as w,lu as x,Uy as y,d as z,x as A,A as B,$t as C,Jy as D,fy as E,ft as F,kt as G,_t as H,jt as I,Nt as J,Vt as K,St as L,Kt as M,Bu as N,ot as O,Ft as P,xt as Q,At as R,Et as S,Ot as T,It as U,Pt as V,Ct as W,mt as X,nt as Y,gt as Z,pt as _,it as $,Cy as aa,ku as ba};