@swapkit/toolboxes 6.1.0 → 6.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # @swapkit/toolboxes
2
2
 
3
+ ## 6.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#437](https://github.com/swapkit/sdk/pull/437) [`5baea45`](https://github.com/swapkit/sdk/commit/5baea45e1595c1582e1d1911fa99177f5e8150f0) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Export `tronAddressToHex` from `@swapkit/toolboxes/tron` so hardware wallets can reuse the checksum-validated address conversion.
8
+ - [#436](https://github.com/swapkit/sdk/pull/436) [`b7890a5`](https://github.com/swapkit/sdk/commit/b7890a5413c888b7114c512f197bd944672c5256) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Fee-bump replacements from nested segwit and taproot addresses can now be signed by external wallets
9
+ - [#419](https://github.com/swapkit/sdk/pull/419) [`b1b908b`](https://github.com/swapkit/sdk/commit/b1b908b64f5078d7bead574c5ff45f9ce4995ee8) Thanks [@ice-chillios](https://github.com/ice-chillios)! - Remove the CTRL (formerly XDEFI) and Leap wallet options, along with CTRL provider detection, its account-change listener and wallet-specific error codes. Update Cosmos signer documentation to refer to supported wallets. Integrations must remove CTRL and Leap from wallet configuration and use a supported wallet instead.
10
+ - [#433](https://github.com/swapkit/sdk/pull/433) [`c52f562`](https://github.com/swapkit/sdk/commit/c52f56237e2a9149ba12a89e0c8a47fb6138c66c) Thanks [@mfaizan1](https://github.com/mfaizan1)! - Accept PSBT inputs a wallet has already finalized. OKX Wallet finalizes inside `signPsbt` and drops `tapKeySig`, so `finalize()` threw `finalize/taproot: unknown input` and every OKX taproot send failed before broadcast. (via @swapkit/utxo-signer@3.1.1)
11
+ - [#434](https://github.com/swapkit/sdk/pull/434) [`151c624`](https://github.com/swapkit/sdk/commit/151c6247a0c84e75d365853a48630d20d746477e) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Support Zcash swaps through THORChain: only transparent addresses are accepted and the ZEC minimum amount matches the THORChain dust threshold. (via @swapkit/helpers@6.1.1)
12
+ - [#435](https://github.com/swapkit/sdk/pull/435) [`94a2a79`](https://github.com/swapkit/sdk/commit/94a2a79867f89b5a12f34169a20e904469a010dc) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Add `tonConnect` to the SKConfig integrations type so wallets can read the TON Connect manifest URL from `SKConfig.get("integrations").tonConnect?.manifestUrl`. (via @swapkit/helpers@6.1.1)
13
+ - [#430](https://github.com/swapkit/sdk/pull/430) [`9d44f87`](https://github.com/swapkit/sdk/commit/9d44f87ec8cd6ebef168a8ea64ec492f25d3d305) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@6.1.1)
14
+
3
15
  ## 6.1.0
4
16
 
5
17
  ### Minor Changes
@@ -1 +1 @@
1
- import"../../chunk-exyqap7m.js";import{hexToBytes as un}from"@noble/hashes/utils.js";import{Chain as fn,getRPCUrlSync as ln,SwapKitError as y,warnOnce as K}from"@swapkit/helpers";import{secp256k1 as gt}from"@noble/curves/secp256k1.js";import{sha256 as _t}from"@noble/hashes/sha2.js";import{keccak_256 as nn}from"@noble/hashes/sha3.js";import{bytesToHex as S,hexToBytes as M}from"@noble/hashes/utils.js";import{createBase58check as en}from"@scure/base";import{SwapKitError as Tt}from"@swapkit/helpers";var L=en(_t),mt=65,rn=2n**256n;function b(n){if(typeof n!=="string")return!1;try{let t=L.decode(n);return t.length===21&&t[0]===mt}catch{return!1}}function wt(n){return S(L.decode(n))}function on(n){return L.decode(n).slice(1)}function pt(n){let t=gt.getPublicKey(M(n),!1),e=nn(t.slice(1)).slice(-20),r=new Uint8Array(21);return r[0]=mt,r.set(e,1),L.encode(r)}function yt({txID:n,privateKey:t}){let e=gt.sign(M(n),M(t),{format:"recovered",prehash:!1}),r=e[0]??0,i=S(e.slice(1,33)),o=S(e.slice(33,65)),c=(r+27).toString(16).padStart(2,"0");return i+o+c}function N({txID:n,raw_data_hex:t}){let e=S(_t(M(t)));if(n!==e)throw new Tt("toolbox_tron_invalid_transaction_integrity",{expected:e,txID:n})}function an(n){return`000000000000000000000000${S(on(n))}`}function sn(n){let t=typeof n==="bigint"?n:BigInt(n);if(t<0n||t>=rn)throw new Tt("toolbox_tron_invalid_token_identifier",{identifier:t.toString()});return t.toString(16).padStart(64,"0")}function R(n){return n.map(({type:t,value:e})=>t==="address"?an(e):sn(BigInt(e))).join("")}function cn(n){return S(new TextEncoder().encode(n))}var dn=/^0x(?:[0-9a-fA-F]{2})+$/;function z(n){return dn.test(n)?n.slice(2):cn(n)}var bt="https://api.trongrid.io",gn=1000,_n=1e5,Tn=1e6,mn=420,wn=1e6,pn=30000,yn=2147483647;function xt(){try{return ln(fn.Tron)}catch{return bt}}function At(n){let t=n!==void 0&&Number.isFinite(n)&&n>0?Math.min(n,yn):pn,e=new AbortController,r=setTimeout(()=>e.abort(),t);return{cleanup:()=>clearTimeout(r),signal:e.signal}}function Z(n){if(!n||typeof n!=="object")return;let{Error:t}=n;return typeof t==="string"&&t.length>0?t:void 0}function hn(n){if(!n)return;if(n.length%2!==0||!/^[0-9a-f]+$/i.test(n))return n;try{let t=new TextDecoder().decode(un(n));return/^[ -~]+$/.test(t)?t:n}catch{return n}}function Et(n,t){if(typeof n!=="string")return!1;if(n===t)return!0;try{return n.toLowerCase()===wt(t).toLowerCase()}catch{return!1}}function Q(n){let t=typeof n==="number"?n:typeof n==="string"&&n.trim()!==""?Number(n):Number.NaN;return Number.isSafeInteger(t)&&t>=0?t:void 0}function C(n){let t=Q(n);return t!==void 0&&t>0?t:void 0}function J(n,t){let e=Q(n),r=Q(t);if(n!==void 0&&e===void 0||t!==void 0&&r===void 0)return 0;return Math.max(0,(e??0)-(r??0))}async function v(n,t,e){let{signal:r,cleanup:i}=At(e);try{let o=await fetch(`${xt()}${n}`,{body:JSON.stringify(t),headers:{"Content-Type":"application/json"},method:"POST",signal:r});if(!o.ok)throw new y("toolbox_tron_trongrid_api_error",{message:`${o.status} ${o.statusText} on ${n}`});return await o.json()}finally{i()}}async function vt(n,t,e){let{signal:r,cleanup:i}=At(e);try{let o=await fetch(`${t??xt()}${n}`,{headers:{"Content-Type":"application/json"},signal:r});if(!o.ok)throw new y("toolbox_tron_trongrid_api_error",{message:`${o.status} ${o.statusText} on ${n}`});return await o.json()}finally{i()}}async function O(n){if(!b(n))throw new y("toolbox_tron_trongrid_api_error",{address:n,message:"Invalid address"});try{let t=await vt(`/v1/accounts/${n}`,bt);if(!(t.success&&t.data)||t.data.length===0)return;let e=t.data.find((r)=>Et(r.address,n));if(!e)return;return{balance:e.balance,trc20:e.trc20||[]}}catch(t){if(t instanceof y)throw t;throw new y("toolbox_tron_trongrid_api_error",{message:t instanceof Error?t.message:"Unknown error"})}}var bn="/wallet/createtransaction";async function Ft({from:n,to:t,amount:e}){let i=await v(bn,{amount:e,owner_address:n,to_address:t,visible:!0});if(!i.txID||!i.raw_data_hex||!i.raw_data)throw new y({errorKey:"toolbox_tron_transaction_creation_failed",info:{error:Z(i)??"Node returned no transaction"}});let c=i.raw_data?.contract?.[0]?.parameter?.value;if(c?.to_address!==t||c?.owner_address!==n||c?.amount!==e)throw new y({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Node returned a transaction that does not match the requested transfer"}});return N(i),i}var xn="/wallet/triggersmartcontract";async function St({ownerAddress:n,contractAddress:t,functionSelector:e,parameter:r,feeLimit:i,callValue:o=0}){let c=await v(xn,{call_value:o,contract_address:t,fee_limit:i,function_selector:e,owner_address:n,parameter:r,visible:!0});if(!c.result?.result||!c.transaction?.txID||!c.transaction?.raw_data_hex)throw new y({errorKey:"toolbox_tron_transaction_creation_failed",info:{code:c.result?.code,error:Z(c)??"Node returned no transaction",message:hn(c.result?.message)}});let T=c.transaction.raw_data?.contract?.[0]?.parameter?.value;if(T?.contract_address!==t||T?.owner_address!==n)throw new y({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Node returned a transaction that does not match the requested contract call"}});return N(c.transaction),c.transaction}function Nt({ownerAddress:n,contractAddress:t,functionSelector:e,parameter:r}){return v("/wallet/triggerconstantcontract",{contract_address:t,function_selector:e,owner_address:n,parameter:r,visible:!0})}function An({ownerAddress:n,contractAddress:t,functionSelector:e,parameter:r}){return v("/wallet/estimateenergy",{contract_address:t,function_selector:e,owner_address:n,parameter:r,visible:!0})}function ht(n){let t=typeof n==="number"?n:typeof n==="string"?Number(n):Number.NaN;return Number.isFinite(t)&&t>0?t:void 0}async function k(n){try{let{result:t,txid:e}=await v("/wallet/broadcasttransaction",{raw_data:n.raw_data,raw_data_hex:n.raw_data_hex,signature:n.signature,txID:n.txID,visible:n.visible});if(!t||!e)throw new y("toolbox_tron_token_transfer_failed");return e}catch(t){throw new y("toolbox_tron_broadcast_failed",{error:t})}}async function I({timeoutMs:n}={}){let t={};try{let{chainParameter:e}=await vt("/wallet/getchainparameters",void 0,n);for(let r of e)if(r&&typeof r.key==="string")t[r.key]=r.value}catch(e){K({condition:!0,id:"tron_chain_params_failed",warning:`Failed to fetch chain params, using defaults: ${e instanceof Error?e.message:e}`})}return{bandwidthFee:C(t.getTransactionFee)??gn,createAccountBandwidthFee:C(t.getCreateAccountFee)??_n,createAccountFee:C(t.getCreateNewAccountFeeInSystemContract)??Tn,energyFee:C(t.getEnergyFee)??mn,memoFee:C(t.getMemoFee)??wn}}async function tt(n){try{let t=await v("/wallet/getaccountresource",{address:n,visible:!0});return{bandwidth:{free:J(t.freeNetLimit,t.freeNetUsed),staked:J(t.NetLimit,t.NetUsed)},energy:J(t.EnergyLimit,t.EnergyUsed)}}catch(t){return K({condition:!0,id:"tron_account_resources_failed",warning:`Failed to fetch account resources, assuming none available: ${t instanceof Error?t.message:t}`}),{bandwidth:{free:0,staked:0},energy:0}}}async function G(n,t={}){return await W(n,t)==="exists"}async function W(n,{timeoutMs:t}={}){if(!b(n))return"missing";try{let e=await v("/wallet/getaccount",{address:n,visible:!0},t);if(!e||typeof e!=="object"||Array.isArray(e)||Z(e))return"unknown";if(Et(e.address,n))return"exists";return Object.keys(e).length===0?"missing":"unknown"}catch{return"unknown"}}async function nt(n){try{let t=await An({...n,ownerAddress:n.sender}),e=t.energy_required??t.energyRequired;if(t.result&&!t.result.result)throw new y("toolbox_tron_trongrid_api_error",{message:t.result.message||"estimateenergy failed"});if(e!==void 0){let r=ht(e);if(r!==void 0)return r;throw new y("toolbox_tron_trongrid_api_error",{message:"Invalid estimateenergy response"})}}catch(t){K({condition:!0,id:"tron_energy_estimation_failed",warning:`Failed to estimate energy with estimateenergy, falling back to triggerconstantcontract: ${t instanceof Error?t.message:t}`})}try{let{energy_used:t}=await Nt({...n,ownerAddress:n.sender}),e=ht(t);if(e!==void 0)return e;throw new y("toolbox_tron_trongrid_api_error",{message:"Invalid triggerconstantcontract energy response"})}catch(t){throw K({condition:!0,id:"tron_energy_estimation_fallback_failed",warning:`Failed to estimate energy: ${t instanceof Error?t.message:t}`}),new y("toolbox_tron_trongrid_api_error",{message:`Unable to estimate contract energy: ${t instanceof Error?t.message:t}`})}}async function Rt({assetAddress:n,owner:t,spender:e}){let r=R([{type:"address",value:t},{type:"address",value:e}]),o=(await Nt({contractAddress:n,functionSelector:"allowance(address,address)",ownerAddress:e,parameter:r})).constant_result?.[0];if(!o)return 0n;try{return BigInt(`0x${o}`)}catch{return 0n}}import{bytesToHex as In}from"@noble/hashes/utils.js";import{HDKey as Pn}from"@scure/bip32";import{mnemonicToSeedSync as Bn}from"@scure/bip39";import{AssetValue as B,Chain as x,derivationPathToString as Mt,getChainConfig as Cn,getRPCUrl as kn,NetworkDerivationPath as Lt,SwapKitError as _,updateDerivationPath as Kt,warnOnce as j}from"@swapkit/helpers";import{match as Dn,P as rt}from"ts-pattern";import{sha256 as En}from"@noble/hashes/sha2.js";import{bytesToHex as It,hexToBytes as Pt}from"@noble/hashes/utils.js";import{SwapKitError as P}from"@swapkit/helpers";var V=0,Bt=1,q=2,Ct=5,vn=8,Fn=10,Sn=18;function et(n,t){let e=0n,r=0n,i=t;while(i<n.length&&i-t<10){let o=n[i++];if(o===void 0)break;if(e|=BigInt(o&127)<<r,r+=7n,(o&128)===0)return[e,i]}throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Malformed varint in transaction raw_data"}})}function D(n){let t=[],e=n<0n?n+2n**64n:n;while(e>=128n)t.push(Number(e&0x7fn)|128),e>>=7n;return t.push(Number(e)),t}function H(n,t,e){let r=n.get(t);if(r)r.push(e);else n.set(t,[e])}function Nn(n){let t=new Map,e=0;while(e<n.length){let[r,i]=et(n,e);e=i;let o=Number(r>>3n),c=Number(r&7n);if(c===V){let[m,T]=et(n,e);e=T,H(t,o,{data:new Uint8Array(D(m)),wireType:V})}else if(c===q){let[m,T]=et(n,e);e=T;let A=Number(m);if(A<0||e+A>n.length)throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Length-delimited proto field overruns transaction raw_data"}});let U=n.slice(e,e+A);e+=A,H(t,o,{data:U,wireType:q})}else if(c===Bt){if(e+8>n.length)throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"64-bit proto field overruns transaction raw_data"}});let m=n.slice(e,e+8);e+=8,H(t,o,{data:m,wireType:Bt})}else if(c===Ct){if(e+4>n.length)throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"32-bit proto field overruns transaction raw_data"}});let m=n.slice(e,e+4);e+=4,H(t,o,{data:m,wireType:Ct})}else throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Unsupported proto wire type in transaction raw_data"}})}return t}function Rn(n){let t=[];for(let[o,c]of[...n.entries()].sort(([m],[T])=>m-T))for(let{wireType:m,data:T}of c){let A=BigInt(o<<3|m);if(t.push(new Uint8Array(D(A))),m===q)t.push(new Uint8Array(D(BigInt(T.length))));t.push(T)}let e=t.reduce((o,c)=>o+c.length,0),r=new Uint8Array(e),i=0;for(let o of t)r.set(o,i),i+=o.length;return r}function kt(n,t){if(!n||n.length%2!==0)throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Transaction raw_data_hex is empty or not byte-aligned"}});let e=Pt(n),r=Nn(e);if(t.expiration!==void 0)r.set(vn,[{data:new Uint8Array(D(BigInt(t.expiration))),wireType:V}]);if(t.data!==void 0)r.set(Fn,[{data:Pt(t.data),wireType:q}]);if(t.fee_limit!==void 0)r.set(Sn,[{data:new Uint8Array(D(BigInt(t.fee_limit))),wireType:V}]);let i=Rn(r),o=It(i),c=It(En(i));return{raw_data_hex:o,txID:c}}var Un=b,Mn=Cn(x.Tron).baseDecimal,Ln=64,Kn=67,On=139,Ot=211;function Dt(n){let t=1,e=n>>7n;while(e>0n)t+=1,e>>=7n;return t}var $t=65000,at=25000,ot="TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",$n="115792089237316195423570985008687907853269984665640564039457584007913129639935",it=2500,X=(n)=>B.from({chain:x.Tron,fromBaseDecimal:Mn,value:n}),st=(n,t)=>t?n.memoFee:0;function ct(n,t){let e=n;if(t){let r=z(t).length/2;e+=1+Dt(BigInt(r))+r}return e+1+Dt(BigInt(e))+Kn+Ln}function Gt({bandwidthFee:n,pools:t,requiredBytes:e}){return t.staked>=e||t.free>=e?0:e*n}function Wt({bandwidth:n={free:0,staked:0},chainParams:t,memo:e,recipientStatus:r}){let i=st(t,e),o=t.createAccountFee+t.createAccountBandwidthFee,c=Gt({bandwidthFee:t.bandwidthFee,pools:n,requiredBytes:ct(On,e)});if(r==="exists")return c+i;if(r==="missing")return o+i;return Math.max(o,c)+i}async function Ht(n,t){let e=n||$t,r=t??(await I()).energyFee,i=e*r,o=Math.ceil(i*1.5);return Math.min(Math.max(o,1e7),150000000)}async function Vt({assetValue:n,memo:t,recipient:e,timeoutMs:r}){let[i,o]=await Promise.all([I({timeoutMs:r}),W(e,{timeoutMs:r})]);if(j({condition:n.chain!==x.Tron,id:"tron_conservative_fee_foreign_asset",warning:"Non-Tron asset passed to the Tron fee estimate; reserving the TRC-20 fee"}),n.chain===x.Tron&&n.isGasAsset)return X(Wt({chainParams:i,memo:t,recipientStatus:o}));let m=await Ht($t+(o==="exists"?0:at),i.energyFee),T=st(i,t);return X(m+ct(Ot,t)*i.bandwidthFee+T)}async function Gn({assetValue:n,recipient:t,memo:e,timeoutMs:r=it}){return j({condition:!b(t),id:"tron_sweep_deduction_invalid_recipient",warning:"Invalid Tron sweep recipient; assuming the account needs activation"}),await Vt({assetValue:n,memo:e==null?void 0:String(e),recipient:t,timeoutMs:Number.isFinite(r)&&r>0?r:it})}function qt({phrase:n,derivationPath:t}){let e=Pn.fromMasterSeed(Bn(n)).derive(t);if(!e.privateKey)throw new _("toolbox_tron_no_signer");return In(e.privateKey)}function Wn(n,t){return{...n,value:String(t)}}function Hn(n,t){if(!t)return n;return{...n,data:t.startsWith("0x")?t:`0x${t}`}}function Vn({phrase:n,derivationPath:t,index:e}){let r=t||Mt(Kt(Lt[x.Tron],{index:e||0}));return qt({derivationPath:r,phrase:n})}function qn({phrase:n,derivationPath:t}){let e=qt({derivationPath:t,phrase:n}),r=pt(e);return{getAddress:()=>Promise.resolve(r),signTransaction:(i)=>{N(i);let o=yt({privateKey:e,txID:i.txID});return Promise.resolve({...i,signature:[o]})}}}function Ut({transaction:n,memo:t,expiration:e,feeLimit:r}){let i={},o={};if(r!==void 0&&n.raw_data)i.fee_limit=r,o.fee_limit=r;if(t){let T=z(t);i.data=T,o.data=T}if(e){let T=n.raw_data.expiration+e*1000;i.expiration=T,o.expiration=T}if(Object.keys(i).length===0)return n;let{raw_data_hex:c,txID:m}=kt(n.raw_data_hex,i);return{...n,raw_data:{...n.raw_data,...o},raw_data_hex:c,txID:m}}function jn(n={}){let t="index"in n?n.index||0:0,e=Mt("derivationPath"in n&&n.derivationPath?n.derivationPath:Kt(Lt[x.Tron],{index:t})),r,i=!1;function o(){if(i)return Promise.resolve(r);return r=Dn(n).with({phrase:rt.string},({phrase:a})=>qn({derivationPath:e,phrase:a})).with({signer:rt.not(rt.nullish)},({signer:a})=>a).otherwise(()=>{return}),i=!0,Promise.resolve(r)}async function c(){let a=await o();if(!a)throw new _("toolbox_tron_no_signer");return a.getAddress()}async function m({contractAddress:a,functionSelector:s,parameter:d,sender:u,memo:f,expiration:l,extraEnergy:g=0}){let w=await nt({contractAddress:a,functionSelector:s,parameter:d,sender:u}),p=await Ht(w+g),h=await St({contractAddress:a,feeLimit:p,functionSelector:s,ownerAddress:u,parameter:d});return Ut({expiration:l,feeLimit:p,memo:f,transaction:h})}async function T(a){if(!b(a))return[B.from({chain:x.Tron})];try{let s=await O(a);if(!s)return[B.from({chain:x.Tron})];let d=[B.from({chain:x.Tron,fromBaseDecimal:6,value:String(s.balance)})],u=s.trc20?.find((f)=>(ot in f));if(u){let f=u[ot];d.push(B.from({asset:`TRON.USDT-${ot}`,fromBaseDecimal:6,value:f}))}return d}catch(s){return j({condition:!0,id:"tron_toolbox_get_balance_failed",warning:`Tron API getBalance failed: ${s instanceof Error?s.message:s}`}),[B.from({chain:x.Tron})]}}async function A({recipient:a,assetValue:s,memo:d,expiration:u,sweep:f}){if(!b(a))throw new _("toolbox_tron_token_transfer_failed",{message:"invalid address"});let l=await o();if(!l)throw new _("toolbox_tron_no_signer");try{let g=await c(),w=await ut({assetValue:s,expiration:u,memo:d,recipient:a,sender:g,sweep:f}),p=await l.signTransaction(w),h=await k(p);if(!h)throw new _("toolbox_tron_token_transfer_failed",{message:"broadcast failed"});return h}catch(g){if(g instanceof _&&g.errorKey==="toolbox_sweep_amount_too_low")throw g;throw new _("toolbox_tron_token_transfer_failed",{message:g instanceof Error?g.message:String(g)})}}async function U({memo:a,recipient:s,senderAddress:d}){let[u,f,l]=await Promise.all([I(),W(s),tt(d)]);return X(Wt({bandwidth:l.bandwidth,chainParams:u,memo:a,recipientStatus:f}))}async function dt({assetValue:a,amountInBaseUnits:s=a.getBaseValue("string"),memo:d,recipient:u,senderAddress:f}){let l=a.address;if(!l)throw new _("toolbox_tron_invalid_token_identifier",{identifier:a.toString()});let[g,w,p,h]=await Promise.all([I(),G(u),tt(f),nt({contractAddress:l,functionSelector:"transfer(address,uint256)",parameter:R([{type:"address",value:u},{type:"uint256",value:s}]),sender:f})]),F=h+(w?0:at),Y=Gt({bandwidthFee:g.bandwidthFee,pools:p.bandwidth,requiredBytes:ct(Ot,d)}),Zt=Math.max(0,F-p.energy)*g.energyFee,tn=st(g,d);return X(Y+Zt+tn)}async function jt({assetValue:a,memo:s,recipient:d,sender:u}){let f=await o();try{let l=u?u:f?await c():void 0;if(!l)return Vt({assetValue:a,memo:s,recipient:d});return a.isGasAsset?U({memo:s,recipient:d,senderAddress:l}):dt({assetValue:a,memo:s,recipient:d,senderAddress:l})}catch(l){throw j({condition:!0,id:"tron_toolbox_fee_estimation_failed",warning:`Failed to calculate exact fee: ${l instanceof Error?l.message:l}`}),new _("toolbox_fee_estimation_failed",{chain:x.Tron,error:l})}}async function Xt({assetValue:a,memo:s,recipient:d,sender:u,sweep:f}){if(!f)return a.getBaseValue("bigint");let[l,g]=await Promise.all([O(u),U({memo:s,recipient:d,senderAddress:u})]),w=BigInt(l?.balance??0)-g.getBaseValue("bigint");if(w<=0n)throw new _({errorKey:"toolbox_sweep_amount_too_low",info:{amount:w.toString(),asset:a.toString()}});return w}async function Yt({assetValue:a,memo:s,recipient:d,sender:u,sweep:f}){if(!f)return a.getBaseValue("string");let l=a.address;if(!l)throw new _("toolbox_tron_invalid_token_identifier",{identifier:a.toString()});let g=await O(u),p=g?.trc20.find((Y)=>(l in Y))?.[l]??"0";if(BigInt(p)<=0n)throw new _({errorKey:"toolbox_sweep_amount_too_low",info:{asset:a.toString(),balance:p}});let h=await dt({amountInBaseUnits:p,assetValue:a,memo:s,recipient:d,senderAddress:u}),E=BigInt(g?.balance??0),F=h.getBaseValue("bigint");if(E<F)throw new _({errorKey:"toolbox_sweep_amount_too_low",info:{asset:a.toString(),nativeBalance:E.toString(),requiredNativeFee:F.toString()}});return p}async function ut({recipient:a,assetValue:s,memo:d,sender:u,expiration:f,sweep:l,recipientExists:g}){if(!b(a)||!b(u))throw new _("toolbox_tron_transaction_creation_failed",{message:"invalid address"});if(s.isGasAsset){let E=await Xt({assetValue:s,expiration:f,memo:d,recipient:a,sender:u,sweep:l});if(E>BigInt(Number.MAX_SAFE_INTEGER))throw new _({errorKey:"toolbox_tron_transaction_creation_failed",info:{amount:E.toString(),reason:`Native transfer amount exceeds the safe integer limit of ${Number.MAX_SAFE_INTEGER} SUN`}});let F=await Ft({amount:Number(E),from:u,to:a});return Ut({expiration:f,memo:d,transaction:F})}let w=s.address;if(!w)throw new _("toolbox_tron_invalid_token_identifier",{identifier:s.toString()});let p=await Yt({assetValue:s,expiration:f,memo:d,recipient:a,sender:u,sweep:l}),h=g??await G(a);return m({contractAddress:w,expiration:f,extraEnergy:h?0:at,functionSelector:"transfer(address,uint256)",memo:d,parameter:R([{type:"address",value:a},{type:"uint256",value:p}]),sender:u})}async function ft(a){N(a);let s=await o();if(!s)throw new _("toolbox_tron_no_signer");return s.signTransaction(a)}async function zt(a){let s=await ft(a);return k(s)}function lt({assetAddress:a,spenderAddress:s,from:d}){return Rt({assetAddress:a,owner:d,spender:s})}async function Jt({assetAddress:a,spenderAddress:s,from:d,amount:u}){let f=await lt({assetAddress:a,from:d,spenderAddress:s});if(!u)return f>0n;return f>=BigInt(u)}async function Qt({assetAddress:a,spenderAddress:s,amount:d,from:u}){if(!b(a)||!b(s))throw new _("toolbox_tron_approve_failed");let f=await o();if(!f)throw new _("toolbox_tron_no_signer");let l=u||await c(),g=d!==void 0?BigInt(d).toString():$n;try{let w=await m({contractAddress:a,functionSelector:"approve(address,uint256)",parameter:R([{type:"address",value:s},{type:"uint256",value:g}]),sender:l}),p=await f.signTransaction(w),h=await k(p);if(!h)throw new _("toolbox_tron_approve_failed");return h}catch(w){if(w instanceof _)throw w;throw new _("toolbox_tron_approve_failed",{error:w})}}return{approve:Qt,broadcastTransaction:k,createTransaction:ut,estimateTransactionFee:jt,getAddress:c,getApprovedAmount:lt,getBalance:T,getRpcUrl:()=>kn(x.Tron),isApproved:Jt,signAndBroadcastTransaction:zt,signTransaction:ft,transfer:A,validateAddress:b}}export{it as TRON_SWEEP_ESTIMATE_TIMEOUT_MS,G as checkTronAccountExists,Gn as estimateTronSweepDeduction,I as getTronChainParameters,Vn as getTronPrivateKeyFromMnemonic,jn as getTronToolbox,Un as validateTronAddress,Hn as withTronTransactionData,Wn as withTronTransactionValue};
1
+ import"../../chunk-exyqap7m.js";import{hexToBytes as un}from"@noble/hashes/utils.js";import{Chain as fn,getRPCUrlSync as ln,SwapKitError as y,warnOnce as K}from"@swapkit/helpers";import{secp256k1 as _t}from"@noble/curves/secp256k1.js";import{sha256 as Tt}from"@noble/hashes/sha2.js";import{keccak_256 as nn}from"@noble/hashes/sha3.js";import{bytesToHex as S,hexToBytes as M}from"@noble/hashes/utils.js";import{createBase58check as en}from"@scure/base";import{SwapKitError as mt}from"@swapkit/helpers";var L=en(Tt),wt=65,rn=2n**256n;function b(n){if(typeof n!=="string")return!1;try{let t=L.decode(n);return t.length===21&&t[0]===wt}catch{return!1}}function z(n){return S(L.decode(n))}function on(n){return L.decode(n).slice(1)}function pt(n){let t=_t.getPublicKey(M(n),!1),e=nn(t.slice(1)).slice(-20),r=new Uint8Array(21);return r[0]=wt,r.set(e,1),L.encode(r)}function yt({txID:n,privateKey:t}){let e=_t.sign(M(n),M(t),{format:"recovered",prehash:!1}),r=e[0]??0,i=S(e.slice(1,33)),o=S(e.slice(33,65)),c=(r+27).toString(16).padStart(2,"0");return i+o+c}function N({txID:n,raw_data_hex:t}){let e=S(Tt(M(t)));if(n!==e)throw new mt("toolbox_tron_invalid_transaction_integrity",{expected:e,txID:n})}function an(n){return`000000000000000000000000${S(on(n))}`}function sn(n){let t=typeof n==="bigint"?n:BigInt(n);if(t<0n||t>=rn)throw new mt("toolbox_tron_invalid_token_identifier",{identifier:t.toString()});return t.toString(16).padStart(64,"0")}function R(n){return n.map(({type:t,value:e})=>t==="address"?an(e):sn(BigInt(e))).join("")}function cn(n){return S(new TextEncoder().encode(n))}var dn=/^0x(?:[0-9a-fA-F]{2})+$/;function J(n){return dn.test(n)?n.slice(2):cn(n)}var bt="https://api.trongrid.io",gn=1000,_n=1e5,Tn=1e6,mn=420,wn=1e6,pn=30000,yn=2147483647;function xt(){try{return ln(fn.Tron)}catch{return bt}}function At(n){let t=n!==void 0&&Number.isFinite(n)&&n>0?Math.min(n,yn):pn,e=new AbortController,r=setTimeout(()=>e.abort(),t);return{cleanup:()=>clearTimeout(r),signal:e.signal}}function tt(n){if(!n||typeof n!=="object")return;let{Error:t}=n;return typeof t==="string"&&t.length>0?t:void 0}function hn(n){if(!n)return;if(n.length%2!==0||!/^[0-9a-f]+$/i.test(n))return n;try{let t=new TextDecoder().decode(un(n));return/^[ -~]+$/.test(t)?t:n}catch{return n}}function Et(n,t){if(typeof n!=="string")return!1;if(n===t)return!0;try{return n.toLowerCase()===z(t).toLowerCase()}catch{return!1}}function Z(n){let t=typeof n==="number"?n:typeof n==="string"&&n.trim()!==""?Number(n):Number.NaN;return Number.isSafeInteger(t)&&t>=0?t:void 0}function C(n){let t=Z(n);return t!==void 0&&t>0?t:void 0}function Q(n,t){let e=Z(n),r=Z(t);if(n!==void 0&&e===void 0||t!==void 0&&r===void 0)return 0;return Math.max(0,(e??0)-(r??0))}async function v(n,t,e){let{signal:r,cleanup:i}=At(e);try{let o=await fetch(`${xt()}${n}`,{body:JSON.stringify(t),headers:{"Content-Type":"application/json"},method:"POST",signal:r});if(!o.ok)throw new y("toolbox_tron_trongrid_api_error",{message:`${o.status} ${o.statusText} on ${n}`});return await o.json()}finally{i()}}async function vt(n,t,e){let{signal:r,cleanup:i}=At(e);try{let o=await fetch(`${t??xt()}${n}`,{headers:{"Content-Type":"application/json"},signal:r});if(!o.ok)throw new y("toolbox_tron_trongrid_api_error",{message:`${o.status} ${o.statusText} on ${n}`});return await o.json()}finally{i()}}async function O(n){if(!b(n))throw new y("toolbox_tron_trongrid_api_error",{address:n,message:"Invalid address"});try{let t=await vt(`/v1/accounts/${n}`,bt);if(!(t.success&&t.data)||t.data.length===0)return;let e=t.data.find((r)=>Et(r.address,n));if(!e)return;return{balance:e.balance,trc20:e.trc20||[]}}catch(t){if(t instanceof y)throw t;throw new y("toolbox_tron_trongrid_api_error",{message:t instanceof Error?t.message:"Unknown error"})}}var bn="/wallet/createtransaction";async function Ft({from:n,to:t,amount:e}){let i=await v(bn,{amount:e,owner_address:n,to_address:t,visible:!0});if(!i.txID||!i.raw_data_hex||!i.raw_data)throw new y({errorKey:"toolbox_tron_transaction_creation_failed",info:{error:tt(i)??"Node returned no transaction"}});let c=i.raw_data?.contract?.[0]?.parameter?.value;if(c?.to_address!==t||c?.owner_address!==n||c?.amount!==e)throw new y({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Node returned a transaction that does not match the requested transfer"}});return N(i),i}var xn="/wallet/triggersmartcontract";async function St({ownerAddress:n,contractAddress:t,functionSelector:e,parameter:r,feeLimit:i,callValue:o=0}){let c=await v(xn,{call_value:o,contract_address:t,fee_limit:i,function_selector:e,owner_address:n,parameter:r,visible:!0});if(!c.result?.result||!c.transaction?.txID||!c.transaction?.raw_data_hex)throw new y({errorKey:"toolbox_tron_transaction_creation_failed",info:{code:c.result?.code,error:tt(c)??"Node returned no transaction",message:hn(c.result?.message)}});let T=c.transaction.raw_data?.contract?.[0]?.parameter?.value;if(T?.contract_address!==t||T?.owner_address!==n)throw new y({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Node returned a transaction that does not match the requested contract call"}});return N(c.transaction),c.transaction}function Nt({ownerAddress:n,contractAddress:t,functionSelector:e,parameter:r}){return v("/wallet/triggerconstantcontract",{contract_address:t,function_selector:e,owner_address:n,parameter:r,visible:!0})}function An({ownerAddress:n,contractAddress:t,functionSelector:e,parameter:r}){return v("/wallet/estimateenergy",{contract_address:t,function_selector:e,owner_address:n,parameter:r,visible:!0})}function ht(n){let t=typeof n==="number"?n:typeof n==="string"?Number(n):Number.NaN;return Number.isFinite(t)&&t>0?t:void 0}async function k(n){try{let{result:t,txid:e}=await v("/wallet/broadcasttransaction",{raw_data:n.raw_data,raw_data_hex:n.raw_data_hex,signature:n.signature,txID:n.txID,visible:n.visible});if(!t||!e)throw new y("toolbox_tron_token_transfer_failed");return e}catch(t){throw new y("toolbox_tron_broadcast_failed",{error:t})}}async function I({timeoutMs:n}={}){let t={};try{let{chainParameter:e}=await vt("/wallet/getchainparameters",void 0,n);for(let r of e)if(r&&typeof r.key==="string")t[r.key]=r.value}catch(e){K({condition:!0,id:"tron_chain_params_failed",warning:`Failed to fetch chain params, using defaults: ${e instanceof Error?e.message:e}`})}return{bandwidthFee:C(t.getTransactionFee)??gn,createAccountBandwidthFee:C(t.getCreateAccountFee)??_n,createAccountFee:C(t.getCreateNewAccountFeeInSystemContract)??Tn,energyFee:C(t.getEnergyFee)??mn,memoFee:C(t.getMemoFee)??wn}}async function nt(n){try{let t=await v("/wallet/getaccountresource",{address:n,visible:!0});return{bandwidth:{free:Q(t.freeNetLimit,t.freeNetUsed),staked:Q(t.NetLimit,t.NetUsed)},energy:Q(t.EnergyLimit,t.EnergyUsed)}}catch(t){return K({condition:!0,id:"tron_account_resources_failed",warning:`Failed to fetch account resources, assuming none available: ${t instanceof Error?t.message:t}`}),{bandwidth:{free:0,staked:0},energy:0}}}async function G(n,t={}){return await W(n,t)==="exists"}async function W(n,{timeoutMs:t}={}){if(!b(n))return"missing";try{let e=await v("/wallet/getaccount",{address:n,visible:!0},t);if(!e||typeof e!=="object"||Array.isArray(e)||tt(e))return"unknown";if(Et(e.address,n))return"exists";return Object.keys(e).length===0?"missing":"unknown"}catch{return"unknown"}}async function et(n){try{let t=await An({...n,ownerAddress:n.sender}),e=t.energy_required??t.energyRequired;if(t.result&&!t.result.result)throw new y("toolbox_tron_trongrid_api_error",{message:t.result.message||"estimateenergy failed"});if(e!==void 0){let r=ht(e);if(r!==void 0)return r;throw new y("toolbox_tron_trongrid_api_error",{message:"Invalid estimateenergy response"})}}catch(t){K({condition:!0,id:"tron_energy_estimation_failed",warning:`Failed to estimate energy with estimateenergy, falling back to triggerconstantcontract: ${t instanceof Error?t.message:t}`})}try{let{energy_used:t}=await Nt({...n,ownerAddress:n.sender}),e=ht(t);if(e!==void 0)return e;throw new y("toolbox_tron_trongrid_api_error",{message:"Invalid triggerconstantcontract energy response"})}catch(t){throw K({condition:!0,id:"tron_energy_estimation_fallback_failed",warning:`Failed to estimate energy: ${t instanceof Error?t.message:t}`}),new y("toolbox_tron_trongrid_api_error",{message:`Unable to estimate contract energy: ${t instanceof Error?t.message:t}`})}}async function Rt({assetAddress:n,owner:t,spender:e}){let r=R([{type:"address",value:t},{type:"address",value:e}]),o=(await Nt({contractAddress:n,functionSelector:"allowance(address,address)",ownerAddress:e,parameter:r})).constant_result?.[0];if(!o)return 0n;try{return BigInt(`0x${o}`)}catch{return 0n}}import{bytesToHex as In}from"@noble/hashes/utils.js";import{HDKey as Pn}from"@scure/bip32";import{mnemonicToSeedSync as Bn}from"@scure/bip39";import{AssetValue as B,Chain as x,derivationPathToString as Mt,getChainConfig as Cn,getRPCUrl as kn,NetworkDerivationPath as Lt,SwapKitError as _,updateDerivationPath as Kt,warnOnce as j}from"@swapkit/helpers";import{match as Dn,P as ot}from"ts-pattern";import{sha256 as En}from"@noble/hashes/sha2.js";import{bytesToHex as It,hexToBytes as Pt}from"@noble/hashes/utils.js";import{SwapKitError as P}from"@swapkit/helpers";var V=0,Bt=1,q=2,Ct=5,vn=8,Fn=10,Sn=18;function rt(n,t){let e=0n,r=0n,i=t;while(i<n.length&&i-t<10){let o=n[i++];if(o===void 0)break;if(e|=BigInt(o&127)<<r,r+=7n,(o&128)===0)return[e,i]}throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Malformed varint in transaction raw_data"}})}function D(n){let t=[],e=n<0n?n+2n**64n:n;while(e>=128n)t.push(Number(e&0x7fn)|128),e>>=7n;return t.push(Number(e)),t}function H(n,t,e){let r=n.get(t);if(r)r.push(e);else n.set(t,[e])}function Nn(n){let t=new Map,e=0;while(e<n.length){let[r,i]=rt(n,e);e=i;let o=Number(r>>3n),c=Number(r&7n);if(c===V){let[m,T]=rt(n,e);e=T,H(t,o,{data:new Uint8Array(D(m)),wireType:V})}else if(c===q){let[m,T]=rt(n,e);e=T;let A=Number(m);if(A<0||e+A>n.length)throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Length-delimited proto field overruns transaction raw_data"}});let U=n.slice(e,e+A);e+=A,H(t,o,{data:U,wireType:q})}else if(c===Bt){if(e+8>n.length)throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"64-bit proto field overruns transaction raw_data"}});let m=n.slice(e,e+8);e+=8,H(t,o,{data:m,wireType:Bt})}else if(c===Ct){if(e+4>n.length)throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"32-bit proto field overruns transaction raw_data"}});let m=n.slice(e,e+4);e+=4,H(t,o,{data:m,wireType:Ct})}else throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Unsupported proto wire type in transaction raw_data"}})}return t}function Rn(n){let t=[];for(let[o,c]of[...n.entries()].sort(([m],[T])=>m-T))for(let{wireType:m,data:T}of c){let A=BigInt(o<<3|m);if(t.push(new Uint8Array(D(A))),m===q)t.push(new Uint8Array(D(BigInt(T.length))));t.push(T)}let e=t.reduce((o,c)=>o+c.length,0),r=new Uint8Array(e),i=0;for(let o of t)r.set(o,i),i+=o.length;return r}function kt(n,t){if(!n||n.length%2!==0)throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Transaction raw_data_hex is empty or not byte-aligned"}});let e=Pt(n),r=Nn(e);if(t.expiration!==void 0)r.set(vn,[{data:new Uint8Array(D(BigInt(t.expiration))),wireType:V}]);if(t.data!==void 0)r.set(Fn,[{data:Pt(t.data),wireType:q}]);if(t.fee_limit!==void 0)r.set(Sn,[{data:new Uint8Array(D(BigInt(t.fee_limit))),wireType:V}]);let i=Rn(r),o=It(i),c=It(En(i));return{raw_data_hex:o,txID:c}}var Un=b,Mn=Cn(x.Tron).baseDecimal,Ln=64,Kn=67,On=139,Ot=211;function Dt(n){let t=1,e=n>>7n;while(e>0n)t+=1,e>>=7n;return t}var $t=65000,it=25000,at="TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",$n="115792089237316195423570985008687907853269984665640564039457584007913129639935",st=2500,X=(n)=>B.from({chain:x.Tron,fromBaseDecimal:Mn,value:n}),ct=(n,t)=>t?n.memoFee:0;function dt(n,t){let e=n;if(t){let r=J(t).length/2;e+=1+Dt(BigInt(r))+r}return e+1+Dt(BigInt(e))+Kn+Ln}function Gt({bandwidthFee:n,pools:t,requiredBytes:e}){return t.staked>=e||t.free>=e?0:e*n}function Wt({bandwidth:n={free:0,staked:0},chainParams:t,memo:e,recipientStatus:r}){let i=ct(t,e),o=t.createAccountFee+t.createAccountBandwidthFee,c=Gt({bandwidthFee:t.bandwidthFee,pools:n,requiredBytes:dt(On,e)});if(r==="exists")return c+i;if(r==="missing")return o+i;return Math.max(o,c)+i}async function Ht(n,t){let e=n||$t,r=t??(await I()).energyFee,i=e*r,o=Math.ceil(i*1.5);return Math.min(Math.max(o,1e7),150000000)}async function Vt({assetValue:n,memo:t,recipient:e,timeoutMs:r}){let[i,o]=await Promise.all([I({timeoutMs:r}),W(e,{timeoutMs:r})]);if(j({condition:n.chain!==x.Tron,id:"tron_conservative_fee_foreign_asset",warning:"Non-Tron asset passed to the Tron fee estimate; reserving the TRC-20 fee"}),n.chain===x.Tron&&n.isGasAsset)return X(Wt({chainParams:i,memo:t,recipientStatus:o}));let m=await Ht($t+(o==="exists"?0:it),i.energyFee),T=ct(i,t);return X(m+dt(Ot,t)*i.bandwidthFee+T)}async function Gn({assetValue:n,recipient:t,memo:e,timeoutMs:r=st}){return j({condition:!b(t),id:"tron_sweep_deduction_invalid_recipient",warning:"Invalid Tron sweep recipient; assuming the account needs activation"}),await Vt({assetValue:n,memo:e==null?void 0:String(e),recipient:t,timeoutMs:Number.isFinite(r)&&r>0?r:st})}function qt({phrase:n,derivationPath:t}){let e=Pn.fromMasterSeed(Bn(n)).derive(t);if(!e.privateKey)throw new _("toolbox_tron_no_signer");return In(e.privateKey)}function Wn(n,t){return{...n,value:String(t)}}function Hn(n,t){if(!t)return n;return{...n,data:t.startsWith("0x")?t:`0x${t}`}}function Vn({phrase:n,derivationPath:t,index:e}){let r=t||Mt(Kt(Lt[x.Tron],{index:e||0}));return qt({derivationPath:r,phrase:n})}function qn({phrase:n,derivationPath:t}){let e=qt({derivationPath:t,phrase:n}),r=pt(e);return{getAddress:()=>Promise.resolve(r),signTransaction:(i)=>{N(i);let o=yt({privateKey:e,txID:i.txID});return Promise.resolve({...i,signature:[o]})}}}function Ut({transaction:n,memo:t,expiration:e,feeLimit:r}){let i={},o={};if(r!==void 0&&n.raw_data)i.fee_limit=r,o.fee_limit=r;if(t){let T=J(t);i.data=T,o.data=T}if(e){let T=n.raw_data.expiration+e*1000;i.expiration=T,o.expiration=T}if(Object.keys(i).length===0)return n;let{raw_data_hex:c,txID:m}=kt(n.raw_data_hex,i);return{...n,raw_data:{...n.raw_data,...o},raw_data_hex:c,txID:m}}function jn(n={}){let t="index"in n?n.index||0:0,e=Mt("derivationPath"in n&&n.derivationPath?n.derivationPath:Kt(Lt[x.Tron],{index:t})),r,i=!1;function o(){if(i)return Promise.resolve(r);return r=Dn(n).with({phrase:ot.string},({phrase:a})=>qn({derivationPath:e,phrase:a})).with({signer:ot.not(ot.nullish)},({signer:a})=>a).otherwise(()=>{return}),i=!0,Promise.resolve(r)}async function c(){let a=await o();if(!a)throw new _("toolbox_tron_no_signer");return a.getAddress()}async function m({contractAddress:a,functionSelector:s,parameter:d,sender:u,memo:f,expiration:l,extraEnergy:g=0}){let w=await et({contractAddress:a,functionSelector:s,parameter:d,sender:u}),p=await Ht(w+g),h=await St({contractAddress:a,feeLimit:p,functionSelector:s,ownerAddress:u,parameter:d});return Ut({expiration:l,feeLimit:p,memo:f,transaction:h})}async function T(a){if(!b(a))return[B.from({chain:x.Tron})];try{let s=await O(a);if(!s)return[B.from({chain:x.Tron})];let d=[B.from({chain:x.Tron,fromBaseDecimal:6,value:String(s.balance)})],u=s.trc20?.find((f)=>(at in f));if(u){let f=u[at];d.push(B.from({asset:`TRON.USDT-${at}`,fromBaseDecimal:6,value:f}))}return d}catch(s){return j({condition:!0,id:"tron_toolbox_get_balance_failed",warning:`Tron API getBalance failed: ${s instanceof Error?s.message:s}`}),[B.from({chain:x.Tron})]}}async function A({recipient:a,assetValue:s,memo:d,expiration:u,sweep:f}){if(!b(a))throw new _("toolbox_tron_token_transfer_failed",{message:"invalid address"});let l=await o();if(!l)throw new _("toolbox_tron_no_signer");try{let g=await c(),w=await ft({assetValue:s,expiration:u,memo:d,recipient:a,sender:g,sweep:f}),p=await l.signTransaction(w),h=await k(p);if(!h)throw new _("toolbox_tron_token_transfer_failed",{message:"broadcast failed"});return h}catch(g){if(g instanceof _&&g.errorKey==="toolbox_sweep_amount_too_low")throw g;throw new _("toolbox_tron_token_transfer_failed",{message:g instanceof Error?g.message:String(g)})}}async function U({memo:a,recipient:s,senderAddress:d}){let[u,f,l]=await Promise.all([I(),W(s),nt(d)]);return X(Wt({bandwidth:l.bandwidth,chainParams:u,memo:a,recipientStatus:f}))}async function ut({assetValue:a,amountInBaseUnits:s=a.getBaseValue("string"),memo:d,recipient:u,senderAddress:f}){let l=a.address;if(!l)throw new _("toolbox_tron_invalid_token_identifier",{identifier:a.toString()});let[g,w,p,h]=await Promise.all([I(),G(u),nt(f),et({contractAddress:l,functionSelector:"transfer(address,uint256)",parameter:R([{type:"address",value:u},{type:"uint256",value:s}]),sender:f})]),F=h+(w?0:it),Y=Gt({bandwidthFee:g.bandwidthFee,pools:p.bandwidth,requiredBytes:dt(Ot,d)}),Zt=Math.max(0,F-p.energy)*g.energyFee,tn=ct(g,d);return X(Y+Zt+tn)}async function jt({assetValue:a,memo:s,recipient:d,sender:u}){let f=await o();try{let l=u?u:f?await c():void 0;if(!l)return Vt({assetValue:a,memo:s,recipient:d});return a.isGasAsset?U({memo:s,recipient:d,senderAddress:l}):ut({assetValue:a,memo:s,recipient:d,senderAddress:l})}catch(l){throw j({condition:!0,id:"tron_toolbox_fee_estimation_failed",warning:`Failed to calculate exact fee: ${l instanceof Error?l.message:l}`}),new _("toolbox_fee_estimation_failed",{chain:x.Tron,error:l})}}async function Xt({assetValue:a,memo:s,recipient:d,sender:u,sweep:f}){if(!f)return a.getBaseValue("bigint");let[l,g]=await Promise.all([O(u),U({memo:s,recipient:d,senderAddress:u})]),w=BigInt(l?.balance??0)-g.getBaseValue("bigint");if(w<=0n)throw new _({errorKey:"toolbox_sweep_amount_too_low",info:{amount:w.toString(),asset:a.toString()}});return w}async function Yt({assetValue:a,memo:s,recipient:d,sender:u,sweep:f}){if(!f)return a.getBaseValue("string");let l=a.address;if(!l)throw new _("toolbox_tron_invalid_token_identifier",{identifier:a.toString()});let g=await O(u),p=g?.trc20.find((Y)=>(l in Y))?.[l]??"0";if(BigInt(p)<=0n)throw new _({errorKey:"toolbox_sweep_amount_too_low",info:{asset:a.toString(),balance:p}});let h=await ut({amountInBaseUnits:p,assetValue:a,memo:s,recipient:d,senderAddress:u}),E=BigInt(g?.balance??0),F=h.getBaseValue("bigint");if(E<F)throw new _({errorKey:"toolbox_sweep_amount_too_low",info:{asset:a.toString(),nativeBalance:E.toString(),requiredNativeFee:F.toString()}});return p}async function ft({recipient:a,assetValue:s,memo:d,sender:u,expiration:f,sweep:l,recipientExists:g}){if(!b(a)||!b(u))throw new _("toolbox_tron_transaction_creation_failed",{message:"invalid address"});if(s.isGasAsset){let E=await Xt({assetValue:s,expiration:f,memo:d,recipient:a,sender:u,sweep:l});if(E>BigInt(Number.MAX_SAFE_INTEGER))throw new _({errorKey:"toolbox_tron_transaction_creation_failed",info:{amount:E.toString(),reason:`Native transfer amount exceeds the safe integer limit of ${Number.MAX_SAFE_INTEGER} SUN`}});let F=await Ft({amount:Number(E),from:u,to:a});return Ut({expiration:f,memo:d,transaction:F})}let w=s.address;if(!w)throw new _("toolbox_tron_invalid_token_identifier",{identifier:s.toString()});let p=await Yt({assetValue:s,expiration:f,memo:d,recipient:a,sender:u,sweep:l}),h=g??await G(a);return m({contractAddress:w,expiration:f,extraEnergy:h?0:it,functionSelector:"transfer(address,uint256)",memo:d,parameter:R([{type:"address",value:a},{type:"uint256",value:p}]),sender:u})}async function lt(a){N(a);let s=await o();if(!s)throw new _("toolbox_tron_no_signer");return s.signTransaction(a)}async function zt(a){let s=await lt(a);return k(s)}function gt({assetAddress:a,spenderAddress:s,from:d}){return Rt({assetAddress:a,owner:d,spender:s})}async function Jt({assetAddress:a,spenderAddress:s,from:d,amount:u}){let f=await gt({assetAddress:a,from:d,spenderAddress:s});if(!u)return f>0n;return f>=BigInt(u)}async function Qt({assetAddress:a,spenderAddress:s,amount:d,from:u}){if(!b(a)||!b(s))throw new _("toolbox_tron_approve_failed");let f=await o();if(!f)throw new _("toolbox_tron_no_signer");let l=u||await c(),g=d!==void 0?BigInt(d).toString():$n;try{let w=await m({contractAddress:a,functionSelector:"approve(address,uint256)",parameter:R([{type:"address",value:s},{type:"uint256",value:g}]),sender:l}),p=await f.signTransaction(w),h=await k(p);if(!h)throw new _("toolbox_tron_approve_failed");return h}catch(w){if(w instanceof _)throw w;throw new _("toolbox_tron_approve_failed",{error:w})}}return{approve:Qt,broadcastTransaction:k,createTransaction:ft,estimateTransactionFee:jt,getAddress:c,getApprovedAmount:gt,getBalance:T,getRpcUrl:()=>kn(x.Tron),isApproved:Jt,signAndBroadcastTransaction:zt,signTransaction:lt,transfer:A,validateAddress:b}}export{st as TRON_SWEEP_ESTIMATE_TIMEOUT_MS,G as checkTronAccountExists,Gn as estimateTronSweepDeduction,I as getTronChainParameters,Vn as getTronPrivateKeyFromMnemonic,jn as getTronToolbox,z as tronAddressToHex,Un as validateTronAddress,Hn as withTronTransactionData,Wn as withTronTransactionValue};
@@ -1 +1 @@
1
- import{ha as St,ia as jt}from"../../chunk-xdkdc1f0.js";import"../../chunk-exyqap7m.js";import{NetworkDerivationPath as Cn}from"@swapkit/helpers";function Z(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`${e} must be a non-negative integer, got: ${t}`)}function ee({accountIndex:e,chain:t,derivationPath:n}){if(e!==void 0)Z("accountIndex",e);let[r,s,a]=n??Cn[t];return[r,s,e??a]}function Ae({accountIndex:e,change:t=!1,chain:n,derivationPath:r,index:s}){return Z("index",s),[...ee({accountIndex:e,chain:n,derivationPath:r}),Number(t),s]}function pe(e){return e[2]??0}function Xn({deriveAddress:e,getBalance:t,getUtxos:n}){async function r(o){let{accountIndex:p,count:c,startIndex:u=0,change:i=!1}=o;if(Z("count",c),c<1)throw RangeError("count must be at least 1");Z("startIndex",u);let l=[];for(let h=0;h<c;h++){let m=await e({accountIndex:p,change:i,index:u+h});if(m)l.push(m)}return l}async function s(o){let{gapLimit:p=20,change:c=!1}=o??{},u=[],i=0,l=0;while(i<p){let h=await e({change:c,index:l});if(!h)break;if((await t(h.address)).some((y)=>y.getValue("number")>0))u.push(h),i=0;else i++;l++}return u}async function a(o=20){let[p,c]=await Promise.all([s({change:!1,gapLimit:o}),s({change:!0,gapLimit:o})]),u=[...p,...c],i=await Promise.all(u.map(async(h)=>{let f=(await t(h.address)).reduce((y,b)=>y+b.getValue("number"),0);return{...h,balance:f}})),l=i.reduce((h,m)=>h+m.balance,0);return{addresses:i,total:l}}async function d(o=20){let[p,c]=await Promise.all([s({change:!1,gapLimit:o}),s({change:!0,gapLimit:o})]),u=[...p,...c];return(await Promise.all(u.map(async(l)=>(await n(l.address)).map((m)=>({...m,address:l.address,derivationIndex:l.index,isChange:l.change}))))).flat()}return{deriveAddresses:r,getAggregatedBalance:a,getAggregatedUtxos:d,scanForAddresses:s}}import{Chain as C,getRPCUrl as Bn,RequestClient as Re,SKConfig as kn,SwapKitError as H,warnOnce as Kn}from"@swapkit/helpers";import{NETWORKS as le}from"@swapkit/utxo-signer";async function Fn({chain:e,txHash:t}){let n=`${he(e)}/push/transaction`,r=JSON.stringify({data:t});try{let s=await Re.post(n,{body:r,headers:{"Content-Type":"application/json"}});if(s.context.code!==200)throw new H("toolbox_utxo_broadcast_failed",{error:s.context.error||"Transaction broadcast failed"});return s.data?.transaction_hash||t}catch(s){let a=await Bn(e);if(a){let d=JSON.stringify({id:St(),jsonrpc:"2.0",method:"sendrawtransaction",params:[t]}),o=await Re.post(a,{body:d,headers:{"Content-Type":"application/json"}});if(o.error)throw new H("toolbox_utxo_broadcast_failed",{error:o.error?.message});if(o.result.includes('"code":-26'))throw new H("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return o.result}throw s}}function he(e){return`https://api.blockchair.com/${Dn(e)}`}function At(e){switch(e){case C.Bitcoin:return 5;case C.Dogecoin:return 1e4;case C.Litecoin:return 1;case C.Zcash:return 1;default:return 2}}function Dn(e){switch(e){case C.BitcoinCash:return"bitcoin-cash";case C.Litecoin:return"litecoin";case C.Dash:return"dash";case C.Dogecoin:return"dogecoin";case C.Zcash:return"zcash";case C.Polkadot:return"polkadot";default:return"bitcoin"}}async function In(e){try{let{feePerKb:t}=await Re.get(`https://app.bitgo.com/api/v2/${e.toLowerCase()}/tx/fee`),n=t/1000;return Math.max(n,At(e))}catch{return At(e)}}async function Oe(e,t){let n=await Re.get(`${e}${t?`${e.includes("?")?"&":"?"}key=${t}`:""}`);if(!n||n.context.code!==200)throw new H("toolbox_utxo_api_error",{error:`Failed to query ${e}`});return n.data}async function Hn({chain:e,apiKey:t}){let n=await Oe(`${he(e)}/stats`,t);if(typeof n.best_block_height!=="number")throw new H("toolbox_utxo_api_error",{error:"Missing best_block_height in stats response"});return n.best_block_height}async function Ct({address:e,chain:t,apiKey:n}){if(!e)throw new H("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await Oe(`${he(t)}/dashboards/address/${e}?transaction_details=true`,n))[e]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function Rn({address:e,chain:t,apiKey:n}){return(await Ct({address:e,apiKey:n,chain:t}))?.address.balance||0}async function Xt({chain:e,apiKey:t,txHash:n}){if(!n)throw new H("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await Oe(`${he(e)}/raw/transaction/${n}`,t))?.[n]?.raw_transaction||""}catch(r){let s=r instanceof Error?r.message:String(r);return console.error(`Failed to fetch raw transaction: ${s}`),""}}var En=4294967294;async function Mn({chain:e,apiKey:t,txHash:n}){if(!n)throw new H("toolbox_utxo_invalid_params",{error:"TxHash is required"});let s=(await Oe(`${he(e)}/dashboards/transaction/${n}`,t))?.[n];if(!s)throw new H("toolbox_utxo_tx_not_found",{txHash:n});let{transaction:a,inputs:d,outputs:o}=s,p=d.map((u)=>u.spending_sequence),c=a.is_rbf===!0||p.some((u)=>u<En);return{blockId:a.block_id,confirmed:a.block_id!==-1,fee:a.fee,inputs:d,isRBF:c,outputs:o,sequences:p,size:a.size,txid:a.hash,weight:a.weight}}async function Nn({chain:e,address:t,apiKey:n,offset:r=0,limit:s=30}){return(await Oe(`${he(e)}/outputs?q=recipient(${t}),is_spent(false)&s=value(desc)&fields=is_spent,transaction_hash,index,value,script_hex,block_id,spending_signature_hex&limit=${s}&offset=${r}`,n)).map(({is_spent:p,script_hex:c,block_id:u,transaction_hash:i,index:l,value:h,spending_signature_hex:m})=>({hash:i,index:l,is_confirmed:u!==-1,is_spent:p,script_hex:c,txHex:m,value:h}))}function Zn(e){return e.reduce((t,n)=>t+n.value,0)}function Ot(e,t){let n=[...e].sort((r,s)=>s.value-r.value);if(t){let r=[],s=0;for(let a of n)if(r.push(a),s+=a.value,s>=t)break;return r}return n}async function Bt({chain:e,address:t,apiKey:n,targetValue:r,accumulativeValue:s=0,offset:a=0,limit:d=30}){if(!t)throw new H("toolbox_utxo_invalid_params",{error:"Address is required"});try{let o=await Nn({address:t,apiKey:n,chain:e,limit:d,offset:a,targetValue:r}),c=o.length<d,u=o.filter(({is_spent:y})=>!y),i=Zn(u),l=s+i,h=r&&l>=r;if(c||h)return Ot(u,r);let m=await Bt({accumulativeValue:l,address:t,apiKey:n,chain:e,limit:d,offset:a+d,targetValue:r}),f=[...u,...m];return Ot(f,r)}catch(o){let p=o instanceof Error?o.message:String(o);return console.error(`Failed to fetch unspent UTXOs: ${p}`),[]}}async function zn({address:e,chain:t,apiKey:n,fetchTxHex:r=!0,targetValue:s}){let a=await Bt({address:e,apiKey:n,chain:t,targetValue:s}),d=r?await Promise.all(a.map(({hash:o})=>Xt({apiKey:n,chain:t,txHash:o}))):[];return a.map(({hash:o,index:p,script_hex:c,value:u},i)=>({address:e,hash:o,index:p,txHex:r?d[i]:void 0,value:u,witnessUtxo:{script:Buffer.from(c,"hex"),value:u}}))}function A(e){let t=kn.get("apiKeys").blockchair||"";return Kn({condition:!t,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(n)=>Fn({chain:e,txHash:n}),getAddressData:(n)=>Ct({address:n,apiKey:t,chain:e}),getBalance:(n)=>Rn({address:n,apiKey:t,chain:e}),getBlockHeight:()=>Hn({apiKey:t,chain:e}),getRawTx:(n)=>Xt({apiKey:t,chain:e,txHash:n}),getSuggestedTxFee:()=>In(e),getTransactionDetails:(n)=>Mn({apiKey:t,chain:e,txHash:n}),getUtxos:(n)=>zn({...n,apiKey:t,chain:e})}}function Hs(e){return e}function Rs(){return function(t){switch(t){case C.Bitcoin:return le.bitcoin;case C.BitcoinCash:return le.bitcoinCash;case C.Dash:return le.dash;case C.Litecoin:return le.litecoin;case C.Dogecoin:return le.dogecoin;case C.Zcash:return le.zcash;default:throw new H("toolbox_utxo_not_supported",{chain:t})}}}import{sha256 as Yn}from"@noble/hashes/sha2.js";import{createBase58check as jn}from"@scure/base";import{SwapKitError as Kt}from"@swapkit/helpers";import{CashAddrType as Ee,decodeCashAddr as Wn,encodeCashAddr as Ln}from"@swapkit/utxo-signer";var $n={P2PKH:Ee.P2PKH,P2SH:Ee.P2SH},Vn={[Ee.P2PKH]:"P2PKH",[Ee.P2SH]:"P2SH"};function qn(e,t,n){return Ln({hash:n,prefix:e,type:$n[t]})}function Gn(e){let t=Wn(e),n=Vn[t.type];if(!n)throw Error(`Unknown CashAddr type: ${t.type}`);return{hash:t.hash,prefix:t.prefix,type:n}}var st={decode:Gn,encode:qn};var Ft=jn(Yn);var Dt;((n)=>{n.Mainnet="mainnet";n.Testnet="testnet"})(Dt||={});var te={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}},Jn={["p2pkh"]:"pkh",["p2sh"]:"sh"};function $s(e){return Ne(e)!==void 0}function Vs(e){return ot(e).network}function G(e){let t=ot(e);if(t.format==="legacy")return e;return tr(t)}function Me(e){let t=ot(e);return nr(t)}function Ne(e){if(typeof e!=="string")return;let t=Qn(e)??er(e);return t&&{...t,scriptType:Jn[t.type]}}function ot(e){let t=Ne(e);if(!t)throw new Kt("toolbox_utxo_invalid_address",{address:e});return t}function Qn(e){try{let t=Ft.decode(e);if(t.length!==21)throw new Kt("toolbox_utxo_invalid_address",{address:e});let n=t[0],r=Array.prototype.slice.call(t,1);switch(n){case te.legacy.mainnet.p2pkh:return{format:"legacy",hash:r,network:"mainnet",type:"p2pkh"};case te.legacy.mainnet.p2sh:return{format:"legacy",hash:r,network:"mainnet",type:"p2sh"};case te.legacy.testnet.p2pkh:return{format:"legacy",hash:r,network:"testnet",type:"p2pkh"};case te.legacy.testnet.p2sh:return{format:"legacy",hash:r,network:"testnet",type:"p2sh"};case te.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2pkh"};case te.bitpay.mainnet.p2sh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function er(e){if(e.indexOf(":")!==-1)try{return kt(e)}catch{}else{let t=["bitcoincash","bchtest","bchreg"];for(let n of t)try{return kt(`${n}:${e}`)}catch{}}return}function kt(e){try{let{hash:t,prefix:n,type:r}=st.decode(e);return{format:"cashaddr",hash:Array.prototype.slice.call(t,0),network:n==="bitcoincash"?"mainnet":"testnet",type:r==="P2PKH"?"p2pkh":"p2sh"}}catch{return}}function tr(e){let t=te.legacy[e.network][e.type],n=Buffer.alloc(1+e.hash.length);return n[0]=t,n.set(e.hash,1),Ft.encode(n)}function nr(e){let t=e.network==="mainnet"?"bitcoincash":"bchtest",n=e.type==="p2pkh"?"P2PKH":"P2SH",r=new Uint8Array(e.hash);return st.encode(t,n,r)}import{Chain as oe,SwapKitError as Tt}from"@swapkit/helpers";import{SwapKitError as qe,UTXO_SCRIPT_TYPE_LIST as Ar,UTXO_SCRIPT_TYPES as $t,UTXOScriptType as Ge}from"@swapkit/helpers";import{Script as Or}from"@swapkit/utxo-signer";import{Chain as at}from"@swapkit/helpers";import{getAddressScriptType as sr,getTransparentZcashAddressType as or,getZcashAddressType as ar}from"@swapkit/utxo-signer";import{match as ir}from"ts-pattern";import{Chain as fe}from"@swapkit/helpers";import{NETWORKS as Te}from"@swapkit/utxo-signer";import{match as rr}from"ts-pattern";function U(e){return rr(e).with(fe.Bitcoin,()=>Te.bitcoin).with(fe.BitcoinCash,()=>Te.bitcoinCash).with(fe.Dash,()=>Te.dash).with(fe.Dogecoin,()=>Te.dogecoin).with(fe.Litecoin,()=>Te.litecoin).with(fe.Zcash,()=>Te.zcash).exhaustive()}function z(e){return e.replace(/(bchtest:|bitcoincash:)/,"")}function Se(e){if(typeof e!=="string")return null;let t=Ne(z(e));if(!t||t.network!=="mainnet")return null;return t.scriptType}var cr=["sprout","sapling","unified"];function dr(e){let t=or(e,U(at.Zcash));if(t)return t;let n=ar(e);return n&&cr.includes(n)?n:null}function Y({address:e,chain:t}){return ir(t).with(at.BitcoinCash,()=>Se(e)).with(at.Zcash,()=>dr(e)).otherwise(()=>sr(e,U(t)))}import{Chain as ne,derivationPathToString as It,getPurposeFromPath as ur,getUTXOScriptTypeForPath as Ht,getUTXOScriptTypeForPurpose as Mt,resolveDerivationPath as pr,SwapKitError as Ce,UTXO_SCRIPT_TYPE_LIST as Rt,UTXO_SCRIPT_TYPES as me,UTXOChains as lr,UTXOScriptType as O,updateDerivationPath as hr,warnOnce as fr}from"@swapkit/helpers";import{CashAddrPrefix as Tr,CashAddrType as mr,encodeCashAddr as yr,OutScript as Nt,p2pkh as gr,p2sh as xr,p2tr as br,p2wpkh as Et}from"@swapkit/utxo-signer";var Ze=Object.freeze([O.P2PKH]),wr=Object.freeze({[ne.Bitcoin]:Rt,[ne.BitcoinCash]:Ze,[ne.Dash]:Ze,[ne.Dogecoin]:Ze,[ne.Litecoin]:Rt,[ne.Zcash]:Ze});function We(e){return wr[e]}function it(e){return We(e).some((t)=>me[t].witness)}function ye(e,t){return We(e).includes(t)}function Le(e,t){if(ye(e,t))return t;throw new Ce("toolbox_utxo_unsupported_script_type",{chain:e,error:`${e} cannot encode ${t}; supported: ${We(e).join(", ")}`,scriptType:t,supported:We(e)})}var Zt=lr.filter((e)=>!it(e));function Pr({purpose:e,scriptType:t}){let n=Mt(e);return n===void 0||n===t}function ct({chain:e,purpose:t,scriptType:n}){fr({condition:!Pr({purpose:t,scriptType:n}),id:`utxo_off_standard_encoding_${e}_${t}_${n}`,warning:`${e}: encoding m/${t}' keys as ${n}, not the ${Mt(t)} the path implies. No other wallet derives these addresses: move funds out of them, never receive into them.`})}function $e({chain:e,derivationPath:t,index:n=0,scriptType:r}){if(t){if(!r){let o=Ht(t);throw new Ce("toolbox_utxo_invalid_params",{chain:e,derivationPath:It(t),error:`scriptType is required alongside derivationPath: getUTXOScriptTypeForPath gives the standard one${o?` (${o})`:""}, or state another deliberately.`})}return Le(e,r),ct({chain:e,purpose:ur(t),scriptType:r}),{derivationPath:t,scriptType:r}}let s=pr({chain:e,index:n}),a=r?hr(s,{purpose:me[r].purpose}):s,d=r??Ht(a);if(!d)throw new Ce("toolbox_utxo_invalid_params",{chain:e,derivationPath:It(a),error:`${e}: the default derivation path has no standard script type`});return Le(e,d),{derivationPath:a,scriptType:d}}function Ur(e){return e.length===32?e:e.slice(1)}function ze(e,t){if(!e.address)throw new Ce("toolbox_utxo_invalid_address",{error:`Could not derive a ${t} address`});return e}var vr={[O.P2PKH]:(e,t)=>{let{address:n,script:r}=ze(gr(e,t),O.P2PKH);return{address:n,script:r}},[O.P2SH_P2WPKH]:(e,t)=>{let n=Et(e,t),{address:r,script:s}=ze(xr(n,t),O.P2SH_P2WPKH);return{address:r,redeemScript:n.script,script:s}},[O.P2WPKH]:(e,t)=>{let{address:n,script:r}=ze(Et(e,t),O.P2WPKH);return{address:n,script:r}},[O.P2TR]:(e,t)=>{let n=Ur(e),{address:r,script:s}=ze(br(n,void 0,t),O.P2TR);return{address:r,script:s,tapInternalKey:n}}};function Ve(e,t,n){return vr[e](t,n)}function dt(e,t){if(e!==ne.BitcoinCash)return t.address;let n=Nt.decode(t.script);if(n.type!=="pkh")throw new Ce("toolbox_utxo_invalid_address",{chain:e,error:`Cannot encode ${n.type} as CashAddr`});return yr({hash:n.hash,prefix:Tr.MAINNET,type:mr.P2PKH}).replace(/^bitcoincash:/,"")}var _r=Object.freeze({pkh:O.P2PKH,sh:O.P2SH_P2WPKH,tr:O.P2TR,wpkh:O.P2WPKH}),zt=Object.freeze({pkh:me[O.P2PKH].outputSize,sh:me[O.P2SH_P2WPKH].outputSize,tr:me[O.P2TR].outputSize,wpkh:me[O.P2WPKH].outputSize,wsh:43});function Wt(e){return e in zt}function Lt(e){return Wt(e)?zt[e]:void 0}function Xe(e){return _r[e]}function ut(e){try{let{type:t}=Nt.decode(e);return Wt(t)?Xe(t):void 0}catch{return}}import{UTXOScriptType as se}from"@swapkit/helpers";var ho=1000,lt=10,Sr=2,Cr=10;function R(e){let t=new Uint8Array(Buffer.from(e,"utf8"));return Or.encode(["RETURN",t])}function Vt(e){return Object.fromEntries(Ar.map((t)=>[t,$t[t][e]]))}var qt=Vt("inputSize"),pt=Vt("outputSize"),ht=(e)=>$t[e].witness,Ye=(e,t)=>{let n=Y({address:e,chain:t});if(!n)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let r=Xe(n);if(!r||!ye(t,r))throw new qe("toolbox_utxo_unsupported_script_type",{address:e,addressType:n,chain:t,error:"Address is valid but its script type is not one the SDK spends from"});return r},Xr=(e,t)=>{let n=Y({address:e,chain:t});if(!n)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let r=Lt(n);if(!r)throw new qe("toolbox_utxo_unsupported_script_type",{address:e,addressType:n,chain:t,error:"Address is valid but a transparent transaction cannot pay to it"});return r},ge=({chain:e,inputs:t,outputs:n,feeRate:r})=>{let s=t[0]?Be(t[0],e):Ge.P2PKH,a=r?t.filter((u)=>u.value>=qt["type"in u&&u.type?u.type:Ge.P2PKH]*Math.ceil(r)):t,d=0,o=0;for(let u of a)if(d+=re(u,e),!ht(Be(u,e)))o++;let p=n?.reduce((u,i)=>u+je(i,e),0)||pt[s],c=o<a.length;return lt+d+p+ft(c,o)},Be=(e,t)=>{if("type"in e&&e.type)return e.type;if("address"in e&&e.address)return Ye(e.address,t);return Ge.P2PKH},re=(e,t)=>qt[Be(e,t)],ft=(e,t)=>e?Math.ceil((Sr+t)/4):0,je=(e,t,n)=>{if(e?.script)return Cr+e.script.length+(e.script.length>=74?2:1);if(n)return pt[n];if("address"in e&&e.address)return Xr(e.address,t);return pt[Ge.P2PKH]};function ke(e){switch(e){case oe.Bitcoin:case oe.BitcoinCash:return 550;case oe.Dash:case oe.Litecoin:return 5500;case oe.Dogecoin:return 1e5;case oe.Zcash:return 546;default:throw new Tt("toolbox_utxo_not_supported",{chain:e})}}function E({inputs:e,outputs:t,feeRate:n=1,chain:r=oe.Bitcoin,changeAddress:s="",sweep:a=!1}){let d=ke(r),o=e.filter((f)=>{let y=re(f,r)*n;return a?f.value>Math.max(y,d):y<=f.value});if(a){let f=Math.ceil(n*ge({chain:r,inputs:o,outputs:t})),y=o.reduce((X,L)=>X+L.value,0),b=y-f;if(b<=d)throw new Tt("toolbox_sweep_amount_too_low",{available:y,dustThreshold:d,fee:f});let S=t.findIndex((X)=>("address"in X)&&X.address);if(S===-1)throw new Tt("toolbox_utxo_invalid_params",{error:"Sweep requires a recipient output"});return{fee:f,inputs:o,outputs:t.map((X,L)=>L===S?{...X,value:b}:X)}}let p=lt+t.reduce((f,y)=>f+je(y,r),0),c=t.reduce((f,y)=>f+y.value,0),u=0,i=0,l=!1,h=0,m=[];for(let f of o){if(u+=re(f,r),ht(Be(f,r)))l=!0;else i++;h+=f.value,m.push(f);let y=(p+u+ft(l,i))*n,b=y+c;if(h<b)continue;let S=h-b,X=n*je({address:s,value:0},r);if(S>X){let L=X+y,Pe=h-(c+Math.ceil(L));if(Pe>Math.max(re({value:0},r)*n,ke(r)))return{fee:Math.ceil(L),inputs:m,outputs:t.concat({address:s,value:Pe})}}return{fee:Math.ceil(y),inputs:m,outputs:t}}return{fee:Math.ceil(n*ge({chain:r,inputs:e,outputs:t}))}}import{Chain as we,SwapKitError as Bs}from"@swapkit/helpers";import{hex as un}from"@scure/base";import{Chain as Yr,derivationPathToString as jr,FeeOption as Jr,resolveDerivationPath as Qr,SwapKitError as W}from"@swapkit/helpers";import{BCHSigHash as es,CashAddrPrefix as pn,CashAddrType as ln,encodeCashAddr as hn,NETWORKS as ts,p2pkh as fn,Transaction as Tn}from"@swapkit/utxo-signer";import{secp256k1 as Br}from"@noble/curves/secp256k1.js";import{hex as ae}from"@scure/base";import{HDKey as Jt}from"@scure/bip32";import{mnemonicToSeedSync as xt}from"@scure/bip39";import{AssetValue as mt,applyFeeMultiplier as Gt,Chain as Fe,derivationPathToString as Ke,FeeOption as M,NetworkDerivationPath as kr,SwapKitError as P,SwapKitNumber as Kr,UTXO_SCRIPT_TYPES as Fr,warnOnce as Dr}from"@swapkit/helpers";import{BCHSigHash as Qt,RBF_SEQUENCE as Ir,SigHash as Yt,Transaction as yt,utils as Hr,WIF as en}from"@swapkit/utxo-signer";var Je=[Fe.Bitcoin];function tn({address:e,chain:t}){return Y({address:e,chain:t})!==null}function Rr({phrase:e,derivationPath:t,network:n,seed:r}){let s=r??xt(e),d=Jt.fromMasterSeed(s,n.bip32).derive(t);if(!d.privateKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive private key from phrase"});return d.privateKey}function gt(e){return Br.getPublicKey(e,!0)}function De({publicKey:e,chain:t,network:n,scriptType:r}){return dt(t,Ve(r,e,n))}function xe({phrase:e,derivationPath:t,chain:n,wif:r,seed:s}){let a=U(n);if(r){let c=en(a).decode(r),u=gt(c);return{privateKey:c,publicKey:u}}if(!e)throw new P("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let d=t||Ke(kr[n]),o=Rr({derivationPath:d,network:a,phrase:e,seed:s}),p=gt(o);return{privateKey:o,publicKey:p}}function Er(e,t){return en(U(t)).encode(e)}function Mr({phrase:e,derivationPath:t,chain:n,seed:r}){let s=t.split("/");if(s.length<4)throw new P("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${s.length}): ${t}`});let a=U(n),d=r??xt(e),o=Jt.fromMasterSeed(d,a.bip32),p=s.slice(0,4).join("/");return o.derive(p)}function Nr(e,t){if(!e||!Fr[e].witness)return!1;return e!==se.P2SH_P2WPKH||!!t}function nn({chain:e,script:t,publicKey:n,network:r}){let s=ut(t);if(s!==se.P2SH_P2WPKH&&s!==se.P2TR)return{};if(!ye(e,s))return{};let a=Ve(s,n,r);if(Hr.compareBytes(a.script,t)!==0)return{};return s===se.P2TR?{tapInternalKey:a.tapInternalKey}:{redeemScript:a.redeemScript}}function Zr(e,t,n){if(!n)return!1;let r=Y({address:e,chain:t}),s=r?Xe(r):void 0;if(!s||!ye(t,s))return!1;let a=dt(t,Ve(s,n,U(t)));return t===Fe.BitcoinCash?z(a)===z(e):a===e}function zr(e){return e.witnessUtxo?.script??e.nonWitnessUtxo?.outputs[e.index??0]?.script}function bt({chain:e,tx:t,publicKey:n,network:r,indexes:s}){let a=s??Array.from({length:t.inputsLength},(o,p)=>p),d=[];for(let o of a){let p=t.getInput(o),c=zr(p);if(!c)continue;let{redeemScript:u,tapInternalKey:i}=nn({chain:e,network:r,publicKey:n,script:c}),l={index:o};if(u&&!p.redeemScript)l.redeemScript=u;if(i&&!p.tapInternalKey)l.tapInternalKey=i;if(l.redeemScript||l.tapInternalKey)d.push(l)}return d}function ie({inputs:e,outputs:t,chain:n,tx:r,sender:s,compiledMemo:a,enableRBF:d=!1}){let o=U(n),p=it(n),c=d?Ir:void 0,u=new Set;for(let i of e){let l=`${i.hash}:${i.index}`;if(u.has(l))throw new P("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});u.add(l);let h=typeof i.hash==="string"?ae.decode(i.hash):i.hash,m=i.witnessUtxo?ut(i.witnessUtxo.script):void 0,f=i.publicKey&&i.witnessUtxo?nn({chain:n,network:o,publicKey:i.publicKey,script:i.witnessUtxo.script}):{};if(p&&i.witnessUtxo&&Nr(m,f.redeemScript))r.addInput({...f,index:i.index,sequence:c,txid:h,witnessUtxo:{amount:BigInt(i.witnessUtxo.value),script:i.witnessUtxo.script}});else if(i.txHex)r.addInput({...f,index:i.index,nonWitnessUtxo:ae.decode(i.txHex),sequence:c,txid:h,...n===Fe.BitcoinCash?{sighashType:Qt.ALL}:{}});else throw new P("toolbox_utxo_invalid_params",{error:`Input ${l} cannot be signed from its witnessUtxo alone: it needs its previous transaction (txHex), or — if it is a nested-segwit output — the public key that controls it, which its redeemScript derives from`})}for(let i of t){let l="address"in i&&i.address?i.address:s;if(n===Fe.BitcoinCash)l=G(l);if(i.script)if(a)r.addOutput({amount:0n,script:a});else throw new P("toolbox_utxo_invalid_params",{error:"An output carrying a script needs the compiled memo it carries"});else r.addOutputAddress(l,BigInt(i.value),o)}return{inputs:e,tx:r}}async function be(e){let t=await A(e).getSuggestedTxFee();return{[M.Average]:t,[M.Fast]:Gt(t,M.Fast),[M.Fastest]:Gt(t,M.Fastest)}}async function rn({assetValue:e,recipient:t,memo:n,sender:r,sweep:s,fetchTxHex:a=!1,publicKey:d},o,{forEstimateOnly:p=!1}={}){let c=e.chain,u=Ye(r,c),i=u===se.P2PKH||u===se.P2SH_P2WPKH&&!Zr(r,c,d),l=a||!p&&i,h=e.getBaseValue("number"),m=s?void 0:o??(await be(c))[M.Fastest],f=s||m===void 0?void 0:Math.ceil(h+m*5000);return{inputs:await A(c).getUtxos({address:r,fetchTxHex:l,targetValue:f}),outputs:[{address:t,value:s?0:h},...n?[{address:"",script:R(n),value:0}]:[]]}}async function sn({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s,fetchTxHex:a=!1,enableRBF:d=!1,sweep:o,publicKey:p}){let c=e.chain,u=n?R(n):null,i=await rn({assetValue:e,fetchTxHex:a,memo:n,publicKey:p,recipient:t,sender:s,sweep:o},r),{inputs:l,outputs:h}=E({...i,chain:c,changeAddress:s,feeRate:r,sweep:o});if(!(l&&h))throw new P("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let m=p?l.map((S)=>({...S,publicKey:p})):l,f=new yt({allowUnknownOutputs:!!u,version:1}),{inputs:y,tx:b}=ie({chain:c,compiledMemo:u,enableRBF:d,inputs:m,outputs:h,sender:s,tx:f});return{inputs:y,tx:b,utxos:i.inputs}}async function on({assetValue:e,feeOptionKey:t=M.Fast,feeRate:n,memo:r,sender:s,recipient:a,sweep:d}){let o=e.chain,p,c;if(n!==void 0)p=n,c=Math.floor(n);else{let i=await be(o);p=i[M.Fastest],c=i[t]}let u=await rn({assetValue:e,memo:r,recipient:a,sender:s,sweep:d},p,{forEstimateOnly:!0});return E({...u,chain:o,changeAddress:s,feeRate:c,sweep:d})}function Wr(e){return async function({from:n,memo:r,feeRate:s,feeOptionKey:a=M.Fast,recipient:d=n,recipients:o=1}){let p=s??(await be(e))[a],u=(await A(e).getUtxos({address:n,fetchTxHex:!1})).filter((f)=>f.value>Math.max(ke(e),re(f,e)*p));if(!u.length)return mt.from({chain:e});let i=typeof o==="number"?Math.max(o,1):o.length,l=typeof o==="number"||i===0?Array.from({length:i||1},()=>({address:d,value:0})):[...o];if(r)l.push({address:n,script:R(r),value:0});let{outputs:h}=E({chain:e,feeRate:p,inputs:u,outputs:l,sweep:!0}),m=h?.[0]?.value??0;return mt.from({chain:e,value:BigInt(m)})}}function Lr(e){return async function(n){let{fee:r}=await on(n);return mt.from({chain:e,value:Kr.fromBigInt(BigInt(r),8).getValue("string")})}}function $r({chain:e,phrase:t,derivationPath:n,scriptType:r,seed:s}){let a=U(e),{privateKey:d,publicKey:o}=xe({chain:e,derivationPath:n,phrase:t,seed:s}),p=an(e);return{getAddress:()=>De({chain:e,network:a,publicKey:o,scriptType:r}),privateKey:d,publicKey:o,signTransaction:(c)=>{for(let{index:u,...i}of bt({chain:e,network:a,publicKey:o,tx:c}))c.updateInput(u,i);return c.sign(d,p),c}}}function an(e){return e===Fe.BitcoinCash?[Qt.ALL]:[Yt.ALL,Yt.DEFAULT]}function Vr(e,t,n){return async function({memo:s,recipient:a,feeOptionKey:d,feeRate:o,assetValue:p,enableRBF:c=!1,sweep:u}){let i=await t?.getAddress();if(!(t&&i))throw new P("toolbox_utxo_no_signer");if(!a)throw new P("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});Dr({condition:c&&!Je.includes(e),id:`rbf_not_supported_${e}`,warning:`RBF (Replace-by-Fee) is not reliably supported on ${e}. Transaction will be created without RBF signaling.`});let l=c&&Je.includes(e),h=o||(await be(e))[d||M.Fast],{tx:m}=await sn({assetValue:p,enableRBF:l,feeRate:h,memo:s,publicKey:n,recipient:a,sender:i,sweep:u}),f=await t.signTransaction(m);return f.finalize(),A(e).broadcastTx(ae.encode(f.extract()))}}function cn(e){return(t)=>tn({address:t,chain:e})}function dn(e,{scriptType:t}){let n=U(e);return function(s){if(!s)throw new P("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return De({chain:e,network:n,publicKey:s.publicKey,scriptType:t})}}function qr(e){let t=e?.publicKey;if(t===void 0)return;if(t instanceof Uint8Array&&t.length===33)return t;throw new P("toolbox_utxo_invalid_params",{error:"signer.publicKey must be a 33-byte compressed public key (Uint8Array)"})}function ce(e){let{chain:t}=e,n=e.phrase?e:void 0;if(!n&&"derivationPath"in e&&e.derivationPath!==void 0)throw new P("toolbox_utxo_invalid_params",{error:"derivationPath needs a phrase; a toolbox built around a signer uses the signer's addresses"});let r=n?.phrase,s=n?.index??0,a=r?xt(r):void 0,{derivationPath:d,scriptType:o}=$e({chain:t,derivationPath:n?.derivationPath,index:s,scriptType:e.scriptType}),p=Ke(d),c=r?$r({chain:t,derivationPath:p,phrase:r,scriptType:o,seed:a}):void 0,u=n?void 0:e.signer,i=c||u,l=r?xe({chain:t,derivationPath:p,phrase:r,seed:a}):void 0,h=l?.publicKey??qr(u);function m(){if(i)return i.getAddress();return Promise.resolve(void 0)}function f(T){if(!r)return;let g=ee({accountIndex:T,chain:t,derivationPath:d});return Mr({chain:t,derivationPath:Ke(g),phrase:r,seed:a})}let y=f();function b(){if(!y)return;return y.publicExtendedKey}function S({accountIndex:T}={}){let g=T===void 0?y:f(T);if(!g)return;let w=ee({accountIndex:T,chain:t,derivationPath:d});return{accountIndex:pe(w),path:Ke(w),xpub:g.publicExtendedKey}}function X({accountIndex:T,index:g,change:w=!1}){let _=T===void 0?y:f(T);if(!_)return;let x=Ae({accountIndex:T,chain:t,change:w,derivationPath:d,index:g}),k=U(t),F=_.deriveChild(Number(w)).deriveChild(g);if(!F.publicKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let B=De({chain:t,network:k,publicKey:F.publicKey,scriptType:o}),K=ae.encode(F.publicKey);return{accountIndex:pe(x),address:B,change:w,index:g,path:Ke(x),pubkey:K}}async function L(T){if(!Je.includes(t))return{reason:`RBF is not supported on ${t}`,supported:!1};let g=await A(t).getTransactionDetails(T);return{canReplace:g.isRBF&&!g.confirmed,confirmed:g.confirmed,enabled:g.isRBF,fee:g.fee,sequences:g.sequences,supported:!0}}async function Pe({txid:T,newFeeRate:g,recipient:w,memo:_}){if(!Je.includes(t))throw new P("toolbox_utxo_rbf_not_supported",{chain:t});let x=await A(t).getTransactionDetails(T);if(!x.isRBF)throw new P("toolbox_utxo_tx_not_replaceable",{txid:T});if(x.confirmed)throw new P("toolbox_utxo_tx_already_confirmed",{blockId:x.blockId,txid:T});let k=x.inputs.reduce((v,I)=>v+I.value,0),B=x.outputs.find((v)=>v.recipient===w)?.value||0;if(B===0)throw new P("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let K=await Promise.all(x.inputs.map(async(v)=>{let I=await A(t).getRawTx(v.transaction_hash);return{address:v.recipient,hash:v.transaction_hash,index:v.index,publicKey:h,txHex:I,value:v.value,witnessUtxo:void 0}})),D=_?R(_):null,J=k-B-x.fee,Ue=await m(),ue=[];if(D)ue.push({address:"",script:D,value:0});if(J>ke(t)&&Ue)ue.push({address:Ue,value:J});let He=ge({chain:t,inputs:K.map((v)=>({...v,type:Ye(v.address,t)})),outputs:[{address:w,value:B},...ue]}),V=Math.ceil(He*g);if(V<=x.fee)throw new P("toolbox_utxo_rbf_fee_too_low",{newFee:V,originalFee:x.fee});let ve=V-x.fee,Q=B-ve;if(Q<=0)throw new P("toolbox_utxo_rbf_insufficient_change");let _e=new yt({allowUnknownOutputs:!!D,version:1}),tt=[{address:w,value:Q},...ue];return ie({chain:t,compiledMemo:D,inputs:K,outputs:tt,sender:Ue||w,tx:_e}),{feeDelta:ve,newFee:V,originalFee:x.fee,tx:_e}}async function vn({txid:T,newFeeRate:g,recipient:w,memo:_}){let{tx:x,originalFee:k,newFee:F}=await Pe({memo:_,newFeeRate:g,recipient:w,txid:T}),B=await et(x);B.finalize();let K=await A(t).broadcastTx(ae.encode(B.extract()));return{newFee:F,originalFee:k,txid:K}}function vt({accountIndex:T,index:g,change:w=!1}){Z("index",g);let _=T===void 0?y:f(T);if(!_)return;return _.deriveChild(Number(w)).deriveChild(g).privateKey||void 0}function _t({tx:T,inputDerivations:g}){if(!y)throw new P("toolbox_utxo_no_signer");let w=an(t),_=U(t);for(let x=0;x<g.length;x++){let k=g[x];if(!k)continue;let{derivationIndex:F,isChange:B}=k,K=vt({change:B,index:F});if(!K)throw new P("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${x} at index ${F}`});for(let{index:D,...J}of bt({chain:t,indexes:[x],network:_,publicKey:gt(K),tx:T}))T.updateInput(D,J);T.signIdx(K,x,w)}return T}async function _n({utxos:T,recipient:g,assetValue:w,memo:_,feeRate:x,feeOptionKey:k,changeAddress:F,sweep:B}){if(B)throw new P("toolbox_utxo_invalid_params",{error:"Sweep is not supported for transfers from multiple addresses"});if(!y)throw new P("toolbox_utxo_no_signer");let K=x||(await be(t))[k||M.Fast],D=_?R(_):null,J=[{address:g,value:w.getBaseValue("number")}];if(D)J.push({address:"",script:D,value:0});let Ue=T.map(({address:v,hash:I,index:q,value:nt,txHex:Sn,witnessUtxo:rt})=>({address:v,hash:I,index:q,txHex:Sn,value:nt,witnessUtxo:rt?{script:rt.script,value:rt.value}:void 0})),ue=T[0]?.address,He=F||await m()||ue||g,{inputs:V,outputs:ve}=E({chain:t,changeAddress:He,feeRate:K,inputs:Ue,outputs:J});if(!(V&&ve))throw new P("toolbox_utxo_insufficient_balance",{assetValue:w,sender:"multiple addresses"});let Q=new yt({allowUnknownOutputs:!!D,version:1}),_e=V.map((v)=>{let I=T.find((q)=>q.hash===v.hash&&q.index===v.index);return I?{derivationIndex:I.derivationIndex,isChange:I.isChange}:{derivationIndex:0,isChange:!1}}),tt=V.map((v,I)=>{let q=_e[I],nt=q?y.deriveChild(Number(q.isChange)).deriveChild(q.derivationIndex).publicKey:null;return{...v,publicKey:nt??void 0}});return ie({chain:t,compiledMemo:D,inputs:tt,outputs:ve,sender:He,tx:Q}),_t({inputDerivations:_e,tx:Q}),Q.finalize(),A(t).broadcastTx(ae.encode(Q.extract()))}function An({address:T,gapLimit:g=20}){if(!y)return;for(let w=0;w<g;w++){let _=X({change:!1,index:w}),x=X({change:!0,index:w}),k=_?.address===T?!1:x?.address===T;if(_?.address===T||x?.address===T)return{change:k,index:w}}return}function et(T){if(!i)throw new P("toolbox_utxo_no_signer");return i.signTransaction(T)}async function On(T){let g=await et(T);return g.finalize(),await A(t).broadcastTx(ae.encode(g.extract()))}return{accumulative:E,broadcastTx:(T)=>A(t).broadcastTx(T),bumpFee:vn,calculateTxSize:(T)=>ge({...T,chain:t}),createKeysForPath:(T)=>xe({...T,chain:t}),createReplacementTransaction:Pe,createTransaction:(T)=>sn({publicKey:h,...T}),deriveAddressAtIndex:X,derivePrivateKeyAtIndex:vt,estimateMaxSendableAmount:Wr(t),estimateTransactionFee:Lr(t),getAddress:m,getAddressFromKeys:dn(t,{scriptType:o}),getAddressType:(T)=>Y({address:T,chain:t}),getBalance:jt(t),getExtendedPublicKey:b,getExtendedPublicKeyInfo:S,getFeeRates:()=>be(t),getInputsOutputsFee:on,getNetworkForChain:()=>U(t),getPrivateKeyFromMnemonic:(T)=>Er(xe({...T,chain:t}).privateKey,t),isRBFEnabled:L,keys:l,resolveDerivationIndex:An,scriptType:o,signAndBroadcastTransaction:On,signTransaction:et,signTransactionWithMultipleKeys:_t,transfer:Vr(t,i,h),transferFromMultipleAddresses:_n,validateAddress:cn(t)}}import{getZcashAddressType as Gr,validateZcashAddress as wt}from"@swapkit/utxo-signer";function Ie(e){return Se(e)!==null}var N=Yr.BitcoinCash;function Qe(e){return z(Me(e))}function ns(e){let t=U(N);function n(s){return s.sign(e.privateKey,[es.ALL]),s}function r(){let s=fn(e.publicKey,t);if(!s.hash)throw new W("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let a=hn({hash:s.hash,prefix:pn.MAINNET,type:ln.P2PKH});return Promise.resolve(a.replace(/^bitcoincash:/,""))}return{getAddress:r,signTransaction:n}}function mn(e={}){let t="phrase"in e?e.phrase:void 0,n="index"in e?e.index||0:0,r="derivationPath"in e?e.derivationPath:void 0,s=Qr({chain:N,derivationPath:r,index:n}),a=jr(s),d=t?xe({chain:N,derivationPath:a,phrase:t}):void 0,o=d?ns(d):("signer"in e)?e.signer:void 0;function p(){return Promise.resolve(o?.getAddress())}let c="scriptType"in e?e.scriptType:void 0,{getBalance:u,getFeeRates:i,broadcastTx:l,...h}=ce(t?{chain:N,index:n,phrase:t,...r?{derivationPath:r,scriptType:c}:{scriptType:c}}:{chain:N,scriptType:c});function m(b,S=!0){return u(z(Me(b)))}function f(b){if(!o)throw new W("toolbox_utxo_no_signer");return o.signTransaction(b)}async function y(b){let S=await f(b);return S.finalize(),await l(un.encode(S.extract()))}return{...h,broadcastTx:l,buildTx:ss,createTransaction:yn,getAddress:p,getAddressFromKeys:os,getBalance:m,getFeeRates:i,signAndBroadcastTransaction:y,signTransaction:f,stripPrefix:z,stripToCashAddress:Qe,transfer:rs({broadcastTx:l,getFeeRates:i,signer:o}),validateAddress:Ie}}async function yn({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s,sweep:a}){if(!Ie(t))throw new W("toolbox_utxo_invalid_address",{address:t});let d=Math.ceil(e.getBaseValue("number")+r*7500),o=await A(N).getUtxos({address:Qe(s),fetchTxHex:!0,targetValue:a?void 0:d}),p=n?R(n):null,c=[],u=G(t);if(c.push({address:u,value:a?0:e.getBaseValue("number")}),p)c.push({script:p,value:0});let{inputs:i,outputs:l}=E({chain:N,feeRate:r,inputs:o,outputs:c,sweep:a});if(!(i&&l))throw new W("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let h=new Tn({allowUnknownOutputs:!!p,version:1}),m=G(s),{inputs:f,tx:y}=ie({chain:N,compiledMemo:p,inputs:i,outputs:l.map((b)=>("address"in b)&&b.address?{...b,address:G(b.address)}:b),sender:m,tx:h});return{inputs:f,tx:y,utxos:i}}function rs({broadcastTx:e,getFeeRates:t,signer:n}){return async function({recipient:s,assetValue:a,feeOptionKey:d=Jr.Fast,sweep:o,...p}){let c=await n?.getAddress();if(!(n&&c))throw new W("toolbox_utxo_no_signer");if(!s)throw new W("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let u=p.feeRate||(await t())[d],{tx:i}=await yn({...p,assetValue:a,feeRate:u,recipient:s,sender:c,sweep:o}),l=await n.signTransaction(i);return l.finalize(),e(un.encode(l.extract()))}}async function ss({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s}){let a=Me(t);if(!Ie(a))throw new W("toolbox_utxo_invalid_address",{address:a});let d=Math.ceil(e.getBaseValue("number")+r*7500),o=await A(N).getUtxos({address:Qe(s),fetchTxHex:!0,targetValue:d}),p=Number(r.toFixed(0)),c=n?R(n):null,u=[];if(u.push({address:G(t),value:e.getBaseValue("number")}),c)u.push({script:c,value:0});let{inputs:i,outputs:l}=E({chain:N,feeRate:p,inputs:o,outputs:u});if(!(i&&l))throw new W("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let h=new Tn({allowUnknownOutputs:!!c,version:1}),{inputs:m,tx:f}=ie({chain:N,compiledMemo:c,inputs:i,outputs:l,sender:G(s),tx:h});return{inputs:m,tx:f,utxos:o}}function os(e){let t=ts.bitcoinCash,n=fn(e.publicKey,t);if(!n.hash)throw new W("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return hn({hash:n.hash,prefix:pn.MAINNET,type:ln.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as as,hex as is}from"@scure/base";import{HDKey as bn}from"@scure/bip32";import{mnemonicToSeedSync as wn}from"@scure/bip39";import{Chain as j,derivationPathToString as cs,FeeOption as ds,SwapKitError as de}from"@swapkit/helpers";import{Address as us,createZcashTransaction as ps,getZcashConsensusBranchId as ls,isTransparentZcashAddress as gn,OutScript as hs,PCZT as fs,utils as Pn,WIF as Ts,ZcashConsensusBranchId as ms,ZcashPSBT as ys,ZcashSigHash as Pt,ZcashVersionGroupId as gs}from"@swapkit/utxo-signer";import{match as xs,P as Ut}from"ts-pattern";var bs=as(Pn.sha256);function ws(e){return bs.encode(e)}function Ps({phrase:e,derivationPath:t}){let n=wn(e),s=bn.fromMasterSeed(n).derive(t);if(!s.privateKey||!s.publicKey)throw new de("toolbox_utxo_invalid_params");let{privateKey:a,publicKey:d}=s,o=Pn.hash160(d),p=new Uint8Array([28,184]),c=new Uint8Array(p.length+o.length);c.set(p,0),c.set(o,p.length);let u=ws(c);return{getAddress:()=>Promise.resolve(u),signTransaction:(i)=>{if(i instanceof ys){let l=i.toPCZT();return l.signAllInputs(a,d,Pt.ALL),l.finalizeAllInputs(),Promise.resolve(l.extract())}if(i instanceof fs)return i.signAllInputs(a,d,Pt.ALL),i.finalizeAllInputs(),Promise.resolve(i.extract());return i.signAllInputs(a,d,Pt.ALL),Promise.resolve(i)}}}function Us({inputs:e,outputs:t,tx:n,sender:r,compiledMemo:s}){let a=U(j.Zcash);for(let d of e){let o=us(a).decode(r),p=hs.encode(o);n.addInput({index:d.index,script:p,sequence:4294967295,txid:is.decode(d.hash),value:BigInt(d.value)})}for(let d of t){let o="address"in d&&d.address?d.address:r,p=d.script;if(p&&!s)continue;if(p&&s)n.addOutput({amount:0n,script:s});else n.addOutputAddress(o,BigInt(d.value),a)}return{inputs:e,tx:n}}async function vs(){try{let e=await A(j.Zcash).getBlockHeight();return ls(e+1)}catch{return ms.IRONWOOD}}async function xn(e){let{assetValue:t,recipient:n,memo:r,feeRate:s,sender:a,fetchTxHex:d,sweep:o}=e,p=U(j.Zcash);if(!gn(a,p))throw new de("toolbox_utxo_invalid_address",{address:a});if(!gn(n,p))throw new de("toolbox_utxo_invalid_address",{address:n,error:"Zcash transaction creation currently supports transparent addresses only"});let c=r?R(r):null,u=await A(j.Zcash).getUtxos({address:a,fetchTxHex:d!==!1}),i=[{address:n,value:o?0:Number(t.getBaseValue("string"))},...c?[{script:c,value:0}]:[]],{inputs:l,outputs:h}=E({chain:j.Zcash,changeAddress:a,feeRate:s,inputs:u,outputs:i,sweep:o});if(!(l&&h))throw new de("toolbox_utxo_insufficient_balance",{assetValue:t,sender:a});let m=ps({consensusBranchId:await vs(),expiryHeight:0,lockTime:0,version:4,versionGroupId:gs.SAPLING}),{tx:f,inputs:y}=Us({compiledMemo:c,inputs:l,outputs:h,sender:a,tx:m});return{inputs:y,outputs:h,tx:f}}function Un(e={}){let t="scriptType"in e?e.scriptType:void 0,n=xs(e).with({signer:Ut.not(Ut.nullish)},({signer:c})=>c).with({phrase:Ut.string},({phrase:c,derivationPath:u,index:i=0})=>{let{derivationPath:l}=$e({chain:j.Zcash,derivationPath:u,index:i,scriptType:t}),h=cs(l);return Ps({derivationPath:h,phrase:c})}).otherwise(()=>{return}),r=ce({chain:j.Zcash,scriptType:t,signer:n});async function s(c){if(!n)throw new de("toolbox_utxo_no_signer");return await n.signTransaction(c)}async function a(c){let u=await s(c);return r.broadcastTx(u.toHex())}async function d({recipient:c,assetValue:u,feeOptionKey:i=ds.Fast,sweep:l,...h}){let m=await n?.getAddress();if(!(n&&m))throw new de("toolbox_utxo_no_signer");let f=h.feeRate||(await r.getFeeRates())[i],{tx:y}=await xn({...h,assetValue:u,feeRate:f,recipient:c,sender:m,sweep:l}),S=(await n.signTransaction(y)).toHex();return r.broadcastTx(S)}function o({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let i=wn(c),h=bn.fromMasterSeed(i).derive(u);if(!h.privateKey||!h.publicKey)throw new de("toolbox_utxo_invalid_params");return{privateKey:h.privateKey,publicKey:h.publicKey}}function p({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let i=o({derivationPath:u,phrase:c}),l=U(j.Zcash);return Ts(l).encode(i.privateKey)}return{...r,createKeysForPath:o,createTransaction:xn,getPrivateKeyFromMnemonic:p,signAndBroadcastTransaction:a,signTransaction:s,transfer:d,validateAddress:wt}}import{hex as _s}from"@scure/base";import{HDKey as As}from"@scure/bip32";import{derivationPathToString as Os,NetworkDerivationPath as Ss,updateDerivationPath as Cs}from"@swapkit/helpers";function Xs({xpub:e,chain:t,count:n,startIndex:r=0,accountIndex:s,purpose:a,scriptType:d}){if(Z("count",n),n<1)throw RangeError("count must be at least 1");Z("startIndex",r),Le(t,d),ct({chain:t,purpose:a,scriptType:d});let o=U(t),p=As.fromExtendedKey(e,o.bip32),c=a===void 0?void 0:Cs(Ss[t],{purpose:a}),u=ee({accountIndex:s,chain:t,derivationPath:c}),i=pe(u),l=[];for(let h of[!1,!0]){let m=p.deriveChild(Number(h));for(let f=0;f<n;f++){let y=r+f,b=m.deriveChild(y);if(!b.publicKey)continue;let S=Ae({accountIndex:s,chain:t,change:h,derivationPath:c,index:y});l.push({accountIndex:i,address:De({chain:t,network:o,publicKey:b.publicKey,scriptType:d}),change:h,index:y,pubkey:_s.encode(b.publicKey),...a===void 0?{}:{path:Os(S)}})}}return l}function ga(e,t){switch(e){case we.BitcoinCash:return mn(t||{});case we.Zcash:return Un(t);case we.Bitcoin:case we.Dogecoin:case we.Litecoin:case we.Dash:return ce({chain:e,...t});default:throw new Bs("toolbox_utxo_not_supported",{chain:e})}}export{qt as InputSizes,ho as MIN_TX_FEE,Cr as OP_RETURN_OVERHEAD,pt as OutputSizes,Sr as SEGWIT_MARKER_FLAG_WEIGHT,lt as TX_OVERHEAD,se as UTXOScriptType,Dt as UtxoNetwork,E as accumulative,ie as addInputsAndOutputs,dn as addressFromKeysGetter,Z as assertDerivationIndex,ge as calculateTxSize,R as compileMemo,mn as createBCHToolbox,Hs as createCustomUtxoApi,Xn as createHDWalletHelpers,ce as createUTXOToolbox,Un as createZcashToolbox,Xs as deriveAddressesFromXpub,Vs as detectAddressNetwork,Se as getBchAddressType,ke as getDustThreshold,Be as getInputScriptType,re as getInputSize,bt as getMissingSpendingMetadata,U as getNetworkForChain,je as getOutputSize,Xr as getOutputSizeForAddress,Ye as getScriptTypeForAddress,pe as getUTXOAccountIndexFromPath,ee as getUTXOAccountPath,Ae as getUTXOAddressPath,cn as getUTXOAddressValidator,Y as getUtxoAddressType,A as getUtxoApi,Rs as getUtxoNetwork,ga as getUtxoToolbox,ft as getWitnessOverhead,Gr as getZcashAddressType,ht as isSegwitScriptType,$s as isValidAddress,Zt as nonSegwitChains,z as stripPrefix,Qe as stripToCashAddress,Me as toCashAddress,G as toLegacyAddress,Ne as tryDecodeAddress,Ie as validateBchAddress,tn as validateUtxoAddress,wt as validateZcashAddress};
1
+ import{ha as St,ia as jt}from"../../chunk-xdkdc1f0.js";import"../../chunk-exyqap7m.js";import{NetworkDerivationPath as Cn}from"@swapkit/helpers";function z(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`${e} must be a non-negative integer, got: ${t}`)}function te({accountIndex:e,chain:t,derivationPath:n}){if(e!==void 0)z("accountIndex",e);let[r,s,a]=n??Cn[t];return[r,s,e??a]}function Ae({accountIndex:e,change:t=!1,chain:n,derivationPath:r,index:s}){return z("index",s),[...te({accountIndex:e,chain:n,derivationPath:r}),Number(t),s]}function pe(e){return e[2]??0}function Xn({deriveAddress:e,getBalance:t,getUtxos:n}){async function r(o){let{accountIndex:p,count:c,startIndex:u=0,change:i=!1}=o;if(z("count",c),c<1)throw RangeError("count must be at least 1");z("startIndex",u);let l=[];for(let h=0;h<c;h++){let m=await e({accountIndex:p,change:i,index:u+h});if(m)l.push(m)}return l}async function s(o){let{gapLimit:p=20,change:c=!1}=o??{},u=[],i=0,l=0;while(i<p){let h=await e({change:c,index:l});if(!h)break;if((await t(h.address)).some((y)=>y.getValue("number")>0))u.push(h),i=0;else i++;l++}return u}async function a(o=20){let[p,c]=await Promise.all([s({change:!1,gapLimit:o}),s({change:!0,gapLimit:o})]),u=[...p,...c],i=await Promise.all(u.map(async(h)=>{let f=(await t(h.address)).reduce((y,b)=>y+b.getValue("number"),0);return{...h,balance:f}})),l=i.reduce((h,m)=>h+m.balance,0);return{addresses:i,total:l}}async function d(o=20){let[p,c]=await Promise.all([s({change:!1,gapLimit:o}),s({change:!0,gapLimit:o})]),u=[...p,...c];return(await Promise.all(u.map(async(l)=>(await n(l.address)).map((m)=>({...m,address:l.address,derivationIndex:l.index,isChange:l.change}))))).flat()}return{deriveAddresses:r,getAggregatedBalance:a,getAggregatedUtxos:d,scanForAddresses:s}}import{Chain as C,getRPCUrl as Bn,RequestClient as Re,SKConfig as kn,SwapKitError as R,warnOnce as Kn}from"@swapkit/helpers";import{NETWORKS as le}from"@swapkit/utxo-signer";async function Fn({chain:e,txHash:t}){let n=`${he(e)}/push/transaction`,r=JSON.stringify({data:t});try{let s=await Re.post(n,{body:r,headers:{"Content-Type":"application/json"}});if(s.context.code!==200)throw new R("toolbox_utxo_broadcast_failed",{error:s.context.error||"Transaction broadcast failed"});return s.data?.transaction_hash||t}catch(s){let a=await Bn(e);if(a){let d=JSON.stringify({id:St(),jsonrpc:"2.0",method:"sendrawtransaction",params:[t]}),o=await Re.post(a,{body:d,headers:{"Content-Type":"application/json"}});if(o.error)throw new R("toolbox_utxo_broadcast_failed",{error:o.error?.message});if(o.result.includes('"code":-26'))throw new R("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return o.result}throw s}}function he(e){return`https://api.blockchair.com/${Dn(e)}`}function At(e){switch(e){case C.Bitcoin:return 5;case C.Dogecoin:return 1e4;case C.Litecoin:return 1;case C.Zcash:return 1;default:return 2}}function Dn(e){switch(e){case C.BitcoinCash:return"bitcoin-cash";case C.Litecoin:return"litecoin";case C.Dash:return"dash";case C.Dogecoin:return"dogecoin";case C.Zcash:return"zcash";case C.Polkadot:return"polkadot";default:return"bitcoin"}}async function In(e){try{let{feePerKb:t}=await Re.get(`https://app.bitgo.com/api/v2/${e.toLowerCase()}/tx/fee`),n=t/1000;return Math.max(n,At(e))}catch{return At(e)}}async function Oe(e,t){let n=await Re.get(`${e}${t?`${e.includes("?")?"&":"?"}key=${t}`:""}`);if(!n||n.context.code!==200)throw new R("toolbox_utxo_api_error",{error:`Failed to query ${e}`});return n.data}async function Hn({chain:e,apiKey:t}){let n=await Oe(`${he(e)}/stats`,t);if(typeof n.best_block_height!=="number")throw new R("toolbox_utxo_api_error",{error:"Missing best_block_height in stats response"});return n.best_block_height}async function Ct({address:e,chain:t,apiKey:n}){if(!e)throw new R("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await Oe(`${he(t)}/dashboards/address/${e}?transaction_details=true`,n))[e]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function Rn({address:e,chain:t,apiKey:n}){return(await Ct({address:e,apiKey:n,chain:t}))?.address.balance||0}async function Xt({chain:e,apiKey:t,txHash:n}){if(!n)throw new R("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await Oe(`${he(e)}/raw/transaction/${n}`,t))?.[n]?.raw_transaction||""}catch(r){let s=r instanceof Error?r.message:String(r);return console.error(`Failed to fetch raw transaction: ${s}`),""}}var En=4294967294;async function Mn({chain:e,apiKey:t,txHash:n}){if(!n)throw new R("toolbox_utxo_invalid_params",{error:"TxHash is required"});let s=(await Oe(`${he(e)}/dashboards/transaction/${n}`,t))?.[n];if(!s)throw new R("toolbox_utxo_tx_not_found",{txHash:n});let{transaction:a,inputs:d,outputs:o}=s,p=d.map((u)=>u.spending_sequence),c=a.is_rbf===!0||p.some((u)=>u<En);return{blockId:a.block_id,confirmed:a.block_id!==-1,fee:a.fee,inputs:d,isRBF:c,outputs:o,sequences:p,size:a.size,txid:a.hash,weight:a.weight}}async function Nn({chain:e,address:t,apiKey:n,offset:r=0,limit:s=30}){return(await Oe(`${he(e)}/outputs?q=recipient(${t}),is_spent(false)&s=value(desc)&fields=is_spent,transaction_hash,index,value,script_hex,block_id,spending_signature_hex&limit=${s}&offset=${r}`,n)).map(({is_spent:p,script_hex:c,block_id:u,transaction_hash:i,index:l,value:h,spending_signature_hex:m})=>({hash:i,index:l,is_confirmed:u!==-1,is_spent:p,script_hex:c,txHex:m,value:h}))}function Zn(e){return e.reduce((t,n)=>t+n.value,0)}function Ot(e,t){let n=[...e].sort((r,s)=>s.value-r.value);if(t){let r=[],s=0;for(let a of n)if(r.push(a),s+=a.value,s>=t)break;return r}return n}async function Bt({chain:e,address:t,apiKey:n,targetValue:r,accumulativeValue:s=0,offset:a=0,limit:d=30}){if(!t)throw new R("toolbox_utxo_invalid_params",{error:"Address is required"});try{let o=await Nn({address:t,apiKey:n,chain:e,limit:d,offset:a,targetValue:r}),c=o.length<d,u=o.filter(({is_spent:y})=>!y),i=Zn(u),l=s+i,h=r&&l>=r;if(c||h)return Ot(u,r);let m=await Bt({accumulativeValue:l,address:t,apiKey:n,chain:e,limit:d,offset:a+d,targetValue:r}),f=[...u,...m];return Ot(f,r)}catch(o){let p=o instanceof Error?o.message:String(o);return console.error(`Failed to fetch unspent UTXOs: ${p}`),[]}}async function zn({address:e,chain:t,apiKey:n,fetchTxHex:r=!0,targetValue:s}){let a=await Bt({address:e,apiKey:n,chain:t,targetValue:s}),d=r?await Promise.all(a.map(({hash:o})=>Xt({apiKey:n,chain:t,txHash:o}))):[];return a.map(({hash:o,index:p,script_hex:c,value:u},i)=>({address:e,hash:o,index:p,txHex:r?d[i]:void 0,value:u,witnessUtxo:{script:Buffer.from(c,"hex"),value:u}}))}function A(e){let t=kn.get("apiKeys").blockchair||"";return Kn({condition:!t,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(n)=>Fn({chain:e,txHash:n}),getAddressData:(n)=>Ct({address:n,apiKey:t,chain:e}),getBalance:(n)=>Rn({address:n,apiKey:t,chain:e}),getBlockHeight:()=>Hn({apiKey:t,chain:e}),getRawTx:(n)=>Xt({apiKey:t,chain:e,txHash:n}),getSuggestedTxFee:()=>In(e),getTransactionDetails:(n)=>Mn({apiKey:t,chain:e,txHash:n}),getUtxos:(n)=>zn({...n,apiKey:t,chain:e})}}function Hs(e){return e}function Rs(){return function(t){switch(t){case C.Bitcoin:return le.bitcoin;case C.BitcoinCash:return le.bitcoinCash;case C.Dash:return le.dash;case C.Litecoin:return le.litecoin;case C.Dogecoin:return le.dogecoin;case C.Zcash:return le.zcash;default:throw new R("toolbox_utxo_not_supported",{chain:t})}}}import{sha256 as Yn}from"@noble/hashes/sha2.js";import{createBase58check as jn}from"@scure/base";import{SwapKitError as Kt}from"@swapkit/helpers";import{CashAddrType as Ee,decodeCashAddr as Wn,encodeCashAddr as Ln}from"@swapkit/utxo-signer";var $n={P2PKH:Ee.P2PKH,P2SH:Ee.P2SH},Vn={[Ee.P2PKH]:"P2PKH",[Ee.P2SH]:"P2SH"};function qn(e,t,n){return Ln({hash:n,prefix:e,type:$n[t]})}function Gn(e){let t=Wn(e),n=Vn[t.type];if(!n)throw Error(`Unknown CashAddr type: ${t.type}`);return{hash:t.hash,prefix:t.prefix,type:n}}var ot={decode:Gn,encode:qn};var Ft=jn(Yn);var Dt;((n)=>{n.Mainnet="mainnet";n.Testnet="testnet"})(Dt||={});var ne={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}},Jn={["p2pkh"]:"pkh",["p2sh"]:"sh"};function $s(e){return Ne(e)!==void 0}function Vs(e){return at(e).network}function G(e){let t=at(e);if(t.format==="legacy")return e;return tr(t)}function Me(e){let t=at(e);return nr(t)}function Ne(e){if(typeof e!=="string")return;let t=Qn(e)??er(e);return t&&{...t,scriptType:Jn[t.type]}}function at(e){let t=Ne(e);if(!t)throw new Kt("toolbox_utxo_invalid_address",{address:e});return t}function Qn(e){try{let t=Ft.decode(e);if(t.length!==21)throw new Kt("toolbox_utxo_invalid_address",{address:e});let n=t[0],r=Array.prototype.slice.call(t,1);switch(n){case ne.legacy.mainnet.p2pkh:return{format:"legacy",hash:r,network:"mainnet",type:"p2pkh"};case ne.legacy.mainnet.p2sh:return{format:"legacy",hash:r,network:"mainnet",type:"p2sh"};case ne.legacy.testnet.p2pkh:return{format:"legacy",hash:r,network:"testnet",type:"p2pkh"};case ne.legacy.testnet.p2sh:return{format:"legacy",hash:r,network:"testnet",type:"p2sh"};case ne.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2pkh"};case ne.bitpay.mainnet.p2sh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function er(e){if(e.indexOf(":")!==-1)try{return kt(e)}catch{}else{let t=["bitcoincash","bchtest","bchreg"];for(let n of t)try{return kt(`${n}:${e}`)}catch{}}return}function kt(e){try{let{hash:t,prefix:n,type:r}=ot.decode(e);return{format:"cashaddr",hash:Array.prototype.slice.call(t,0),network:n==="bitcoincash"?"mainnet":"testnet",type:r==="P2PKH"?"p2pkh":"p2sh"}}catch{return}}function tr(e){let t=ne.legacy[e.network][e.type],n=Buffer.alloc(1+e.hash.length);return n[0]=t,n.set(e.hash,1),Ft.encode(n)}function nr(e){let t=e.network==="mainnet"?"bitcoincash":"bchtest",n=e.type==="p2pkh"?"P2PKH":"P2SH",r=new Uint8Array(e.hash);return ot.encode(t,n,r)}import{Chain as ae,SwapKitError as mt}from"@swapkit/helpers";import{SwapKitError as qe,UTXO_SCRIPT_TYPE_LIST as Ar,UTXO_SCRIPT_TYPES as $t,UTXOScriptType as Ge}from"@swapkit/helpers";import{Script as Or}from"@swapkit/utxo-signer";import{Chain as it}from"@swapkit/helpers";import{getAddressScriptType as sr,getTransparentZcashAddressType as or,getZcashAddressType as ar}from"@swapkit/utxo-signer";import{match as ir}from"ts-pattern";import{Chain as fe}from"@swapkit/helpers";import{NETWORKS as Te}from"@swapkit/utxo-signer";import{match as rr}from"ts-pattern";function U(e){return rr(e).with(fe.Bitcoin,()=>Te.bitcoin).with(fe.BitcoinCash,()=>Te.bitcoinCash).with(fe.Dash,()=>Te.dash).with(fe.Dogecoin,()=>Te.dogecoin).with(fe.Litecoin,()=>Te.litecoin).with(fe.Zcash,()=>Te.zcash).exhaustive()}function W(e){return e.replace(/(bchtest:|bitcoincash:)/,"")}function Se(e){if(typeof e!=="string")return null;let t=Ne(W(e));if(!t||t.network!=="mainnet")return null;return t.scriptType}var cr=["sprout","sapling","unified"];function dr(e){let t=or(e,U(it.Zcash));if(t)return t;let n=ar(e);return n&&cr.includes(n)?n:null}function Y({address:e,chain:t}){return ir(t).with(it.BitcoinCash,()=>Se(e)).with(it.Zcash,()=>dr(e)).otherwise(()=>sr(e,U(t)))}import{Chain as re,derivationPathToString as It,getPurposeFromPath as ur,getUTXOScriptTypeForPath as Ht,getUTXOScriptTypeForPurpose as Mt,resolveDerivationPath as pr,SwapKitError as Ce,UTXO_SCRIPT_TYPE_LIST as Rt,UTXO_SCRIPT_TYPES as me,UTXOChains as lr,UTXOScriptType as O,updateDerivationPath as hr,warnOnce as fr}from"@swapkit/helpers";import{CashAddrPrefix as Tr,CashAddrType as mr,encodeCashAddr as yr,OutScript as Nt,p2pkh as gr,p2sh as xr,p2tr as br,p2wpkh as Et}from"@swapkit/utxo-signer";var Ze=Object.freeze([O.P2PKH]),wr=Object.freeze({[re.Bitcoin]:Rt,[re.BitcoinCash]:Ze,[re.Dash]:Ze,[re.Dogecoin]:Ze,[re.Litecoin]:Rt,[re.Zcash]:Ze});function We(e){return wr[e]}function ct(e){return We(e).some((t)=>me[t].witness)}function ye(e,t){return We(e).includes(t)}function Le(e,t){if(ye(e,t))return t;throw new Ce("toolbox_utxo_unsupported_script_type",{chain:e,error:`${e} cannot encode ${t}; supported: ${We(e).join(", ")}`,scriptType:t,supported:We(e)})}var Zt=lr.filter((e)=>!ct(e));function Pr({purpose:e,scriptType:t}){let n=Mt(e);return n===void 0||n===t}function dt({chain:e,purpose:t,scriptType:n}){fr({condition:!Pr({purpose:t,scriptType:n}),id:`utxo_off_standard_encoding_${e}_${t}_${n}`,warning:`${e}: encoding m/${t}' keys as ${n}, not the ${Mt(t)} the path implies. No other wallet derives these addresses: move funds out of them, never receive into them.`})}function $e({chain:e,derivationPath:t,index:n=0,scriptType:r}){if(t){if(!r){let o=Ht(t);throw new Ce("toolbox_utxo_invalid_params",{chain:e,derivationPath:It(t),error:`scriptType is required alongside derivationPath: getUTXOScriptTypeForPath gives the standard one${o?` (${o})`:""}, or state another deliberately.`})}return Le(e,r),dt({chain:e,purpose:ur(t),scriptType:r}),{derivationPath:t,scriptType:r}}let s=pr({chain:e,index:n}),a=r?hr(s,{purpose:me[r].purpose}):s,d=r??Ht(a);if(!d)throw new Ce("toolbox_utxo_invalid_params",{chain:e,derivationPath:It(a),error:`${e}: the default derivation path has no standard script type`});return Le(e,d),{derivationPath:a,scriptType:d}}function Ur(e){return e.length===32?e:e.slice(1)}function ze(e,t){if(!e.address)throw new Ce("toolbox_utxo_invalid_address",{error:`Could not derive a ${t} address`});return e}var vr={[O.P2PKH]:(e,t)=>{let{address:n,script:r}=ze(gr(e,t),O.P2PKH);return{address:n,script:r}},[O.P2SH_P2WPKH]:(e,t)=>{let n=Et(e,t),{address:r,script:s}=ze(xr(n,t),O.P2SH_P2WPKH);return{address:r,redeemScript:n.script,script:s}},[O.P2WPKH]:(e,t)=>{let{address:n,script:r}=ze(Et(e,t),O.P2WPKH);return{address:n,script:r}},[O.P2TR]:(e,t)=>{let n=Ur(e),{address:r,script:s}=ze(br(n,void 0,t),O.P2TR);return{address:r,script:s,tapInternalKey:n}}};function Ve(e,t,n){return vr[e](t,n)}function ut(e,t){if(e!==re.BitcoinCash)return t.address;let n=Nt.decode(t.script);if(n.type!=="pkh")throw new Ce("toolbox_utxo_invalid_address",{chain:e,error:`Cannot encode ${n.type} as CashAddr`});return yr({hash:n.hash,prefix:Tr.MAINNET,type:mr.P2PKH}).replace(/^bitcoincash:/,"")}var _r=Object.freeze({pkh:O.P2PKH,sh:O.P2SH_P2WPKH,tr:O.P2TR,wpkh:O.P2WPKH}),zt=Object.freeze({pkh:me[O.P2PKH].outputSize,sh:me[O.P2SH_P2WPKH].outputSize,tr:me[O.P2TR].outputSize,wpkh:me[O.P2WPKH].outputSize,wsh:43});function Wt(e){return e in zt}function Lt(e){return Wt(e)?zt[e]:void 0}function Xe(e){return _r[e]}function pt(e){try{let{type:t}=Nt.decode(e);return Wt(t)?Xe(t):void 0}catch{return}}import{UTXOScriptType as oe}from"@swapkit/helpers";var ho=1000,ht=10,Sr=2,Cr=10;function E(e){let t=new Uint8Array(Buffer.from(e,"utf8"));return Or.encode(["RETURN",t])}function Vt(e){return Object.fromEntries(Ar.map((t)=>[t,$t[t][e]]))}var qt=Vt("inputSize"),lt=Vt("outputSize"),ft=(e)=>$t[e].witness,Ye=(e,t)=>{let n=Y({address:e,chain:t});if(!n)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let r=Xe(n);if(!r||!ye(t,r))throw new qe("toolbox_utxo_unsupported_script_type",{address:e,addressType:n,chain:t,error:"Address is valid but its script type is not one the SDK spends from"});return r},Xr=(e,t)=>{let n=Y({address:e,chain:t});if(!n)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let r=Lt(n);if(!r)throw new qe("toolbox_utxo_unsupported_script_type",{address:e,addressType:n,chain:t,error:"Address is valid but a transparent transaction cannot pay to it"});return r},ge=({chain:e,inputs:t,outputs:n,feeRate:r})=>{let s=t[0]?Be(t[0],e):Ge.P2PKH,a=r?t.filter((u)=>u.value>=qt["type"in u&&u.type?u.type:Ge.P2PKH]*Math.ceil(r)):t,d=0,o=0;for(let u of a)if(d+=se(u,e),!ft(Be(u,e)))o++;let p=n?.reduce((u,i)=>u+je(i,e),0)||lt[s],c=o<a.length;return ht+d+p+Tt(c,o)},Be=(e,t)=>{if("type"in e&&e.type)return e.type;if("address"in e&&e.address)return Ye(e.address,t);return Ge.P2PKH},se=(e,t)=>qt[Be(e,t)],Tt=(e,t)=>e?Math.ceil((Sr+t)/4):0,je=(e,t,n)=>{if(e?.script)return Cr+e.script.length+(e.script.length>=74?2:1);if(n)return lt[n];if("address"in e&&e.address)return Xr(e.address,t);return lt[Ge.P2PKH]};function ke(e){switch(e){case ae.Bitcoin:case ae.BitcoinCash:return 550;case ae.Dash:case ae.Litecoin:return 5500;case ae.Dogecoin:return 1e5;case ae.Zcash:return 546;default:throw new mt("toolbox_utxo_not_supported",{chain:e})}}function M({inputs:e,outputs:t,feeRate:n=1,chain:r=ae.Bitcoin,changeAddress:s="",sweep:a=!1}){let d=ke(r),o=e.filter((f)=>{let y=se(f,r)*n;return a?f.value>Math.max(y,d):y<=f.value});if(a){let f=Math.ceil(n*ge({chain:r,inputs:o,outputs:t})),y=o.reduce((X,V)=>X+V.value,0),b=y-f;if(b<=d)throw new mt("toolbox_sweep_amount_too_low",{available:y,dustThreshold:d,fee:f});let S=t.findIndex((X)=>("address"in X)&&X.address);if(S===-1)throw new mt("toolbox_utxo_invalid_params",{error:"Sweep requires a recipient output"});return{fee:f,inputs:o,outputs:t.map((X,V)=>V===S?{...X,value:b}:X)}}let p=ht+t.reduce((f,y)=>f+je(y,r),0),c=t.reduce((f,y)=>f+y.value,0),u=0,i=0,l=!1,h=0,m=[];for(let f of o){if(u+=se(f,r),ft(Be(f,r)))l=!0;else i++;h+=f.value,m.push(f);let y=(p+u+Tt(l,i))*n,b=y+c;if(h<b)continue;let S=h-b,X=n*je({address:s,value:0},r);if(S>X){let V=X+y,Pe=h-(c+Math.ceil(V));if(Pe>Math.max(se({value:0},r)*n,ke(r)))return{fee:Math.ceil(V),inputs:m,outputs:t.concat({address:s,value:Pe})}}return{fee:Math.ceil(y),inputs:m,outputs:t}}return{fee:Math.ceil(n*ge({chain:r,inputs:e,outputs:t}))}}import{Chain as we,SwapKitError as Bs}from"@swapkit/helpers";import{hex as un}from"@scure/base";import{Chain as Yr,derivationPathToString as jr,FeeOption as Jr,resolveDerivationPath as Qr,SwapKitError as L}from"@swapkit/helpers";import{BCHSigHash as es,CashAddrPrefix as pn,CashAddrType as ln,encodeCashAddr as hn,NETWORKS as ts,p2pkh as fn,Transaction as Tn}from"@swapkit/utxo-signer";import{secp256k1 as Br}from"@noble/curves/secp256k1.js";import{hex as j}from"@scure/base";import{HDKey as Jt}from"@scure/bip32";import{mnemonicToSeedSync as xt}from"@scure/bip39";import{AssetValue as yt,applyFeeMultiplier as Gt,Chain as Fe,derivationPathToString as Ke,FeeOption as N,NetworkDerivationPath as kr,SwapKitError as P,SwapKitNumber as Kr,UTXO_SCRIPT_TYPES as Fr,warnOnce as Dr}from"@swapkit/helpers";import{BCHSigHash as Qt,RBF_SEQUENCE as Ir,SigHash as Yt,Transaction as Je,utils as Hr,WIF as en}from"@swapkit/utxo-signer";var Qe=[Fe.Bitcoin];function tn({address:e,chain:t}){return Y({address:e,chain:t})!==null}function Rr({phrase:e,derivationPath:t,network:n,seed:r}){let s=r??xt(e),d=Jt.fromMasterSeed(s,n.bip32).derive(t);if(!d.privateKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive private key from phrase"});return d.privateKey}function gt(e){return Br.getPublicKey(e,!0)}function De({publicKey:e,chain:t,network:n,scriptType:r}){return ut(t,Ve(r,e,n))}function xe({phrase:e,derivationPath:t,chain:n,wif:r,seed:s}){let a=U(n);if(r){let c=en(a).decode(r),u=gt(c);return{privateKey:c,publicKey:u}}if(!e)throw new P("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let d=t||Ke(kr[n]),o=Rr({derivationPath:d,network:a,phrase:e,seed:s}),p=gt(o);return{privateKey:o,publicKey:p}}function Er(e,t){return en(U(t)).encode(e)}function Mr({phrase:e,derivationPath:t,chain:n,seed:r}){let s=t.split("/");if(s.length<4)throw new P("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${s.length}): ${t}`});let a=U(n),d=r??xt(e),o=Jt.fromMasterSeed(d,a.bip32),p=s.slice(0,4).join("/");return o.derive(p)}function Nr(e,t){if(!e||!Fr[e].witness)return!1;return e!==oe.P2SH_P2WPKH||!!t}function nn({chain:e,script:t,publicKey:n,network:r}){let s=pt(t);if(s!==oe.P2SH_P2WPKH&&s!==oe.P2TR)return{};if(!ye(e,s))return{};let a=Ve(s,n,r);if(Hr.compareBytes(a.script,t)!==0)return{};return s===oe.P2TR?{tapInternalKey:a.tapInternalKey}:{redeemScript:a.redeemScript}}function Zr(e,t,n){if(!n)return!1;let r=Y({address:e,chain:t}),s=r?Xe(r):void 0;if(!s||!ye(t,s))return!1;let a=ut(t,Ve(s,n,U(t)));return t===Fe.BitcoinCash?W(a)===W(e):a===e}function zr(e){return e.witnessUtxo?.script??e.nonWitnessUtxo?.outputs[e.index??0]?.script}function bt({chain:e,tx:t,publicKey:n,network:r,indexes:s}){let a=s??Array.from({length:t.inputsLength},(o,p)=>p),d=[];for(let o of a){let p=t.getInput(o),c=zr(p);if(!c)continue;let{redeemScript:u,tapInternalKey:i}=nn({chain:e,network:r,publicKey:n,script:c}),l={index:o};if(u&&!p.redeemScript)l.redeemScript=u;if(i&&!p.tapInternalKey)l.tapInternalKey=i;if(l.redeemScript||l.tapInternalKey)d.push(l)}return d}function ie({inputs:e,outputs:t,chain:n,tx:r,sender:s,compiledMemo:a,enableRBF:d=!1}){let o=U(n),p=ct(n),c=d?Ir:void 0,u=new Set;for(let i of e){let l=`${i.hash}:${i.index}`;if(u.has(l))throw new P("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});u.add(l);let h=typeof i.hash==="string"?j.decode(i.hash):i.hash,m=i.witnessUtxo?pt(i.witnessUtxo.script):void 0,f=i.publicKey&&i.witnessUtxo?nn({chain:n,network:o,publicKey:i.publicKey,script:i.witnessUtxo.script}):{};if(p&&i.witnessUtxo&&Nr(m,f.redeemScript))r.addInput({...f,index:i.index,sequence:c,txid:h,witnessUtxo:{amount:BigInt(i.witnessUtxo.value),script:i.witnessUtxo.script}});else if(i.txHex)r.addInput({...f,index:i.index,nonWitnessUtxo:j.decode(i.txHex),sequence:c,txid:h,...n===Fe.BitcoinCash?{sighashType:Qt.ALL}:{}});else throw new P("toolbox_utxo_invalid_params",{error:`Input ${l} cannot be signed from its witnessUtxo alone: it needs its previous transaction (txHex), or — if it is a nested-segwit output — the public key that controls it, which its redeemScript derives from`})}for(let i of t){let l="address"in i&&i.address?i.address:s;if(n===Fe.BitcoinCash)l=G(l);if(i.script)if(a)r.addOutput({amount:0n,script:a});else throw new P("toolbox_utxo_invalid_params",{error:"An output carrying a script needs the compiled memo it carries"});else r.addOutputAddress(l,BigInt(i.value),o)}return{inputs:e,tx:r}}async function be(e){let t=await A(e).getSuggestedTxFee();return{[N.Average]:t,[N.Fast]:Gt(t,N.Fast),[N.Fastest]:Gt(t,N.Fastest)}}async function rn({assetValue:e,recipient:t,memo:n,sender:r,sweep:s,fetchTxHex:a=!1,publicKey:d},o,{forEstimateOnly:p=!1}={}){let c=e.chain,u=Ye(r,c),i=u===oe.P2PKH||u===oe.P2SH_P2WPKH&&!Zr(r,c,d),l=a||!p&&i,h=e.getBaseValue("number"),m=s?void 0:o??(await be(c))[N.Fastest],f=s||m===void 0?void 0:Math.ceil(h+m*5000);return{inputs:await A(c).getUtxos({address:r,fetchTxHex:l,targetValue:f}),outputs:[{address:t,value:s?0:h},...n?[{address:"",script:E(n),value:0}]:[]]}}async function sn({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s,fetchTxHex:a=!1,enableRBF:d=!1,sweep:o,publicKey:p}){let c=e.chain,u=n?E(n):null,i=await rn({assetValue:e,fetchTxHex:a,memo:n,publicKey:p,recipient:t,sender:s,sweep:o},r),{inputs:l,outputs:h}=M({...i,chain:c,changeAddress:s,feeRate:r,sweep:o});if(!(l&&h))throw new P("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let m=p?l.map((S)=>({...S,publicKey:p})):l,f=new Je({allowUnknownOutputs:!!u,version:1}),{inputs:y,tx:b}=ie({chain:c,compiledMemo:u,enableRBF:d,inputs:m,outputs:h,sender:s,tx:f});return{inputs:y,tx:b,utxos:i.inputs}}async function on({assetValue:e,feeOptionKey:t=N.Fast,feeRate:n,memo:r,sender:s,recipient:a,sweep:d}){let o=e.chain,p,c;if(n!==void 0)p=n,c=Math.floor(n);else{let i=await be(o);p=i[N.Fastest],c=i[t]}let u=await rn({assetValue:e,memo:r,recipient:a,sender:s,sweep:d},p,{forEstimateOnly:!0});return M({...u,chain:o,changeAddress:s,feeRate:c,sweep:d})}function Wr(e){return async function({from:n,memo:r,feeRate:s,feeOptionKey:a=N.Fast,recipient:d=n,recipients:o=1}){let p=s??(await be(e))[a],u=(await A(e).getUtxos({address:n,fetchTxHex:!1})).filter((f)=>f.value>Math.max(ke(e),se(f,e)*p));if(!u.length)return yt.from({chain:e});let i=typeof o==="number"?Math.max(o,1):o.length,l=typeof o==="number"||i===0?Array.from({length:i||1},()=>({address:d,value:0})):[...o];if(r)l.push({address:n,script:E(r),value:0});let{outputs:h}=M({chain:e,feeRate:p,inputs:u,outputs:l,sweep:!0}),m=h?.[0]?.value??0;return yt.from({chain:e,value:BigInt(m)})}}function Lr(e){return async function(n){let{fee:r}=await on(n);return yt.from({chain:e,value:Kr.fromBigInt(BigInt(r),8).getValue("string")})}}function $r({chain:e,phrase:t,derivationPath:n,scriptType:r,seed:s}){let a=U(e),{privateKey:d,publicKey:o}=xe({chain:e,derivationPath:n,phrase:t,seed:s}),p=an(e);return{getAddress:()=>De({chain:e,network:a,publicKey:o,scriptType:r}),privateKey:d,publicKey:o,signTransaction:(c)=>{for(let{index:u,...i}of bt({chain:e,network:a,publicKey:o,tx:c}))c.updateInput(u,i);return c.sign(d,p),c}}}function an(e){return e===Fe.BitcoinCash?[Qt.ALL]:[Yt.ALL,Yt.DEFAULT]}function Vr(e,t,n){return async function({memo:s,recipient:a,feeOptionKey:d,feeRate:o,assetValue:p,enableRBF:c=!1,sweep:u}){let i=await t?.getAddress();if(!(t&&i))throw new P("toolbox_utxo_no_signer");if(!a)throw new P("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});Dr({condition:c&&!Qe.includes(e),id:`rbf_not_supported_${e}`,warning:`RBF (Replace-by-Fee) is not reliably supported on ${e}. Transaction will be created without RBF signaling.`});let l=c&&Qe.includes(e),h=o||(await be(e))[d||N.Fast],{tx:m}=await sn({assetValue:p,enableRBF:l,feeRate:h,memo:s,publicKey:n,recipient:a,sender:i,sweep:u}),f=await t.signTransaction(m);return f.finalize(),A(e).broadcastTx(j.encode(f.extract()))}}function cn(e){return(t)=>tn({address:t,chain:e})}function dn(e,{scriptType:t}){let n=U(e);return function(s){if(!s)throw new P("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return De({chain:e,network:n,publicKey:s.publicKey,scriptType:t})}}function qr(e){let t=e?.publicKey;if(t===void 0)return;if(t instanceof Uint8Array&&t.length===33)return t;throw new P("toolbox_utxo_invalid_params",{error:"signer.publicKey must be a 33-byte compressed public key (Uint8Array)"})}function ce(e){let{chain:t}=e,n=e.phrase?e:void 0;if(!n&&"derivationPath"in e&&e.derivationPath!==void 0)throw new P("toolbox_utxo_invalid_params",{error:"derivationPath needs a phrase; a toolbox built around a signer uses the signer's addresses"});let r=n?.phrase,s=n?.index??0,a=r?xt(r):void 0,{derivationPath:d,scriptType:o}=$e({chain:t,derivationPath:n?.derivationPath,index:s,scriptType:e.scriptType}),p=Ke(d),c=r?$r({chain:t,derivationPath:p,phrase:r,scriptType:o,seed:a}):void 0,u=n?void 0:e.signer,i=c||u,l=r?xe({chain:t,derivationPath:p,phrase:r,seed:a}):void 0,h=l?.publicKey??qr(u);function m(){if(i)return i.getAddress();return Promise.resolve(void 0)}function f(T){if(!r)return;let g=te({accountIndex:T,chain:t,derivationPath:d});return Mr({chain:t,derivationPath:Ke(g),phrase:r,seed:a})}let y=f();function b(){if(!y)return;return y.publicExtendedKey}function S({accountIndex:T}={}){let g=T===void 0?y:f(T);if(!g)return;let w=te({accountIndex:T,chain:t,derivationPath:d});return{accountIndex:pe(w),path:Ke(w),xpub:g.publicExtendedKey}}function X({accountIndex:T,index:g,change:w=!1}){let _=T===void 0?y:f(T);if(!_)return;let x=Ae({accountIndex:T,chain:t,change:w,derivationPath:d,index:g}),K=U(t),I=_.deriveChild(Number(w)).deriveChild(g);if(!I.publicKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let B=De({chain:t,network:K,publicKey:I.publicKey,scriptType:o}),F=j.encode(I.publicKey);return{accountIndex:pe(x),address:B,change:w,index:g,path:Ke(x),pubkey:F}}async function V(T){if(!Qe.includes(t))return{reason:`RBF is not supported on ${t}`,supported:!1};let g=await A(t).getTransactionDetails(T);return{canReplace:g.isRBF&&!g.confirmed,confirmed:g.confirmed,enabled:g.isRBF,fee:g.fee,sequences:g.sequences,supported:!0}}async function Pe({txid:T,newFeeRate:g,recipient:w,memo:_}){if(!Qe.includes(t))throw new P("toolbox_utxo_rbf_not_supported",{chain:t});let x=await A(t).getTransactionDetails(T);if(!x.isRBF)throw new P("toolbox_utxo_tx_not_replaceable",{txid:T});if(x.confirmed)throw new P("toolbox_utxo_tx_already_confirmed",{blockId:x.blockId,txid:T});let K=x.inputs.reduce((v,D)=>v+D.value,0),B=x.outputs.find((v)=>v.recipient===w)?.value||0;if(B===0)throw new P("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let F=await Promise.all(x.inputs.map(async(v)=>{let D=await A(t).getRawTx(v.transaction_hash),k=Je.fromRaw(j.decode(D),{allowUnknownOutputs:!0,disableScriptCheck:!0}).getOutput(v.index);return{address:v.recipient,hash:v.transaction_hash,index:v.index,publicKey:h,txHex:D,value:v.value,witnessUtxo:k.script&&k.amount!==void 0?{script:Buffer.from(k.script),value:Number(k.amount)}:void 0}})),H=_?E(_):null,Q=K-B-x.fee,Ue=await m(),ue=[];if(H)ue.push({address:"",script:H,value:0});if(Q>ke(t)&&Ue)ue.push({address:Ue,value:Q});let He=ge({chain:t,inputs:F.map((v)=>({...v,type:Ye(v.address,t)})),outputs:[{address:w,value:B},...ue]}),q=Math.ceil(He*g);if(q<=x.fee)throw new P("toolbox_utxo_rbf_fee_too_low",{newFee:q,originalFee:x.fee});let ve=q-x.fee,ee=B-ve;if(ee<=0)throw new P("toolbox_utxo_rbf_insufficient_change");let _e=new Je({allowUnknownOutputs:!!H,version:1}),nt=[{address:w,value:ee},...ue];return ie({chain:t,compiledMemo:H,inputs:F,outputs:nt,sender:Ue||w,tx:_e}),{feeDelta:ve,newFee:q,originalFee:x.fee,tx:_e}}async function vn({txid:T,newFeeRate:g,recipient:w,memo:_}){let{tx:x,originalFee:K,newFee:I}=await Pe({memo:_,newFeeRate:g,recipient:w,txid:T}),B=await tt(x);B.finalize();let F=await A(t).broadcastTx(j.encode(B.extract()));return{newFee:I,originalFee:K,txid:F}}function vt({accountIndex:T,index:g,change:w=!1}){z("index",g);let _=T===void 0?y:f(T);if(!_)return;return _.deriveChild(Number(w)).deriveChild(g).privateKey||void 0}function _t({tx:T,inputDerivations:g}){if(!y)throw new P("toolbox_utxo_no_signer");let w=an(t),_=U(t);for(let x=0;x<g.length;x++){let K=g[x];if(!K)continue;let{derivationIndex:I,isChange:B}=K,F=vt({change:B,index:I});if(!F)throw new P("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${x} at index ${I}`});for(let{index:H,...Q}of bt({chain:t,indexes:[x],network:_,publicKey:gt(F),tx:T}))T.updateInput(H,Q);T.signIdx(F,x,w)}return T}async function _n({utxos:T,recipient:g,assetValue:w,memo:_,feeRate:x,feeOptionKey:K,changeAddress:I,sweep:B}){if(B)throw new P("toolbox_utxo_invalid_params",{error:"Sweep is not supported for transfers from multiple addresses"});if(!y)throw new P("toolbox_utxo_no_signer");let F=x||(await be(t))[K||N.Fast],H=_?E(_):null,Q=[{address:g,value:w.getBaseValue("number")}];if(H)Q.push({address:"",script:H,value:0});let Ue=T.map(({address:v,hash:D,index:k,value:rt,txHex:Sn,witnessUtxo:st})=>({address:v,hash:D,index:k,txHex:Sn,value:rt,witnessUtxo:st?{script:st.script,value:st.value}:void 0})),ue=T[0]?.address,He=I||await m()||ue||g,{inputs:q,outputs:ve}=M({chain:t,changeAddress:He,feeRate:F,inputs:Ue,outputs:Q});if(!(q&&ve))throw new P("toolbox_utxo_insufficient_balance",{assetValue:w,sender:"multiple addresses"});let ee=new Je({allowUnknownOutputs:!!H,version:1}),_e=q.map((v)=>{let D=T.find((k)=>k.hash===v.hash&&k.index===v.index);return D?{derivationIndex:D.derivationIndex,isChange:D.isChange}:{derivationIndex:0,isChange:!1}}),nt=q.map((v,D)=>{let k=_e[D],rt=k?y.deriveChild(Number(k.isChange)).deriveChild(k.derivationIndex).publicKey:null;return{...v,publicKey:rt??void 0}});return ie({chain:t,compiledMemo:H,inputs:nt,outputs:ve,sender:He,tx:ee}),_t({inputDerivations:_e,tx:ee}),ee.finalize(),A(t).broadcastTx(j.encode(ee.extract()))}function An({address:T,gapLimit:g=20}){if(!y)return;for(let w=0;w<g;w++){let _=X({change:!1,index:w}),x=X({change:!0,index:w}),K=_?.address===T?!1:x?.address===T;if(_?.address===T||x?.address===T)return{change:K,index:w}}return}function tt(T){if(!i)throw new P("toolbox_utxo_no_signer");return i.signTransaction(T)}async function On(T){let g=await tt(T);return g.finalize(),await A(t).broadcastTx(j.encode(g.extract()))}return{accumulative:M,broadcastTx:(T)=>A(t).broadcastTx(T),bumpFee:vn,calculateTxSize:(T)=>ge({...T,chain:t}),createKeysForPath:(T)=>xe({...T,chain:t}),createReplacementTransaction:Pe,createTransaction:(T)=>sn({publicKey:h,...T}),deriveAddressAtIndex:X,derivePrivateKeyAtIndex:vt,estimateMaxSendableAmount:Wr(t),estimateTransactionFee:Lr(t),getAddress:m,getAddressFromKeys:dn(t,{scriptType:o}),getAddressType:(T)=>Y({address:T,chain:t}),getBalance:jt(t),getExtendedPublicKey:b,getExtendedPublicKeyInfo:S,getFeeRates:()=>be(t),getInputsOutputsFee:on,getNetworkForChain:()=>U(t),getPrivateKeyFromMnemonic:(T)=>Er(xe({...T,chain:t}).privateKey,t),isRBFEnabled:V,keys:l,resolveDerivationIndex:An,scriptType:o,signAndBroadcastTransaction:On,signTransaction:tt,signTransactionWithMultipleKeys:_t,transfer:Vr(t,i,h),transferFromMultipleAddresses:_n,validateAddress:cn(t)}}import{getZcashAddressType as Gr,validateZcashAddress as wt}from"@swapkit/utxo-signer";function Ie(e){return Se(e)!==null}var Z=Yr.BitcoinCash;function et(e){return W(Me(e))}function ns(e){let t=U(Z);function n(s){return s.sign(e.privateKey,[es.ALL]),s}function r(){let s=fn(e.publicKey,t);if(!s.hash)throw new L("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let a=hn({hash:s.hash,prefix:pn.MAINNET,type:ln.P2PKH});return Promise.resolve(a.replace(/^bitcoincash:/,""))}return{getAddress:r,signTransaction:n}}function mn(e={}){let t="phrase"in e?e.phrase:void 0,n="index"in e?e.index||0:0,r="derivationPath"in e?e.derivationPath:void 0,s=Qr({chain:Z,derivationPath:r,index:n}),a=jr(s),d=t?xe({chain:Z,derivationPath:a,phrase:t}):void 0,o=d?ns(d):("signer"in e)?e.signer:void 0;function p(){return Promise.resolve(o?.getAddress())}let c="scriptType"in e?e.scriptType:void 0,{getBalance:u,getFeeRates:i,broadcastTx:l,...h}=ce(t?{chain:Z,index:n,phrase:t,...r?{derivationPath:r,scriptType:c}:{scriptType:c}}:{chain:Z,scriptType:c});function m(b,S=!0){return u(W(Me(b)))}function f(b){if(!o)throw new L("toolbox_utxo_no_signer");return o.signTransaction(b)}async function y(b){let S=await f(b);return S.finalize(),await l(un.encode(S.extract()))}return{...h,broadcastTx:l,buildTx:ss,createTransaction:yn,getAddress:p,getAddressFromKeys:os,getBalance:m,getFeeRates:i,signAndBroadcastTransaction:y,signTransaction:f,stripPrefix:W,stripToCashAddress:et,transfer:rs({broadcastTx:l,getFeeRates:i,signer:o}),validateAddress:Ie}}async function yn({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s,sweep:a}){if(!Ie(t))throw new L("toolbox_utxo_invalid_address",{address:t});let d=Math.ceil(e.getBaseValue("number")+r*7500),o=await A(Z).getUtxos({address:et(s),fetchTxHex:!0,targetValue:a?void 0:d}),p=n?E(n):null,c=[],u=G(t);if(c.push({address:u,value:a?0:e.getBaseValue("number")}),p)c.push({script:p,value:0});let{inputs:i,outputs:l}=M({chain:Z,feeRate:r,inputs:o,outputs:c,sweep:a});if(!(i&&l))throw new L("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let h=new Tn({allowUnknownOutputs:!!p,version:1}),m=G(s),{inputs:f,tx:y}=ie({chain:Z,compiledMemo:p,inputs:i,outputs:l.map((b)=>("address"in b)&&b.address?{...b,address:G(b.address)}:b),sender:m,tx:h});return{inputs:f,tx:y,utxos:i}}function rs({broadcastTx:e,getFeeRates:t,signer:n}){return async function({recipient:s,assetValue:a,feeOptionKey:d=Jr.Fast,sweep:o,...p}){let c=await n?.getAddress();if(!(n&&c))throw new L("toolbox_utxo_no_signer");if(!s)throw new L("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let u=p.feeRate||(await t())[d],{tx:i}=await yn({...p,assetValue:a,feeRate:u,recipient:s,sender:c,sweep:o}),l=await n.signTransaction(i);return l.finalize(),e(un.encode(l.extract()))}}async function ss({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s}){let a=Me(t);if(!Ie(a))throw new L("toolbox_utxo_invalid_address",{address:a});let d=Math.ceil(e.getBaseValue("number")+r*7500),o=await A(Z).getUtxos({address:et(s),fetchTxHex:!0,targetValue:d}),p=Number(r.toFixed(0)),c=n?E(n):null,u=[];if(u.push({address:G(t),value:e.getBaseValue("number")}),c)u.push({script:c,value:0});let{inputs:i,outputs:l}=M({chain:Z,feeRate:p,inputs:o,outputs:u});if(!(i&&l))throw new L("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let h=new Tn({allowUnknownOutputs:!!c,version:1}),{inputs:m,tx:f}=ie({chain:Z,compiledMemo:c,inputs:i,outputs:l,sender:G(s),tx:h});return{inputs:m,tx:f,utxos:o}}function os(e){let t=ts.bitcoinCash,n=fn(e.publicKey,t);if(!n.hash)throw new L("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return hn({hash:n.hash,prefix:pn.MAINNET,type:ln.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as as,hex as is}from"@scure/base";import{HDKey as bn}from"@scure/bip32";import{mnemonicToSeedSync as wn}from"@scure/bip39";import{Chain as J,derivationPathToString as cs,FeeOption as ds,SwapKitError as de}from"@swapkit/helpers";import{Address as us,createZcashTransaction as ps,getZcashConsensusBranchId as ls,isTransparentZcashAddress as gn,OutScript as hs,PCZT as fs,utils as Pn,WIF as Ts,ZcashConsensusBranchId as ms,ZcashPSBT as ys,ZcashSigHash as Pt,ZcashVersionGroupId as gs}from"@swapkit/utxo-signer";import{match as xs,P as Ut}from"ts-pattern";var bs=as(Pn.sha256);function ws(e){return bs.encode(e)}function Ps({phrase:e,derivationPath:t}){let n=wn(e),s=bn.fromMasterSeed(n).derive(t);if(!s.privateKey||!s.publicKey)throw new de("toolbox_utxo_invalid_params");let{privateKey:a,publicKey:d}=s,o=Pn.hash160(d),p=new Uint8Array([28,184]),c=new Uint8Array(p.length+o.length);c.set(p,0),c.set(o,p.length);let u=ws(c);return{getAddress:()=>Promise.resolve(u),signTransaction:(i)=>{if(i instanceof ys){let l=i.toPCZT();return l.signAllInputs(a,d,Pt.ALL),l.finalizeAllInputs(),Promise.resolve(l.extract())}if(i instanceof fs)return i.signAllInputs(a,d,Pt.ALL),i.finalizeAllInputs(),Promise.resolve(i.extract());return i.signAllInputs(a,d,Pt.ALL),Promise.resolve(i)}}}function Us({inputs:e,outputs:t,tx:n,sender:r,compiledMemo:s}){let a=U(J.Zcash);for(let d of e){let o=us(a).decode(r),p=hs.encode(o);n.addInput({index:d.index,script:p,sequence:4294967295,txid:is.decode(d.hash),value:BigInt(d.value)})}for(let d of t){let o="address"in d&&d.address?d.address:r,p=d.script;if(p&&!s)continue;if(p&&s)n.addOutput({amount:0n,script:s});else n.addOutputAddress(o,BigInt(d.value),a)}return{inputs:e,tx:n}}async function vs(){try{let e=await A(J.Zcash).getBlockHeight();return ls(e+1)}catch{return ms.IRONWOOD}}async function xn(e){let{assetValue:t,recipient:n,memo:r,feeRate:s,sender:a,fetchTxHex:d,sweep:o}=e,p=U(J.Zcash);if(!gn(a,p))throw new de("toolbox_utxo_invalid_address",{address:a});if(!gn(n,p))throw new de("toolbox_utxo_invalid_address",{address:n,error:"Zcash transaction creation currently supports transparent addresses only"});let c=r?E(r):null,u=await A(J.Zcash).getUtxos({address:a,fetchTxHex:d!==!1}),i=[{address:n,value:o?0:Number(t.getBaseValue("string"))},...c?[{script:c,value:0}]:[]],{inputs:l,outputs:h}=M({chain:J.Zcash,changeAddress:a,feeRate:s,inputs:u,outputs:i,sweep:o});if(!(l&&h))throw new de("toolbox_utxo_insufficient_balance",{assetValue:t,sender:a});let m=ps({consensusBranchId:await vs(),expiryHeight:0,lockTime:0,version:4,versionGroupId:gs.SAPLING}),{tx:f,inputs:y}=Us({compiledMemo:c,inputs:l,outputs:h,sender:a,tx:m});return{inputs:y,outputs:h,tx:f}}function Un(e={}){let t="scriptType"in e?e.scriptType:void 0,n=xs(e).with({signer:Ut.not(Ut.nullish)},({signer:c})=>c).with({phrase:Ut.string},({phrase:c,derivationPath:u,index:i=0})=>{let{derivationPath:l}=$e({chain:J.Zcash,derivationPath:u,index:i,scriptType:t}),h=cs(l);return Ps({derivationPath:h,phrase:c})}).otherwise(()=>{return}),r=ce({chain:J.Zcash,scriptType:t,signer:n});async function s(c){if(!n)throw new de("toolbox_utxo_no_signer");return await n.signTransaction(c)}async function a(c){let u=await s(c);return r.broadcastTx(u.toHex())}async function d({recipient:c,assetValue:u,feeOptionKey:i=ds.Fast,sweep:l,...h}){let m=await n?.getAddress();if(!(n&&m))throw new de("toolbox_utxo_no_signer");let f=h.feeRate||(await r.getFeeRates())[i],{tx:y}=await xn({...h,assetValue:u,feeRate:f,recipient:c,sender:m,sweep:l}),S=(await n.signTransaction(y)).toHex();return r.broadcastTx(S)}function o({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let i=wn(c),h=bn.fromMasterSeed(i).derive(u);if(!h.privateKey||!h.publicKey)throw new de("toolbox_utxo_invalid_params");return{privateKey:h.privateKey,publicKey:h.publicKey}}function p({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let i=o({derivationPath:u,phrase:c}),l=U(J.Zcash);return Ts(l).encode(i.privateKey)}return{...r,createKeysForPath:o,createTransaction:xn,getPrivateKeyFromMnemonic:p,signAndBroadcastTransaction:a,signTransaction:s,transfer:d,validateAddress:wt}}import{hex as _s}from"@scure/base";import{HDKey as As}from"@scure/bip32";import{derivationPathToString as Os,NetworkDerivationPath as Ss,updateDerivationPath as Cs}from"@swapkit/helpers";function Xs({xpub:e,chain:t,count:n,startIndex:r=0,accountIndex:s,purpose:a,scriptType:d}){if(z("count",n),n<1)throw RangeError("count must be at least 1");z("startIndex",r),Le(t,d),dt({chain:t,purpose:a,scriptType:d});let o=U(t),p=As.fromExtendedKey(e,o.bip32),c=a===void 0?void 0:Cs(Ss[t],{purpose:a}),u=te({accountIndex:s,chain:t,derivationPath:c}),i=pe(u),l=[];for(let h of[!1,!0]){let m=p.deriveChild(Number(h));for(let f=0;f<n;f++){let y=r+f,b=m.deriveChild(y);if(!b.publicKey)continue;let S=Ae({accountIndex:s,chain:t,change:h,derivationPath:c,index:y});l.push({accountIndex:i,address:De({chain:t,network:o,publicKey:b.publicKey,scriptType:d}),change:h,index:y,pubkey:_s.encode(b.publicKey),...a===void 0?{}:{path:Os(S)}})}}return l}function ga(e,t){switch(e){case we.BitcoinCash:return mn(t||{});case we.Zcash:return Un(t);case we.Bitcoin:case we.Dogecoin:case we.Litecoin:case we.Dash:return ce({chain:e,...t});default:throw new Bs("toolbox_utxo_not_supported",{chain:e})}}export{qt as InputSizes,ho as MIN_TX_FEE,Cr as OP_RETURN_OVERHEAD,lt as OutputSizes,Sr as SEGWIT_MARKER_FLAG_WEIGHT,ht as TX_OVERHEAD,oe as UTXOScriptType,Dt as UtxoNetwork,M as accumulative,ie as addInputsAndOutputs,dn as addressFromKeysGetter,z as assertDerivationIndex,ge as calculateTxSize,E as compileMemo,mn as createBCHToolbox,Hs as createCustomUtxoApi,Xn as createHDWalletHelpers,ce as createUTXOToolbox,Un as createZcashToolbox,Xs as deriveAddressesFromXpub,Vs as detectAddressNetwork,Se as getBchAddressType,ke as getDustThreshold,Be as getInputScriptType,se as getInputSize,bt as getMissingSpendingMetadata,U as getNetworkForChain,je as getOutputSize,Xr as getOutputSizeForAddress,Ye as getScriptTypeForAddress,pe as getUTXOAccountIndexFromPath,te as getUTXOAccountPath,Ae as getUTXOAddressPath,cn as getUTXOAddressValidator,Y as getUtxoAddressType,A as getUtxoApi,Rs as getUtxoNetwork,ga as getUtxoToolbox,Tt as getWitnessOverhead,Gr as getZcashAddressType,ft as isSegwitScriptType,$s as isValidAddress,Zt as nonSegwitChains,W as stripPrefix,et as stripToCashAddress,Me as toCashAddress,G as toLegacyAddress,Ne as tryDecodeAddress,Ie as validateBchAddress,tn as validateUtxoAddress,wt as validateZcashAddress};
@@ -27,7 +27,7 @@ export type MultisigTx = {
27
27
  };
28
28
  /**
29
29
  * Account data returned by signers (matches the cosmjs `AccountData` shape that
30
- * external wallet adapters — Keplr, Leap, Ledger — already produce).
30
+ * external wallet adapters such as Keplr and Ledger already produce).
31
31
  */
32
32
  export type AccountData = {
33
33
  address: string;
@@ -57,7 +57,7 @@ export type DirectSignDoc = {
57
57
  accountNumber: bigint;
58
58
  };
59
59
  /**
60
- * Offline signer for `SIGN_MODE_DIRECT` (Keplr-direct, Leap-direct, local
60
+ * Offline signer for `SIGN_MODE_DIRECT` (Keplr-direct and the local
61
61
  * cosmos-signer wrapper). Replaces `@cosmjs/proto-signing` `OfflineDirectSigner`.
62
62
  */
63
63
  export interface OfflineDirectSigner {
@@ -68,7 +68,7 @@ export interface OfflineDirectSigner {
68
68
  }>;
69
69
  }
70
70
  /**
71
- * Offline signer for `SIGN_MODE_LEGACY_AMINO_JSON` (Keplr-amino, Leap-amino,
71
+ * Offline signer for `SIGN_MODE_LEGACY_AMINO_JSON` (Keplr-amino,
72
72
  * Ledger, local amino wrappers). Replaces `@cosmjs/amino` `OfflineAminoSigner`.
73
73
  */
74
74
  export interface OfflineAminoSigner {
@@ -1,4 +1,5 @@
1
1
  export { checkTronAccountExists, getTronChainParameters } from "./helpers/trongrid";
2
+ export { tronAddressToHex } from "./helpers/utils";
2
3
  export { estimateTronSweepDeduction, getTronPrivateKeyFromMnemonic, getTronToolbox, TRON_SWEEP_ESTIMATE_TIMEOUT_MS, validateTronAddress, withTronTransactionData, withTronTransactionValue, } from "./toolbox";
3
4
  export type { TronApprovedParams, TronApproveParams, TronCreateTransactionParams, TronIsApprovedParams, TronSignedTransaction, TronSigner, TronToolboxOptions, TronTransaction, TronTransactionMetadata, TronTransactionWithMetadata, TronTransferParams, } from "./types";
4
5
  import type { getTronToolbox } from "./toolbox";
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "dependencies": { "@swapkit/helpers": "6.1.0", "@swapkit/utxo-signer": "3.1.0" },
2
+ "dependencies": { "@swapkit/helpers": "6.1.1", "@swapkit/utxo-signer": "3.1.1" },
3
3
  "description": "SwapKit - Toolboxes",
4
4
  "devDependencies": {
5
5
  "@aptos-labs/ts-sdk": "7.0.1",
@@ -131,5 +131,5 @@
131
131
  "type-check:go": "tsgo"
132
132
  },
133
133
  "type": "module",
134
- "version": "6.1.0"
134
+ "version": "6.2.0"
135
135
  }