@swapkit/toolboxes 6.3.0 → 6.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/chunk-1shb645r.js +1 -0
  3. package/dist/{chunk-exyqap7m.js → chunk-pz8xe0qj.js} +1 -1
  4. package/dist/{chunk-xdkdc1f0.js → chunk-qk8kg62t.js} +1 -1
  5. package/dist/chunk-vdabez6b.js +2 -0
  6. package/dist/src/aleo/index.js +1 -1
  7. package/dist/src/aptos/index.js +1 -1
  8. package/dist/src/cardano/index.js +1 -1
  9. package/dist/src/cosmos/index.js +1 -1
  10. package/dist/src/evm/index.js +1 -1
  11. package/dist/src/hypercore/index.js +1 -1
  12. package/dist/src/index.js +1 -1
  13. package/dist/src/lightspark/index.js +1 -0
  14. package/dist/src/near/index.js +1 -1
  15. package/dist/src/radix/index.js +1 -1
  16. package/dist/src/ripple/index.js +1 -1
  17. package/dist/src/solana/index.js +1 -1
  18. package/dist/src/starknet/index.js +1 -1
  19. package/dist/src/stellar/index.js +1 -1
  20. package/dist/src/substrate/index.js +1 -1
  21. package/dist/src/sui/index.js +1 -1
  22. package/dist/src/ton/index.js +1 -1
  23. package/dist/src/tron/index.js +1 -1
  24. package/dist/src/utxo/index.js +1 -1
  25. package/dist/types/evm/helpers.d.ts +4 -0
  26. package/dist/types/evm/toolbox/baseEVMToolbox.d.ts +1 -1
  27. package/dist/types/evm/toolbox/evm.d.ts +24 -24
  28. package/dist/types/evm/toolbox/op.d.ts +2 -2
  29. package/dist/types/hypercore/payin.d.ts +0 -1
  30. package/dist/types/lightspark/__tests__/vendorMissing.probe.d.ts +1 -0
  31. package/dist/types/lightspark/helpers.d.ts +13 -0
  32. package/dist/types/lightspark/index.d.ts +3 -0
  33. package/dist/types/lightspark/invoiceAssert.d.ts +18 -0
  34. package/dist/types/lightspark/toolbox.d.ts +13 -0
  35. package/dist/types/lightspark/types.d.ts +196 -0
  36. package/dist/types/starknet/types.d.ts +1 -0
  37. package/dist/types/sui/__tests__/grpcClientMock.d.ts +37 -0
  38. package/package.json +6 -2
  39. package/dist/chunk-ncc6qmj6.js +0 -1
  40. package/dist/chunk-ygq25ce3.js +0 -2
@@ -1 +1 @@
1
- import{ja as k}from"../../chunk-exyqap7m.js";import{isValidSuiAddress as V}from"@mysten/sui/utils";import{AssetValue as x,Chain as _,derivationPathToString as W,getChainConfig as K,getRPCUrlSync as J,resolveDerivationPath as L,SwapKitError as y}from"@swapkit/helpers";import{match as M,P as j}from"ts-pattern";var I="0x2::sui::SUI",R=256,Y=50000000;async function U(t,a,i,o){let r=[],s,f=0n;while(!0){let c=await t.getCoins({coinType:i,cursor:s,owner:a});if(r.push(...c.data),f+=c.data.reduce((T,w)=>T+BigInt(w.balance),0n),!c.hasNextPage||o!==void 0&&f>=o)return r;s=c.nextCursor}}async function N(t){return BigInt(await t.getReferenceGasPrice())}function v({coinObjectId:t,digest:a,version:i}){return{digest:a,objectId:t,version:i}}function Q(t,a,i,o=!1){let r=a.reduce((l,S)=>l+BigInt(S.balance),0n);if(r<i)throw new y("toolbox_sui_insufficient_balance",{available:r.toString(),required:i.toString()});let{selectedCoins:s}=a.reduce((l,S)=>{if(l.total>=i)return l;return{selectedCoins:[...l.selectedCoins,S],total:l.total+BigInt(S.balance)}},{selectedCoins:[],total:0n}),f=s[0],c=t.objectRef(v(f)),T=s.slice(1).map((l)=>t.objectRef(v(l)));if(T.length>0)t.mergeCoins(c,T);if(o)return c;let[w]=t.splitCoins(c,[i]);return w}function H(t,a){let i=t.reduce((o,r)=>o+BigInt(r.balance),0n);if(i<=0n)throw new y({errorKey:"toolbox_sweep_amount_too_low",info:{asset:a,available:i.toString()}});return i}function q(t){if(t.length>R)throw new y({errorKey:"toolbox_sui_transaction_creation_error",info:{coinCount:t.length,maxGasPaymentCoins:R,reason:`SUI transactions support at most ${R} gas payment coins`}})}function X(t,a,i,o,r,s){let f=i.getBaseValue("bigint");if(s)H(a,i.toString()),q(a);else F(a,f+BigInt(o));if(t.setGasPayment(a.map(v)),s)t.transferObjects([t.gas],r);else{let[c]=t.splitCoins(t.gas,[i.getBaseValue("string")]);t.transferObjects([c],r)}}function F(t,a){let i=t.reduce((o,r)=>o+BigInt(r.balance),0n);if(i<a)throw new y("toolbox_sui_insufficient_balance",{available:i.toString(),required:a.toString()})}async function z({assetValue:t,gasBudget:a,recipient:i,sender:o,suiClient:r,sweep:s,tx:f}){let c=t.getBaseValue("bigint"),[T,w]=await Promise.all([N(r),U(r,o,I,s?void 0:c+BigInt(a))]);if(f.setGasPrice(T),X(f,w,t,a,i,s),s){let l=w.reduce((S,A)=>S+BigInt(A.balance),0n);return l<BigInt(a)?l:a}return a}async function Z({assetValue:t,gasBudget:a,recipient:i,sender:o,suiClient:r,sweep:s,tx:f}){let c=t.address;if(!c)throw new y("toolbox_sui_missing_coin_type");let T=t.getBaseValue("bigint"),[w,l,S]=await Promise.all([N(r),U(r,o,I,BigInt(a)),U(r,o,c,s?void 0:T)]);if(!S.length&&!s)throw new y("toolbox_sui_no_coins_found",{coinType:c});let A=s?H(S,t.toString()):T;if(F(l,BigInt(a)),s)q(l);f.setGasPrice(w),f.setGasPayment(l.map(v));let D=Q(f,S,A,s);f.transferObjects([D],i)}function tt(t){try{return V(t)}catch{return!1}}function O(t){return"signWithIntent"in t}function at({provider:t,...a}={}){let i;async function o(){if(i)return i;return i=await M(a).with({phrase:j.string},async({phrase:n,derivationPath:e,index:g=0})=>{let{Ed25519Keypair:d}=await import("@mysten/sui/keypairs/ed25519"),u=L({chain:_.Sui,derivationPath:e,index:g});if(u.length!==5||u[3]!==0||u[4]!==0)throw new y("toolbox_derivation_slot_unsupported",{chain:_.Sui,derivationPath:u});let m=W(u,{allHardened:!0});return d.deriveKeypair(n,m)}).with({signer:j.any},({signer:n})=>n).otherwise(()=>{return}),i}async function r(n=t){let{SuiJsonRpcClient:e}=await import("@mysten/sui/jsonRpc");return new e({network:"mainnet",url:n||J(_.Sui)})}async function s(){return(await o())?.toSuiAddress()||""}function f(n){try{let e=x.from({address:n,chain:_.Sui});return{asset:e.toString(),decimals:e.decimal}}catch{}return null}async function c(n){let e=n||await s();if(!e)throw new y("toolbox_sui_address_required");let{baseDecimal:g,chain:d}=K(_.Sui);try{let m=await(await r()).getAllBalances({owner:e}),b=m.find(({coinType:p})=>p===I)?.totalBalance||"0",B=[x.from({chain:d,fromBaseDecimal:g,value:b})];for(let{coinType:p,totalBalance:h}of m){if(p===I||Number(h)<=0)continue;let C=f(p);if(C)B.push(x.from({asset:C.asset,fromBaseDecimal:C.decimals,value:h}))}return B}catch{return[x.from({chain:d})]}}async function T(n){let e=x.from({chain:_.Sui,value:"0.01"});if(!n)return e;try{let g=await r(),{txBytes:d}=await w(n),{effects:{status:u,gasUsed:m}}=await g.dryRunTransactionBlock({transactionBlock:d});if(u.status!=="success")return e;let{baseDecimal:b}=K(_.Sui),B=BigInt(m.computationCost)+BigInt(m.storageCost)-BigInt(m.storageRebate);return x.from({chain:_.Sui,fromBaseDecimal:b,value:B.toString()})}catch{return e}}async function w({recipient:n,assetValue:e,gasBudget:g,sender:d,sweep:u}){let{Transaction:m}=await import("@mysten/sui/transactions"),b=d||await s(),B=g||Y;if(!b)throw new y("toolbox_sui_no_sender");try{let p=await r(),h=new m;h.setSender(b);let C={assetValue:e,gasBudget:B,recipient:n,sender:b,suiClient:p,sweep:u,tx:h},G;if(e.isGasAsset||e.symbol==="SUI"){let P=await z(C);if(BigInt(P)<BigInt(B))G=BigInt(P);h.setGasBudget(P)}else await Z(C),h.setGasBudget(B);let E=await h.build({client:p});if(G!==void 0){let{effects:{status:P}}=await p.dryRunTransactionBlock({transactionBlock:E});if(P.status!=="success")throw new y({errorKey:"toolbox_sweep_amount_too_low",info:{asset:e.toString(),budget:G.toString(),error:P.error}})}return{tx:h,txBytes:E}}catch(p){if(p instanceof y)throw p;throw new y("toolbox_sui_transaction_creation_error",{error:p})}}async function l(n){let e=await o();if(!e)throw new y("toolbox_sui_no_signer");if(n instanceof Uint8Array)return e.signTransaction(n);let{txBytes:g}="tx"in n?n:await w(n);return e.signTransaction(g)}async function S({assetValue:n,gasBudget:e,recipient:g,sweep:d}){let u=await o();if(!u)throw new y("toolbox_sui_no_signer");let m=u.toSuiAddress()||await s();if(!m)throw new y("toolbox_sui_no_sender");let{txBytes:b}=await w({assetValue:n,gasBudget:e,recipient:g,sender:m,sweep:d}),B=await r();if(!O(u)){let h=await u.signTransaction(b),{digest:C}=await B.executeTransactionBlock({signature:h.signature,transactionBlock:h.bytes});return C}let{digest:p}=await B.signAndExecuteTransaction({signer:u,transaction:b});return p}async function A(n){let e=await r(),{digest:g}=await e.executeTransactionBlock({signature:n.signature,transactionBlock:n.bytes});return g}async function D(n){let e=await o();if(!e)throw new y("toolbox_sui_no_signer");let g=await r(),d;if(typeof n==="string")d=Uint8Array.from(Buffer.from(n,"base64"));else if(n instanceof Uint8Array)d=n;else d=await n.build({client:g});if(!O(e)){let m=await e.signTransaction(d),{digest:b}=await g.executeTransactionBlock({signature:m.signature,transactionBlock:m.bytes});return b}let{digest:u}=await g.signAndExecuteTransaction({signer:e,transaction:d});return u}return{broadcastTransaction:A,createTransaction:w,estimateTransactionFee:T,getAddress:s,getBalance:c,signAndBroadcastTransaction:D,signTransaction:l,transfer:S,validateAddress:tt}}export{at as getSuiToolbox,tt as validateSuiAddress};
1
+ import{ka as G}from"../../chunk-pz8xe0qj.js";import{fromBase64 as W,isValidSuiAddress as z,normalizeStructTag as F}from"@mysten/sui/utils";import{AssetValue as A,Chain as C,derivationPathToString as H,getChainConfig as j,getRPCUrlSync as Q,resolveDerivationPath as X,SwapKitError as f}from"@swapkit/helpers";import{match as Z,P as K}from"ts-pattern";var k="0x2::sui::SUI",J=F(k),D=256,nn=50000000;async function*q({fetchPage:n}){let t;do{let e=await n(t);yield e.items,t=e.hasNextPage?e.cursor:null}while(t)}async function tn(n){let t=[];for await(let e of n)t.push(...e);return t}async function O({coinType:n,owner:t,suiClient:e,targetBalance:o}){let r=[],s=0n,d=q({fetchPage:async(c)=>{let m=await e.listCoins({coinType:n,cursor:c,owner:t});return{...m,items:m.objects}}});for await(let c of d)if(r.push(...c),s+=c.reduce((m,p)=>m+BigInt(p.balance),0n),o!==void 0&&s>=o)break;return r}function en({owner:n,suiClient:t}){return tn(q({fetchPage:async(e)=>{let o=await t.listBalances({cursor:e,owner:n});return{...o,items:o.balances}}}))}async function L(n){let{referenceGasPrice:t}=await n.getReferenceGasPrice();return BigInt(t)}function x({objectId:n,digest:t,version:e}){return{digest:t,objectId:n,version:e}}function R(n){return n.$kind==="Transaction"?n.Transaction:n.FailedTransaction}async function U({signedTransaction:{bytes:n,signature:t},suiClient:e}){let o=await e.executeTransaction({signatures:[t],transaction:W(n)});return R(o).digest}function an(n,t,e,o=!1){let r=t.reduce((l,w)=>l+BigInt(w.balance),0n);if(r<e)throw new f("toolbox_sui_insufficient_balance",{available:r.toString(),required:e.toString()});let{selectedCoins:s}=t.reduce((l,w)=>{if(l.total>=e)return l;return{selectedCoins:[...l.selectedCoins,w],total:l.total+BigInt(w.balance)}},{selectedCoins:[],total:0n}),d=s[0],c=n.objectRef(x(d)),m=s.slice(1).map((l)=>n.objectRef(x(l)));if(m.length>0)n.mergeCoins(c,m);if(o)return c;let[p]=n.splitCoins(c,[e]);return p}function M(n,t){let e=n.reduce((o,r)=>o+BigInt(r.balance),0n);if(e<=0n)throw new f({errorKey:"toolbox_sweep_amount_too_low",info:{asset:t,available:e.toString()}});return e}function V(n){if(n.length>D)throw new f({errorKey:"toolbox_sui_transaction_creation_error",info:{coinCount:n.length,maxGasPaymentCoins:D,reason:`SUI transactions support at most ${D} gas payment coins`}})}function rn(n,t,e,o,r,s){let d=e.getBaseValue("bigint");if(s)M(t,e.toString()),V(t);else Y(t,d+BigInt(o));if(n.setGasPayment(t.map(x)),s)n.transferObjects([n.gas],r);else{let[c]=n.splitCoins(n.gas,[e.getBaseValue("string")]);n.transferObjects([c],r)}}function Y(n,t){let e=n.reduce((o,r)=>o+BigInt(r.balance),0n);if(e<t)throw new f("toolbox_sui_insufficient_balance",{available:e.toString(),required:t.toString()})}async function on({assetValue:n,gasBudget:t,recipient:e,sender:o,suiClient:r,sweep:s,tx:d}){let c=n.getBaseValue("bigint"),[m,p]=await Promise.all([L(r),O({coinType:k,owner:o,suiClient:r,targetBalance:s?void 0:c+BigInt(t)})]);if(d.setGasPrice(m),rn(d,p,n,t,e,s),s){let l=p.reduce((w,P)=>w+BigInt(P.balance),0n);return l<BigInt(t)?l:t}return t}async function sn({assetValue:n,gasBudget:t,recipient:e,sender:o,suiClient:r,sweep:s,tx:d}){let c=n.address;if(!c)throw new f("toolbox_sui_missing_coin_type");let m=n.getBaseValue("bigint"),[p,l,w]=await Promise.all([L(r),O({coinType:k,owner:o,suiClient:r,targetBalance:BigInt(t)}),O({coinType:c,owner:o,suiClient:r,targetBalance:s?void 0:m})]);if(!w.length&&!s)throw new f("toolbox_sui_no_coins_found",{coinType:c});let P=s?M(w,n.toString()):m;if(Y(l,BigInt(t)),s)V(l);d.setGasPrice(p),d.setGasPayment(l.map(x));let I=an(d,w,P,s);d.transferObjects([I],e)}function cn(n){try{return z(n)}catch{return!1}}function fn({provider:n,...t}={}){let e;async function o(){if(e)return e;return e=await Z(t).with({phrase:K.string},async({phrase:i,derivationPath:a,index:y=0})=>{let{Ed25519Keypair:T}=await import("@mysten/sui/keypairs/ed25519"),g=X({chain:C.Sui,derivationPath:a,index:y});if(g.length!==5||g[3]!==0||g[4]!==0)throw new f("toolbox_derivation_slot_unsupported",{chain:C.Sui,derivationPath:g});let h=H(g,{allHardened:!0});return T.deriveKeypair(i,h)}).with({signer:K.any},({signer:i})=>i).otherwise(()=>{return}),e}async function r(i=n){let{SuiGrpcClient:a}=await import("@mysten/sui/grpc");return new a({baseUrl:i||Q(C.Sui),network:"mainnet"})}async function s(){return(await o())?.toSuiAddress()||""}function d(i){try{let a=A.from({address:i,chain:C.Sui});return{asset:a.toString(),decimals:a.decimal}}catch{}return null}async function c(i){let a=i||await s();if(!a)throw new f("toolbox_sui_address_required");let{baseDecimal:y,chain:T}=j(C.Sui),g;try{g=await en({owner:a,suiClient:await r()})}catch(u){throw new f("toolbox_sui_balance_error",{address:a,error:u})}let h=({coinType:u})=>F(u)===J,_=g.find(h)?.balance||"0",S=[A.from({chain:T,fromBaseDecimal:y,value:_})];for(let u of g){if(h(u)||BigInt(u.balance)<=0n)continue;let b=d(u.coinType);if(b)S.push(A.from({asset:b.asset,fromBaseDecimal:b.decimals,value:u.balance}))}return S}async function m(i){let a=A.from({chain:C.Sui,value:"0.01"});if(!i)return a;try{let y=await r(),{txBytes:T}=await p(i),g=await y.simulateTransaction({include:{effects:!0},transaction:T}),{effects:h,status:_}=R(g);if(!_.success)return a;let{gasUsed:S}=h,{baseDecimal:u}=j(C.Sui),b=BigInt(S.computationCost)+BigInt(S.storageCost)-BigInt(S.storageRebate);return A.from({chain:C.Sui,fromBaseDecimal:u,value:b.toString()})}catch{return a}}async function p({recipient:i,assetValue:a,gasBudget:y,sender:T,sweep:g}){let{Transaction:h}=await import("@mysten/sui/transactions"),_=T||await s(),S=y||nn;if(!_)throw new f("toolbox_sui_no_sender");try{let u=await r(),b=new h;b.setSender(_);let E={assetValue:a,gasBudget:S,recipient:i,sender:_,suiClient:u,sweep:g,tx:b},v;if(a.isGasAsset||a.symbol==="SUI"){let B=await on(E);if(BigInt(B)<BigInt(S))v=BigInt(B);b.setGasBudget(B)}else await sn(E),b.setGasBudget(S);let N=await b.build({client:u});if(v!==void 0){let{status:B}=R(await u.simulateTransaction({transaction:N}));if(!B.success)throw new f({errorKey:"toolbox_sweep_amount_too_low",info:{asset:a.toString(),budget:v.toString(),error:B.error.message}})}return{tx:b,txBytes:N}}catch(u){if(u instanceof f)throw u;throw new f("toolbox_sui_transaction_creation_error",{error:u})}}async function l(i){let a=await o();if(!a)throw new f("toolbox_sui_no_signer");if(i instanceof Uint8Array)return a.signTransaction(i);let{txBytes:y}="tx"in i?i:await p(i);return a.signTransaction(y)}async function w({assetValue:i,gasBudget:a,recipient:y,sweep:T}){let g=await o();if(!g)throw new f("toolbox_sui_no_signer");let h=g.toSuiAddress()||await s();if(!h)throw new f("toolbox_sui_no_sender");let{txBytes:_}=await p({assetValue:i,gasBudget:a,recipient:y,sender:h,sweep:T}),S=await r();return U({signedTransaction:await g.signTransaction(_),suiClient:S})}async function P(i){return U({signedTransaction:i,suiClient:await r()})}async function I(i){let a=await o();if(!a)throw new f("toolbox_sui_no_signer");let y=await r(),T;if(typeof i==="string")T=Uint8Array.from(Buffer.from(i,"base64"));else if(i instanceof Uint8Array)T=i;else T=await i.build({client:y});return U({signedTransaction:await a.signTransaction(T),suiClient:y})}return{broadcastTransaction:P,createTransaction:p,estimateTransactionFee:m,getAddress:s,getBalance:c,signAndBroadcastTransaction:I,signTransaction:l,transfer:w,validateAddress:cn}}export{fn as getSuiToolbox,cn as validateSuiAddress};
@@ -1 +1 @@
1
- import{ia as U}from"../../chunk-xdkdc1f0.js";import{ja as w}from"../../chunk-exyqap7m.js";import{AssetValue as et,Chain as g,getChainConfig as nt,getRPCUrl as ot,NetworkDerivationPath as rt,SwapKitError as d,SwapKitNumber as st}from"@swapkit/helpers";import{Address as i,beginCell as x,Cell as j,external as at,internal as it,loadStateInit as ct,SendMode as N,storeMessage as dt,toNano as L}from"@ton/core";import{match as F,P as B}from"ts-pattern";var lt=260734629,ut=L("0.01"),ft=L("0.05"),G=N.PAY_GAS_SEPARATELY+N.IGNORE_ERRORS,gt=N.CARRY_ALL_REMAINING_BALANCE+N.IGNORE_ERRORS,Tt=60000,O,v=0;async function wt(){let u=Date.now();if(O&&u-v<Tt)return O;let{getHttpEndpoint:p}=await import("@orbs-network/ton-access");return O=await p(),v=u,O}async function pt(){try{return await ot(g.Ton)}catch{return await wt()}}function Nt(u={}){let p,S,A;async function f(){if(!p){let{TonClient:t}=await import("@ton/ton"),e=u.provider??await pt();p=new t({endpoint:e})}return p}async function h(){return(await b()).address.toString()}async function C(){if(A)return A;return A=await F(u).with({phrase:B.string},async({phrase:t,derivationPath:e,index:n=0})=>{let r=rt[g.Ton],o=e?.some((a,c)=>a!==r[c]);if(n||o)throw new d("toolbox_derivation_slot_unsupported",{chain:g.Ton,derivationPath:e,index:n});let{mnemonicToWalletKey:s}=await import("@ton/crypto");return s(t.split(" "))}).with({signer:B.any},({signer:t})=>t).otherwise(()=>{return}),A}async function b(t){if(!S||t){let e=await C(),n=await f(),r=t||e;if(!r)throw new d("core_wallet_connection_not_found");let{WalletContractV4:o}=await import("@ton/ton"),s=o.create({publicKey:r.publicKey,workchain:0});S=n.open(s)}return S}let J=U(g.Ton);async function q({assetValue:t,recipient:e,memo:n,sender:r,sweep:o,jettonWalletAddress:s}){if(t.isGasAsset){if(o){let tt=r||await h(),K=await(await f()).getBalance(i.parse(tt));if(K<=0n)throw new d("toolbox_sweep_amount_too_low",{asset:t.toString(),balance:K.toString()})}let Z=n?D(n).toBoc().toString("base64"):void 0;return[{address:e,amount:t.getBaseValue("string"),payload:Z}]}let a=t.address;if(!a)throw new d({errorKey:"core_swap_contract_not_found",info:{asset:t.toString()}});let c=r??await h(),l=s?i.parse(s):await I({jettonMasterAddress:a,ownerAddress:c}),y=l.toString(),_=i.parse(e),T=i.parse(c),m=o?await H(l):t.getBaseValue("bigint");if(o&&m<=0n)throw new d("toolbox_sweep_amount_too_low",{asset:t.toString(),balance:m.toString()});let Q=n?D(n):void 0,X=V({destinationAddress:_,forwardPayload:Q,jettonAmount:m,responseAddress:T});return[{address:y,amount:ft.toString(),payload:X.toBoc().toString("base64")}]}async function M({sender:t,sweep:e,...n}){let r=e&&n.assetValue.isGasAsset?gt:G;return{messages:await q({...n,sender:t,sweep:e}),sendMode:r}}function k(t){if(!Array.isArray(t))return t;let[e]=t;return{messages:t.map(({sendMode:r,...o})=>o),sendMode:e?.sendMode??G}}function E(t){return t.map((e)=>{let n=e.payload?j.fromBase64(e.payload):void 0,r=e.stateInit?ct(j.fromBase64(e.stateInit).asSlice()):void 0,o=i.parse(e.address),s=i.isFriendly(e.address)?i.parseFriendly(e.address).isBounceable:!0;return it({body:n,bounce:s,init:r,to:o,value:BigInt(e.amount)})})}async function P(t){let e=await C(),n=await b();if(!n||!e)throw new d("core_wallet_connection_not_found");let r=await f(),{state:o}=await r.getContractState(n.address),s=o==="active",a=s?await n.getSeqno():0,{messages:c,sendMode:l}=k(t),y=n.createTransfer({messages:E(c),secretKey:e.secretKey,sendMode:l,seqno:a}),_=at({body:y,init:s?void 0:n.init,to:n.address});return x().store(dt(_)).endCell()}async function W(t){return await(await f()).sendFile(t.toBoc()),t.hash().toString("hex")}async function R(t){let e=await P(t);return W(e)}async function Y({assetValue:t,recipient:e,memo:n,sweep:r}){let o=await M({assetValue:t,memo:n,recipient:e,sweep:r});return R(o)}async function z({sender:t,...e}){let{baseDecimal:n}=nt(g.Ton),r=await F(t).with(B.string,(a)=>i.parseFriendly(a).address).otherwise(async()=>(await b()).address);if(!r)throw new d("toolbox_fee_estimation_failed",{chain:g.Ton});let o=et.from({chain:g.Ton,value:"0.01"}),s=await f();try{let a=await M({sender:t,...e}),c=await C(),l=await b();if(!l||!c)return o;let y=await l.getSeqno(),_=l.createTransfer({messages:E(a.messages),secretKey:c.secretKey,sendMode:a.sendMode,seqno:y}),{source_fees:T}=await s.estimateExternalMessageFee(r,{body:_,ignoreSignature:!0,initCode:null,initData:null}),m=T.in_fwd_fee+T.storage_fee+T.gas_fee+T.fwd_fee;return o.set(st.fromBigInt(BigInt(m),n))}catch{return o}}async function I({jettonMasterAddress:t,ownerAddress:e}){try{let n=await f(),r=i.parse(t),o=i.parse(e),{JettonMaster:s}=await import("@ton/ton");return await n.open(s.create(r)).getWalletAddress(o)}catch{throw new d({errorKey:"core_swap_contract_not_found",info:{jettonMasterAddress:t,ownerAddress:e}})}}async function H(t){try{let e=await f(),{JettonWallet:n}=await import("@ton/ton");return await e.open(n.create(t)).getBalance()}catch{throw new d({errorKey:"core_swap_contract_not_found",info:{jettonWalletAddress:t.toString()}})}}function V({jettonAmount:t,destinationAddress:e,responseAddress:n,forwardAmount:r=ut,forwardPayload:o}){let s=x().storeUint(lt,32).storeUint(0,64).storeCoins(t).storeAddress(e).storeAddress(n).storeBit(0).storeCoins(r);if(o)s.storeBit(1).storeRef(o);else s.storeBit(0);return s.endCell()}function D(t){return x().storeUint(0,32).storeStringTail(t).endCell()}return{broadcastTransaction:W,createTransaction:M,estimateTransactionFee:z,getAddress:h,getBalance:J,getJettonWalletAddress:I,sign:P,signAndBroadcastTransaction:R,transfer:Y,validateAddress:yt}}function yt(u){try{return i.parse(u),!0}catch{return!1}}export{Nt as getTONToolbox,yt as validateTonAddress};
1
+ import{ja as U}from"../../chunk-qk8kg62t.js";import{ka as w}from"../../chunk-pz8xe0qj.js";import{AssetValue as et,Chain as g,getChainConfig as nt,getRPCUrl as ot,NetworkDerivationPath as rt,SwapKitError as d,SwapKitNumber as st}from"@swapkit/helpers";import{Address as i,beginCell as x,Cell as j,external as at,internal as it,loadStateInit as ct,SendMode as N,storeMessage as dt,toNano as L}from"@ton/core";import{match as F,P as B}from"ts-pattern";var lt=260734629,ut=L("0.01"),ft=L("0.05"),G=N.PAY_GAS_SEPARATELY+N.IGNORE_ERRORS,gt=N.CARRY_ALL_REMAINING_BALANCE+N.IGNORE_ERRORS,Tt=60000,O,v=0;async function wt(){let u=Date.now();if(O&&u-v<Tt)return O;let{getHttpEndpoint:p}=await import("@orbs-network/ton-access");return O=await p(),v=u,O}async function pt(){try{return await ot(g.Ton)}catch{return await wt()}}function Nt(u={}){let p,S,A;async function f(){if(!p){let{TonClient:t}=await import("@ton/ton"),e=u.provider??await pt();p=new t({endpoint:e})}return p}async function h(){return(await b()).address.toString()}async function C(){if(A)return A;return A=await F(u).with({phrase:B.string},async({phrase:t,derivationPath:e,index:n=0})=>{let r=rt[g.Ton],o=e?.some((a,c)=>a!==r[c]);if(n||o)throw new d("toolbox_derivation_slot_unsupported",{chain:g.Ton,derivationPath:e,index:n});let{mnemonicToWalletKey:s}=await import("@ton/crypto");return s(t.split(" "))}).with({signer:B.any},({signer:t})=>t).otherwise(()=>{return}),A}async function b(t){if(!S||t){let e=await C(),n=await f(),r=t||e;if(!r)throw new d("core_wallet_connection_not_found");let{WalletContractV4:o}=await import("@ton/ton"),s=o.create({publicKey:r.publicKey,workchain:0});S=n.open(s)}return S}let J=U(g.Ton);async function q({assetValue:t,recipient:e,memo:n,sender:r,sweep:o,jettonWalletAddress:s}){if(t.isGasAsset){if(o){let tt=r||await h(),K=await(await f()).getBalance(i.parse(tt));if(K<=0n)throw new d("toolbox_sweep_amount_too_low",{asset:t.toString(),balance:K.toString()})}let Z=n?D(n).toBoc().toString("base64"):void 0;return[{address:e,amount:t.getBaseValue("string"),payload:Z}]}let a=t.address;if(!a)throw new d({errorKey:"core_swap_contract_not_found",info:{asset:t.toString()}});let c=r??await h(),l=s?i.parse(s):await I({jettonMasterAddress:a,ownerAddress:c}),y=l.toString(),_=i.parse(e),T=i.parse(c),m=o?await H(l):t.getBaseValue("bigint");if(o&&m<=0n)throw new d("toolbox_sweep_amount_too_low",{asset:t.toString(),balance:m.toString()});let Q=n?D(n):void 0,X=V({destinationAddress:_,forwardPayload:Q,jettonAmount:m,responseAddress:T});return[{address:y,amount:ft.toString(),payload:X.toBoc().toString("base64")}]}async function M({sender:t,sweep:e,...n}){let r=e&&n.assetValue.isGasAsset?gt:G;return{messages:await q({...n,sender:t,sweep:e}),sendMode:r}}function k(t){if(!Array.isArray(t))return t;let[e]=t;return{messages:t.map(({sendMode:r,...o})=>o),sendMode:e?.sendMode??G}}function E(t){return t.map((e)=>{let n=e.payload?j.fromBase64(e.payload):void 0,r=e.stateInit?ct(j.fromBase64(e.stateInit).asSlice()):void 0,o=i.parse(e.address),s=i.isFriendly(e.address)?i.parseFriendly(e.address).isBounceable:!0;return it({body:n,bounce:s,init:r,to:o,value:BigInt(e.amount)})})}async function P(t){let e=await C(),n=await b();if(!n||!e)throw new d("core_wallet_connection_not_found");let r=await f(),{state:o}=await r.getContractState(n.address),s=o==="active",a=s?await n.getSeqno():0,{messages:c,sendMode:l}=k(t),y=n.createTransfer({messages:E(c),secretKey:e.secretKey,sendMode:l,seqno:a}),_=at({body:y,init:s?void 0:n.init,to:n.address});return x().store(dt(_)).endCell()}async function W(t){return await(await f()).sendFile(t.toBoc()),t.hash().toString("hex")}async function R(t){let e=await P(t);return W(e)}async function Y({assetValue:t,recipient:e,memo:n,sweep:r}){let o=await M({assetValue:t,memo:n,recipient:e,sweep:r});return R(o)}async function z({sender:t,...e}){let{baseDecimal:n}=nt(g.Ton),r=await F(t).with(B.string,(a)=>i.parseFriendly(a).address).otherwise(async()=>(await b()).address);if(!r)throw new d("toolbox_fee_estimation_failed",{chain:g.Ton});let o=et.from({chain:g.Ton,value:"0.01"}),s=await f();try{let a=await M({sender:t,...e}),c=await C(),l=await b();if(!l||!c)return o;let y=await l.getSeqno(),_=l.createTransfer({messages:E(a.messages),secretKey:c.secretKey,sendMode:a.sendMode,seqno:y}),{source_fees:T}=await s.estimateExternalMessageFee(r,{body:_,ignoreSignature:!0,initCode:null,initData:null}),m=T.in_fwd_fee+T.storage_fee+T.gas_fee+T.fwd_fee;return o.set(st.fromBigInt(BigInt(m),n))}catch{return o}}async function I({jettonMasterAddress:t,ownerAddress:e}){try{let n=await f(),r=i.parse(t),o=i.parse(e),{JettonMaster:s}=await import("@ton/ton");return await n.open(s.create(r)).getWalletAddress(o)}catch{throw new d({errorKey:"core_swap_contract_not_found",info:{jettonMasterAddress:t,ownerAddress:e}})}}async function H(t){try{let e=await f(),{JettonWallet:n}=await import("@ton/ton");return await e.open(n.create(t)).getBalance()}catch{throw new d({errorKey:"core_swap_contract_not_found",info:{jettonWalletAddress:t.toString()}})}}function V({jettonAmount:t,destinationAddress:e,responseAddress:n,forwardAmount:r=ut,forwardPayload:o}){let s=x().storeUint(lt,32).storeUint(0,64).storeCoins(t).storeAddress(e).storeAddress(n).storeBit(0).storeCoins(r);if(o)s.storeBit(1).storeRef(o);else s.storeBit(0);return s.endCell()}function D(t){return x().storeUint(0,32).storeStringTail(t).endCell()}return{broadcastTransaction:W,createTransaction:M,estimateTransactionFee:z,getAddress:h,getBalance:J,getJettonWalletAddress:I,sign:P,signAndBroadcastTransaction:R,transfer:Y,validateAddress:yt}}function yt(u){try{return i.parse(u),!0}catch{return!1}}export{Nt as getTONToolbox,yt as validateTonAddress};
@@ -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 _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
+ import"../../chunk-pz8xe0qj.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 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};
1
+ import{ia as St,ja as jt}from"../../chunk-qk8kg62t.js";import"../../chunk-pz8xe0qj.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};
@@ -33,6 +33,10 @@ export declare function buildEIP712DomainType(domain: {
33
33
  name: "chainId" | "name" | "version" | "verifyingContract" | "salt";
34
34
  type: "string" | "address" | "uint256" | "bytes32";
35
35
  }[];
36
+ export declare function normalizeTypedDataForSigner<TTypedData extends {
37
+ domain: Parameters<typeof buildEIP712DomainType>[0];
38
+ types: Record<string, unknown>;
39
+ }>(typedData: TTypedData): TTypedData;
36
40
  export declare function parseEIP712FromEVMTx({ chain, abi, data, to, }: {
37
41
  chain: EVMChain;
38
42
  abi: readonly JsonFragment[];
@@ -174,7 +174,7 @@ export declare function BaseEVMToolbox<P extends Provider | BrowserProvider, S e
174
174
  chainId?: bigint;
175
175
  }) => Promise<import("ethers").Authorization>) | undefined;
176
176
  signMessage: ((message: string | Uint8Array) => Promise<string>) | undefined;
177
- signTypedData: (({ domain, types, value }: SignTypedDataParams) => Promise<string>) | undefined;
177
+ signTypedData: ((params: SignTypedDataParams) => Promise<string>) | undefined;
178
178
  transfer: ({ assetValue, memo, recipient, feeOptionKey, sender, sweep, ...tx }: EVMTransferParams) => Promise<string>;
179
179
  validateAddress: typeof validateEVMAddress;
180
180
  };