@swapkit/toolboxes 6.0.0 → 6.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/src/solana/index.js +1 -1
- package/dist/src/tron/index.js +1 -1
- package/dist/src/utxo/index.js +1 -1
- package/dist/types/solana/index.d.ts +3 -0
- package/dist/types/solana/toolbox.d.ts +2 -2
- package/dist/types/tron/__tests__/transactionFixture.d.ts +46 -0
- package/dist/types/tron/helpers/trongrid.d.ts +21 -8
- package/dist/types/tron/helpers/utils.d.ts +1 -0
- package/dist/types/tron/index.d.ts +2 -1
- package/dist/types/tron/toolbox.d.ts +21 -0
- package/dist/types/utxo/helpers/coinselect.d.ts +1 -1
- package/dist/types/utxo/toolbox/params.d.ts +4 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# @swapkit/toolboxes
|
|
2
2
|
|
|
3
|
+
## 6.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#372](https://github.com/swapkit/sdk/pull/372) [`3f07d19`](https://github.com/swapkit/sdk/commit/3f07d19c90e320d1f04ce4088efa66f2edcff24d) Thanks [@ice-chillios](https://github.com/ice-chillios)! - **New `estimateTronSweepDeduction({ assetValue, recipient, memo?, timeoutMs? })`** — a bounded, recipient-aware quote-time reserve for a Tron sweep. A caller reserving a flat constant cannot see a fresh recipient's activation cost, so an address funded with exactly the sell amount swept short of activating the destination and the transfer failed on chain.
|
|
8
|
+
- [#422](https://github.com/swapkit/sdk/pull/422) [`8a1e977`](https://github.com/swapkit/sdk/commit/8a1e977fc99eae87beb62390066d835a721b5c37) Thanks [@ice-chillios](https://github.com/ice-chillios)! - Use an external UTXO signer's optional account `publicKey` consistently in `transfer`, `createTransaction` and `createReplacementTransaction`, so nested segwit and taproot inputs receive their spending metadata. The key must be a 33-byte `Uint8Array`; other values throw `toolbox_utxo_invalid_params`.
|
|
9
|
+
- [#426](https://github.com/swapkit/sdk/pull/426) [`489fa6c`](https://github.com/swapkit/sdk/commit/489fa6c90f668c65b3b7ec2a7d355449f5312ce2) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Add Relay support: `ProviderName.RELAY` is now available, and Relay routes resolve to the generic `swapkit` plugin for any wallet (like Flashnet, Mayan and PactSwap), which signs the route's prebuilt EVM transaction. (via @swapkit/helpers@6.1.0)
|
|
10
|
+
- [#427](https://github.com/swapkit/sdk/pull/427) [`607fac7`](https://github.com/swapkit/sdk/commit/607fac77adfa5fc2e3bd221c71a82b2a99337b56) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - `getTHORNameCost` and `getMAYANameCost` now match on-chain pricing: the 10 RUNE / 10 CACAO registration fee already includes the first year, and each extra year costs 1.0512 (20 tor or 2000 base units per block × 5,256,000 blocks). (via @swapkit/helpers@6.1.0)
|
|
11
|
+
- [#415](https://github.com/swapkit/sdk/pull/415) [`3e3dca0`](https://github.com/swapkit/sdk/commit/3e3dca0aea7625917a797c1a8183c60a47ae5574) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@6.1.0)
|
|
12
|
+
|
|
13
|
+
## 6.0.1
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- [#424](https://github.com/swapkit/sdk/pull/424) [`3254bf4`](https://github.com/swapkit/sdk/commit/3254bf4d7496289307c2f22edabf627f63479611) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Solana: the payer SOL check for SPL transfers that create the recipient's associated token account is now opt-in. Pass `checkPayerBalance: true` to `createTransaction` or `transfer` to get `toolbox_solana_insufficient_balance` instead of a transaction that fails simulation; by default no extra RPC calls are made and the transaction is returned as before. The recipient token account is still created with `CreateIdempotent`.
|
|
18
|
+
- [#415](https://github.com/swapkit/sdk/pull/415) [`3e3dca0`](https://github.com/swapkit/sdk/commit/3e3dca0aea7625917a797c1a8183c60a47ae5574) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@6.0.1)
|
|
19
|
+
|
|
3
20
|
## 6.0.0
|
|
4
21
|
|
|
5
22
|
### Major Changes
|
package/dist/src/solana/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ia as D}from"../../chunk-xdkdc1f0.js";import{ja as
|
|
1
|
+
import{ia as D}from"../../chunk-xdkdc1f0.js";import{ja as d}from"../../chunk-exyqap7m.js";import{PublicKey as P}from"@solana/web3.js";import{AssetValue as A,Chain as p,DerivationPath as F,derivationPathToString as G,getChainConfig as O,getRPCUrl as N,NetworkDerivationPath as L,SwapKitError as T,updateDerivationPath as E}from"@swapkit/helpers";import{match as U,P as B}from"ts-pattern";async function j(n){let e=A.from({address:n,chain:p.Solana});if(e.symbol!=="UNKNOWN")return{decimals:e.decimal||0,id:n,logoURI:e.getIconUrl(),name:e.symbol,symbol:e.ticker};let t=`https://lite-api.jup.ag/tokens/v2/search?query=${encodeURIComponent(n)}`;try{let o=await fetch(t);if(!o.ok)return null;let r=await o.json();if(!Array.isArray(r)||r.length===0)return null;return r.find((a)=>a.id===n)||null}catch{return null}}async function V(n){let e=await w(),{PublicKey:t}=await import("@solana/web3.js"),{TOKEN_PROGRAM_ID:o}=await import("@solana/spl-token"),r=new t(n),{baseDecimal:i}=O(p.Solana),a=await e.getBalance(r),c=[A.from({chain:p.Solana,fromBaseDecimal:i,value:a||0})],s=await e.getParsedTokenAccountsByOwner(r,{programId:o});for(let{account:m}of s.value){let l=m.data.parsed.info,f=l.mint,y=l.tokenAmount.amount;if(Number(y)===0)continue;let u=await j(f),g=u?.symbol||"UNKNOWN",h=u?.decimals||l.tokenAmount.decimals;c.push(A.from({asset:`${p.Solana}.${g}-${f}`,fromBaseDecimal:h,value:y}))}return c}function M(n){try{let e=new P(n);return P.isOnCurve(e.toBytes())}catch{return!1}}function en(n){let e=n&&"index"in n?n.index||0:0,t=G(n&&"derivationPath"in n&&n.derivationPath?n.derivationPath:E(L[p.Solana],{index:e})),o;async function r(){if(o)return o;return o=await U(n).with({phrase:B.string},({phrase:a})=>I({derivationPath:t,phrase:a})).with({signer:B.any},({signer:a})=>a).otherwise(()=>{return}),o}async function i(){let a=await r();return a?.publicKey?R(a.publicKey):""}return{broadcastTransaction:_(w),createKeysForPath:I,createTransaction:K(w),createTransactionFromInstructions:Z,estimateTransactionFee:q(w),getAddress:i,getAddressFromPubKey:R,getBalance:D(p.Solana),getBalanceFromRPC:V,getConnection:w,getPubkeyFromAddress:(a)=>new P(a),signAndBroadcastTransaction:async(a)=>{let c=await x(w,r)(a);return _(w)(c)},signTransaction:x(w,r),transfer:J(w,r),validateAddress:M}}function q(n){return async({recipient:e,assetValue:t,memo:o,isProgramDerivedAddress:r,sender:i})=>{let a=await n(),c=await K(n)({assetValue:t,isProgramDerivedAddress:r,memo:o,recipient:e,sender:i}),s=await C(a,c),{baseDecimal:m}=O(p.Solana);return A.from({chain:p.Solana,fromBaseDecimal:m,value:s})}}async function C(n,e){let t=await n.getFeeForMessage(e.compileMessage());if(t.value===null)throw new T("toolbox_fee_estimation_failed","Could not estimate Solana fee.");return t.value}async function w(){let{Connection:n}=await import("@solana/web3.js"),e=await N(p.Solana);return new n(e,{commitment:"confirmed",fetchMiddleware:(t,o,r)=>{let i={};for(let[a,c]of Object.entries(o?.headers??{})){let s=a.toLowerCase();if(s!=="pragma"&&s!=="solana-client")i[a]=c}r(t,{...o,headers:i})}})}function W(n){return async({assetValue:e,recipient:t,sender:o,isProgramDerivedAddress:r,sweep:i})=>{let a=new P(o);if(e.isGasAsset){let{Transaction:c,SystemProgram:s}=await import("@solana/web3.js");return new c().add(s.transfer({fromPubkey:a,lamports:i?0:e.getBaseValue("number"),toPubkey:new P(t)}))}if(e.address){let c=await n();return H({amount:i?0:e.getBaseValue("number"),connection:c,decimals:e.decimal,from:a,isProgramDerivedAddress:r,recipient:t,sweep:i,tokenAddress:e.address})}return}}async function H({tokenAddress:n,recipient:e,from:t,connection:o,amount:r,decimals:i,isProgramDerivedAddress:a,sweep:c}){let{getAssociatedTokenAddress:s,getAccount:m,createAssociatedTokenAccountIdempotentInstruction:l,createTransferCheckedInstruction:f}=await import("@solana/spl-token"),{Transaction:y}=await import("@solana/web3.js"),u=new y,g=new P(n),h=await s(g,t),S=new P(e),b=await s(g,S,a),k=!1;try{await m(o,b),k=!0}catch{}if(!k)u.add(l(t,b,S,g));let v=c?BigInt((await o.getTokenAccountBalance(h)).value.amount):r;if(c&&v<=0n)throw new T({errorKey:"toolbox_sweep_amount_too_low",info:{asset:n,balance:v.toString()}});return u.add(f(h,g,b,t,v,i)),u}async function z(n,e,t){let{ACCOUNT_SIZE:o,ASSOCIATED_TOKEN_PROGRAM_ID:r}=await import("@solana/spl-token");if(!e.instructions.some(({programId:f})=>f.equals(r)))return;let[a,c,s,m]=await Promise.all([n.getBalance(t),C(n,e),n.getMinimumBalanceForRentExemption(o),n.getMinimumBalanceForRentExemption(0)]),l=c+s+m;if(a<l)throw new T({errorKey:"toolbox_solana_insufficient_balance",info:{balance:a,fee:c,rentReserve:m,required:l,tokenAccountRent:s}})}function K(n){return async({checkPayerBalance:e=!1,recipient:t,assetValue:o,memo:r,isProgramDerivedAddress:i,sender:a,recentBlockhash:c,sweep:s})=>{let{createMemoInstruction:m}=await import("@solana/spl-memo"),l=new P(a);if(!(i||M(t)))throw new T("core_transaction_invalid_recipient_address");let f,y=()=>f??=n(),u=await W(y)({assetValue:o,isProgramDerivedAddress:i,recipient:t,sender:a,sweep:s});if(!u)throw new T("core_transaction_invalid_sender_address");if(r)u.add(m(r));if(u.recentBlockhash=c??(await(await y()).getLatestBlockhash()).blockhash,u.feePayer=l,e&&!o.isGasAsset)await z(await y(),u,l);if(s&&o.isGasAsset){let g=await y(),[h,S,b]=await Promise.all([g.getBalance(l),C(g,u),g.getMinimumBalanceForRentExemption(0)]),k=h-S-b;if(k<=0)throw new T({errorKey:"toolbox_sweep_amount_too_low",info:{balance:h,fee:S,rentReserve:b}});let{SystemProgram:v}=await import("@solana/web3.js");u.instructions[0]=v.transfer({fromPubkey:l,lamports:k,toPubkey:new P(t)})}return u}}async function Z({instructions:n}){let{Transaction:e}=await import("@solana/web3.js"),t=new e().add(...n);if(!t)throw new T("core_transaction_invalid_sender_address");return t}function J(n,e){return async({recipient:t,assetValue:o,checkPayerBalance:r,memo:i,isProgramDerivedAddress:a,sweep:c})=>{let s=await e();if(!s)throw new T("core_transaction_invalid_sender_address");let m=s.publicKey?.toString()??(await s.connect()).publicKey.toString(),l=await K(n)({assetValue:o,checkPayerBalance:r,isProgramDerivedAddress:a,memo:i,recipient:t,sender:m,sweep:c});if("signTransaction"in s){let f=await s.signTransaction(l);return _(n)(f)}return l.sign(s),_(n)(l)}}function _(n){return async(e)=>(await n()).sendRawTransaction(e.serialize())}function x(n,e){return async(t)=>{let o=await e();if(!o)throw new T("toolbox_solana_no_signer");let{VersionedTransaction:r}=await import("@solana/web3.js");if(!(t instanceof r)){let a=await(await n()).getLatestBlockhash();t.recentBlockhash=a.blockhash,t.feePayer=o.publicKey||void 0}if("connect"in o)return await o.signTransaction(t);return t.sign([o]),t}}async function I({phrase:n,derivationPath:e=F.SOL}){let{HDKey:t}=await import("micro-key-producer/slip10.js"),{mnemonicToSeedSync:o}=await import("@scure/bip39"),{Keypair:r}=await import("@solana/web3.js"),i=o(n),a=t.fromMasterSeed(i);return r.fromSeed(a.derive(e,!0).privateKey)}function R(n){return n.toString()}export{I as createKeysForPath,j as fetchTokenMetaData,en as getSolanaToolbox,M as validateSolanaAddress};
|
package/dist/src/tron/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"../../chunk-exyqap7m.js";import{bytesToHex as we}from"@noble/hashes/utils.js";import{HDKey as pe}from"@scure/bip32";import{mnemonicToSeedSync as he}from"@scure/bip39";import{AssetValue as A,Chain as b,derivationPathToString as Dt,getChainConfig as ye,getRPCUrl as be,NetworkDerivationPath as Ut,SwapKitError as m,updateDerivationPath as kt,warnOnce as Nt}from"@swapkit/helpers";import{match as xe,P as z}from"ts-pattern";import{sha256 as jt}from"@noble/hashes/sha2.js";import{bytesToHex as it,hexToBytes as st}from"@noble/hashes/utils.js";import{SwapKitError as I}from"@swapkit/helpers";var K=0,ct=1,L=2,dt=5,Xt=8,Yt=10,zt=18;function j(e,t){let n=0n,o=0n,i=t;while(i<e.length&&i-t<10){let c=e[i++];if(c===void 0)break;if(n|=BigInt(c&127)<<o,o+=7n,(c&128)===0)return[n,i]}throw new I({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Malformed varint in transaction raw_data"}})}function B(e){let t=[],n=e<0n?e+2n**64n:e;while(n>=128n)t.push(Number(n&0x7fn)|128),n>>=7n;return t.push(Number(n)),t}function k(e,t,n){let o=e.get(t);if(o)o.push(n);else e.set(t,[n])}function Jt(e){let t=new Map,n=0;while(n<e.length){let[o,i]=j(e,n);n=i;let c=Number(o>>3n),l=Number(o&7n);if(l===K){let[p,w]=j(e,n);n=w,k(t,c,{data:new Uint8Array(B(p)),wireType:K})}else if(l===L){let[p,w]=j(e,n);n=w;let v=Number(p);if(v<0||n+v>e.length)throw new I({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Length-delimited proto field overruns transaction raw_data"}});let V=e.slice(n,n+v);n+=v,k(t,c,{data:V,wireType:L})}else if(l===ct){if(n+8>e.length)throw new I({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"64-bit proto field overruns transaction raw_data"}});let p=e.slice(n,n+8);n+=8,k(t,c,{data:p,wireType:ct})}else if(l===dt){if(n+4>e.length)throw new I({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"32-bit proto field overruns transaction raw_data"}});let p=e.slice(n,n+4);n+=4,k(t,c,{data:p,wireType:dt})}else throw new I({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Unsupported proto wire type in transaction raw_data"}})}return t}function Qt(e){let t=[];for(let[c,l]of[...e.entries()].sort(([p],[w])=>p-w))for(let{wireType:p,data:w}of l){let v=BigInt(c<<3|p);if(t.push(new Uint8Array(B(v))),p===L)t.push(new Uint8Array(B(BigInt(w.length))));t.push(w)}let n=t.reduce((c,l)=>c+l.length,0),o=new Uint8Array(n),i=0;for(let c of t)o.set(c,i),i+=c.length;return o}function ut(e,t){if(!e||e.length%2!==0)throw new I({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Transaction raw_data_hex is empty or not byte-aligned"}});let n=st(e),o=Jt(n);if(t.expiration!==void 0)o.set(Xt,[{data:new Uint8Array(B(BigInt(t.expiration))),wireType:K}]);if(t.data!==void 0)o.set(Yt,[{data:st(t.data),wireType:L}]);if(t.fee_limit!==void 0)o.set(zt,[{data:new Uint8Array(B(BigInt(t.fee_limit))),wireType:K}]);let i=Qt(o),c=it(i),l=it(jt(i));return{raw_data_hex:c,txID:l}}import{hexToBytes as ae}from"@noble/hashes/utils.js";import{Chain as ie,getRPCUrlSync as se,SwapKitError as y,warnOnce as G}from"@swapkit/helpers";import{secp256k1 as lt}from"@noble/curves/secp256k1.js";import{sha256 as ft}from"@noble/hashes/sha2.js";import{keccak_256 as Zt}from"@noble/hashes/sha3.js";import{bytesToHex as N,hexToBytes as M}from"@noble/hashes/utils.js";import{createBase58check as te}from"@scure/base";import{SwapKitError as gt}from"@swapkit/helpers";var O=te(ft),_t=65,ee=2n**256n;function x(e){if(typeof e!=="string")return!1;try{let t=O.decode(e);return t.length===21&&t[0]===_t}catch{return!1}}function mt(e){return N(O.decode(e))}function ne(e){return O.decode(e).slice(1)}function Tt(e){let t=lt.getPublicKey(M(e),!1),n=Zt(t.slice(1)).slice(-20),o=new Uint8Array(21);return o[0]=_t,o.set(n,1),O.encode(o)}function wt({txID:e,privateKey:t}){let n=lt.sign(M(e),M(t),{format:"recovered",prehash:!1}),o=n[0]??0,i=N(n.slice(1,33)),c=N(n.slice(33,65)),l=(o+27).toString(16).padStart(2,"0");return i+c+l}function R({txID:e,raw_data_hex:t}){let n=N(ft(M(t)));if(e!==n)throw new gt("toolbox_tron_invalid_transaction_integrity",{expected:n,txID:e})}function re(e){return`000000000000000000000000${N(ne(e))}`}function oe(e){let t=typeof e==="bigint"?e:BigInt(e);if(t<0n||t>=ee)throw new gt("toolbox_tron_invalid_token_identifier",{identifier:t.toString()});return t.toString(16).padStart(64,"0")}function S(e){return e.map(({type:t,value:n})=>t==="address"?re(n):oe(BigInt(n))).join("")}function pt(e){return N(new TextEncoder().encode(e))}var yt="https://api.trongrid.io",ce=1000,de=1e6,ue=420,le=1e6,fe=30000;function bt(){try{return se(ie.Tron)}catch{return yt}}function xt(){let e=new AbortController,t=setTimeout(()=>e.abort(),fe);return{cleanup:()=>clearTimeout(t),signal:e.signal}}function At(e){if(!e||typeof e!=="object")return;let{Error:t}=e;return typeof t==="string"&&t.length>0?t:void 0}function ge(e){if(!e)return;if(e.length%2!==0||!/^[0-9a-f]+$/i.test(e))return e;try{let t=new TextDecoder().decode(ae(e));return/^[ -~]+$/.test(t)?t:e}catch{return e}}async function P(e,t){let{signal:n,cleanup:o}=xt();try{let i=await fetch(`${bt()}${e}`,{body:JSON.stringify(t),headers:{"Content-Type":"application/json"},method:"POST",signal:n});if(!i.ok)throw new y("toolbox_tron_trongrid_api_error",{message:`${i.status} ${i.statusText} on ${e}`});return await i.json()}finally{o()}}async function vt(e,t){let{signal:n,cleanup:o}=xt();try{let i=await fetch(`${t??bt()}${e}`,{headers:{"Content-Type":"application/json"},signal:n});if(!i.ok)throw new y("toolbox_tron_trongrid_api_error",{message:`${i.status} ${i.statusText} on ${e}`});return await i.json()}finally{o()}}async function W(e){if(!x(e))throw new y("toolbox_tron_trongrid_api_error",{address:e,message:"Invalid address"});try{let t=await vt(`/v1/accounts/${e}`,yt);if(!(t.success&&t.data)||t.data.length===0)return;let n;try{n=mt(e).toLowerCase()}catch{n=e.toLowerCase()}let o=t.data.find((i)=>i.address.toLowerCase()===n);if(!o)return;return{balance:o.balance,trc20:o.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 _e="/wallet/createtransaction";async function Et({from:e,to:t,amount:n}){let i=await P(_e,{amount:n,owner_address:e,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:At(i)??"Node returned no transaction"}});let l=i.raw_data?.contract?.[0]?.parameter?.value;if(l?.to_address!==t||l?.owner_address!==e||l?.amount!==n)throw new y({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Node returned a transaction that does not match the requested transfer"}});return R(i),i}var me="/wallet/triggersmartcontract";async function Ft({ownerAddress:e,contractAddress:t,functionSelector:n,parameter:o,feeLimit:i,callValue:c=0}){let l=await P(me,{call_value:c,contract_address:t,fee_limit:i,function_selector:n,owner_address:e,parameter:o,visible:!0});if(!l.result?.result||!l.transaction?.txID||!l.transaction?.raw_data_hex)throw new y({errorKey:"toolbox_tron_transaction_creation_failed",info:{code:l.result?.code,error:At(l)??"Node returned no transaction",message:ge(l.result?.message)}});let w=l.transaction.raw_data?.contract?.[0]?.parameter?.value;if(w?.contract_address!==t||w?.owner_address!==e)throw new y({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Node returned a transaction that does not match the requested contract call"}});return R(l.transaction),l.transaction}function Pt({ownerAddress:e,contractAddress:t,functionSelector:n,parameter:o}){return P("/wallet/triggerconstantcontract",{contract_address:t,function_selector:n,owner_address:e,parameter:o,visible:!0})}function Te({ownerAddress:e,contractAddress:t,functionSelector:n,parameter:o}){return P("/wallet/estimateenergy",{contract_address:t,function_selector:n,owner_address:e,parameter:o,visible:!0})}function ht(e){let t=typeof e==="number"?e:typeof e==="string"?Number(e):Number.NaN;return Number.isFinite(t)&&t>0?t:void 0}async function C(e){try{let{result:t,txid:n}=await P("/wallet/broadcasttransaction",{raw_data:e.raw_data,raw_data_hex:e.raw_data_hex,signature:e.signature,txID:e.txID,visible:e.visible});if(!t||!n)throw new y("toolbox_tron_token_transfer_failed");return n}catch(t){throw new y("toolbox_tron_broadcast_failed",{error:t})}}async function D(){let e={};try{let{chainParameter:t}=await vt("/wallet/getchainparameters");for(let n of t)e[n.key]=n.value}catch(t){G({condition:!0,id:"tron_chain_params_failed",warning:`Failed to fetch chain params, using defaults: ${t instanceof Error?t.message:t}`})}return{bandwidthFee:e.getTransactionFee??ce,createAccountFee:e.getCreateNewAccountFeeInSystemContract??e.getCreateAccountFee??de,energyFee:e.getEnergyFee??ue,memoFee:e.getMemoFee??le}}async function X(e){try{let t=await P("/wallet/getaccountresource",{address:e,visible:!0});return{bandwidth:{free:(t.freeNetLimit??600)-(t.freeNetUsed??0),total:t.NetLimit??0,used:t.NetUsed??0},energy:{total:t.EnergyLimit??0,used:t.EnergyUsed??0}}}catch(t){return G({condition:!0,id:"tron_account_resources_failed",warning:`Failed to fetch account resources, using defaults: ${t instanceof Error?t.message:t}`}),{bandwidth:{free:600,total:0,used:0},energy:{total:0,used:0}}}}async function U(e){try{let t=await P("/wallet/getaccount",{address:e,visible:!0});return t&&Object.keys(t).length>0}catch{return!1}}async function Y(e){try{let t=await Te({...e,ownerAddress:e.sender}),n=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(n!==void 0){let o=ht(n);if(o!==void 0)return o;throw new y("toolbox_tron_trongrid_api_error",{message:"Invalid estimateenergy response"})}}catch(t){G({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 Pt({...e,ownerAddress:e.sender}),n=ht(t);if(n!==void 0)return n;throw new y("toolbox_tron_trongrid_api_error",{message:"Invalid triggerconstantcontract energy response"})}catch(t){throw G({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 It({assetAddress:e,owner:t,spender:n}){let o=S([{type:"address",value:t},{type:"address",value:n}]),c=(await Pt({contractAddress:e,functionSelector:"allowance(address,address)",ownerAddress:n,parameter:o})).constant_result?.[0];if(!c)return 0n;try{return BigInt(`0x${c}`)}catch{return 0n}}var Ae=x,H=ye(b.Tron).baseDecimal,Rt=268,St=65000,J=25000,Bt=345,Q="TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",ve="115792089237316195423570985008687907853269984665640564039457584007913129639935";function Kt({phrase:e,derivationPath:t}){let n=pe.fromMasterSeed(he(e)).derive(t);if(!n.privateKey)throw new m("toolbox_tron_no_signer");return we(n.privateKey)}function Ee(e,t){return{...e,value:String(t)}}function Fe(e,t){if(!t)return e;return{...e,data:t.startsWith("0x")?t:`0x${t}`}}function Pe({phrase:e,derivationPath:t,index:n}){let o=t||Dt(kt(Ut[b.Tron],{index:n||0}));return Kt({derivationPath:o,phrase:e})}function Ie({phrase:e,derivationPath:t}){let n=Kt({derivationPath:t,phrase:e}),o=Tt(n);return{getAddress:()=>Promise.resolve(o),signTransaction:(i)=>{R(i);let c=wt({privateKey:n,txID:i.txID});return Promise.resolve({...i,signature:[c]})}}}function Ct({transaction:e,memo:t,expiration:n,feeLimit:o}){let i={},c={};if(o!==void 0&&e.raw_data)i.fee_limit=o,c.fee_limit=o;if(t){let w=t.startsWith("0x")?t.replace(/^0x/,""):pt(t);i.data=w,c.data=w}if(n){let w=e.raw_data.expiration+n*1000;i.expiration=w,c.expiration=w}if(Object.keys(i).length===0)return e;let{raw_data_hex:l,txID:p}=ut(e.raw_data_hex,i);return{...e,raw_data:{...e.raw_data,...c},raw_data_hex:l,txID:p}}function Ne(e={}){let t="index"in e?e.index||0:0,n=Dt("derivationPath"in e&&e.derivationPath?e.derivationPath:kt(Ut[b.Tron],{index:t})),o,i=!1;function c(){if(i)return Promise.resolve(o);return o=xe(e).with({phrase:z.string},({phrase:r})=>Ie({derivationPath:n,phrase:r})).with({signer:z.not(z.nullish)},({signer:r})=>r).otherwise(()=>{return}),i=!0,Promise.resolve(o)}async function l(){let r=await c();if(!r)throw new m("toolbox_tron_no_signer");return r.getAddress()}async function p(r,a){let d=r||St,s=a??(await D()).energyFee,u=d*s,f=Math.ceil(u*1.5);return Math.min(Math.max(f,1e7),150000000)}async function w({contractAddress:r,functionSelector:a,parameter:d,sender:s,memo:u,expiration:f,extraEnergy:g=0}){let _=await Y({contractAddress:r,functionSelector:a,parameter:d,sender:s}),T=await p(_+g),h=await Ft({contractAddress:r,feeLimit:T,functionSelector:a,ownerAddress:s,parameter:d});return Ct({expiration:f,feeLimit:T,memo:u,transaction:h})}async function v(r){if(!x(r))return[A.from({chain:b.Tron})];try{let a=await W(r);if(!a)return[A.from({chain:b.Tron})];let d=[A.from({chain:b.Tron,fromBaseDecimal:6,value:String(a.balance)})],s=a.trc20?.find((u)=>(Q in u));if(s){let u=s[Q];d.push(A.from({asset:`TRON.USDT-${Q}`,fromBaseDecimal:6,value:u}))}return d}catch(a){return Nt({condition:!0,id:"tron_toolbox_get_balance_failed",warning:`Tron API getBalance failed: ${a instanceof Error?a.message:a}`}),[A.from({chain:b.Tron})]}}async function V({recipient:r,assetValue:a,memo:d,expiration:s,sweep:u}){if(!x(r))throw new m("toolbox_tron_token_transfer_failed",{message:"invalid address"});let f=await c();if(!f)throw new m("toolbox_tron_no_signer");try{let g=await l(),_=await nt({assetValue:a,expiration:s,memo:d,recipient:r,sender:g,sweep:u}),T=await f.signTransaction(_),h=await C(T);if(!h)throw new m("toolbox_tron_token_transfer_failed",{message:"broadcast failed"});return h}catch(g){if(g instanceof m&&g.errorKey==="toolbox_sweep_amount_too_low")throw g;throw new m("toolbox_tron_token_transfer_failed",{message:g instanceof Error?g.message:String(g)})}}function Z({requiredBandwidth:r,resources:a,feePerUnit:d}){let s=Math.max(0,a.free+a.total-a.used);return r>s?(r-s)*d:0}async function tt({memo:r,recipient:a,senderAddress:d}){let[s,u,f]=await Promise.all([D(),U(a),X(d)]),g=u?0:s.createAccountFee,_=Z({feePerUnit:s.bandwidthFee,requiredBandwidth:Rt,resources:f.bandwidth}),T=r?s.memoFee:0;return A.from({chain:b.Tron,fromBaseDecimal:H,value:g+_+T})}async function et({assetValue:r,amountInBaseUnits:a=r.getBaseValue("string"),memo:d,recipient:s,senderAddress:u}){let f=r.address;if(!f)throw new m("toolbox_tron_invalid_token_identifier",{identifier:r.toString()});let[g,_,T,h]=await Promise.all([D(),U(s),X(u),Y({contractAddress:f,functionSelector:"transfer(address,uint256)",parameter:S([{type:"address",value:s},{type:"uint256",value:a}]),sender:u})]),F=h+(_?0:J),q=Z({feePerUnit:g.bandwidthFee,requiredBandwidth:Bt,resources:T.bandwidth}),at=Math.max(0,T.energy.total-T.energy.used),Vt=F>at?(F-at)*g.energyFee:0,qt=d?g.memoFee:0;return A.from({chain:b.Tron,fromBaseDecimal:H,value:q+Vt+qt})}async function Lt({assetValue:r,memo:a,recipient:d}){let[s,u]=await Promise.all([D(),U(d)]);if(r.isGasAsset){let T=u?0:s.createAccountFee,h=a?s.memoFee:0;return A.from({chain:b.Tron,fromBaseDecimal:H,value:T+Rt*s.bandwidthFee+h})}let g=await p(St+(u?0:J),s.energyFee),_=a?s.memoFee:0;return A.from({chain:b.Tron,fromBaseDecimal:H,value:g+Bt*s.bandwidthFee+_})}async function Mt({assetValue:r,memo:a,recipient:d,sender:s}){let u=await c();try{let f=s?s:u?await l():void 0;if(!f)return Lt({assetValue:r,memo:a,recipient:d});return r.isGasAsset?tt({memo:a,recipient:d,senderAddress:f}):et({assetValue:r,memo:a,recipient:d,senderAddress:f})}catch(f){throw Nt({condition:!0,id:"tron_toolbox_fee_estimation_failed",warning:`Failed to calculate exact fee: ${f instanceof Error?f.message:f}`}),new m("toolbox_fee_estimation_failed",{chain:b.Tron,error:f})}}async function Ot({assetValue:r,memo:a,recipient:d,sender:s,sweep:u}){if(!u)return r.getBaseValue("bigint");let[f,g]=await Promise.all([W(s),tt({memo:a,recipient:d,senderAddress:s})]),_=BigInt(f?.balance??0)-g.getBaseValue("bigint");if(_<=0n)throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{amount:_.toString(),asset:r.toString()}});return _}async function $t({assetValue:r,memo:a,recipient:d,sender:s,sweep:u}){if(!u)return r.getBaseValue("string");let f=r.address;if(!f)throw new m("toolbox_tron_invalid_token_identifier",{identifier:r.toString()});let g=await W(s),T=g?.trc20.find((q)=>(f in q))?.[f]??"0";if(BigInt(T)<=0n)throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{asset:r.toString(),balance:T}});let h=await et({amountInBaseUnits:T,assetValue:r,memo:a,recipient:d,senderAddress:s}),E=BigInt(g?.balance??0),F=h.getBaseValue("bigint");if(E<F)throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{asset:r.toString(),nativeBalance:E.toString(),requiredNativeFee:F.toString()}});return T}async function nt({recipient:r,assetValue:a,memo:d,sender:s,expiration:u,sweep:f,recipientExists:g}){if(!x(r)||!x(s))throw new m("toolbox_tron_transaction_creation_failed",{message:"invalid address"});if(a.isGasAsset){let E=await Ot({assetValue:a,expiration:u,memo:d,recipient:r,sender:s,sweep:f});if(E>BigInt(Number.MAX_SAFE_INTEGER))throw new m({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 Et({amount:Number(E),from:s,to:r});return Ct({expiration:u,memo:d,transaction:F})}let _=a.address;if(!_)throw new m("toolbox_tron_invalid_token_identifier",{identifier:a.toString()});let T=await $t({assetValue:a,expiration:u,memo:d,recipient:r,sender:s,sweep:f}),h=g??await U(r);return w({contractAddress:_,expiration:u,extraEnergy:h?0:J,functionSelector:"transfer(address,uint256)",memo:d,parameter:S([{type:"address",value:r},{type:"uint256",value:T}]),sender:s})}async function rt(r){R(r);let a=await c();if(!a)throw new m("toolbox_tron_no_signer");return a.signTransaction(r)}async function Gt(r){let a=await rt(r);return C(a)}function ot({assetAddress:r,spenderAddress:a,from:d}){return It({assetAddress:r,owner:d,spender:a})}async function Wt({assetAddress:r,spenderAddress:a,from:d,amount:s}){let u=await ot({assetAddress:r,from:d,spenderAddress:a});if(!s)return u>0n;return u>=BigInt(s)}async function Ht({assetAddress:r,spenderAddress:a,amount:d,from:s}){if(!x(r)||!x(a))throw new m("toolbox_tron_approve_failed");let u=await c();if(!u)throw new m("toolbox_tron_no_signer");let f=s||await l(),g=d!==void 0?BigInt(d).toString():ve;try{let _=await w({contractAddress:r,functionSelector:"approve(address,uint256)",parameter:S([{type:"address",value:a},{type:"uint256",value:g}]),sender:f}),T=await u.signTransaction(_),h=await C(T);if(!h)throw new m("toolbox_tron_approve_failed");return h}catch(_){if(_ instanceof m)throw _;throw new m("toolbox_tron_approve_failed",{error:_})}}return{approve:Ht,broadcastTransaction:C,createTransaction:nt,estimateTransactionFee:Mt,getAddress:l,getApprovedAmount:ot,getBalance:v,getRpcUrl:()=>be(b.Tron),isApproved:Wt,signAndBroadcastTransaction:Gt,signTransaction:rt,transfer:V,validateAddress:x}}export{Pe as getTronPrivateKeyFromMnemonic,Ne as getTronToolbox,Ae as validateTronAddress,Fe as withTronTransactionData,Ee as withTronTransactionValue};
|
|
1
|
+
import"../../chunk-exyqap7m.js";import{hexToBytes as un}from"@noble/hashes/utils.js";import{Chain as fn,getRPCUrlSync as ln,SwapKitError as y,warnOnce as K}from"@swapkit/helpers";import{secp256k1 as gt}from"@noble/curves/secp256k1.js";import{sha256 as _t}from"@noble/hashes/sha2.js";import{keccak_256 as nn}from"@noble/hashes/sha3.js";import{bytesToHex as S,hexToBytes as M}from"@noble/hashes/utils.js";import{createBase58check as en}from"@scure/base";import{SwapKitError as Tt}from"@swapkit/helpers";var L=en(_t),mt=65,rn=2n**256n;function b(n){if(typeof n!=="string")return!1;try{let t=L.decode(n);return t.length===21&&t[0]===mt}catch{return!1}}function wt(n){return S(L.decode(n))}function on(n){return L.decode(n).slice(1)}function pt(n){let t=gt.getPublicKey(M(n),!1),e=nn(t.slice(1)).slice(-20),r=new Uint8Array(21);return r[0]=mt,r.set(e,1),L.encode(r)}function yt({txID:n,privateKey:t}){let e=gt.sign(M(n),M(t),{format:"recovered",prehash:!1}),r=e[0]??0,i=S(e.slice(1,33)),o=S(e.slice(33,65)),c=(r+27).toString(16).padStart(2,"0");return i+o+c}function N({txID:n,raw_data_hex:t}){let e=S(_t(M(t)));if(n!==e)throw new Tt("toolbox_tron_invalid_transaction_integrity",{expected:e,txID:n})}function an(n){return`000000000000000000000000${S(on(n))}`}function sn(n){let t=typeof n==="bigint"?n:BigInt(n);if(t<0n||t>=rn)throw new Tt("toolbox_tron_invalid_token_identifier",{identifier:t.toString()});return t.toString(16).padStart(64,"0")}function R(n){return n.map(({type:t,value:e})=>t==="address"?an(e):sn(BigInt(e))).join("")}function cn(n){return S(new TextEncoder().encode(n))}var dn=/^0x(?:[0-9a-fA-F]{2})+$/;function z(n){return dn.test(n)?n.slice(2):cn(n)}var bt="https://api.trongrid.io",gn=1000,_n=1e5,Tn=1e6,mn=420,wn=1e6,pn=30000,yn=2147483647;function xt(){try{return ln(fn.Tron)}catch{return bt}}function At(n){let t=n!==void 0&&Number.isFinite(n)&&n>0?Math.min(n,yn):pn,e=new AbortController,r=setTimeout(()=>e.abort(),t);return{cleanup:()=>clearTimeout(r),signal:e.signal}}function Z(n){if(!n||typeof n!=="object")return;let{Error:t}=n;return typeof t==="string"&&t.length>0?t:void 0}function hn(n){if(!n)return;if(n.length%2!==0||!/^[0-9a-f]+$/i.test(n))return n;try{let t=new TextDecoder().decode(un(n));return/^[ -~]+$/.test(t)?t:n}catch{return n}}function Et(n,t){if(typeof n!=="string")return!1;if(n===t)return!0;try{return n.toLowerCase()===wt(t).toLowerCase()}catch{return!1}}function Q(n){let t=typeof n==="number"?n:typeof n==="string"&&n.trim()!==""?Number(n):Number.NaN;return Number.isSafeInteger(t)&&t>=0?t:void 0}function C(n){let t=Q(n);return t!==void 0&&t>0?t:void 0}function J(n,t){let e=Q(n),r=Q(t);if(n!==void 0&&e===void 0||t!==void 0&&r===void 0)return 0;return Math.max(0,(e??0)-(r??0))}async function v(n,t,e){let{signal:r,cleanup:i}=At(e);try{let o=await fetch(`${xt()}${n}`,{body:JSON.stringify(t),headers:{"Content-Type":"application/json"},method:"POST",signal:r});if(!o.ok)throw new y("toolbox_tron_trongrid_api_error",{message:`${o.status} ${o.statusText} on ${n}`});return await o.json()}finally{i()}}async function vt(n,t,e){let{signal:r,cleanup:i}=At(e);try{let o=await fetch(`${t??xt()}${n}`,{headers:{"Content-Type":"application/json"},signal:r});if(!o.ok)throw new y("toolbox_tron_trongrid_api_error",{message:`${o.status} ${o.statusText} on ${n}`});return await o.json()}finally{i()}}async function O(n){if(!b(n))throw new y("toolbox_tron_trongrid_api_error",{address:n,message:"Invalid address"});try{let t=await vt(`/v1/accounts/${n}`,bt);if(!(t.success&&t.data)||t.data.length===0)return;let e=t.data.find((r)=>Et(r.address,n));if(!e)return;return{balance:e.balance,trc20:e.trc20||[]}}catch(t){if(t instanceof y)throw t;throw new y("toolbox_tron_trongrid_api_error",{message:t instanceof Error?t.message:"Unknown error"})}}var bn="/wallet/createtransaction";async function Ft({from:n,to:t,amount:e}){let i=await v(bn,{amount:e,owner_address:n,to_address:t,visible:!0});if(!i.txID||!i.raw_data_hex||!i.raw_data)throw new y({errorKey:"toolbox_tron_transaction_creation_failed",info:{error:Z(i)??"Node returned no transaction"}});let c=i.raw_data?.contract?.[0]?.parameter?.value;if(c?.to_address!==t||c?.owner_address!==n||c?.amount!==e)throw new y({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Node returned a transaction that does not match the requested transfer"}});return N(i),i}var xn="/wallet/triggersmartcontract";async function St({ownerAddress:n,contractAddress:t,functionSelector:e,parameter:r,feeLimit:i,callValue:o=0}){let c=await v(xn,{call_value:o,contract_address:t,fee_limit:i,function_selector:e,owner_address:n,parameter:r,visible:!0});if(!c.result?.result||!c.transaction?.txID||!c.transaction?.raw_data_hex)throw new y({errorKey:"toolbox_tron_transaction_creation_failed",info:{code:c.result?.code,error:Z(c)??"Node returned no transaction",message:hn(c.result?.message)}});let T=c.transaction.raw_data?.contract?.[0]?.parameter?.value;if(T?.contract_address!==t||T?.owner_address!==n)throw new y({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Node returned a transaction that does not match the requested contract call"}});return N(c.transaction),c.transaction}function Nt({ownerAddress:n,contractAddress:t,functionSelector:e,parameter:r}){return v("/wallet/triggerconstantcontract",{contract_address:t,function_selector:e,owner_address:n,parameter:r,visible:!0})}function An({ownerAddress:n,contractAddress:t,functionSelector:e,parameter:r}){return v("/wallet/estimateenergy",{contract_address:t,function_selector:e,owner_address:n,parameter:r,visible:!0})}function ht(n){let t=typeof n==="number"?n:typeof n==="string"?Number(n):Number.NaN;return Number.isFinite(t)&&t>0?t:void 0}async function k(n){try{let{result:t,txid:e}=await v("/wallet/broadcasttransaction",{raw_data:n.raw_data,raw_data_hex:n.raw_data_hex,signature:n.signature,txID:n.txID,visible:n.visible});if(!t||!e)throw new y("toolbox_tron_token_transfer_failed");return e}catch(t){throw new y("toolbox_tron_broadcast_failed",{error:t})}}async function I({timeoutMs:n}={}){let t={};try{let{chainParameter:e}=await vt("/wallet/getchainparameters",void 0,n);for(let r of e)if(r&&typeof r.key==="string")t[r.key]=r.value}catch(e){K({condition:!0,id:"tron_chain_params_failed",warning:`Failed to fetch chain params, using defaults: ${e instanceof Error?e.message:e}`})}return{bandwidthFee:C(t.getTransactionFee)??gn,createAccountBandwidthFee:C(t.getCreateAccountFee)??_n,createAccountFee:C(t.getCreateNewAccountFeeInSystemContract)??Tn,energyFee:C(t.getEnergyFee)??mn,memoFee:C(t.getMemoFee)??wn}}async function tt(n){try{let t=await v("/wallet/getaccountresource",{address:n,visible:!0});return{bandwidth:{free:J(t.freeNetLimit,t.freeNetUsed),staked:J(t.NetLimit,t.NetUsed)},energy:J(t.EnergyLimit,t.EnergyUsed)}}catch(t){return K({condition:!0,id:"tron_account_resources_failed",warning:`Failed to fetch account resources, assuming none available: ${t instanceof Error?t.message:t}`}),{bandwidth:{free:0,staked:0},energy:0}}}async function G(n,t={}){return await W(n,t)==="exists"}async function W(n,{timeoutMs:t}={}){if(!b(n))return"missing";try{let e=await v("/wallet/getaccount",{address:n,visible:!0},t);if(!e||typeof e!=="object"||Array.isArray(e)||Z(e))return"unknown";if(Et(e.address,n))return"exists";return Object.keys(e).length===0?"missing":"unknown"}catch{return"unknown"}}async function nt(n){try{let t=await An({...n,ownerAddress:n.sender}),e=t.energy_required??t.energyRequired;if(t.result&&!t.result.result)throw new y("toolbox_tron_trongrid_api_error",{message:t.result.message||"estimateenergy failed"});if(e!==void 0){let r=ht(e);if(r!==void 0)return r;throw new y("toolbox_tron_trongrid_api_error",{message:"Invalid estimateenergy response"})}}catch(t){K({condition:!0,id:"tron_energy_estimation_failed",warning:`Failed to estimate energy with estimateenergy, falling back to triggerconstantcontract: ${t instanceof Error?t.message:t}`})}try{let{energy_used:t}=await Nt({...n,ownerAddress:n.sender}),e=ht(t);if(e!==void 0)return e;throw new y("toolbox_tron_trongrid_api_error",{message:"Invalid triggerconstantcontract energy response"})}catch(t){throw K({condition:!0,id:"tron_energy_estimation_fallback_failed",warning:`Failed to estimate energy: ${t instanceof Error?t.message:t}`}),new y("toolbox_tron_trongrid_api_error",{message:`Unable to estimate contract energy: ${t instanceof Error?t.message:t}`})}}async function Rt({assetAddress:n,owner:t,spender:e}){let r=R([{type:"address",value:t},{type:"address",value:e}]),o=(await Nt({contractAddress:n,functionSelector:"allowance(address,address)",ownerAddress:e,parameter:r})).constant_result?.[0];if(!o)return 0n;try{return BigInt(`0x${o}`)}catch{return 0n}}import{bytesToHex as In}from"@noble/hashes/utils.js";import{HDKey as Pn}from"@scure/bip32";import{mnemonicToSeedSync as Bn}from"@scure/bip39";import{AssetValue as B,Chain as x,derivationPathToString as Mt,getChainConfig as Cn,getRPCUrl as kn,NetworkDerivationPath as Lt,SwapKitError as _,updateDerivationPath as Kt,warnOnce as j}from"@swapkit/helpers";import{match as Dn,P as rt}from"ts-pattern";import{sha256 as En}from"@noble/hashes/sha2.js";import{bytesToHex as It,hexToBytes as Pt}from"@noble/hashes/utils.js";import{SwapKitError as P}from"@swapkit/helpers";var V=0,Bt=1,q=2,Ct=5,vn=8,Fn=10,Sn=18;function et(n,t){let e=0n,r=0n,i=t;while(i<n.length&&i-t<10){let o=n[i++];if(o===void 0)break;if(e|=BigInt(o&127)<<r,r+=7n,(o&128)===0)return[e,i]}throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Malformed varint in transaction raw_data"}})}function D(n){let t=[],e=n<0n?n+2n**64n:n;while(e>=128n)t.push(Number(e&0x7fn)|128),e>>=7n;return t.push(Number(e)),t}function H(n,t,e){let r=n.get(t);if(r)r.push(e);else n.set(t,[e])}function Nn(n){let t=new Map,e=0;while(e<n.length){let[r,i]=et(n,e);e=i;let o=Number(r>>3n),c=Number(r&7n);if(c===V){let[m,T]=et(n,e);e=T,H(t,o,{data:new Uint8Array(D(m)),wireType:V})}else if(c===q){let[m,T]=et(n,e);e=T;let A=Number(m);if(A<0||e+A>n.length)throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Length-delimited proto field overruns transaction raw_data"}});let U=n.slice(e,e+A);e+=A,H(t,o,{data:U,wireType:q})}else if(c===Bt){if(e+8>n.length)throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"64-bit proto field overruns transaction raw_data"}});let m=n.slice(e,e+8);e+=8,H(t,o,{data:m,wireType:Bt})}else if(c===Ct){if(e+4>n.length)throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"32-bit proto field overruns transaction raw_data"}});let m=n.slice(e,e+4);e+=4,H(t,o,{data:m,wireType:Ct})}else throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Unsupported proto wire type in transaction raw_data"}})}return t}function Rn(n){let t=[];for(let[o,c]of[...n.entries()].sort(([m],[T])=>m-T))for(let{wireType:m,data:T}of c){let A=BigInt(o<<3|m);if(t.push(new Uint8Array(D(A))),m===q)t.push(new Uint8Array(D(BigInt(T.length))));t.push(T)}let e=t.reduce((o,c)=>o+c.length,0),r=new Uint8Array(e),i=0;for(let o of t)r.set(o,i),i+=o.length;return r}function kt(n,t){if(!n||n.length%2!==0)throw new P({errorKey:"toolbox_tron_transaction_creation_failed",info:{reason:"Transaction raw_data_hex is empty or not byte-aligned"}});let e=Pt(n),r=Nn(e);if(t.expiration!==void 0)r.set(vn,[{data:new Uint8Array(D(BigInt(t.expiration))),wireType:V}]);if(t.data!==void 0)r.set(Fn,[{data:Pt(t.data),wireType:q}]);if(t.fee_limit!==void 0)r.set(Sn,[{data:new Uint8Array(D(BigInt(t.fee_limit))),wireType:V}]);let i=Rn(r),o=It(i),c=It(En(i));return{raw_data_hex:o,txID:c}}var Un=b,Mn=Cn(x.Tron).baseDecimal,Ln=64,Kn=67,On=139,Ot=211;function Dt(n){let t=1,e=n>>7n;while(e>0n)t+=1,e>>=7n;return t}var $t=65000,at=25000,ot="TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",$n="115792089237316195423570985008687907853269984665640564039457584007913129639935",it=2500,X=(n)=>B.from({chain:x.Tron,fromBaseDecimal:Mn,value:n}),st=(n,t)=>t?n.memoFee:0;function ct(n,t){let e=n;if(t){let r=z(t).length/2;e+=1+Dt(BigInt(r))+r}return e+1+Dt(BigInt(e))+Kn+Ln}function Gt({bandwidthFee:n,pools:t,requiredBytes:e}){return t.staked>=e||t.free>=e?0:e*n}function Wt({bandwidth:n={free:0,staked:0},chainParams:t,memo:e,recipientStatus:r}){let i=st(t,e),o=t.createAccountFee+t.createAccountBandwidthFee,c=Gt({bandwidthFee:t.bandwidthFee,pools:n,requiredBytes:ct(On,e)});if(r==="exists")return c+i;if(r==="missing")return o+i;return Math.max(o,c)+i}async function Ht(n,t){let e=n||$t,r=t??(await I()).energyFee,i=e*r,o=Math.ceil(i*1.5);return Math.min(Math.max(o,1e7),150000000)}async function Vt({assetValue:n,memo:t,recipient:e,timeoutMs:r}){let[i,o]=await Promise.all([I({timeoutMs:r}),W(e,{timeoutMs:r})]);if(j({condition:n.chain!==x.Tron,id:"tron_conservative_fee_foreign_asset",warning:"Non-Tron asset passed to the Tron fee estimate; reserving the TRC-20 fee"}),n.chain===x.Tron&&n.isGasAsset)return X(Wt({chainParams:i,memo:t,recipientStatus:o}));let m=await Ht($t+(o==="exists"?0:at),i.energyFee),T=st(i,t);return X(m+ct(Ot,t)*i.bandwidthFee+T)}async function Gn({assetValue:n,recipient:t,memo:e,timeoutMs:r=it}){return j({condition:!b(t),id:"tron_sweep_deduction_invalid_recipient",warning:"Invalid Tron sweep recipient; assuming the account needs activation"}),await Vt({assetValue:n,memo:e==null?void 0:String(e),recipient:t,timeoutMs:Number.isFinite(r)&&r>0?r:it})}function qt({phrase:n,derivationPath:t}){let e=Pn.fromMasterSeed(Bn(n)).derive(t);if(!e.privateKey)throw new _("toolbox_tron_no_signer");return In(e.privateKey)}function Wn(n,t){return{...n,value:String(t)}}function Hn(n,t){if(!t)return n;return{...n,data:t.startsWith("0x")?t:`0x${t}`}}function Vn({phrase:n,derivationPath:t,index:e}){let r=t||Mt(Kt(Lt[x.Tron],{index:e||0}));return qt({derivationPath:r,phrase:n})}function qn({phrase:n,derivationPath:t}){let e=qt({derivationPath:t,phrase:n}),r=pt(e);return{getAddress:()=>Promise.resolve(r),signTransaction:(i)=>{N(i);let o=yt({privateKey:e,txID:i.txID});return Promise.resolve({...i,signature:[o]})}}}function Ut({transaction:n,memo:t,expiration:e,feeLimit:r}){let i={},o={};if(r!==void 0&&n.raw_data)i.fee_limit=r,o.fee_limit=r;if(t){let T=z(t);i.data=T,o.data=T}if(e){let T=n.raw_data.expiration+e*1000;i.expiration=T,o.expiration=T}if(Object.keys(i).length===0)return n;let{raw_data_hex:c,txID:m}=kt(n.raw_data_hex,i);return{...n,raw_data:{...n.raw_data,...o},raw_data_hex:c,txID:m}}function jn(n={}){let t="index"in n?n.index||0:0,e=Mt("derivationPath"in n&&n.derivationPath?n.derivationPath:Kt(Lt[x.Tron],{index:t})),r,i=!1;function o(){if(i)return Promise.resolve(r);return r=Dn(n).with({phrase:rt.string},({phrase:a})=>qn({derivationPath:e,phrase:a})).with({signer:rt.not(rt.nullish)},({signer:a})=>a).otherwise(()=>{return}),i=!0,Promise.resolve(r)}async function c(){let a=await o();if(!a)throw new _("toolbox_tron_no_signer");return a.getAddress()}async function m({contractAddress:a,functionSelector:s,parameter:d,sender:u,memo:f,expiration:l,extraEnergy:g=0}){let w=await nt({contractAddress:a,functionSelector:s,parameter:d,sender:u}),p=await Ht(w+g),h=await St({contractAddress:a,feeLimit:p,functionSelector:s,ownerAddress:u,parameter:d});return Ut({expiration:l,feeLimit:p,memo:f,transaction:h})}async function T(a){if(!b(a))return[B.from({chain:x.Tron})];try{let s=await O(a);if(!s)return[B.from({chain:x.Tron})];let d=[B.from({chain:x.Tron,fromBaseDecimal:6,value:String(s.balance)})],u=s.trc20?.find((f)=>(ot in f));if(u){let f=u[ot];d.push(B.from({asset:`TRON.USDT-${ot}`,fromBaseDecimal:6,value:f}))}return d}catch(s){return j({condition:!0,id:"tron_toolbox_get_balance_failed",warning:`Tron API getBalance failed: ${s instanceof Error?s.message:s}`}),[B.from({chain:x.Tron})]}}async function A({recipient:a,assetValue:s,memo:d,expiration:u,sweep:f}){if(!b(a))throw new _("toolbox_tron_token_transfer_failed",{message:"invalid address"});let l=await o();if(!l)throw new _("toolbox_tron_no_signer");try{let g=await c(),w=await ut({assetValue:s,expiration:u,memo:d,recipient:a,sender:g,sweep:f}),p=await l.signTransaction(w),h=await k(p);if(!h)throw new _("toolbox_tron_token_transfer_failed",{message:"broadcast failed"});return h}catch(g){if(g instanceof _&&g.errorKey==="toolbox_sweep_amount_too_low")throw g;throw new _("toolbox_tron_token_transfer_failed",{message:g instanceof Error?g.message:String(g)})}}async function U({memo:a,recipient:s,senderAddress:d}){let[u,f,l]=await Promise.all([I(),W(s),tt(d)]);return X(Wt({bandwidth:l.bandwidth,chainParams:u,memo:a,recipientStatus:f}))}async function dt({assetValue:a,amountInBaseUnits:s=a.getBaseValue("string"),memo:d,recipient:u,senderAddress:f}){let l=a.address;if(!l)throw new _("toolbox_tron_invalid_token_identifier",{identifier:a.toString()});let[g,w,p,h]=await Promise.all([I(),G(u),tt(f),nt({contractAddress:l,functionSelector:"transfer(address,uint256)",parameter:R([{type:"address",value:u},{type:"uint256",value:s}]),sender:f})]),F=h+(w?0:at),Y=Gt({bandwidthFee:g.bandwidthFee,pools:p.bandwidth,requiredBytes:ct(Ot,d)}),Zt=Math.max(0,F-p.energy)*g.energyFee,tn=st(g,d);return X(Y+Zt+tn)}async function jt({assetValue:a,memo:s,recipient:d,sender:u}){let f=await o();try{let l=u?u:f?await c():void 0;if(!l)return Vt({assetValue:a,memo:s,recipient:d});return a.isGasAsset?U({memo:s,recipient:d,senderAddress:l}):dt({assetValue:a,memo:s,recipient:d,senderAddress:l})}catch(l){throw j({condition:!0,id:"tron_toolbox_fee_estimation_failed",warning:`Failed to calculate exact fee: ${l instanceof Error?l.message:l}`}),new _("toolbox_fee_estimation_failed",{chain:x.Tron,error:l})}}async function Xt({assetValue:a,memo:s,recipient:d,sender:u,sweep:f}){if(!f)return a.getBaseValue("bigint");let[l,g]=await Promise.all([O(u),U({memo:s,recipient:d,senderAddress:u})]),w=BigInt(l?.balance??0)-g.getBaseValue("bigint");if(w<=0n)throw new _({errorKey:"toolbox_sweep_amount_too_low",info:{amount:w.toString(),asset:a.toString()}});return w}async function Yt({assetValue:a,memo:s,recipient:d,sender:u,sweep:f}){if(!f)return a.getBaseValue("string");let l=a.address;if(!l)throw new _("toolbox_tron_invalid_token_identifier",{identifier:a.toString()});let g=await O(u),p=g?.trc20.find((Y)=>(l in Y))?.[l]??"0";if(BigInt(p)<=0n)throw new _({errorKey:"toolbox_sweep_amount_too_low",info:{asset:a.toString(),balance:p}});let h=await dt({amountInBaseUnits:p,assetValue:a,memo:s,recipient:d,senderAddress:u}),E=BigInt(g?.balance??0),F=h.getBaseValue("bigint");if(E<F)throw new _({errorKey:"toolbox_sweep_amount_too_low",info:{asset:a.toString(),nativeBalance:E.toString(),requiredNativeFee:F.toString()}});return p}async function ut({recipient:a,assetValue:s,memo:d,sender:u,expiration:f,sweep:l,recipientExists:g}){if(!b(a)||!b(u))throw new _("toolbox_tron_transaction_creation_failed",{message:"invalid address"});if(s.isGasAsset){let E=await Xt({assetValue:s,expiration:f,memo:d,recipient:a,sender:u,sweep:l});if(E>BigInt(Number.MAX_SAFE_INTEGER))throw new _({errorKey:"toolbox_tron_transaction_creation_failed",info:{amount:E.toString(),reason:`Native transfer amount exceeds the safe integer limit of ${Number.MAX_SAFE_INTEGER} SUN`}});let F=await Ft({amount:Number(E),from:u,to:a});return Ut({expiration:f,memo:d,transaction:F})}let w=s.address;if(!w)throw new _("toolbox_tron_invalid_token_identifier",{identifier:s.toString()});let p=await Yt({assetValue:s,expiration:f,memo:d,recipient:a,sender:u,sweep:l}),h=g??await G(a);return m({contractAddress:w,expiration:f,extraEnergy:h?0:at,functionSelector:"transfer(address,uint256)",memo:d,parameter:R([{type:"address",value:a},{type:"uint256",value:p}]),sender:u})}async function ft(a){N(a);let s=await o();if(!s)throw new _("toolbox_tron_no_signer");return s.signTransaction(a)}async function zt(a){let s=await ft(a);return k(s)}function lt({assetAddress:a,spenderAddress:s,from:d}){return Rt({assetAddress:a,owner:d,spender:s})}async function Jt({assetAddress:a,spenderAddress:s,from:d,amount:u}){let f=await lt({assetAddress:a,from:d,spenderAddress:s});if(!u)return f>0n;return f>=BigInt(u)}async function Qt({assetAddress:a,spenderAddress:s,amount:d,from:u}){if(!b(a)||!b(s))throw new _("toolbox_tron_approve_failed");let f=await o();if(!f)throw new _("toolbox_tron_no_signer");let l=u||await c(),g=d!==void 0?BigInt(d).toString():$n;try{let w=await m({contractAddress:a,functionSelector:"approve(address,uint256)",parameter:R([{type:"address",value:s},{type:"uint256",value:g}]),sender:l}),p=await f.signTransaction(w),h=await k(p);if(!h)throw new _("toolbox_tron_approve_failed");return h}catch(w){if(w instanceof _)throw w;throw new _("toolbox_tron_approve_failed",{error:w})}}return{approve:Qt,broadcastTransaction:k,createTransaction:ut,estimateTransactionFee:jt,getAddress:c,getApprovedAmount:lt,getBalance:T,getRpcUrl:()=>kn(x.Tron),isApproved:Jt,signAndBroadcastTransaction:zt,signTransaction:ft,transfer:A,validateAddress:b}}export{it as TRON_SWEEP_ESTIMATE_TIMEOUT_MS,G as checkTronAccountExists,Gn as estimateTronSweepDeduction,I as getTronChainParameters,Vn as getTronPrivateKeyFromMnemonic,jn as getTronToolbox,Un as validateTronAddress,Hn as withTronTransactionData,Wn as withTronTransactionValue};
|
package/dist/src/utxo/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ha as St,ia as jt}from"../../chunk-xdkdc1f0.js";import"../../chunk-exyqap7m.js";import{NetworkDerivationPath as Sn}from"@swapkit/helpers";function Z(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`${e} must be a non-negative integer, got: ${t}`)}function ee({accountIndex:e,chain:t,derivationPath:n}){if(e!==void 0)Z("accountIndex",e);let[r,s,a]=n??Sn[t];return[r,s,e??a]}function Ae({accountIndex:e,change:t=!1,chain:n,derivationPath:r,index:s}){return Z("index",s),[...ee({accountIndex:e,chain:n,derivationPath:r}),Number(t),s]}function pe(e){return e[2]??0}function Cn({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 Xn,RequestClient as Re,SKConfig as Bn,SwapKitError as H,warnOnce as kn}from"@swapkit/helpers";import{NETWORKS as le}from"@swapkit/utxo-signer";async function Kn({chain:e,txHash:t}){let n=`${he(e)}/push/transaction`,r=JSON.stringify({data:t});try{let s=await Re.post(n,{body:r,headers:{"Content-Type":"application/json"}});if(s.context.code!==200)throw new H("toolbox_utxo_broadcast_failed",{error:s.context.error||"Transaction broadcast failed"});return s.data?.transaction_hash||t}catch(s){let a=await Xn(e);if(a){let d=JSON.stringify({id:St(),jsonrpc:"2.0",method:"sendrawtransaction",params:[t]}),o=await Re.post(a,{body:d,headers:{"Content-Type":"application/json"}});if(o.error)throw new H("toolbox_utxo_broadcast_failed",{error:o.error?.message});if(o.result.includes('"code":-26'))throw new H("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return o.result}throw s}}function he(e){return`https://api.blockchair.com/${Fn(e)}`}function _t(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 Fn(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 Dn(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,_t(e))}catch{return _t(e)}}async function _e(e,t){let n=await Re.get(`${e}${t?`${e.includes("?")?"&":"?"}key=${t}`:""}`);if(!n||n.context.code!==200)throw new H("toolbox_utxo_api_error",{error:`Failed to query ${e}`});return n.data}async function In({chain:e,apiKey:t}){let n=await _e(`${he(e)}/stats`,t);if(typeof n.best_block_height!=="number")throw new H("toolbox_utxo_api_error",{error:"Missing best_block_height in stats response"});return n.best_block_height}async function Ct({address:e,chain:t,apiKey:n}){if(!e)throw new H("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await _e(`${he(t)}/dashboards/address/${e}?transaction_details=true`,n))[e]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function Hn({address:e,chain:t,apiKey:n}){return(await Ct({address:e,apiKey:n,chain:t}))?.address.balance||0}async function Xt({chain:e,apiKey:t,txHash:n}){if(!n)throw new H("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await _e(`${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 Rn=4294967294;async function En({chain:e,apiKey:t,txHash:n}){if(!n)throw new H("toolbox_utxo_invalid_params",{error:"TxHash is required"});let s=(await _e(`${he(e)}/dashboards/transaction/${n}`,t))?.[n];if(!s)throw new H("toolbox_utxo_tx_not_found",{txHash:n});let{transaction:a,inputs:d,outputs:o}=s,p=d.map((u)=>u.spending_sequence),c=a.is_rbf===!0||p.some((u)=>u<Rn);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 Mn({chain:e,address:t,apiKey:n,offset:r=0,limit:s=30}){return(await _e(`${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 Nn(e){return e.reduce((t,n)=>t+n.value,0)}function Ot(e,t){let n=[...e].sort((r,s)=>s.value-r.value);if(t){let r=[],s=0;for(let a of n)if(r.push(a),s+=a.value,s>=t)break;return r}return n}async function Bt({chain:e,address:t,apiKey:n,targetValue:r,accumulativeValue:s=0,offset:a=0,limit:d=30}){if(!t)throw new H("toolbox_utxo_invalid_params",{error:"Address is required"});try{let o=await Mn({address:t,apiKey:n,chain:e,limit:d,offset:a,targetValue:r}),c=o.length<d,u=o.filter(({is_spent:y})=>!y),i=Nn(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 O(e){let t=Bn.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)=>Kn({chain:e,txHash:n}),getAddressData:(n)=>Ct({address:n,apiKey:t,chain:e}),getBalance:(n)=>Hn({address:n,apiKey:t,chain:e}),getBlockHeight:()=>In({apiKey:t,chain:e}),getRawTx:(n)=>Xt({apiKey:t,chain:e,txHash:n}),getSuggestedTxFee:()=>Dn(e),getTransactionDetails:(n)=>En({apiKey:t,chain:e,txHash:n}),getUtxos:(n)=>Zn({...n,apiKey:t,chain:e})}}function Ds(e){return e}function Is(){return function(t){switch(t){case C.Bitcoin:return le.bitcoin;case C.BitcoinCash:return le.bitcoinCash;case C.Dash:return le.dash;case C.Litecoin:return le.litecoin;case C.Dogecoin:return le.dogecoin;case C.Zcash:return le.zcash;default:throw new H("toolbox_utxo_not_supported",{chain:t})}}}import{sha256 as Gn}from"@noble/hashes/sha2.js";import{createBase58check as Yn}from"@scure/base";import{SwapKitError as Kt}from"@swapkit/helpers";import{CashAddrType as Ee,decodeCashAddr as zn,encodeCashAddr as Wn}from"@swapkit/utxo-signer";var Ln={P2PKH:Ee.P2PKH,P2SH:Ee.P2SH},$n={[Ee.P2PKH]:"P2PKH",[Ee.P2SH]:"P2SH"};function Vn(e,t,n){return Wn({hash:n,prefix:e,type:Ln[t]})}function qn(e){let t=zn(e),n=$n[t.type];if(!n)throw Error(`Unknown CashAddr type: ${t.type}`);return{hash:t.hash,prefix:t.prefix,type:n}}var st={decode:qn,encode:Vn};var Ft=Yn(Gn);var Dt;((n)=>{n.Mainnet="mainnet";n.Testnet="testnet"})(Dt||={});var te={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}},jn={["p2pkh"]:"pkh",["p2sh"]:"sh"};function Ws(e){return Ne(e)!==void 0}function Ls(e){return ot(e).network}function G(e){let t=ot(e);if(t.format==="legacy")return e;return er(t)}function Me(e){let t=ot(e);return tr(t)}function Ne(e){if(typeof e!=="string")return;let t=Jn(e)??Qn(e);return t&&{...t,scriptType:jn[t.type]}}function ot(e){let t=Ne(e);if(!t)throw new Kt("toolbox_utxo_invalid_address",{address:e});return t}function Jn(e){try{let t=Ft.decode(e);if(t.length!==21)throw new Kt("toolbox_utxo_invalid_address",{address:e});let n=t[0],r=Array.prototype.slice.call(t,1);switch(n){case te.legacy.mainnet.p2pkh:return{format:"legacy",hash:r,network:"mainnet",type:"p2pkh"};case te.legacy.mainnet.p2sh:return{format:"legacy",hash:r,network:"mainnet",type:"p2sh"};case te.legacy.testnet.p2pkh:return{format:"legacy",hash:r,network:"testnet",type:"p2pkh"};case te.legacy.testnet.p2sh:return{format:"legacy",hash:r,network:"testnet",type:"p2sh"};case te.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2pkh"};case te.bitpay.mainnet.p2sh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function Qn(e){if(e.indexOf(":")!==-1)try{return kt(e)}catch{}else{let t=["bitcoincash","bchtest","bchreg"];for(let n of t)try{return kt(`${n}:${e}`)}catch{}}return}function kt(e){try{let{hash:t,prefix:n,type:r}=st.decode(e);return{format:"cashaddr",hash:Array.prototype.slice.call(t,0),network:n==="bitcoincash"?"mainnet":"testnet",type:r==="P2PKH"?"p2pkh":"p2sh"}}catch{return}}function er(e){let t=te.legacy[e.network][e.type],n=Buffer.alloc(1+e.hash.length);return n[0]=t,n.set(e.hash,1),Ft.encode(n)}function tr(e){let t=e.network==="mainnet"?"bitcoincash":"bchtest",n=e.type==="p2pkh"?"P2PKH":"P2SH",r=new Uint8Array(e.hash);return st.encode(t,n,r)}import{Chain as oe,SwapKitError as Tt}from"@swapkit/helpers";import{SwapKitError as qe,UTXO_SCRIPT_TYPE_LIST as Ar,UTXO_SCRIPT_TYPES as $t,UTXOScriptType as Ge}from"@swapkit/helpers";import{Script as _r}from"@swapkit/utxo-signer";import{Chain as at}from"@swapkit/helpers";import{getAddressScriptType as rr,getTransparentZcashAddressType as sr,getZcashAddressType as or}from"@swapkit/utxo-signer";import{match as ar}from"ts-pattern";import{Chain as fe}from"@swapkit/helpers";import{NETWORKS as Te}from"@swapkit/utxo-signer";import{match as nr}from"ts-pattern";function P(e){return nr(e).with(fe.Bitcoin,()=>Te.bitcoin).with(fe.BitcoinCash,()=>Te.bitcoinCash).with(fe.Dash,()=>Te.dash).with(fe.Dogecoin,()=>Te.dogecoin).with(fe.Litecoin,()=>Te.litecoin).with(fe.Zcash,()=>Te.zcash).exhaustive()}function z(e){return e.replace(/(bchtest:|bitcoincash:)/,"")}function Oe(e){if(typeof e!=="string")return null;let t=Ne(z(e));if(!t||t.network!=="mainnet")return null;return t.scriptType}var ir=["sprout","sapling","unified"];function cr(e){let t=sr(e,P(at.Zcash));if(t)return t;let n=or(e);return n&&ir.includes(n)?n:null}function Y({address:e,chain:t}){return ar(t).with(at.BitcoinCash,()=>Oe(e)).with(at.Zcash,()=>cr(e)).otherwise(()=>rr(e,P(t)))}import{Chain as ne,derivationPathToString as It,getPurposeFromPath as dr,getUTXOScriptTypeForPath as Ht,getUTXOScriptTypeForPurpose as Mt,resolveDerivationPath as ur,SwapKitError as Se,UTXO_SCRIPT_TYPE_LIST as Rt,UTXO_SCRIPT_TYPES as me,UTXOChains as pr,UTXOScriptType as S,updateDerivationPath as lr,warnOnce as hr}from"@swapkit/helpers";import{CashAddrPrefix as fr,CashAddrType as Tr,encodeCashAddr as mr,OutScript as Nt,p2pkh as yr,p2sh as gr,p2tr as xr,p2wpkh as Et}from"@swapkit/utxo-signer";var Ze=Object.freeze([S.P2PKH]),br=Object.freeze({[ne.Bitcoin]:Rt,[ne.BitcoinCash]:Ze,[ne.Dash]:Ze,[ne.Dogecoin]:Ze,[ne.Litecoin]:Rt,[ne.Zcash]:Ze});function We(e){return br[e]}function it(e){return We(e).some((t)=>me[t].witness)}function ye(e,t){return We(e).includes(t)}function Le(e,t){if(ye(e,t))return t;throw new Se("toolbox_utxo_unsupported_script_type",{chain:e,error:`${e} cannot encode ${t}; supported: ${We(e).join(", ")}`,scriptType:t,supported:We(e)})}var Zt=pr.filter((e)=>!it(e));function wr({purpose:e,scriptType:t}){let n=Mt(e);return n===void 0||n===t}function ct({chain:e,purpose:t,scriptType:n}){hr({condition:!wr({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 Se("toolbox_utxo_invalid_params",{chain:e,derivationPath:It(t),error:`scriptType is required alongside derivationPath: getUTXOScriptTypeForPath gives the standard one${o?` (${o})`:""}, or state another deliberately.`})}return Le(e,r),ct({chain:e,purpose:dr(t),scriptType:r}),{derivationPath:t,scriptType:r}}let s=ur({chain:e,index:n}),a=r?lr(s,{purpose:me[r].purpose}):s,d=r??Ht(a);if(!d)throw new Se("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 Pr(e){return e.length===32?e:e.slice(1)}function ze(e,t){if(!e.address)throw new Se("toolbox_utxo_invalid_address",{error:`Could not derive a ${t} address`});return e}var Ur={[S.P2PKH]:(e,t)=>{let{address:n,script:r}=ze(yr(e,t),S.P2PKH);return{address:n,script:r}},[S.P2SH_P2WPKH]:(e,t)=>{let n=Et(e,t),{address:r,script:s}=ze(gr(n,t),S.P2SH_P2WPKH);return{address:r,redeemScript:n.script,script:s}},[S.P2WPKH]:(e,t)=>{let{address:n,script:r}=ze(Et(e,t),S.P2WPKH);return{address:n,script:r}},[S.P2TR]:(e,t)=>{let n=Pr(e),{address:r,script:s}=ze(xr(n,void 0,t),S.P2TR);return{address:r,script:s,tapInternalKey:n}}};function Ve(e,t,n){return Ur[e](t,n)}function dt(e,t){if(e!==ne.BitcoinCash)return t.address;let n=Nt.decode(t.script);if(n.type!=="pkh")throw new Se("toolbox_utxo_invalid_address",{chain:e,error:`Cannot encode ${n.type} as CashAddr`});return mr({hash:n.hash,prefix:fr.MAINNET,type:Tr.P2PKH}).replace(/^bitcoincash:/,"")}var vr=Object.freeze({pkh:S.P2PKH,sh:S.P2SH_P2WPKH,tr:S.P2TR,wpkh:S.P2WPKH}),zt=Object.freeze({pkh:me[S.P2PKH].outputSize,sh:me[S.P2SH_P2WPKH].outputSize,tr:me[S.P2TR].outputSize,wpkh:me[S.P2WPKH].outputSize,wsh:43});function Wt(e){return e in zt}function Lt(e){return Wt(e)?zt[e]:void 0}function Ce(e){return vr[e]}function ut(e){try{let{type:t}=Nt.decode(e);return Wt(t)?Ce(t):void 0}catch{return}}import{UTXOScriptType as se}from"@swapkit/helpers";var po=1000,lt=10,Or=2,Sr=10;function R(e){let t=new Uint8Array(Buffer.from(e,"utf8"));return _r.encode(["RETURN",t])}function Vt(e){return Object.fromEntries(Ar.map((t)=>[t,$t[t][e]]))}var qt=Vt("inputSize"),pt=Vt("outputSize"),ht=(e)=>$t[e].witness,Ye=(e,t)=>{let n=Y({address:e,chain:t});if(!n)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let r=Ce(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},Cr=(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]?Xe(t[0],e):Ge.P2PKH,a=r?t.filter((u)=>u.value>=qt["type"in u&&u.type?u.type:Ge.P2PKH]*Math.ceil(r)):t,d=0,o=0;for(let u of a)if(d+=re(u,e),!ht(Xe(u,e)))o++;let p=n?.reduce((u,i)=>u+je(i,e),0)||pt[s],c=o<a.length;return lt+d+p+ft(c,o)},Xe=(e,t)=>{if("type"in e&&e.type)return e.type;if("address"in e&&e.address)return Ye(e.address,t);return Ge.P2PKH},re=(e,t)=>qt[Xe(e,t)],ft=(e,t)=>e?Math.ceil((Or+t)/4):0,je=(e,t,n)=>{if(e?.script)return Sr+e.script.length+(e.script.length>=74?2:1);if(n)return pt[n];if("address"in e&&e.address)return Cr(e.address,t);return pt[Ge.P2PKH]};function Be(e){switch(e){case oe.Bitcoin:case oe.BitcoinCash:return 550;case oe.Dash:case oe.Litecoin:return 5500;case oe.Dogecoin:return 1e5;case oe.Zcash:return 546;default:throw new Tt("toolbox_utxo_not_supported",{chain:e})}}function E({inputs:e,outputs:t,feeRate:n=1,chain:r=oe.Bitcoin,changeAddress:s="",sweep:a=!1}){let d=Be(r),o=e.filter((f)=>{let y=re(f,r)*n;return a?f.value>Math.max(y,d):y<=f.value});if(a){let f=Math.ceil(n*ge({chain:r,inputs:o,outputs:t})),y=o.reduce((B,W)=>B+W.value,0),b=y-f;if(b<=d)throw new Tt("toolbox_sweep_amount_too_low",{available:y,dustThreshold:d,fee:f});let A=t.findIndex((B)=>("address"in B)&&B.address);if(A===-1)throw new Tt("toolbox_utxo_invalid_params",{error:"Sweep requires a recipient output"});return{fee:f,inputs:o,outputs:t.map((B,W)=>W===A?{...B,value:b}:B)}}let p=lt+t.reduce((f,y)=>f+je(y,r),0),c=t.reduce((f,y)=>f+y.value,0),u=0,i=0,l=!1,h=0,m=[];for(let f of o){if(u+=re(f,r),ht(Xe(f,r)))l=!0;else i++;h+=f.value,m.push(f);let y=(p+u+ft(l,i))*n,b=y+c;if(h<b)continue;let A=h-b,B=n*je({address:s,value:0},r);if(A>B){let W=B+y,Ie=h-(c+Math.ceil(W));if(Ie>Math.max(re({value:0},r)*n,Be(r)))return{fee:Math.ceil(W),inputs:m,outputs:t.concat({address:s,value:Ie})}}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 Cs}from"@swapkit/helpers";import{hex as un}from"@scure/base";import{Chain as qr,derivationPathToString as Gr,FeeOption as Yr,resolveDerivationPath as jr,SwapKitError as L}from"@swapkit/helpers";import{BCHSigHash as Jr,CashAddrPrefix as pn,CashAddrType as ln,encodeCashAddr as hn,NETWORKS as Qr,p2pkh as fn,Transaction as Tn}from"@swapkit/utxo-signer";import{secp256k1 as Xr}from"@noble/curves/secp256k1.js";import{hex as ae}from"@scure/base";import{HDKey as Jt}from"@scure/bip32";import{mnemonicToSeedSync as xt}from"@scure/bip39";import{AssetValue as mt,applyFeeMultiplier as Gt,Chain as Ke,derivationPathToString as ke,FeeOption as M,NetworkDerivationPath as Br,SwapKitError as U,SwapKitNumber as kr,UTXO_SCRIPT_TYPES as Kr,warnOnce as Fr}from"@swapkit/helpers";import{BCHSigHash as Qt,RBF_SEQUENCE as Dr,SigHash as Yt,Transaction as yt,utils as Ir,WIF as en}from"@swapkit/utxo-signer";var Je=[Ke.Bitcoin];function tn({address:e,chain:t}){return Y({address:e,chain:t})!==null}function Hr({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 U("toolbox_utxo_invalid_params",{error:"Could not derive private key from phrase"});return d.privateKey}function gt(e){return Xr.getPublicKey(e,!0)}function Fe({publicKey:e,chain:t,network:n,scriptType:r}){return dt(t,Ve(r,e,n))}function xe({phrase:e,derivationPath:t,chain:n,wif:r,seed:s}){let a=P(n);if(r){let c=en(a).decode(r),u=gt(c);return{privateKey:c,publicKey:u}}if(!e)throw new U("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let d=t||ke(Br[n]),o=Hr({derivationPath:d,network:a,phrase:e,seed:s}),p=gt(o);return{privateKey:o,publicKey:p}}function Rr(e,t){return en(P(t)).encode(e)}function Er({phrase:e,derivationPath:t,chain:n,seed:r}){let s=t.split("/");if(s.length<4)throw new U("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${s.length}): ${t}`});let a=P(n),d=r??xt(e),o=Jt.fromMasterSeed(d,a.bip32),p=s.slice(0,4).join("/");return o.derive(p)}function Mr(e,t){if(!e||!Kr[e].witness)return!1;return e!==se.P2SH_P2WPKH||!!t}function nn({chain:e,script:t,publicKey:n,network:r}){let s=ut(t);if(s!==se.P2SH_P2WPKH&&s!==se.P2TR)return{};if(!ye(e,s))return{};let a=Ve(s,n,r);if(Ir.compareBytes(a.script,t)!==0)return{};return s===se.P2TR?{tapInternalKey:a.tapInternalKey}:{redeemScript:a.redeemScript}}function Nr(e,t,n){if(!n)return!1;let r=Y({address:e,chain:t}),s=r?Ce(r):void 0;if(!s||!ye(t,s))return!1;let a=dt(t,Ve(s,n,P(t)));return t===Ke.BitcoinCash?z(a)===z(e):a===e}function Zr(e){return e.witnessUtxo?.script??e.nonWitnessUtxo?.outputs[e.index??0]?.script}function bt({chain:e,tx:t,publicKey:n,network:r,indexes:s}){let a=s??Array.from({length:t.inputsLength},(o,p)=>p),d=[];for(let o of a){let p=t.getInput(o),c=Zr(p);if(!c)continue;let{redeemScript:u,tapInternalKey:i}=nn({chain:e,network:r,publicKey:n,script:c}),l={index:o};if(u&&!p.redeemScript)l.redeemScript=u;if(i&&!p.tapInternalKey)l.tapInternalKey=i;if(l.redeemScript||l.tapInternalKey)d.push(l)}return d}function ie({inputs:e,outputs:t,chain:n,tx:r,sender:s,compiledMemo:a,enableRBF:d=!1}){let o=P(n),p=it(n),c=d?Dr:void 0,u=new Set;for(let i of e){let l=`${i.hash}:${i.index}`;if(u.has(l))throw new U("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});u.add(l);let h=typeof i.hash==="string"?ae.decode(i.hash):i.hash,m=i.witnessUtxo?ut(i.witnessUtxo.script):void 0,f=i.publicKey&&i.witnessUtxo?nn({chain:n,network:o,publicKey:i.publicKey,script:i.witnessUtxo.script}):{};if(p&&i.witnessUtxo&&Mr(m,f.redeemScript))r.addInput({...f,index:i.index,sequence:c,txid:h,witnessUtxo:{amount:BigInt(i.witnessUtxo.value),script:i.witnessUtxo.script}});else if(i.txHex)r.addInput({...f,index:i.index,nonWitnessUtxo:ae.decode(i.txHex),sequence:c,txid:h,...n===Ke.BitcoinCash?{sighashType:Qt.ALL}:{}});else throw new U("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===Ke.BitcoinCash)l=G(l);if(i.script)if(a)r.addOutput({amount:0n,script:a});else throw new U("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 O(e).getSuggestedTxFee();return{[M.Average]:t,[M.Fast]:Gt(t,M.Fast),[M.Fastest]:Gt(t,M.Fastest)}}async function rn({assetValue:e,recipient:t,memo:n,sender:r,sweep:s,fetchTxHex:a=!1,publicKey:d},o,{forEstimateOnly:p=!1}={}){let c=e.chain,u=Ye(r,c),i=u===se.P2PKH||u===se.P2SH_P2WPKH&&!Nr(r,c,d),l=a||!p&&i,h=e.getBaseValue("number"),m=s?void 0:o??(await be(c))[M.Fastest],f=s||m===void 0?void 0:Math.ceil(h+m*5000);return{inputs:await O(c).getUtxos({address:r,fetchTxHex:l,targetValue:f}),outputs:[{address:t,value:s?0:h},...n?[{address:"",script:R(n),value:0}]:[]]}}async function sn({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s,fetchTxHex:a=!1,enableRBF:d=!1,sweep:o,publicKey:p}){let c=e.chain,u=n?R(n):null,i=await rn({assetValue:e,fetchTxHex:a,memo:n,publicKey:p,recipient:t,sender:s,sweep:o},r),{inputs:l,outputs:h}=E({...i,chain:c,changeAddress:s,feeRate:r,sweep:o});if(!(l&&h))throw new U("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let m=p?l.map((A)=>({...A,publicKey:p})):l,f=new yt({allowUnknownOutputs:!!u,version:1}),{inputs:y,tx:b}=ie({chain:c,compiledMemo:u,enableRBF:d,inputs:m,outputs:h,sender:s,tx:f});return{inputs:y,tx:b,utxos:i.inputs}}async function on({assetValue:e,feeOptionKey:t=M.Fast,feeRate:n,memo:r,sender:s,recipient:a,sweep:d}){let o=e.chain,p,c;if(n!==void 0)p=n,c=Math.floor(n);else{let i=await be(o);p=i[M.Fastest],c=i[t]}let u=await rn({assetValue:e,memo:r,recipient:a,sender:s,sweep:d},p,{forEstimateOnly:!0});return E({...u,chain:o,changeAddress:s,feeRate:c,sweep:d})}function zr(e){return async function({from:n,memo:r,feeRate:s,feeOptionKey:a=M.Fast,recipient:d=n,recipients:o=1}){let p=s??(await be(e))[a],u=(await O(e).getUtxos({address:n,fetchTxHex:!1})).filter((f)=>f.value>Math.max(Be(e),re(f,e)*p));if(!u.length)return mt.from({chain:e});let i=typeof o==="number"?Math.max(o,1):o.length,l=typeof o==="number"||i===0?Array.from({length:i||1},()=>({address:d,value:0})):[...o];if(r)l.push({address:n,script:R(r),value:0});let{outputs:h}=E({chain:e,feeRate:p,inputs:u,outputs:l,sweep:!0}),m=h?.[0]?.value??0;return mt.from({chain:e,value:BigInt(m)})}}function Wr(e){return async function(n){let{fee:r}=await on(n);return mt.from({chain:e,value:kr.fromBigInt(BigInt(r),8).getValue("string")})}}function Lr({chain:e,phrase:t,derivationPath:n,scriptType:r,seed:s}){let a=P(e),{privateKey:d,publicKey:o}=xe({chain:e,derivationPath:n,phrase:t,seed:s}),p=an(e);return{getAddress:()=>Fe({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===Ke.BitcoinCash?[Qt.ALL]:[Yt.ALL,Yt.DEFAULT]}function $r(e,t){return async function({memo:r,recipient:s,feeOptionKey:a,feeRate:d,assetValue:o,enableRBF:p=!1,sweep:c}){let u=await t?.getAddress();if(!(t&&u))throw new U("toolbox_utxo_no_signer");if(!s)throw new U("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});Fr({condition:p&&!Je.includes(e),id:`rbf_not_supported_${e}`,warning:`RBF (Replace-by-Fee) is not reliably supported on ${e}. Transaction will be created without RBF signaling.`});let i=p&&Je.includes(e),l=d||(await be(e))[a||M.Fast],{tx:h}=await sn({assetValue:o,enableRBF:i,feeRate:l,memo:r,publicKey:t.publicKey,recipient:s,sender:u,sweep:c}),m=await t.signTransaction(h);return m.finalize(),O(e).broadcastTx(ae.encode(m.extract()))}}function cn(e){return(t)=>tn({address:t,chain:e})}function dn(e,{scriptType:t}){let n=P(e);return function(s){if(!s)throw new U("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return Fe({chain:e,network:n,publicKey:s.publicKey,scriptType:t})}}function ce(e){let{chain:t}=e,n=e.phrase?e:void 0,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?Lr({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;function h(){if(i)return i.getAddress();return Promise.resolve(void 0)}function m(T){if(!r)return;let g=ee({accountIndex:T,chain:t,derivationPath:d});return Er({chain:t,derivationPath:ke(g),phrase:r,seed:a})}let f=m();function y(){if(!f)return;return f.publicExtendedKey}function b({accountIndex:T}={}){let g=T===void 0?f:m(T);if(!g)return;let w=ee({accountIndex:T,chain:t,derivationPath:d});return{accountIndex:pe(w),path:ke(w),xpub:g.publicExtendedKey}}function A({accountIndex:T,index:g,change:w=!1}){let _=T===void 0?f:m(T);if(!_)return;let x=Ae({accountIndex:T,chain:t,change:w,derivationPath:d,index:g}),k=P(t),F=_.deriveChild(Number(w)).deriveChild(g);if(!F.publicKey)throw new U("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let X=Fe({chain:t,network:k,publicKey:F.publicKey,scriptType:o}),K=ae.encode(F.publicKey);return{accountIndex:pe(x),address:X,change:w,index:g,path:ke(x),pubkey:K}}async function B(T){if(!Je.includes(t))return{reason:`RBF is not supported on ${t}`,supported:!1};let g=await O(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 W({txid:T,newFeeRate:g,recipient:w,memo:_}){if(!Je.includes(t))throw new U("toolbox_utxo_rbf_not_supported",{chain:t});let x=await O(t).getTransactionDetails(T);if(!x.isRBF)throw new U("toolbox_utxo_tx_not_replaceable",{txid:T});if(x.confirmed)throw new U("toolbox_utxo_tx_already_confirmed",{blockId:x.blockId,txid:T});let k=x.inputs.reduce((v,I)=>v+I.value,0),X=x.outputs.find((v)=>v.recipient===w)?.value||0;if(X===0)throw new U("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let K=await Promise.all(x.inputs.map(async(v)=>{let I=await O(t).getRawTx(v.transaction_hash);return{address:v.recipient,hash:v.transaction_hash,index:v.index,publicKey:l?.publicKey,txHex:I,value:v.value,witnessUtxo:void 0}})),D=_?R(_):null,J=k-X-x.fee,Pe=await h(),ue=[];if(D)ue.push({address:"",script:D,value:0});if(J>Be(t)&&Pe)ue.push({address:Pe,value:J});let He=ge({chain:t,inputs:K.map((v)=>({...v,type:Ye(v.address,t)})),outputs:[{address:w,value:X},...ue]}),V=Math.ceil(He*g);if(V<=x.fee)throw new U("toolbox_utxo_rbf_fee_too_low",{newFee:V,originalFee:x.fee});let Ue=V-x.fee,Q=X-Ue;if(Q<=0)throw new U("toolbox_utxo_rbf_insufficient_change");let ve=new yt({allowUnknownOutputs:!!D,version:1}),tt=[{address:w,value:Q},...ue];return ie({chain:t,compiledMemo:D,inputs:K,outputs:tt,sender:Pe||w,tx:ve}),{feeDelta:Ue,newFee:V,originalFee:x.fee,tx:ve}}async function Ie({txid:T,newFeeRate:g,recipient:w,memo:_}){let{tx:x,originalFee:k,newFee:F}=await W({memo:_,newFeeRate:g,recipient:w,txid:T}),X=await et(x);X.finalize();let K=await O(t).broadcastTx(ae.encode(X.extract()));return{newFee:F,originalFee:k,txid:K}}function vt({accountIndex:T,index:g,change:w=!1}){Z("index",g);let _=T===void 0?f:m(T);if(!_)return;return _.deriveChild(Number(w)).deriveChild(g).privateKey||void 0}function At({tx:T,inputDerivations:g}){if(!f)throw new U("toolbox_utxo_no_signer");let w=an(t),_=P(t);for(let x=0;x<g.length;x++){let k=g[x];if(!k)continue;let{derivationIndex:F,isChange:X}=k,K=vt({change:X,index:F});if(!K)throw new U("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${x} at index ${F}`});for(let{index:D,...J}of bt({chain:t,indexes:[x],network:_,publicKey:gt(K),tx:T}))T.updateInput(D,J);T.signIdx(K,x,w)}return T}async function vn({utxos:T,recipient:g,assetValue:w,memo:_,feeRate:x,feeOptionKey:k,changeAddress:F,sweep:X}){if(X)throw new U("toolbox_utxo_invalid_params",{error:"Sweep is not supported for transfers from multiple addresses"});if(!f)throw new U("toolbox_utxo_no_signer");let K=x||(await be(t))[k||M.Fast],D=_?R(_):null,J=[{address:g,value:w.getBaseValue("number")}];if(D)J.push({address:"",script:D,value:0});let Pe=T.map(({address:v,hash:I,index:q,value:nt,txHex:On,witnessUtxo:rt})=>({address:v,hash:I,index:q,txHex:On,value:nt,witnessUtxo:rt?{script:rt.script,value:rt.value}:void 0})),ue=T[0]?.address,He=F||await h()||ue||g,{inputs:V,outputs:Ue}=E({chain:t,changeAddress:He,feeRate:K,inputs:Pe,outputs:J});if(!(V&&Ue))throw new U("toolbox_utxo_insufficient_balance",{assetValue:w,sender:"multiple addresses"});let Q=new yt({allowUnknownOutputs:!!D,version:1}),ve=V.map((v)=>{let I=T.find((q)=>q.hash===v.hash&&q.index===v.index);return I?{derivationIndex:I.derivationIndex,isChange:I.isChange}:{derivationIndex:0,isChange:!1}}),tt=V.map((v,I)=>{let q=ve[I],nt=q?f.deriveChild(Number(q.isChange)).deriveChild(q.derivationIndex).publicKey:null;return{...v,publicKey:nt??void 0}});return ie({chain:t,compiledMemo:D,inputs:tt,outputs:Ue,sender:He,tx:Q}),At({inputDerivations:ve,tx:Q}),Q.finalize(),O(t).broadcastTx(ae.encode(Q.extract()))}function An({address:T,gapLimit:g=20}){if(!f)return;for(let w=0;w<g;w++){let _=A({change:!1,index:w}),x=A({change:!0,index:w}),k=_?.address===T?!1:x?.address===T;if(_?.address===T||x?.address===T)return{change:k,index:w}}return}function et(T){if(!i)throw new U("toolbox_utxo_no_signer");return i.signTransaction(T)}async function _n(T){let g=await et(T);return g.finalize(),await O(t).broadcastTx(ae.encode(g.extract()))}return{accumulative:E,broadcastTx:(T)=>O(t).broadcastTx(T),bumpFee:Ie,calculateTxSize:(T)=>ge({...T,chain:t}),createKeysForPath:(T)=>xe({...T,chain:t}),createReplacementTransaction:W,createTransaction:(T)=>sn({publicKey:l?.publicKey,...T}),deriveAddressAtIndex:A,derivePrivateKeyAtIndex:vt,estimateMaxSendableAmount:zr(t),estimateTransactionFee:Wr(t),getAddress:h,getAddressFromKeys:dn(t,{scriptType:o}),getAddressType:(T)=>Y({address:T,chain:t}),getBalance:jt(t),getExtendedPublicKey:y,getExtendedPublicKeyInfo:b,getFeeRates:()=>be(t),getInputsOutputsFee:on,getNetworkForChain:()=>P(t),getPrivateKeyFromMnemonic:(T)=>Rr(xe({...T,chain:t}).privateKey,t),isRBFEnabled:B,keys:l,resolveDerivationIndex:An,scriptType:o,signAndBroadcastTransaction:_n,signTransaction:et,signTransactionWithMultipleKeys:At,transfer:$r(t,i),transferFromMultipleAddresses:vn,validateAddress:cn(t)}}import{getZcashAddressType as Vr,validateZcashAddress as wt}from"@swapkit/utxo-signer";function De(e){return Oe(e)!==null}var N=qr.BitcoinCash;function Qe(e){return z(Me(e))}function es(e){let t=P(N);function n(s){return s.sign(e.privateKey,[Jr.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=jr({chain:N,derivationPath:r,index:n}),a=Gr(s),d=t?xe({chain:N,derivationPath:a,phrase:t}):void 0,o=d?es(d):("signer"in e)?e.signer:void 0;function p(){return Promise.resolve(o?.getAddress())}let c="scriptType"in e?e.scriptType:void 0,{getBalance:u,getFeeRates:i,broadcastTx:l,...h}=ce(t?{chain:N,index:n,phrase:t,...r?{derivationPath:r,scriptType:c}:{scriptType:c}}:{chain:N,scriptType:c});function m(b,A=!0){return u(z(Me(b)))}function f(b){if(!o)throw new L("toolbox_utxo_no_signer");return o.signTransaction(b)}async function y(b){let A=await f(b);return A.finalize(),await l(un.encode(A.extract()))}return{...h,broadcastTx:l,buildTx:ns,createTransaction:yn,getAddress:p,getAddressFromKeys:rs,getBalance:m,getFeeRates:i,signAndBroadcastTransaction:y,signTransaction:f,stripPrefix:z,stripToCashAddress:Qe,transfer:ts({broadcastTx:l,getFeeRates:i,signer:o}),validateAddress:De}}async function yn({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s,sweep:a}){if(!De(t))throw new L("toolbox_utxo_invalid_address",{address:t});let d=Math.ceil(e.getBaseValue("number")+r*7500),o=await O(N).getUtxos({address:Qe(s),fetchTxHex:!0,targetValue:a?void 0:d}),p=n?R(n):null,c=[],u=G(t);if(c.push({address:u,value:a?0:e.getBaseValue("number")}),p)c.push({script:p,value:0});let{inputs:i,outputs:l}=E({chain:N,feeRate:r,inputs:o,outputs:c,sweep:a});if(!(i&&l))throw new 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:N,compiledMemo:p,inputs:i,outputs:l.map((b)=>("address"in b)&&b.address?{...b,address:G(b.address)}:b),sender:m,tx:h});return{inputs:f,tx:y,utxos:i}}function ts({broadcastTx:e,getFeeRates:t,signer:n}){return async function({recipient:s,assetValue:a,feeOptionKey:d=Yr.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 ns({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s}){let a=Me(t);if(!De(a))throw new L("toolbox_utxo_invalid_address",{address:a});let d=Math.ceil(e.getBaseValue("number")+r*7500),o=await O(N).getUtxos({address:Qe(s),fetchTxHex:!0,targetValue:d}),p=Number(r.toFixed(0)),c=n?R(n):null,u=[];if(u.push({address:G(t),value:e.getBaseValue("number")}),c)u.push({script:c,value:0});let{inputs:i,outputs:l}=E({chain:N,feeRate:p,inputs:o,outputs:u});if(!(i&&l))throw new L("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let h=new Tn({allowUnknownOutputs:!!c,version:1}),{inputs:m,tx:f}=ie({chain:N,compiledMemo:c,inputs:i,outputs:l,sender:G(s),tx:h});return{inputs:m,tx:f,utxos:o}}function rs(e){let t=Qr.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 ss,hex as os}from"@scure/base";import{HDKey as bn}from"@scure/bip32";import{mnemonicToSeedSync as wn}from"@scure/bip39";import{Chain as j,derivationPathToString as as,FeeOption as is,SwapKitError as de}from"@swapkit/helpers";import{Address as cs,createZcashTransaction as ds,getZcashConsensusBranchId as us,isTransparentZcashAddress as gn,OutScript as ps,PCZT as ls,utils as Pn,WIF as hs,ZcashConsensusBranchId as fs,ZcashPSBT as Ts,ZcashSigHash as Pt,ZcashVersionGroupId as ms}from"@swapkit/utxo-signer";import{match as ys,P as Ut}from"ts-pattern";var gs=ss(Pn.sha256);function xs(e){return gs.encode(e)}function bs({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=xs(c);return{getAddress:()=>Promise.resolve(u),signTransaction:(i)=>{if(i instanceof Ts){let l=i.toPCZT();return l.signAllInputs(a,d,Pt.ALL),l.finalizeAllInputs(),Promise.resolve(l.extract())}if(i instanceof ls)return i.signAllInputs(a,d,Pt.ALL),i.finalizeAllInputs(),Promise.resolve(i.extract());return i.signAllInputs(a,d,Pt.ALL),Promise.resolve(i)}}}function ws({inputs:e,outputs:t,tx:n,sender:r,compiledMemo:s}){let a=P(j.Zcash);for(let d of e){let o=cs(a).decode(r),p=ps.encode(o);n.addInput({index:d.index,script:p,sequence:4294967295,txid:os.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 Ps(){try{let e=await O(j.Zcash).getBlockHeight();return us(e+1)}catch{return fs.IRONWOOD}}async function xn(e){let{assetValue:t,recipient:n,memo:r,feeRate:s,sender:a,fetchTxHex:d,sweep:o}=e,p=P(j.Zcash);if(!gn(a,p))throw new de("toolbox_utxo_invalid_address",{address:a});if(!gn(n,p))throw new de("toolbox_utxo_invalid_address",{address:n,error:"Zcash transaction creation currently supports transparent addresses only"});let c=r?R(r):null,u=await O(j.Zcash).getUtxos({address:a,fetchTxHex:d!==!1}),i=[{address:n,value:o?0:Number(t.getBaseValue("string"))},...c?[{script:c,value:0}]:[]],{inputs:l,outputs:h}=E({chain:j.Zcash,changeAddress:a,feeRate:s,inputs:u,outputs:i,sweep:o});if(!(l&&h))throw new de("toolbox_utxo_insufficient_balance",{assetValue:t,sender:a});let m=ds({consensusBranchId:await Ps(),expiryHeight:0,lockTime:0,version:4,versionGroupId:ms.SAPLING}),{tx:f,inputs:y}=ws({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=ys(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=as(l);return bs({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=is.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}),A=(await n.signTransaction(y)).toHex();return r.broadcastTx(A)}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=P(j.Zcash);return hs(l).encode(i.privateKey)}return{...r,createKeysForPath:o,createTransaction:xn,getPrivateKeyFromMnemonic:p,signAndBroadcastTransaction:a,signTransaction:s,transfer:d,validateAddress:wt}}import{hex as Us}from"@scure/base";import{HDKey as vs}from"@scure/bip32";import{derivationPathToString as As,NetworkDerivationPath as _s,updateDerivationPath as Os}from"@swapkit/helpers";function Ss({xpub:e,chain:t,count:n,startIndex:r=0,accountIndex:s,purpose:a,scriptType:d}){if(Z("count",n),n<1)throw RangeError("count must be at least 1");Z("startIndex",r),Le(t,d),ct({chain:t,purpose:a,scriptType:d});let o=P(t),p=vs.fromExtendedKey(e,o.bip32),c=a===void 0?void 0:Os(_s[t],{purpose:a}),u=ee({accountIndex:s,chain:t,derivationPath:c}),i=pe(u),l=[];for(let h of[!1,!0]){let m=p.deriveChild(Number(h));for(let f=0;f<n;f++){let y=r+f,b=m.deriveChild(y);if(!b.publicKey)continue;let A=Ae({accountIndex:s,chain:t,change:h,derivationPath:c,index:y});l.push({accountIndex:i,address:Fe({chain:t,network:o,publicKey:b.publicKey,scriptType:d}),change:h,index:y,pubkey:Us.encode(b.publicKey),...a===void 0?{}:{path:As(A)}})}}return l}function ma(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 Cs("toolbox_utxo_not_supported",{chain:e})}}export{qt as InputSizes,po as MIN_TX_FEE,Sr as OP_RETURN_OVERHEAD,pt as OutputSizes,Or as SEGWIT_MARKER_FLAG_WEIGHT,lt as TX_OVERHEAD,se as UTXOScriptType,Dt as UtxoNetwork,E as accumulative,ie as addInputsAndOutputs,dn as addressFromKeysGetter,Z as assertDerivationIndex,ge as calculateTxSize,R as compileMemo,mn as createBCHToolbox,Ds as createCustomUtxoApi,Cn as createHDWalletHelpers,ce as createUTXOToolbox,Un as createZcashToolbox,Ss as deriveAddressesFromXpub,Ls as detectAddressNetwork,Oe as getBchAddressType,Be as getDustThreshold,Xe as getInputScriptType,re as getInputSize,bt as getMissingSpendingMetadata,P as getNetworkForChain,je as getOutputSize,Cr as getOutputSizeForAddress,Ye as getScriptTypeForAddress,pe as getUTXOAccountIndexFromPath,ee as getUTXOAccountPath,Ae as getUTXOAddressPath,cn as getUTXOAddressValidator,Y as getUtxoAddressType,O as getUtxoApi,Is as getUtxoNetwork,ma as getUtxoToolbox,ft as getWitnessOverhead,Vr as getZcashAddressType,ht as isSegwitScriptType,Ws as isValidAddress,Zt as nonSegwitChains,z as stripPrefix,Qe as stripToCashAddress,Me as toCashAddress,G as toLegacyAddress,Ne as tryDecodeAddress,De as validateBchAddress,tn as validateUtxoAddress,wt as validateZcashAddress};
|
|
1
|
+
import{ha as St,ia as jt}from"../../chunk-xdkdc1f0.js";import"../../chunk-exyqap7m.js";import{NetworkDerivationPath as Cn}from"@swapkit/helpers";function Z(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`${e} must be a non-negative integer, got: ${t}`)}function ee({accountIndex:e,chain:t,derivationPath:n}){if(e!==void 0)Z("accountIndex",e);let[r,s,a]=n??Cn[t];return[r,s,e??a]}function Ae({accountIndex:e,change:t=!1,chain:n,derivationPath:r,index:s}){return Z("index",s),[...ee({accountIndex:e,chain:n,derivationPath:r}),Number(t),s]}function pe(e){return e[2]??0}function Xn({deriveAddress:e,getBalance:t,getUtxos:n}){async function r(o){let{accountIndex:p,count:c,startIndex:u=0,change:i=!1}=o;if(Z("count",c),c<1)throw RangeError("count must be at least 1");Z("startIndex",u);let l=[];for(let h=0;h<c;h++){let m=await e({accountIndex:p,change:i,index:u+h});if(m)l.push(m)}return l}async function s(o){let{gapLimit:p=20,change:c=!1}=o??{},u=[],i=0,l=0;while(i<p){let h=await e({change:c,index:l});if(!h)break;if((await t(h.address)).some((y)=>y.getValue("number")>0))u.push(h),i=0;else i++;l++}return u}async function a(o=20){let[p,c]=await Promise.all([s({change:!1,gapLimit:o}),s({change:!0,gapLimit:o})]),u=[...p,...c],i=await Promise.all(u.map(async(h)=>{let f=(await t(h.address)).reduce((y,b)=>y+b.getValue("number"),0);return{...h,balance:f}})),l=i.reduce((h,m)=>h+m.balance,0);return{addresses:i,total:l}}async function d(o=20){let[p,c]=await Promise.all([s({change:!1,gapLimit:o}),s({change:!0,gapLimit:o})]),u=[...p,...c];return(await Promise.all(u.map(async(l)=>(await n(l.address)).map((m)=>({...m,address:l.address,derivationIndex:l.index,isChange:l.change}))))).flat()}return{deriveAddresses:r,getAggregatedBalance:a,getAggregatedUtxos:d,scanForAddresses:s}}import{Chain as C,getRPCUrl as Bn,RequestClient as Re,SKConfig as kn,SwapKitError as H,warnOnce as Kn}from"@swapkit/helpers";import{NETWORKS as le}from"@swapkit/utxo-signer";async function Fn({chain:e,txHash:t}){let n=`${he(e)}/push/transaction`,r=JSON.stringify({data:t});try{let s=await Re.post(n,{body:r,headers:{"Content-Type":"application/json"}});if(s.context.code!==200)throw new H("toolbox_utxo_broadcast_failed",{error:s.context.error||"Transaction broadcast failed"});return s.data?.transaction_hash||t}catch(s){let a=await Bn(e);if(a){let d=JSON.stringify({id:St(),jsonrpc:"2.0",method:"sendrawtransaction",params:[t]}),o=await Re.post(a,{body:d,headers:{"Content-Type":"application/json"}});if(o.error)throw new H("toolbox_utxo_broadcast_failed",{error:o.error?.message});if(o.result.includes('"code":-26'))throw new H("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return o.result}throw s}}function he(e){return`https://api.blockchair.com/${Dn(e)}`}function At(e){switch(e){case C.Bitcoin:return 5;case C.Dogecoin:return 1e4;case C.Litecoin:return 1;case C.Zcash:return 1;default:return 2}}function Dn(e){switch(e){case C.BitcoinCash:return"bitcoin-cash";case C.Litecoin:return"litecoin";case C.Dash:return"dash";case C.Dogecoin:return"dogecoin";case C.Zcash:return"zcash";case C.Polkadot:return"polkadot";default:return"bitcoin"}}async function In(e){try{let{feePerKb:t}=await Re.get(`https://app.bitgo.com/api/v2/${e.toLowerCase()}/tx/fee`),n=t/1000;return Math.max(n,At(e))}catch{return At(e)}}async function Oe(e,t){let n=await Re.get(`${e}${t?`${e.includes("?")?"&":"?"}key=${t}`:""}`);if(!n||n.context.code!==200)throw new H("toolbox_utxo_api_error",{error:`Failed to query ${e}`});return n.data}async function Hn({chain:e,apiKey:t}){let n=await Oe(`${he(e)}/stats`,t);if(typeof n.best_block_height!=="number")throw new H("toolbox_utxo_api_error",{error:"Missing best_block_height in stats response"});return n.best_block_height}async function Ct({address:e,chain:t,apiKey:n}){if(!e)throw new H("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await Oe(`${he(t)}/dashboards/address/${e}?transaction_details=true`,n))[e]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function Rn({address:e,chain:t,apiKey:n}){return(await Ct({address:e,apiKey:n,chain:t}))?.address.balance||0}async function Xt({chain:e,apiKey:t,txHash:n}){if(!n)throw new H("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await Oe(`${he(e)}/raw/transaction/${n}`,t))?.[n]?.raw_transaction||""}catch(r){let s=r instanceof Error?r.message:String(r);return console.error(`Failed to fetch raw transaction: ${s}`),""}}var En=4294967294;async function Mn({chain:e,apiKey:t,txHash:n}){if(!n)throw new H("toolbox_utxo_invalid_params",{error:"TxHash is required"});let s=(await Oe(`${he(e)}/dashboards/transaction/${n}`,t))?.[n];if(!s)throw new H("toolbox_utxo_tx_not_found",{txHash:n});let{transaction:a,inputs:d,outputs:o}=s,p=d.map((u)=>u.spending_sequence),c=a.is_rbf===!0||p.some((u)=>u<En);return{blockId:a.block_id,confirmed:a.block_id!==-1,fee:a.fee,inputs:d,isRBF:c,outputs:o,sequences:p,size:a.size,txid:a.hash,weight:a.weight}}async function Nn({chain:e,address:t,apiKey:n,offset:r=0,limit:s=30}){return(await Oe(`${he(e)}/outputs?q=recipient(${t}),is_spent(false)&s=value(desc)&fields=is_spent,transaction_hash,index,value,script_hex,block_id,spending_signature_hex&limit=${s}&offset=${r}`,n)).map(({is_spent:p,script_hex:c,block_id:u,transaction_hash:i,index:l,value:h,spending_signature_hex:m})=>({hash:i,index:l,is_confirmed:u!==-1,is_spent:p,script_hex:c,txHex:m,value:h}))}function Zn(e){return e.reduce((t,n)=>t+n.value,0)}function Ot(e,t){let n=[...e].sort((r,s)=>s.value-r.value);if(t){let r=[],s=0;for(let a of n)if(r.push(a),s+=a.value,s>=t)break;return r}return n}async function Bt({chain:e,address:t,apiKey:n,targetValue:r,accumulativeValue:s=0,offset:a=0,limit:d=30}){if(!t)throw new H("toolbox_utxo_invalid_params",{error:"Address is required"});try{let o=await Nn({address:t,apiKey:n,chain:e,limit:d,offset:a,targetValue:r}),c=o.length<d,u=o.filter(({is_spent:y})=>!y),i=Zn(u),l=s+i,h=r&&l>=r;if(c||h)return Ot(u,r);let m=await Bt({accumulativeValue:l,address:t,apiKey:n,chain:e,limit:d,offset:a+d,targetValue:r}),f=[...u,...m];return Ot(f,r)}catch(o){let p=o instanceof Error?o.message:String(o);return console.error(`Failed to fetch unspent UTXOs: ${p}`),[]}}async function zn({address:e,chain:t,apiKey:n,fetchTxHex:r=!0,targetValue:s}){let a=await Bt({address:e,apiKey:n,chain:t,targetValue:s}),d=r?await Promise.all(a.map(({hash:o})=>Xt({apiKey:n,chain:t,txHash:o}))):[];return a.map(({hash:o,index:p,script_hex:c,value:u},i)=>({address:e,hash:o,index:p,txHex:r?d[i]:void 0,value:u,witnessUtxo:{script:Buffer.from(c,"hex"),value:u}}))}function A(e){let t=kn.get("apiKeys").blockchair||"";return Kn({condition:!t,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(n)=>Fn({chain:e,txHash:n}),getAddressData:(n)=>Ct({address:n,apiKey:t,chain:e}),getBalance:(n)=>Rn({address:n,apiKey:t,chain:e}),getBlockHeight:()=>Hn({apiKey:t,chain:e}),getRawTx:(n)=>Xt({apiKey:t,chain:e,txHash:n}),getSuggestedTxFee:()=>In(e),getTransactionDetails:(n)=>Mn({apiKey:t,chain:e,txHash:n}),getUtxos:(n)=>zn({...n,apiKey:t,chain:e})}}function Hs(e){return e}function Rs(){return function(t){switch(t){case C.Bitcoin:return le.bitcoin;case C.BitcoinCash:return le.bitcoinCash;case C.Dash:return le.dash;case C.Litecoin:return le.litecoin;case C.Dogecoin:return le.dogecoin;case C.Zcash:return le.zcash;default:throw new H("toolbox_utxo_not_supported",{chain:t})}}}import{sha256 as Yn}from"@noble/hashes/sha2.js";import{createBase58check as jn}from"@scure/base";import{SwapKitError as Kt}from"@swapkit/helpers";import{CashAddrType as Ee,decodeCashAddr as Wn,encodeCashAddr as Ln}from"@swapkit/utxo-signer";var $n={P2PKH:Ee.P2PKH,P2SH:Ee.P2SH},Vn={[Ee.P2PKH]:"P2PKH",[Ee.P2SH]:"P2SH"};function qn(e,t,n){return Ln({hash:n,prefix:e,type:$n[t]})}function Gn(e){let t=Wn(e),n=Vn[t.type];if(!n)throw Error(`Unknown CashAddr type: ${t.type}`);return{hash:t.hash,prefix:t.prefix,type:n}}var st={decode:Gn,encode:qn};var Ft=jn(Yn);var Dt;((n)=>{n.Mainnet="mainnet";n.Testnet="testnet"})(Dt||={});var te={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}},Jn={["p2pkh"]:"pkh",["p2sh"]:"sh"};function $s(e){return Ne(e)!==void 0}function Vs(e){return ot(e).network}function G(e){let t=ot(e);if(t.format==="legacy")return e;return tr(t)}function Me(e){let t=ot(e);return nr(t)}function Ne(e){if(typeof e!=="string")return;let t=Qn(e)??er(e);return t&&{...t,scriptType:Jn[t.type]}}function ot(e){let t=Ne(e);if(!t)throw new Kt("toolbox_utxo_invalid_address",{address:e});return t}function Qn(e){try{let t=Ft.decode(e);if(t.length!==21)throw new Kt("toolbox_utxo_invalid_address",{address:e});let n=t[0],r=Array.prototype.slice.call(t,1);switch(n){case te.legacy.mainnet.p2pkh:return{format:"legacy",hash:r,network:"mainnet",type:"p2pkh"};case te.legacy.mainnet.p2sh:return{format:"legacy",hash:r,network:"mainnet",type:"p2sh"};case te.legacy.testnet.p2pkh:return{format:"legacy",hash:r,network:"testnet",type:"p2pkh"};case te.legacy.testnet.p2sh:return{format:"legacy",hash:r,network:"testnet",type:"p2sh"};case te.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2pkh"};case te.bitpay.mainnet.p2sh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function er(e){if(e.indexOf(":")!==-1)try{return kt(e)}catch{}else{let t=["bitcoincash","bchtest","bchreg"];for(let n of t)try{return kt(`${n}:${e}`)}catch{}}return}function kt(e){try{let{hash:t,prefix:n,type:r}=st.decode(e);return{format:"cashaddr",hash:Array.prototype.slice.call(t,0),network:n==="bitcoincash"?"mainnet":"testnet",type:r==="P2PKH"?"p2pkh":"p2sh"}}catch{return}}function tr(e){let t=te.legacy[e.network][e.type],n=Buffer.alloc(1+e.hash.length);return n[0]=t,n.set(e.hash,1),Ft.encode(n)}function nr(e){let t=e.network==="mainnet"?"bitcoincash":"bchtest",n=e.type==="p2pkh"?"P2PKH":"P2SH",r=new Uint8Array(e.hash);return st.encode(t,n,r)}import{Chain as oe,SwapKitError as Tt}from"@swapkit/helpers";import{SwapKitError as qe,UTXO_SCRIPT_TYPE_LIST as Ar,UTXO_SCRIPT_TYPES as $t,UTXOScriptType as Ge}from"@swapkit/helpers";import{Script as Or}from"@swapkit/utxo-signer";import{Chain as at}from"@swapkit/helpers";import{getAddressScriptType as sr,getTransparentZcashAddressType as or,getZcashAddressType as ar}from"@swapkit/utxo-signer";import{match as ir}from"ts-pattern";import{Chain as fe}from"@swapkit/helpers";import{NETWORKS as Te}from"@swapkit/utxo-signer";import{match as rr}from"ts-pattern";function U(e){return rr(e).with(fe.Bitcoin,()=>Te.bitcoin).with(fe.BitcoinCash,()=>Te.bitcoinCash).with(fe.Dash,()=>Te.dash).with(fe.Dogecoin,()=>Te.dogecoin).with(fe.Litecoin,()=>Te.litecoin).with(fe.Zcash,()=>Te.zcash).exhaustive()}function z(e){return e.replace(/(bchtest:|bitcoincash:)/,"")}function Se(e){if(typeof e!=="string")return null;let t=Ne(z(e));if(!t||t.network!=="mainnet")return null;return t.scriptType}var cr=["sprout","sapling","unified"];function dr(e){let t=or(e,U(at.Zcash));if(t)return t;let n=ar(e);return n&&cr.includes(n)?n:null}function Y({address:e,chain:t}){return ir(t).with(at.BitcoinCash,()=>Se(e)).with(at.Zcash,()=>dr(e)).otherwise(()=>sr(e,U(t)))}import{Chain as ne,derivationPathToString as It,getPurposeFromPath as ur,getUTXOScriptTypeForPath as Ht,getUTXOScriptTypeForPurpose as Mt,resolveDerivationPath as pr,SwapKitError as Ce,UTXO_SCRIPT_TYPE_LIST as Rt,UTXO_SCRIPT_TYPES as me,UTXOChains as lr,UTXOScriptType as O,updateDerivationPath as hr,warnOnce as fr}from"@swapkit/helpers";import{CashAddrPrefix as Tr,CashAddrType as mr,encodeCashAddr as yr,OutScript as Nt,p2pkh as gr,p2sh as xr,p2tr as br,p2wpkh as Et}from"@swapkit/utxo-signer";var Ze=Object.freeze([O.P2PKH]),wr=Object.freeze({[ne.Bitcoin]:Rt,[ne.BitcoinCash]:Ze,[ne.Dash]:Ze,[ne.Dogecoin]:Ze,[ne.Litecoin]:Rt,[ne.Zcash]:Ze});function We(e){return wr[e]}function it(e){return We(e).some((t)=>me[t].witness)}function ye(e,t){return We(e).includes(t)}function Le(e,t){if(ye(e,t))return t;throw new Ce("toolbox_utxo_unsupported_script_type",{chain:e,error:`${e} cannot encode ${t}; supported: ${We(e).join(", ")}`,scriptType:t,supported:We(e)})}var Zt=lr.filter((e)=>!it(e));function Pr({purpose:e,scriptType:t}){let n=Mt(e);return n===void 0||n===t}function ct({chain:e,purpose:t,scriptType:n}){fr({condition:!Pr({purpose:t,scriptType:n}),id:`utxo_off_standard_encoding_${e}_${t}_${n}`,warning:`${e}: encoding m/${t}' keys as ${n}, not the ${Mt(t)} the path implies. No other wallet derives these addresses: move funds out of them, never receive into them.`})}function $e({chain:e,derivationPath:t,index:n=0,scriptType:r}){if(t){if(!r){let o=Ht(t);throw new Ce("toolbox_utxo_invalid_params",{chain:e,derivationPath:It(t),error:`scriptType is required alongside derivationPath: getUTXOScriptTypeForPath gives the standard one${o?` (${o})`:""}, or state another deliberately.`})}return Le(e,r),ct({chain:e,purpose:ur(t),scriptType:r}),{derivationPath:t,scriptType:r}}let s=pr({chain:e,index:n}),a=r?hr(s,{purpose:me[r].purpose}):s,d=r??Ht(a);if(!d)throw new Ce("toolbox_utxo_invalid_params",{chain:e,derivationPath:It(a),error:`${e}: the default derivation path has no standard script type`});return Le(e,d),{derivationPath:a,scriptType:d}}function Ur(e){return e.length===32?e:e.slice(1)}function ze(e,t){if(!e.address)throw new Ce("toolbox_utxo_invalid_address",{error:`Could not derive a ${t} address`});return e}var vr={[O.P2PKH]:(e,t)=>{let{address:n,script:r}=ze(gr(e,t),O.P2PKH);return{address:n,script:r}},[O.P2SH_P2WPKH]:(e,t)=>{let n=Et(e,t),{address:r,script:s}=ze(xr(n,t),O.P2SH_P2WPKH);return{address:r,redeemScript:n.script,script:s}},[O.P2WPKH]:(e,t)=>{let{address:n,script:r}=ze(Et(e,t),O.P2WPKH);return{address:n,script:r}},[O.P2TR]:(e,t)=>{let n=Ur(e),{address:r,script:s}=ze(br(n,void 0,t),O.P2TR);return{address:r,script:s,tapInternalKey:n}}};function Ve(e,t,n){return vr[e](t,n)}function dt(e,t){if(e!==ne.BitcoinCash)return t.address;let n=Nt.decode(t.script);if(n.type!=="pkh")throw new Ce("toolbox_utxo_invalid_address",{chain:e,error:`Cannot encode ${n.type} as CashAddr`});return yr({hash:n.hash,prefix:Tr.MAINNET,type:mr.P2PKH}).replace(/^bitcoincash:/,"")}var _r=Object.freeze({pkh:O.P2PKH,sh:O.P2SH_P2WPKH,tr:O.P2TR,wpkh:O.P2WPKH}),zt=Object.freeze({pkh:me[O.P2PKH].outputSize,sh:me[O.P2SH_P2WPKH].outputSize,tr:me[O.P2TR].outputSize,wpkh:me[O.P2WPKH].outputSize,wsh:43});function Wt(e){return e in zt}function Lt(e){return Wt(e)?zt[e]:void 0}function Xe(e){return _r[e]}function ut(e){try{let{type:t}=Nt.decode(e);return Wt(t)?Xe(t):void 0}catch{return}}import{UTXOScriptType as se}from"@swapkit/helpers";var ho=1000,lt=10,Sr=2,Cr=10;function R(e){let t=new Uint8Array(Buffer.from(e,"utf8"));return Or.encode(["RETURN",t])}function Vt(e){return Object.fromEntries(Ar.map((t)=>[t,$t[t][e]]))}var qt=Vt("inputSize"),pt=Vt("outputSize"),ht=(e)=>$t[e].witness,Ye=(e,t)=>{let n=Y({address:e,chain:t});if(!n)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let r=Xe(n);if(!r||!ye(t,r))throw new qe("toolbox_utxo_unsupported_script_type",{address:e,addressType:n,chain:t,error:"Address is valid but its script type is not one the SDK spends from"});return r},Xr=(e,t)=>{let n=Y({address:e,chain:t});if(!n)throw new qe("toolbox_utxo_invalid_address",{address:e,chain:t});let r=Lt(n);if(!r)throw new qe("toolbox_utxo_unsupported_script_type",{address:e,addressType:n,chain:t,error:"Address is valid but a transparent transaction cannot pay to it"});return r},ge=({chain:e,inputs:t,outputs:n,feeRate:r})=>{let s=t[0]?Be(t[0],e):Ge.P2PKH,a=r?t.filter((u)=>u.value>=qt["type"in u&&u.type?u.type:Ge.P2PKH]*Math.ceil(r)):t,d=0,o=0;for(let u of a)if(d+=re(u,e),!ht(Be(u,e)))o++;let p=n?.reduce((u,i)=>u+je(i,e),0)||pt[s],c=o<a.length;return lt+d+p+ft(c,o)},Be=(e,t)=>{if("type"in e&&e.type)return e.type;if("address"in e&&e.address)return Ye(e.address,t);return Ge.P2PKH},re=(e,t)=>qt[Be(e,t)],ft=(e,t)=>e?Math.ceil((Sr+t)/4):0,je=(e,t,n)=>{if(e?.script)return Cr+e.script.length+(e.script.length>=74?2:1);if(n)return pt[n];if("address"in e&&e.address)return Xr(e.address,t);return pt[Ge.P2PKH]};function ke(e){switch(e){case oe.Bitcoin:case oe.BitcoinCash:return 550;case oe.Dash:case oe.Litecoin:return 5500;case oe.Dogecoin:return 1e5;case oe.Zcash:return 546;default:throw new Tt("toolbox_utxo_not_supported",{chain:e})}}function E({inputs:e,outputs:t,feeRate:n=1,chain:r=oe.Bitcoin,changeAddress:s="",sweep:a=!1}){let d=ke(r),o=e.filter((f)=>{let y=re(f,r)*n;return a?f.value>Math.max(y,d):y<=f.value});if(a){let f=Math.ceil(n*ge({chain:r,inputs:o,outputs:t})),y=o.reduce((X,L)=>X+L.value,0),b=y-f;if(b<=d)throw new Tt("toolbox_sweep_amount_too_low",{available:y,dustThreshold:d,fee:f});let S=t.findIndex((X)=>("address"in X)&&X.address);if(S===-1)throw new Tt("toolbox_utxo_invalid_params",{error:"Sweep requires a recipient output"});return{fee:f,inputs:o,outputs:t.map((X,L)=>L===S?{...X,value:b}:X)}}let p=lt+t.reduce((f,y)=>f+je(y,r),0),c=t.reduce((f,y)=>f+y.value,0),u=0,i=0,l=!1,h=0,m=[];for(let f of o){if(u+=re(f,r),ht(Be(f,r)))l=!0;else i++;h+=f.value,m.push(f);let y=(p+u+ft(l,i))*n,b=y+c;if(h<b)continue;let S=h-b,X=n*je({address:s,value:0},r);if(S>X){let L=X+y,Pe=h-(c+Math.ceil(L));if(Pe>Math.max(re({value:0},r)*n,ke(r)))return{fee:Math.ceil(L),inputs:m,outputs:t.concat({address:s,value:Pe})}}return{fee:Math.ceil(y),inputs:m,outputs:t}}return{fee:Math.ceil(n*ge({chain:r,inputs:e,outputs:t}))}}import{Chain as we,SwapKitError as Bs}from"@swapkit/helpers";import{hex as un}from"@scure/base";import{Chain as Yr,derivationPathToString as jr,FeeOption as Jr,resolveDerivationPath as Qr,SwapKitError as W}from"@swapkit/helpers";import{BCHSigHash as es,CashAddrPrefix as pn,CashAddrType as ln,encodeCashAddr as hn,NETWORKS as ts,p2pkh as fn,Transaction as Tn}from"@swapkit/utxo-signer";import{secp256k1 as Br}from"@noble/curves/secp256k1.js";import{hex as ae}from"@scure/base";import{HDKey as Jt}from"@scure/bip32";import{mnemonicToSeedSync as xt}from"@scure/bip39";import{AssetValue as mt,applyFeeMultiplier as Gt,Chain as Fe,derivationPathToString as Ke,FeeOption as M,NetworkDerivationPath as kr,SwapKitError as P,SwapKitNumber as Kr,UTXO_SCRIPT_TYPES as Fr,warnOnce as Dr}from"@swapkit/helpers";import{BCHSigHash as Qt,RBF_SEQUENCE as Ir,SigHash as Yt,Transaction as yt,utils as Hr,WIF as en}from"@swapkit/utxo-signer";var Je=[Fe.Bitcoin];function tn({address:e,chain:t}){return Y({address:e,chain:t})!==null}function Rr({phrase:e,derivationPath:t,network:n,seed:r}){let s=r??xt(e),d=Jt.fromMasterSeed(s,n.bip32).derive(t);if(!d.privateKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive private key from phrase"});return d.privateKey}function gt(e){return Br.getPublicKey(e,!0)}function De({publicKey:e,chain:t,network:n,scriptType:r}){return dt(t,Ve(r,e,n))}function xe({phrase:e,derivationPath:t,chain:n,wif:r,seed:s}){let a=U(n);if(r){let c=en(a).decode(r),u=gt(c);return{privateKey:c,publicKey:u}}if(!e)throw new P("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let d=t||Ke(kr[n]),o=Rr({derivationPath:d,network:a,phrase:e,seed:s}),p=gt(o);return{privateKey:o,publicKey:p}}function Er(e,t){return en(U(t)).encode(e)}function Mr({phrase:e,derivationPath:t,chain:n,seed:r}){let s=t.split("/");if(s.length<4)throw new P("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${s.length}): ${t}`});let a=U(n),d=r??xt(e),o=Jt.fromMasterSeed(d,a.bip32),p=s.slice(0,4).join("/");return o.derive(p)}function Nr(e,t){if(!e||!Fr[e].witness)return!1;return e!==se.P2SH_P2WPKH||!!t}function nn({chain:e,script:t,publicKey:n,network:r}){let s=ut(t);if(s!==se.P2SH_P2WPKH&&s!==se.P2TR)return{};if(!ye(e,s))return{};let a=Ve(s,n,r);if(Hr.compareBytes(a.script,t)!==0)return{};return s===se.P2TR?{tapInternalKey:a.tapInternalKey}:{redeemScript:a.redeemScript}}function Zr(e,t,n){if(!n)return!1;let r=Y({address:e,chain:t}),s=r?Xe(r):void 0;if(!s||!ye(t,s))return!1;let a=dt(t,Ve(s,n,U(t)));return t===Fe.BitcoinCash?z(a)===z(e):a===e}function zr(e){return e.witnessUtxo?.script??e.nonWitnessUtxo?.outputs[e.index??0]?.script}function bt({chain:e,tx:t,publicKey:n,network:r,indexes:s}){let a=s??Array.from({length:t.inputsLength},(o,p)=>p),d=[];for(let o of a){let p=t.getInput(o),c=zr(p);if(!c)continue;let{redeemScript:u,tapInternalKey:i}=nn({chain:e,network:r,publicKey:n,script:c}),l={index:o};if(u&&!p.redeemScript)l.redeemScript=u;if(i&&!p.tapInternalKey)l.tapInternalKey=i;if(l.redeemScript||l.tapInternalKey)d.push(l)}return d}function ie({inputs:e,outputs:t,chain:n,tx:r,sender:s,compiledMemo:a,enableRBF:d=!1}){let o=U(n),p=it(n),c=d?Ir:void 0,u=new Set;for(let i of e){let l=`${i.hash}:${i.index}`;if(u.has(l))throw new P("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});u.add(l);let h=typeof i.hash==="string"?ae.decode(i.hash):i.hash,m=i.witnessUtxo?ut(i.witnessUtxo.script):void 0,f=i.publicKey&&i.witnessUtxo?nn({chain:n,network:o,publicKey:i.publicKey,script:i.witnessUtxo.script}):{};if(p&&i.witnessUtxo&&Nr(m,f.redeemScript))r.addInput({...f,index:i.index,sequence:c,txid:h,witnessUtxo:{amount:BigInt(i.witnessUtxo.value),script:i.witnessUtxo.script}});else if(i.txHex)r.addInput({...f,index:i.index,nonWitnessUtxo:ae.decode(i.txHex),sequence:c,txid:h,...n===Fe.BitcoinCash?{sighashType:Qt.ALL}:{}});else throw new P("toolbox_utxo_invalid_params",{error:`Input ${l} cannot be signed from its witnessUtxo alone: it needs its previous transaction (txHex), or — if it is a nested-segwit output — the public key that controls it, which its redeemScript derives from`})}for(let i of t){let l="address"in i&&i.address?i.address:s;if(n===Fe.BitcoinCash)l=G(l);if(i.script)if(a)r.addOutput({amount:0n,script:a});else throw new P("toolbox_utxo_invalid_params",{error:"An output carrying a script needs the compiled memo it carries"});else r.addOutputAddress(l,BigInt(i.value),o)}return{inputs:e,tx:r}}async function be(e){let t=await A(e).getSuggestedTxFee();return{[M.Average]:t,[M.Fast]:Gt(t,M.Fast),[M.Fastest]:Gt(t,M.Fastest)}}async function rn({assetValue:e,recipient:t,memo:n,sender:r,sweep:s,fetchTxHex:a=!1,publicKey:d},o,{forEstimateOnly:p=!1}={}){let c=e.chain,u=Ye(r,c),i=u===se.P2PKH||u===se.P2SH_P2WPKH&&!Zr(r,c,d),l=a||!p&&i,h=e.getBaseValue("number"),m=s?void 0:o??(await be(c))[M.Fastest],f=s||m===void 0?void 0:Math.ceil(h+m*5000);return{inputs:await A(c).getUtxos({address:r,fetchTxHex:l,targetValue:f}),outputs:[{address:t,value:s?0:h},...n?[{address:"",script:R(n),value:0}]:[]]}}async function sn({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s,fetchTxHex:a=!1,enableRBF:d=!1,sweep:o,publicKey:p}){let c=e.chain,u=n?R(n):null,i=await rn({assetValue:e,fetchTxHex:a,memo:n,publicKey:p,recipient:t,sender:s,sweep:o},r),{inputs:l,outputs:h}=E({...i,chain:c,changeAddress:s,feeRate:r,sweep:o});if(!(l&&h))throw new P("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let m=p?l.map((S)=>({...S,publicKey:p})):l,f=new yt({allowUnknownOutputs:!!u,version:1}),{inputs:y,tx:b}=ie({chain:c,compiledMemo:u,enableRBF:d,inputs:m,outputs:h,sender:s,tx:f});return{inputs:y,tx:b,utxos:i.inputs}}async function on({assetValue:e,feeOptionKey:t=M.Fast,feeRate:n,memo:r,sender:s,recipient:a,sweep:d}){let o=e.chain,p,c;if(n!==void 0)p=n,c=Math.floor(n);else{let i=await be(o);p=i[M.Fastest],c=i[t]}let u=await rn({assetValue:e,memo:r,recipient:a,sender:s,sweep:d},p,{forEstimateOnly:!0});return E({...u,chain:o,changeAddress:s,feeRate:c,sweep:d})}function Wr(e){return async function({from:n,memo:r,feeRate:s,feeOptionKey:a=M.Fast,recipient:d=n,recipients:o=1}){let p=s??(await be(e))[a],u=(await A(e).getUtxos({address:n,fetchTxHex:!1})).filter((f)=>f.value>Math.max(ke(e),re(f,e)*p));if(!u.length)return mt.from({chain:e});let i=typeof o==="number"?Math.max(o,1):o.length,l=typeof o==="number"||i===0?Array.from({length:i||1},()=>({address:d,value:0})):[...o];if(r)l.push({address:n,script:R(r),value:0});let{outputs:h}=E({chain:e,feeRate:p,inputs:u,outputs:l,sweep:!0}),m=h?.[0]?.value??0;return mt.from({chain:e,value:BigInt(m)})}}function Lr(e){return async function(n){let{fee:r}=await on(n);return mt.from({chain:e,value:Kr.fromBigInt(BigInt(r),8).getValue("string")})}}function $r({chain:e,phrase:t,derivationPath:n,scriptType:r,seed:s}){let a=U(e),{privateKey:d,publicKey:o}=xe({chain:e,derivationPath:n,phrase:t,seed:s}),p=an(e);return{getAddress:()=>De({chain:e,network:a,publicKey:o,scriptType:r}),privateKey:d,publicKey:o,signTransaction:(c)=>{for(let{index:u,...i}of bt({chain:e,network:a,publicKey:o,tx:c}))c.updateInput(u,i);return c.sign(d,p),c}}}function an(e){return e===Fe.BitcoinCash?[Qt.ALL]:[Yt.ALL,Yt.DEFAULT]}function Vr(e,t,n){return async function({memo:s,recipient:a,feeOptionKey:d,feeRate:o,assetValue:p,enableRBF:c=!1,sweep:u}){let i=await t?.getAddress();if(!(t&&i))throw new P("toolbox_utxo_no_signer");if(!a)throw new P("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});Dr({condition:c&&!Je.includes(e),id:`rbf_not_supported_${e}`,warning:`RBF (Replace-by-Fee) is not reliably supported on ${e}. Transaction will be created without RBF signaling.`});let l=c&&Je.includes(e),h=o||(await be(e))[d||M.Fast],{tx:m}=await sn({assetValue:p,enableRBF:l,feeRate:h,memo:s,publicKey:n,recipient:a,sender:i,sweep:u}),f=await t.signTransaction(m);return f.finalize(),A(e).broadcastTx(ae.encode(f.extract()))}}function cn(e){return(t)=>tn({address:t,chain:e})}function dn(e,{scriptType:t}){let n=U(e);return function(s){if(!s)throw new P("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return De({chain:e,network:n,publicKey:s.publicKey,scriptType:t})}}function qr(e){let t=e?.publicKey;if(t===void 0)return;if(t instanceof Uint8Array&&t.length===33)return t;throw new P("toolbox_utxo_invalid_params",{error:"signer.publicKey must be a 33-byte compressed public key (Uint8Array)"})}function ce(e){let{chain:t}=e,n=e.phrase?e:void 0;if(!n&&"derivationPath"in e&&e.derivationPath!==void 0)throw new P("toolbox_utxo_invalid_params",{error:"derivationPath needs a phrase; a toolbox built around a signer uses the signer's addresses"});let r=n?.phrase,s=n?.index??0,a=r?xt(r):void 0,{derivationPath:d,scriptType:o}=$e({chain:t,derivationPath:n?.derivationPath,index:s,scriptType:e.scriptType}),p=Ke(d),c=r?$r({chain:t,derivationPath:p,phrase:r,scriptType:o,seed:a}):void 0,u=n?void 0:e.signer,i=c||u,l=r?xe({chain:t,derivationPath:p,phrase:r,seed:a}):void 0,h=l?.publicKey??qr(u);function m(){if(i)return i.getAddress();return Promise.resolve(void 0)}function f(T){if(!r)return;let g=ee({accountIndex:T,chain:t,derivationPath:d});return Mr({chain:t,derivationPath:Ke(g),phrase:r,seed:a})}let y=f();function b(){if(!y)return;return y.publicExtendedKey}function S({accountIndex:T}={}){let g=T===void 0?y:f(T);if(!g)return;let w=ee({accountIndex:T,chain:t,derivationPath:d});return{accountIndex:pe(w),path:Ke(w),xpub:g.publicExtendedKey}}function X({accountIndex:T,index:g,change:w=!1}){let _=T===void 0?y:f(T);if(!_)return;let x=Ae({accountIndex:T,chain:t,change:w,derivationPath:d,index:g}),k=U(t),F=_.deriveChild(Number(w)).deriveChild(g);if(!F.publicKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let B=De({chain:t,network:k,publicKey:F.publicKey,scriptType:o}),K=ae.encode(F.publicKey);return{accountIndex:pe(x),address:B,change:w,index:g,path:Ke(x),pubkey:K}}async function L(T){if(!Je.includes(t))return{reason:`RBF is not supported on ${t}`,supported:!1};let g=await A(t).getTransactionDetails(T);return{canReplace:g.isRBF&&!g.confirmed,confirmed:g.confirmed,enabled:g.isRBF,fee:g.fee,sequences:g.sequences,supported:!0}}async function Pe({txid:T,newFeeRate:g,recipient:w,memo:_}){if(!Je.includes(t))throw new P("toolbox_utxo_rbf_not_supported",{chain:t});let x=await A(t).getTransactionDetails(T);if(!x.isRBF)throw new P("toolbox_utxo_tx_not_replaceable",{txid:T});if(x.confirmed)throw new P("toolbox_utxo_tx_already_confirmed",{blockId:x.blockId,txid:T});let k=x.inputs.reduce((v,I)=>v+I.value,0),B=x.outputs.find((v)=>v.recipient===w)?.value||0;if(B===0)throw new P("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let K=await Promise.all(x.inputs.map(async(v)=>{let I=await A(t).getRawTx(v.transaction_hash);return{address:v.recipient,hash:v.transaction_hash,index:v.index,publicKey:h,txHex:I,value:v.value,witnessUtxo:void 0}})),D=_?R(_):null,J=k-B-x.fee,Ue=await m(),ue=[];if(D)ue.push({address:"",script:D,value:0});if(J>ke(t)&&Ue)ue.push({address:Ue,value:J});let He=ge({chain:t,inputs:K.map((v)=>({...v,type:Ye(v.address,t)})),outputs:[{address:w,value:B},...ue]}),V=Math.ceil(He*g);if(V<=x.fee)throw new P("toolbox_utxo_rbf_fee_too_low",{newFee:V,originalFee:x.fee});let ve=V-x.fee,Q=B-ve;if(Q<=0)throw new P("toolbox_utxo_rbf_insufficient_change");let _e=new yt({allowUnknownOutputs:!!D,version:1}),tt=[{address:w,value:Q},...ue];return ie({chain:t,compiledMemo:D,inputs:K,outputs:tt,sender:Ue||w,tx:_e}),{feeDelta:ve,newFee:V,originalFee:x.fee,tx:_e}}async function vn({txid:T,newFeeRate:g,recipient:w,memo:_}){let{tx:x,originalFee:k,newFee:F}=await Pe({memo:_,newFeeRate:g,recipient:w,txid:T}),B=await et(x);B.finalize();let K=await A(t).broadcastTx(ae.encode(B.extract()));return{newFee:F,originalFee:k,txid:K}}function vt({accountIndex:T,index:g,change:w=!1}){Z("index",g);let _=T===void 0?y:f(T);if(!_)return;return _.deriveChild(Number(w)).deriveChild(g).privateKey||void 0}function _t({tx:T,inputDerivations:g}){if(!y)throw new P("toolbox_utxo_no_signer");let w=an(t),_=U(t);for(let x=0;x<g.length;x++){let k=g[x];if(!k)continue;let{derivationIndex:F,isChange:B}=k,K=vt({change:B,index:F});if(!K)throw new P("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${x} at index ${F}`});for(let{index:D,...J}of bt({chain:t,indexes:[x],network:_,publicKey:gt(K),tx:T}))T.updateInput(D,J);T.signIdx(K,x,w)}return T}async function _n({utxos:T,recipient:g,assetValue:w,memo:_,feeRate:x,feeOptionKey:k,changeAddress:F,sweep:B}){if(B)throw new P("toolbox_utxo_invalid_params",{error:"Sweep is not supported for transfers from multiple addresses"});if(!y)throw new P("toolbox_utxo_no_signer");let K=x||(await be(t))[k||M.Fast],D=_?R(_):null,J=[{address:g,value:w.getBaseValue("number")}];if(D)J.push({address:"",script:D,value:0});let Ue=T.map(({address:v,hash:I,index:q,value:nt,txHex:Sn,witnessUtxo:rt})=>({address:v,hash:I,index:q,txHex:Sn,value:nt,witnessUtxo:rt?{script:rt.script,value:rt.value}:void 0})),ue=T[0]?.address,He=F||await m()||ue||g,{inputs:V,outputs:ve}=E({chain:t,changeAddress:He,feeRate:K,inputs:Ue,outputs:J});if(!(V&&ve))throw new P("toolbox_utxo_insufficient_balance",{assetValue:w,sender:"multiple addresses"});let Q=new yt({allowUnknownOutputs:!!D,version:1}),_e=V.map((v)=>{let I=T.find((q)=>q.hash===v.hash&&q.index===v.index);return I?{derivationIndex:I.derivationIndex,isChange:I.isChange}:{derivationIndex:0,isChange:!1}}),tt=V.map((v,I)=>{let q=_e[I],nt=q?y.deriveChild(Number(q.isChange)).deriveChild(q.derivationIndex).publicKey:null;return{...v,publicKey:nt??void 0}});return ie({chain:t,compiledMemo:D,inputs:tt,outputs:ve,sender:He,tx:Q}),_t({inputDerivations:_e,tx:Q}),Q.finalize(),A(t).broadcastTx(ae.encode(Q.extract()))}function An({address:T,gapLimit:g=20}){if(!y)return;for(let w=0;w<g;w++){let _=X({change:!1,index:w}),x=X({change:!0,index:w}),k=_?.address===T?!1:x?.address===T;if(_?.address===T||x?.address===T)return{change:k,index:w}}return}function et(T){if(!i)throw new P("toolbox_utxo_no_signer");return i.signTransaction(T)}async function On(T){let g=await et(T);return g.finalize(),await A(t).broadcastTx(ae.encode(g.extract()))}return{accumulative:E,broadcastTx:(T)=>A(t).broadcastTx(T),bumpFee:vn,calculateTxSize:(T)=>ge({...T,chain:t}),createKeysForPath:(T)=>xe({...T,chain:t}),createReplacementTransaction:Pe,createTransaction:(T)=>sn({publicKey:h,...T}),deriveAddressAtIndex:X,derivePrivateKeyAtIndex:vt,estimateMaxSendableAmount:Wr(t),estimateTransactionFee:Lr(t),getAddress:m,getAddressFromKeys:dn(t,{scriptType:o}),getAddressType:(T)=>Y({address:T,chain:t}),getBalance:jt(t),getExtendedPublicKey:b,getExtendedPublicKeyInfo:S,getFeeRates:()=>be(t),getInputsOutputsFee:on,getNetworkForChain:()=>U(t),getPrivateKeyFromMnemonic:(T)=>Er(xe({...T,chain:t}).privateKey,t),isRBFEnabled:L,keys:l,resolveDerivationIndex:An,scriptType:o,signAndBroadcastTransaction:On,signTransaction:et,signTransactionWithMultipleKeys:_t,transfer:Vr(t,i,h),transferFromMultipleAddresses:_n,validateAddress:cn(t)}}import{getZcashAddressType as Gr,validateZcashAddress as wt}from"@swapkit/utxo-signer";function Ie(e){return Se(e)!==null}var N=Yr.BitcoinCash;function Qe(e){return z(Me(e))}function ns(e){let t=U(N);function n(s){return s.sign(e.privateKey,[es.ALL]),s}function r(){let s=fn(e.publicKey,t);if(!s.hash)throw new W("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let a=hn({hash:s.hash,prefix:pn.MAINNET,type:ln.P2PKH});return Promise.resolve(a.replace(/^bitcoincash:/,""))}return{getAddress:r,signTransaction:n}}function mn(e={}){let t="phrase"in e?e.phrase:void 0,n="index"in e?e.index||0:0,r="derivationPath"in e?e.derivationPath:void 0,s=Qr({chain:N,derivationPath:r,index:n}),a=jr(s),d=t?xe({chain:N,derivationPath:a,phrase:t}):void 0,o=d?ns(d):("signer"in e)?e.signer:void 0;function p(){return Promise.resolve(o?.getAddress())}let c="scriptType"in e?e.scriptType:void 0,{getBalance:u,getFeeRates:i,broadcastTx:l,...h}=ce(t?{chain:N,index:n,phrase:t,...r?{derivationPath:r,scriptType:c}:{scriptType:c}}:{chain:N,scriptType:c});function m(b,S=!0){return u(z(Me(b)))}function f(b){if(!o)throw new W("toolbox_utxo_no_signer");return o.signTransaction(b)}async function y(b){let S=await f(b);return S.finalize(),await l(un.encode(S.extract()))}return{...h,broadcastTx:l,buildTx:ss,createTransaction:yn,getAddress:p,getAddressFromKeys:os,getBalance:m,getFeeRates:i,signAndBroadcastTransaction:y,signTransaction:f,stripPrefix:z,stripToCashAddress:Qe,transfer:rs({broadcastTx:l,getFeeRates:i,signer:o}),validateAddress:Ie}}async function yn({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s,sweep:a}){if(!Ie(t))throw new W("toolbox_utxo_invalid_address",{address:t});let d=Math.ceil(e.getBaseValue("number")+r*7500),o=await A(N).getUtxos({address:Qe(s),fetchTxHex:!0,targetValue:a?void 0:d}),p=n?R(n):null,c=[],u=G(t);if(c.push({address:u,value:a?0:e.getBaseValue("number")}),p)c.push({script:p,value:0});let{inputs:i,outputs:l}=E({chain:N,feeRate:r,inputs:o,outputs:c,sweep:a});if(!(i&&l))throw new W("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let h=new Tn({allowUnknownOutputs:!!p,version:1}),m=G(s),{inputs:f,tx:y}=ie({chain:N,compiledMemo:p,inputs:i,outputs:l.map((b)=>("address"in b)&&b.address?{...b,address:G(b.address)}:b),sender:m,tx:h});return{inputs:f,tx:y,utxos:i}}function rs({broadcastTx:e,getFeeRates:t,signer:n}){return async function({recipient:s,assetValue:a,feeOptionKey:d=Jr.Fast,sweep:o,...p}){let c=await n?.getAddress();if(!(n&&c))throw new W("toolbox_utxo_no_signer");if(!s)throw new W("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let u=p.feeRate||(await t())[d],{tx:i}=await yn({...p,assetValue:a,feeRate:u,recipient:s,sender:c,sweep:o}),l=await n.signTransaction(i);return l.finalize(),e(un.encode(l.extract()))}}async function ss({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s}){let a=Me(t);if(!Ie(a))throw new W("toolbox_utxo_invalid_address",{address:a});let d=Math.ceil(e.getBaseValue("number")+r*7500),o=await A(N).getUtxos({address:Qe(s),fetchTxHex:!0,targetValue:d}),p=Number(r.toFixed(0)),c=n?R(n):null,u=[];if(u.push({address:G(t),value:e.getBaseValue("number")}),c)u.push({script:c,value:0});let{inputs:i,outputs:l}=E({chain:N,feeRate:p,inputs:o,outputs:u});if(!(i&&l))throw new W("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let h=new Tn({allowUnknownOutputs:!!c,version:1}),{inputs:m,tx:f}=ie({chain:N,compiledMemo:c,inputs:i,outputs:l,sender:G(s),tx:h});return{inputs:m,tx:f,utxos:o}}function os(e){let t=ts.bitcoinCash,n=fn(e.publicKey,t);if(!n.hash)throw new W("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return hn({hash:n.hash,prefix:pn.MAINNET,type:ln.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as as,hex as is}from"@scure/base";import{HDKey as bn}from"@scure/bip32";import{mnemonicToSeedSync as wn}from"@scure/bip39";import{Chain as j,derivationPathToString as cs,FeeOption as ds,SwapKitError as de}from"@swapkit/helpers";import{Address as us,createZcashTransaction as ps,getZcashConsensusBranchId as ls,isTransparentZcashAddress as gn,OutScript as hs,PCZT as fs,utils as Pn,WIF as Ts,ZcashConsensusBranchId as ms,ZcashPSBT as ys,ZcashSigHash as Pt,ZcashVersionGroupId as gs}from"@swapkit/utxo-signer";import{match as xs,P as Ut}from"ts-pattern";var bs=as(Pn.sha256);function ws(e){return bs.encode(e)}function Ps({phrase:e,derivationPath:t}){let n=wn(e),s=bn.fromMasterSeed(n).derive(t);if(!s.privateKey||!s.publicKey)throw new de("toolbox_utxo_invalid_params");let{privateKey:a,publicKey:d}=s,o=Pn.hash160(d),p=new Uint8Array([28,184]),c=new Uint8Array(p.length+o.length);c.set(p,0),c.set(o,p.length);let u=ws(c);return{getAddress:()=>Promise.resolve(u),signTransaction:(i)=>{if(i instanceof ys){let l=i.toPCZT();return l.signAllInputs(a,d,Pt.ALL),l.finalizeAllInputs(),Promise.resolve(l.extract())}if(i instanceof fs)return i.signAllInputs(a,d,Pt.ALL),i.finalizeAllInputs(),Promise.resolve(i.extract());return i.signAllInputs(a,d,Pt.ALL),Promise.resolve(i)}}}function Us({inputs:e,outputs:t,tx:n,sender:r,compiledMemo:s}){let a=U(j.Zcash);for(let d of e){let o=us(a).decode(r),p=hs.encode(o);n.addInput({index:d.index,script:p,sequence:4294967295,txid:is.decode(d.hash),value:BigInt(d.value)})}for(let d of t){let o="address"in d&&d.address?d.address:r,p=d.script;if(p&&!s)continue;if(p&&s)n.addOutput({amount:0n,script:s});else n.addOutputAddress(o,BigInt(d.value),a)}return{inputs:e,tx:n}}async function vs(){try{let e=await A(j.Zcash).getBlockHeight();return ls(e+1)}catch{return ms.IRONWOOD}}async function xn(e){let{assetValue:t,recipient:n,memo:r,feeRate:s,sender:a,fetchTxHex:d,sweep:o}=e,p=U(j.Zcash);if(!gn(a,p))throw new de("toolbox_utxo_invalid_address",{address:a});if(!gn(n,p))throw new de("toolbox_utxo_invalid_address",{address:n,error:"Zcash transaction creation currently supports transparent addresses only"});let c=r?R(r):null,u=await A(j.Zcash).getUtxos({address:a,fetchTxHex:d!==!1}),i=[{address:n,value:o?0:Number(t.getBaseValue("string"))},...c?[{script:c,value:0}]:[]],{inputs:l,outputs:h}=E({chain:j.Zcash,changeAddress:a,feeRate:s,inputs:u,outputs:i,sweep:o});if(!(l&&h))throw new de("toolbox_utxo_insufficient_balance",{assetValue:t,sender:a});let m=ps({consensusBranchId:await vs(),expiryHeight:0,lockTime:0,version:4,versionGroupId:gs.SAPLING}),{tx:f,inputs:y}=Us({compiledMemo:c,inputs:l,outputs:h,sender:a,tx:m});return{inputs:y,outputs:h,tx:f}}function Un(e={}){let t="scriptType"in e?e.scriptType:void 0,n=xs(e).with({signer:Ut.not(Ut.nullish)},({signer:c})=>c).with({phrase:Ut.string},({phrase:c,derivationPath:u,index:i=0})=>{let{derivationPath:l}=$e({chain:j.Zcash,derivationPath:u,index:i,scriptType:t}),h=cs(l);return Ps({derivationPath:h,phrase:c})}).otherwise(()=>{return}),r=ce({chain:j.Zcash,scriptType:t,signer:n});async function s(c){if(!n)throw new de("toolbox_utxo_no_signer");return await n.signTransaction(c)}async function a(c){let u=await s(c);return r.broadcastTx(u.toHex())}async function d({recipient:c,assetValue:u,feeOptionKey:i=ds.Fast,sweep:l,...h}){let m=await n?.getAddress();if(!(n&&m))throw new de("toolbox_utxo_no_signer");let f=h.feeRate||(await r.getFeeRates())[i],{tx:y}=await xn({...h,assetValue:u,feeRate:f,recipient:c,sender:m,sweep:l}),S=(await n.signTransaction(y)).toHex();return r.broadcastTx(S)}function o({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let i=wn(c),h=bn.fromMasterSeed(i).derive(u);if(!h.privateKey||!h.publicKey)throw new de("toolbox_utxo_invalid_params");return{privateKey:h.privateKey,publicKey:h.publicKey}}function p({phrase:c,derivationPath:u="m/44'/133'/0'/0/0"}){let i=o({derivationPath:u,phrase:c}),l=U(j.Zcash);return Ts(l).encode(i.privateKey)}return{...r,createKeysForPath:o,createTransaction:xn,getPrivateKeyFromMnemonic:p,signAndBroadcastTransaction:a,signTransaction:s,transfer:d,validateAddress:wt}}import{hex as _s}from"@scure/base";import{HDKey as As}from"@scure/bip32";import{derivationPathToString as Os,NetworkDerivationPath as Ss,updateDerivationPath as Cs}from"@swapkit/helpers";function Xs({xpub:e,chain:t,count:n,startIndex:r=0,accountIndex:s,purpose:a,scriptType:d}){if(Z("count",n),n<1)throw RangeError("count must be at least 1");Z("startIndex",r),Le(t,d),ct({chain:t,purpose:a,scriptType:d});let o=U(t),p=As.fromExtendedKey(e,o.bip32),c=a===void 0?void 0:Cs(Ss[t],{purpose:a}),u=ee({accountIndex:s,chain:t,derivationPath:c}),i=pe(u),l=[];for(let h of[!1,!0]){let m=p.deriveChild(Number(h));for(let f=0;f<n;f++){let y=r+f,b=m.deriveChild(y);if(!b.publicKey)continue;let S=Ae({accountIndex:s,chain:t,change:h,derivationPath:c,index:y});l.push({accountIndex:i,address:De({chain:t,network:o,publicKey:b.publicKey,scriptType:d}),change:h,index:y,pubkey:_s.encode(b.publicKey),...a===void 0?{}:{path:Os(S)}})}}return l}function ga(e,t){switch(e){case we.BitcoinCash:return mn(t||{});case we.Zcash:return Un(t);case we.Bitcoin:case we.Dogecoin:case we.Litecoin:case we.Dash:return ce({chain:e,...t});default:throw new Bs("toolbox_utxo_not_supported",{chain:e})}}export{qt as InputSizes,ho as MIN_TX_FEE,Cr as OP_RETURN_OVERHEAD,pt as OutputSizes,Sr as SEGWIT_MARKER_FLAG_WEIGHT,lt as TX_OVERHEAD,se as UTXOScriptType,Dt as UtxoNetwork,E as accumulative,ie as addInputsAndOutputs,dn as addressFromKeysGetter,Z as assertDerivationIndex,ge as calculateTxSize,R as compileMemo,mn as createBCHToolbox,Hs as createCustomUtxoApi,Xn as createHDWalletHelpers,ce as createUTXOToolbox,Un as createZcashToolbox,Xs as deriveAddressesFromXpub,Vs as detectAddressNetwork,Se as getBchAddressType,ke as getDustThreshold,Be as getInputScriptType,re as getInputSize,bt as getMissingSpendingMetadata,U as getNetworkForChain,je as getOutputSize,Xr as getOutputSizeForAddress,Ye as getScriptTypeForAddress,pe as getUTXOAccountIndexFromPath,ee as getUTXOAccountPath,Ae as getUTXOAddressPath,cn as getUTXOAddressValidator,Y as getUtxoAddressType,A as getUtxoApi,Rs as getUtxoNetwork,ga as getUtxoToolbox,ft as getWitnessOverhead,Gr as getZcashAddressType,ht as isSegwitScriptType,$s as isValidAddress,Zt as nonSegwitChains,z as stripPrefix,Qe as stripToCashAddress,Me as toCashAddress,G as toLegacyAddress,Ne as tryDecodeAddress,Ie as validateBchAddress,tn as validateUtxoAddress,wt as validateZcashAddress};
|
|
@@ -15,10 +15,13 @@ export interface SolanaProvider {
|
|
|
15
15
|
signTransaction: <T extends Transaction | VersionedTransaction = Transaction>(transaction: T) => Promise<T>;
|
|
16
16
|
}
|
|
17
17
|
export type SolanaCreateTransactionParams = Omit<GenericCreateTransactionParams, "feeRate"> & {
|
|
18
|
+
/** Rejects SPL transfers whose SOL can't cover the fee and the recipient token account rent. Off by default. */
|
|
19
|
+
checkPayerBalance?: boolean;
|
|
18
20
|
isProgramDerivedAddress?: boolean;
|
|
19
21
|
/** Pre-fetched recent blockhash; when provided, skips the getLatestBlockhash round-trip. */
|
|
20
22
|
recentBlockhash?: string;
|
|
21
23
|
};
|
|
22
24
|
export type SolanaTransferParams = Omit<GenericTransferParams, "feeRate"> & {
|
|
25
|
+
checkPayerBalance?: boolean;
|
|
23
26
|
isProgramDerivedAddress?: boolean;
|
|
24
27
|
};
|
|
@@ -23,7 +23,7 @@ export declare function getSolanaToolbox(toolboxParams?: {
|
|
|
23
23
|
}): {
|
|
24
24
|
broadcastTransaction: (transaction: Transaction | VersionedTransaction) => Promise<string>;
|
|
25
25
|
createKeysForPath: typeof createKeysForPath;
|
|
26
|
-
createTransaction: ({ recipient, assetValue, memo, isProgramDerivedAddress, sender, recentBlockhash, sweep, }: SolanaCreateTransactionParams) => Promise<Transaction>;
|
|
26
|
+
createTransaction: ({ checkPayerBalance, recipient, assetValue, memo, isProgramDerivedAddress, sender, recentBlockhash, sweep, }: SolanaCreateTransactionParams) => Promise<Transaction>;
|
|
27
27
|
createTransactionFromInstructions: typeof createTransactionFromInstructions;
|
|
28
28
|
estimateTransactionFee: ({ recipient, assetValue, memo, isProgramDerivedAddress, sender, }: Omit<GenericCreateTransactionParams, "feeRate"> & {
|
|
29
29
|
isProgramDerivedAddress?: boolean;
|
|
@@ -36,7 +36,7 @@ export declare function getSolanaToolbox(toolboxParams?: {
|
|
|
36
36
|
getPubkeyFromAddress: (address: string) => PublicKey;
|
|
37
37
|
signAndBroadcastTransaction: (transaction: Transaction | VersionedTransaction) => Promise<string>;
|
|
38
38
|
signTransaction: (transaction: Transaction | VersionedTransaction) => Promise<Transaction | VersionedTransaction>;
|
|
39
|
-
transfer: ({ recipient, assetValue, memo, isProgramDerivedAddress, sweep }: SolanaTransferParams) => Promise<string>;
|
|
39
|
+
transfer: ({ recipient, assetValue, checkPayerBalance, memo, isProgramDerivedAddress, sweep, }: SolanaTransferParams) => Promise<string>;
|
|
40
40
|
validateAddress: typeof validateSolanaAddress;
|
|
41
41
|
};
|
|
42
42
|
declare function getConnection(): Promise<Connection>;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { TronTransaction } from "../types";
|
|
2
|
+
type Transfer = {
|
|
3
|
+
sender: string;
|
|
4
|
+
data?: Uint8Array;
|
|
5
|
+
} & ({
|
|
6
|
+
amount: number | bigint;
|
|
7
|
+
recipient: string;
|
|
8
|
+
} | {
|
|
9
|
+
contractAddress: string;
|
|
10
|
+
parameter: string;
|
|
11
|
+
feeLimit: number;
|
|
12
|
+
});
|
|
13
|
+
export declare function makeSerializedTransfer(transfer: Transfer): {
|
|
14
|
+
raw_data: {
|
|
15
|
+
ref_block_bytes: string;
|
|
16
|
+
ref_block_hash: string;
|
|
17
|
+
timestamp: number;
|
|
18
|
+
fee_limit?: number | undefined;
|
|
19
|
+
expiration: number;
|
|
20
|
+
data?: string | undefined;
|
|
21
|
+
contract: {
|
|
22
|
+
parameter: {
|
|
23
|
+
type_url: string;
|
|
24
|
+
value: {
|
|
25
|
+
amount: number | bigint;
|
|
26
|
+
owner_address: string;
|
|
27
|
+
to_address: string;
|
|
28
|
+
contract_address?: undefined;
|
|
29
|
+
data?: undefined;
|
|
30
|
+
} | {
|
|
31
|
+
contract_address: string;
|
|
32
|
+
data: string;
|
|
33
|
+
owner_address: string;
|
|
34
|
+
amount?: undefined;
|
|
35
|
+
to_address?: undefined;
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
type: string;
|
|
39
|
+
}[];
|
|
40
|
+
};
|
|
41
|
+
raw_data_hex: string;
|
|
42
|
+
txID: string;
|
|
43
|
+
visible: true;
|
|
44
|
+
};
|
|
45
|
+
export declare function billedTransferBandwidth(transaction: TronTransaction): number;
|
|
46
|
+
export {};
|
|
@@ -17,24 +17,37 @@ export declare function buildContractTransaction({ ownerAddress, contractAddress
|
|
|
17
17
|
callValue?: number;
|
|
18
18
|
}): Promise<TronTransaction>;
|
|
19
19
|
export declare function broadcastTronTransaction(signedTx: TronSignedTransaction): Promise<string>;
|
|
20
|
-
|
|
20
|
+
/**
|
|
21
|
+
* Returns validated fees, using each parameter's protocol default on invalid data or lookup failure.
|
|
22
|
+
* Omitted, non-finite or non-positive timeoutMs uses the 30 s transport default.
|
|
23
|
+
*/
|
|
24
|
+
export declare function getTronChainParameters({ timeoutMs }?: {
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
}): Promise<{
|
|
21
27
|
bandwidthFee: number;
|
|
28
|
+
createAccountBandwidthFee: number;
|
|
22
29
|
createAccountFee: number;
|
|
23
30
|
energyFee: number;
|
|
24
31
|
memoFee: number;
|
|
25
32
|
}>;
|
|
33
|
+
/** Returns remaining free and staked bandwidth plus energy; failed lookups credit nothing. */
|
|
26
34
|
export declare function getTronAccountResources(address: string): Promise<{
|
|
27
35
|
bandwidth: {
|
|
28
36
|
free: number;
|
|
29
|
-
|
|
30
|
-
used: number;
|
|
31
|
-
};
|
|
32
|
-
energy: {
|
|
33
|
-
total: number;
|
|
34
|
-
used: number;
|
|
37
|
+
staked: number;
|
|
35
38
|
};
|
|
39
|
+
energy: number;
|
|
36
40
|
}>;
|
|
37
|
-
|
|
41
|
+
/**
|
|
42
|
+
* Returns false for invalid addresses, lookup failures or responses that do not match the requested account.
|
|
43
|
+
* Omitted, non-finite or non-positive timeoutMs uses the 30 s transport default.
|
|
44
|
+
*/
|
|
45
|
+
export declare function checkTronAccountExists(address: string, options?: {
|
|
46
|
+
timeoutMs?: number;
|
|
47
|
+
}): Promise<boolean>;
|
|
48
|
+
export declare function getTronAccountStatus(address: string, { timeoutMs }?: {
|
|
49
|
+
timeoutMs?: number;
|
|
50
|
+
}): Promise<"unknown" | "missing" | "exists">;
|
|
38
51
|
export declare function estimateContractEnergy(params: {
|
|
39
52
|
contractAddress: string;
|
|
40
53
|
functionSelector: string;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { checkTronAccountExists, getTronChainParameters } from "./helpers/trongrid";
|
|
2
|
+
export { estimateTronSweepDeduction, getTronPrivateKeyFromMnemonic, getTronToolbox, TRON_SWEEP_ESTIMATE_TIMEOUT_MS, validateTronAddress, withTronTransactionData, withTronTransactionValue, } from "./toolbox";
|
|
2
3
|
export type { TronApprovedParams, TronApproveParams, TronCreateTransactionParams, TronIsApprovedParams, TronSignedTransaction, TronSigner, TronToolboxOptions, TronTransaction, TronTransactionMetadata, TronTransactionWithMetadata, TronTransferParams, } from "./types";
|
|
3
4
|
import type { getTronToolbox } from "./toolbox";
|
|
4
5
|
export type TronWallet = ReturnType<typeof getTronToolbox>;
|
|
@@ -3,6 +3,27 @@ import { broadcastTronTransaction } from "./helpers/trongrid";
|
|
|
3
3
|
import { isValidTronAddress } from "./helpers/utils";
|
|
4
4
|
import type { TronApprovedParams, TronApproveParams, TronCreateTransactionParams, TronIsApprovedParams, TronToolboxOptions, TronTransaction, TronTransactionWithMetadata, TronTransferParams } from "./types";
|
|
5
5
|
export declare const validateTronAddress: typeof isValidTronAddress;
|
|
6
|
+
/**
|
|
7
|
+
* Default lookup budget for estimateTronSweepDeduction. Direct TronGrid helpers default to 30 s.
|
|
8
|
+
*/
|
|
9
|
+
export declare const TRON_SWEEP_ESTIMATE_TIMEOUT_MS = 2500;
|
|
10
|
+
/**
|
|
11
|
+
* Estimates a sweep reserve in native TRX without crediting the sender's bandwidth or energy.
|
|
12
|
+
* Native TRX uses bandwidth or account-creation fees; other assets use the TRC-20 fee-limit model.
|
|
13
|
+
*
|
|
14
|
+
* Lookups default to a 2.5 s budget. RPC failures or timeouts use protocol defaults. Unknown recipients
|
|
15
|
+
* reserve the more expensive native billing path, or extra TRC-20 activation energy. Native quotes bound
|
|
16
|
+
* build fees only while chain parameters and recipient activation state remain consistent. Fallback
|
|
17
|
+
* prices and assumed TRC-20 energy can under-reserve. Sweeps check estimated fees again at build time.
|
|
18
|
+
*
|
|
19
|
+
* Non-string memos are coerced to strings; failed coercion rejects the promise.
|
|
20
|
+
*/
|
|
21
|
+
export declare function estimateTronSweepDeduction({ assetValue, recipient, memo, timeoutMs, }: {
|
|
22
|
+
assetValue: AssetValue;
|
|
23
|
+
recipient: string;
|
|
24
|
+
memo?: string;
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
}): Promise<AssetValue>;
|
|
6
27
|
export declare function withTronTransactionValue<TTransaction extends TronTransaction>(transaction: TTransaction, value: string | number | bigint): TTransaction & Required<Pick<TronTransactionWithMetadata, "value">>;
|
|
7
28
|
export declare function withTronTransactionData<TTransaction extends TronTransaction>(transaction: TTransaction, data?: string): TTransaction & Pick<TronTransactionWithMetadata, "data">;
|
|
8
29
|
export declare function getTronPrivateKeyFromMnemonic({ phrase, derivationPath: customPath, index, }: {
|
|
@@ -8,7 +8,7 @@ type AccumulativeParams<T extends UTXOSizeInput> = {
|
|
|
8
8
|
changeAddress?: string;
|
|
9
9
|
sweep?: boolean;
|
|
10
10
|
};
|
|
11
|
-
export declare function getDustThreshold(chain: UTXOChain):
|
|
11
|
+
export declare function getDustThreshold(chain: UTXOChain): 100000 | 550 | 5500 | 546;
|
|
12
12
|
export declare function accumulative<T extends UTXOSizeInput>({ inputs, outputs, feeRate, chain, changeAddress, sweep, }: AccumulativeParams<T>): {
|
|
13
13
|
fee: number;
|
|
14
14
|
inputs: T[];
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { Chain, type ChainSigner, type DerivationPathArray } from "@swapkit/helpers";
|
|
2
2
|
import type { UTXOScriptType } from "../helpers";
|
|
3
|
-
export type UTXOSigner = ChainSigner<any, any
|
|
3
|
+
export type UTXOSigner = ChainSigner<any, any> & {
|
|
4
|
+
/** Compressed (33-byte) public key of the signing account; lets nested segwit and taproot inputs carry their spending metadata. */
|
|
5
|
+
publicKey?: Uint8Array;
|
|
6
|
+
};
|
|
4
7
|
export type ZcashSigner = ChainSigner<any, any>;
|
|
5
8
|
export type UTXOToolboxSignerParams<S = UTXOSigner> = {
|
|
6
9
|
signer?: S;
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"dependencies": { "@swapkit/helpers": "6.
|
|
2
|
+
"dependencies": { "@swapkit/helpers": "6.1.0", "@swapkit/utxo-signer": "3.1.0" },
|
|
3
3
|
"description": "SwapKit - Toolboxes",
|
|
4
4
|
"devDependencies": {
|
|
5
5
|
"@aptos-labs/ts-sdk": "7.0.1",
|
|
@@ -131,5 +131,5 @@
|
|
|
131
131
|
"type-check:go": "tsgo"
|
|
132
132
|
},
|
|
133
133
|
"type": "module",
|
|
134
|
-
"version": "6.
|
|
134
|
+
"version": "6.1.0"
|
|
135
135
|
}
|