@swapkit/toolboxes 5.3.0 → 5.4.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 +14 -0
- package/dist/{chunk-k50sjysj.js → chunk-4428244x.js} +1 -1
- package/dist/{chunk-s1528ghz.js → chunk-as9fracn.js} +1 -1
- package/dist/chunk-dssawneq.js +1 -0
- package/dist/chunk-rn33j2bm.js +2 -0
- package/dist/src/aleo/index.js +1 -1
- package/dist/src/aptos/index.js +1 -1
- package/dist/src/cardano/index.js +1 -1
- package/dist/src/cosmos/index.js +1 -1
- package/dist/src/evm/index.js +1 -1
- package/dist/src/hypercore/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/dist/src/near/index.js +1 -1
- package/dist/src/radix/index.js +1 -1
- package/dist/src/ripple/index.js +1 -1
- package/dist/src/solana/index.js +1 -1
- package/dist/src/starknet/index.js +1 -1
- package/dist/src/stellar/index.js +1 -1
- package/dist/src/substrate/index.js +1 -1
- package/dist/src/sui/index.js +1 -1
- package/dist/src/ton/index.js +1 -1
- package/dist/src/tron/index.js +1 -1
- package/dist/src/utxo/index.js +1 -1
- package/dist/types/evm/toolbox/evm.d.ts +172 -0
- package/dist/types/evm/types.d.ts +2 -1
- package/dist/types/utxo/__tests__/fixtures/utxo.d.ts +178 -0
- package/dist/types/utxo/helpers/bchaddrjs.d.ts +17 -1
- package/dist/types/utxo/helpers/txSize.d.ts +7 -5
- package/dist/types/utxo/index.d.ts +1 -1
- package/dist/types/utxo/toolbox/bitcoinCash.d.ts +1 -0
- package/dist/types/utxo/toolbox/index.d.ts +1 -1
- package/dist/types/utxo/toolbox/utxo.d.ts +6 -0
- package/dist/types/utxo/toolbox/validators.d.ts +2 -1
- package/dist/types/utxo/toolbox/zcash.d.ts +1 -0
- package/package.json +2 -2
- package/dist/chunk-1ma8fv42.js +0 -2
- package/dist/chunk-z8n8qjs5.js +0 -1
package/dist/src/tron/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"../../chunk-k50sjysj.js";import{bytesToHex as we}from"@noble/hashes/utils.js";import{HDKey as pe}from"@scure/bip32";import{mnemonicToSeedSync as ye}from"@scure/bip39";import{AssetValue as A,BaseDecimal as H,Chain as b,derivationPathToString as Dt,getRPCUrl as he,NetworkDerivationPath as Ut,SwapKitError as m,updateDerivationPath as kt,warnOnce as It}from"@swapkit/helpers";import{match as be,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 N}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 N({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 N({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 N({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 N({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 N({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 N({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 h,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 I,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 I(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=I(n.slice(1,33)),c=I(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=I(ft(M(t)));if(e!==n)throw new gt("toolbox_tron_invalid_transaction_integrity",{expected:n,txID:e})}function re(e){return`000000000000000000000000${I(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 I(new TextEncoder().encode(e))}var ht="https://api.trongrid.io",ce=1000,de=1e6,ue=420,le=1e6,fe=30000;function bt(){try{return se(ie.Tron)}catch{return ht}}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 h("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 h("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 h("toolbox_tron_trongrid_api_error",{address:e,message:"Invalid address"});try{let t=await vt(`/v1/accounts/${e}`,ht);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 h)throw t;throw new h("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 h({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 h({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 h({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 h({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 yt(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 h("toolbox_tron_token_transfer_failed");return n}catch(t){throw new h("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 h("toolbox_tron_trongrid_api_error",{message:t.result.message||"estimateenergy failed"});if(n!==void 0){let o=yt(n);if(o!==void 0)return o;throw new h("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=yt(t);if(n!==void 0)return n;throw new h("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 h("toolbox_tron_trongrid_api_error",{message:`Unable to estimate contract energy: ${t instanceof Error?t.message:t}`})}}async function Nt({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 xe=x,Rt=268,St=65000,J=25000,Bt=345,Q="TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",Ae="115792089237316195423570985008687907853269984665640564039457584007913129639935";function Kt({phrase:e,derivationPath:t}){let n=pe.fromMasterSeed(ye(e)).derive(t);if(!n.privateKey)throw new m("toolbox_tron_no_signer");return we(n.privateKey)}function ve(e,t){return{...e,value:String(t)}}function Ee(e,t){if(!t)return e;return{...e,data:t.startsWith("0x")?t:`0x${t}`}}function Fe({phrase:e,derivationPath:t,index:n}){let o=t||Dt(kt(Ut[b.Tron],{index:n||0}));return Kt({derivationPath:o,phrase:e})}function Pe({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=be(e).with({phrase:z.string},({phrase:r})=>Pe({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),y=await Ft({contractAddress:r,feeLimit:T,functionSelector:a,ownerAddress:s,parameter:d});return Ct({expiration:f,feeLimit:T,memo:u,transaction:y})}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 It({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(_),y=await C(T);if(!y)throw new m("toolbox_tron_token_transfer_failed",{message:"broadcast failed"});return y}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.TRON,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,y]=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=y+(_?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.TRON,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,y=a?s.memoFee:0;return A.from({chain:b.Tron,fromBaseDecimal:H.TRON,value:T+Rt*s.bandwidthFee+y})}let g=await p(St+(u?0:J),s.energyFee),_=a?s.memoFee:0;return A.from({chain:b.Tron,fromBaseDecimal:H.TRON,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 It({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 y=await et({amountInBaseUnits:T,assetValue:r,memo:a,recipient:d,senderAddress:s}),E=BigInt(g?.balance??0),F=y.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}),y=g??await U(r);return w({contractAddress:_,expiration:u,extraEnergy:y?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 Nt({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():Ae;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(_),y=await C(T);if(!y)throw new m("toolbox_tron_approve_failed");return y}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:()=>he(b.Tron),isApproved:Wt,signAndBroadcastTransaction:Gt,signTransaction:rt,transfer:V,validateAddress:x}}export{Fe as getTronPrivateKeyFromMnemonic,Ne as getTronToolbox,xe as validateTronAddress,Ee as withTronTransactionData,ve as withTronTransactionValue};
|
|
1
|
+
import"../../chunk-4428244x.js";import{bytesToHex as we}from"@noble/hashes/utils.js";import{HDKey as pe}from"@scure/bip32";import{mnemonicToSeedSync as ye}from"@scure/bip39";import{AssetValue as A,BaseDecimal as H,Chain as b,derivationPathToString as Dt,getRPCUrl as he,NetworkDerivationPath as Ut,SwapKitError as m,updateDerivationPath as kt,warnOnce as It}from"@swapkit/helpers";import{match as be,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 N}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 N({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 N({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 N({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 N({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 N({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 N({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 h,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 I,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 I(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=I(n.slice(1,33)),c=I(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=I(ft(M(t)));if(e!==n)throw new gt("toolbox_tron_invalid_transaction_integrity",{expected:n,txID:e})}function re(e){return`000000000000000000000000${I(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 I(new TextEncoder().encode(e))}var ht="https://api.trongrid.io",ce=1000,de=1e6,ue=420,le=1e6,fe=30000;function bt(){try{return se(ie.Tron)}catch{return ht}}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 h("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 h("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 h("toolbox_tron_trongrid_api_error",{address:e,message:"Invalid address"});try{let t=await vt(`/v1/accounts/${e}`,ht);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 h)throw t;throw new h("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 h({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 h({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 h({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 h({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 yt(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 h("toolbox_tron_token_transfer_failed");return n}catch(t){throw new h("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 h("toolbox_tron_trongrid_api_error",{message:t.result.message||"estimateenergy failed"});if(n!==void 0){let o=yt(n);if(o!==void 0)return o;throw new h("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=yt(t);if(n!==void 0)return n;throw new h("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 h("toolbox_tron_trongrid_api_error",{message:`Unable to estimate contract energy: ${t instanceof Error?t.message:t}`})}}async function Nt({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 xe=x,Rt=268,St=65000,J=25000,Bt=345,Q="TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",Ae="115792089237316195423570985008687907853269984665640564039457584007913129639935";function Kt({phrase:e,derivationPath:t}){let n=pe.fromMasterSeed(ye(e)).derive(t);if(!n.privateKey)throw new m("toolbox_tron_no_signer");return we(n.privateKey)}function ve(e,t){return{...e,value:String(t)}}function Ee(e,t){if(!t)return e;return{...e,data:t.startsWith("0x")?t:`0x${t}`}}function Fe({phrase:e,derivationPath:t,index:n}){let o=t||Dt(kt(Ut[b.Tron],{index:n||0}));return Kt({derivationPath:o,phrase:e})}function Pe({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=be(e).with({phrase:z.string},({phrase:r})=>Pe({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),y=await Ft({contractAddress:r,feeLimit:T,functionSelector:a,ownerAddress:s,parameter:d});return Ct({expiration:f,feeLimit:T,memo:u,transaction:y})}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 It({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(_),y=await C(T);if(!y)throw new m("toolbox_tron_token_transfer_failed",{message:"broadcast failed"});return y}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.TRON,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,y]=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=y+(_?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.TRON,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,y=a?s.memoFee:0;return A.from({chain:b.Tron,fromBaseDecimal:H.TRON,value:T+Rt*s.bandwidthFee+y})}let g=await p(St+(u?0:J),s.energyFee),_=a?s.memoFee:0;return A.from({chain:b.Tron,fromBaseDecimal:H.TRON,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 It({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 y=await et({amountInBaseUnits:T,assetValue:r,memo:a,recipient:d,senderAddress:s}),E=BigInt(g?.balance??0),F=y.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}),y=g??await U(r);return w({contractAddress:_,expiration:u,extraEnergy:y?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 Nt({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():Ae;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(_),y=await C(T);if(!y)throw new m("toolbox_tron_approve_failed");return y}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:()=>he(b.Tron),isApproved:Wt,signAndBroadcastTransaction:Gt,signTransaction:rt,transfer:V,validateAddress:x}}export{Fe as getTronPrivateKeyFromMnemonic,Ne as getTronToolbox,xe as validateTronAddress,Ee as withTronTransactionData,ve as withTronTransactionValue};
|
package/dist/src/utxo/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ea as st,fa as xt}from"../../chunk-s1528ghz.js";import"../../chunk-k50sjysj.js";import{NetworkDerivationPath as $t}from"@swapkit/helpers";function R(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`${e} must be a non-negative integer, got: ${t}`)}function G({accountIndex:e,chain:t,derivationPath:n}){if(e!==void 0)R("accountIndex",e);let[r,s,o]=n??$t[t];return[r,s,e??o]}function xe({accountIndex:e,change:t=!1,chain:n,derivationPath:r,index:s}){return R("index",s),[...G({accountIndex:e,chain:n,derivationPath:r}),Number(t),s]}function ae(e){return e[2]??0}function Vt({deriveAddress:e,getBalance:t,getUtxos:n}){async function r(a){let{accountIndex:c,count:i,startIndex:p=0,change:u=!1}=a;if(R("count",i),i<1)throw RangeError("count must be at least 1");R("startIndex",p);let l=[];for(let h=0;h<i;h++){let m=await e({accountIndex:c,change:u,index:p+h});if(m)l.push(m)}return l}async function s(a){let{gapLimit:c=20,change:i=!1}=a??{},p=[],u=0,l=0;while(u<c){let h=await e({change:i,index:l});if(!h)break;if((await t(h.address)).some((g)=>g.getValue("number")>0))p.push(h),u=0;else u++;l++}return p}async function o(a=20){let[c,i]=await Promise.all([s({change:!1,gapLimit:a}),s({change:!0,gapLimit:a})]),p=[...c,...i],u=await Promise.all(p.map(async(h)=>{let T=(await t(h.address)).reduce((g,y)=>g+y.getValue("number"),0);return{...h,balance:T}})),l=u.reduce((h,m)=>h+m.balance,0);return{addresses:u,total:l}}async function d(a=20){let[c,i]=await Promise.all([s({change:!1,gapLimit:a}),s({change:!0,gapLimit:a})]),p=[...c,...i];return(await Promise.all(p.map(async(l)=>(await n(l.address)).map((m)=>({...m,address:l.address,derivationIndex:l.index,isChange:l.change}))))).flat()}return{deriveAddresses:r,getAggregatedBalance:o,getAggregatedUtxos:d,scanForAddresses:s}}import{Chain as U,getRPCUrl as qt,RequestClient as ke,SKConfig as Gt,SwapKitError as K,warnOnce as jt}from"@swapkit/helpers";import{NETWORKS as ie}from"@swapkit/utxo-signer";async function Jt({chain:e,txHash:t}){let n=`${ce(e)}/push/transaction`,r=JSON.stringify({data:t});try{let s=await ke.post(n,{body:r,headers:{"Content-Type":"application/json"}});if(s.context.code!==200)throw new K("toolbox_utxo_broadcast_failed",{error:s.context.error||"Transaction broadcast failed"});return s.data?.transaction_hash||t}catch(s){let o=await qt(e);if(o){let d=JSON.stringify({id:st(),jsonrpc:"2.0",method:"sendrawtransaction",params:[t]}),a=await ke.post(o,{body:d,headers:{"Content-Type":"application/json"}});if(a.error)throw new K("toolbox_utxo_broadcast_failed",{error:a.error?.message});if(a.result.includes('"code":-26'))throw new K("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return a.result}throw s}}function ce(e){return`https://api.blockchair.com/${Qt(e)}`}function nt(e){switch(e){case U.Bitcoin:return 5;case U.Dogecoin:return 1e4;case U.Litecoin:return 1;case U.Zcash:return 1;default:return 2}}function Qt(e){switch(e){case U.BitcoinCash:return"bitcoin-cash";case U.Litecoin:return"litecoin";case U.Dash:return"dash";case U.Dogecoin:return"dogecoin";case U.Zcash:return"zcash";case U.Polkadot:return"polkadot";default:return"bitcoin"}}async function Yt(e){try{let{feePerKb:t}=await ke.get(`https://app.bitgo.com/api/v2/${e.toLowerCase()}/tx/fee`),n=t/1000;return Math.max(n,nt(e))}catch{return nt(e)}}async function Te(e,t){let n=await ke.get(`${e}${t?`${e.includes("?")?"&":"?"}key=${t}`:""}`);if(!n||n.context.code!==200)throw new K("toolbox_utxo_api_error",{error:`Failed to query ${e}`});return n.data}async function en({chain:e,apiKey:t}){let n=await Te(`${ce(e)}/stats`,t);if(typeof n.best_block_height!=="number")throw new K("toolbox_utxo_api_error",{error:"Missing best_block_height in stats response"});return n.best_block_height}async function ot({address:e,chain:t,apiKey:n}){if(!e)throw new K("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await Te(`${ce(t)}/dashboards/address/${e}?transaction_details=true`,n))[e]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function tn({address:e,chain:t,apiKey:n}){return(await ot({address:e,apiKey:n,chain:t}))?.address.balance||0}async function at({chain:e,apiKey:t,txHash:n}){if(!n)throw new K("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await Te(`${ce(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 nn=4294967294;async function rn({chain:e,apiKey:t,txHash:n}){if(!n)throw new K("toolbox_utxo_invalid_params",{error:"TxHash is required"});let s=(await Te(`${ce(e)}/dashboards/transaction/${n}`,t))?.[n];if(!s)throw new K("toolbox_utxo_tx_not_found",{txHash:n});let{transaction:o,inputs:d,outputs:a}=s,c=d.map((p)=>p.spending_sequence),i=o.is_rbf===!0||c.some((p)=>p<nn);return{blockId:o.block_id,confirmed:o.block_id!==-1,fee:o.fee,inputs:d,isRBF:i,outputs:a,sequences:c,size:o.size,txid:o.hash,weight:o.weight}}async function sn({chain:e,address:t,apiKey:n,offset:r=0,limit:s=30}){return(await Te(`${ce(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:c,script_hex:i,block_id:p,transaction_hash:u,index:l,value:h,spending_signature_hex:m})=>({hash:u,index:l,is_confirmed:p!==-1,is_spent:c,script_hex:i,txHex:m,value:h}))}function on(e){return e.reduce((t,n)=>t+n.value,0)}function rt(e,t){let n=[...e].sort((r,s)=>s.value-r.value);if(t){let r=[],s=0;for(let o of n)if(r.push(o),s+=o.value,s>=t)break;return r}return n}async function it({chain:e,address:t,apiKey:n,targetValue:r,accumulativeValue:s=0,offset:o=0,limit:d=30}){if(!t)throw new K("toolbox_utxo_invalid_params",{error:"Address is required"});try{let a=await sn({address:t,apiKey:n,chain:e,limit:d,offset:o,targetValue:r}),i=a.length<d,p=a.filter(({is_spent:g})=>!g),u=on(p),l=s+u,h=r&&l>=r;if(i||h)return rt(p,r);let m=await it({accumulativeValue:l,address:t,apiKey:n,chain:e,limit:d,offset:o+d,targetValue:r}),T=[...p,...m];return rt(T,r)}catch(a){let c=a instanceof Error?a.message:String(a);return console.error(`Failed to fetch unspent UTXOs: ${c}`),[]}}async function an({address:e,chain:t,apiKey:n,fetchTxHex:r=!0,targetValue:s}){let o=await it({address:e,apiKey:n,chain:t,targetValue:s}),d=r?await Promise.all(o.map(({hash:a})=>at({apiKey:n,chain:t,txHash:a}))):[];return o.map(({hash:a,index:c,script_hex:i,value:p},u)=>({address:e,hash:a,index:c,txHex:r?d[u]:void 0,value:p,witnessUtxo:{script:Buffer.from(i,"hex"),value:p}}))}function _(e){let t=Gt.get("apiKeys").blockchair||"";return jt({condition:!t,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(n)=>Jt({chain:e,txHash:n}),getAddressData:(n)=>ot({address:n,apiKey:t,chain:e}),getBalance:(n)=>tn({address:n,apiKey:t,chain:e}),getBlockHeight:()=>en({apiKey:t,chain:e}),getRawTx:(n)=>at({apiKey:t,chain:e,txHash:n}),getSuggestedTxFee:()=>Yt(e),getTransactionDetails:(n)=>rn({apiKey:t,chain:e,txHash:n}),getUtxos:(n)=>an({...n,apiKey:t,chain:e})}}function Br(e){return e}function Sr(){return function(t){switch(t){case U.Bitcoin:return ie.bitcoin;case U.BitcoinCash:return ie.bitcoinCash;case U.Dash:return ie.dash;case U.Litecoin:return ie.litecoin;case U.Dogecoin:return ie.dogecoin;case U.Zcash:return ie.zcash;default:throw new K("toolbox_utxo_not_supported",{chain:t})}}}import{sha256 as fn}from"@noble/hashes/sha2.js";import{createBase58check as mn}from"@scure/base";import{SwapKitError as ut}from"@swapkit/helpers";import{CashAddrType as Xe,decodeCashAddr as cn,encodeCashAddr as un}from"@swapkit/utxo-signer";var dn={P2PKH:Xe.P2PKH,P2SH:Xe.P2SH},pn={[Xe.P2PKH]:"P2PKH",[Xe.P2SH]:"P2SH"};function ln(e,t,n){return un({hash:n,prefix:e,type:dn[t]})}function hn(e){let t=cn(e),n=pn[t.type];if(!n)throw Error(`Unknown CashAddr type: ${t.type}`);return{hash:t.hash,prefix:t.prefix,type:n}}var Ee={decode:hn,encode:ln};var dt=mn(fn);var pt;((n)=>{n.Mainnet="mainnet";n.Testnet="testnet"})(pt||={});var j={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}};function lt(e){try{return Fe(e),!0}catch{return!1}}function ht(e){return Fe(e)?.network}function Z(e){let t=Fe(e);if(t?.format==="legacy")return e;return Tn(t)}function Ke(e){let t=Fe(e);return yn(t)}function Fe(e){try{let t=gn(e);if(t)return t}catch{}try{let t=xn(e);if(t)return t}catch{}throw new ut("toolbox_utxo_invalid_address",{address:e})}function gn(e){try{let t=dt.decode(e);if(t.length!==21)throw new ut("toolbox_utxo_invalid_address",{address:e});let n=t[0],r=Array.prototype.slice.call(t,1);switch(n){case j.legacy.mainnet.p2pkh:return{format:"legacy",hash:r,network:"mainnet",type:"p2pkh"};case j.legacy.mainnet.p2sh:return{format:"legacy",hash:r,network:"mainnet",type:"p2sh"};case j.legacy.testnet.p2pkh:return{format:"legacy",hash:r,network:"testnet",type:"p2pkh"};case j.legacy.testnet.p2sh:return{format:"legacy",hash:r,network:"testnet",type:"p2sh"};case j.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2pkh"};case j.bitpay.mainnet.p2sh:return{format:"bitpay",hash:r,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function xn(e){if(e.indexOf(":")!==-1)try{return ct(e)}catch{}else{let t=["bitcoincash","bchtest","bchreg"];for(let n of t)try{return ct(`${n}:${e}`)}catch{}}return}function ct(e){try{let{hash:t,prefix:n,type:r}=Ee.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 Tn(e){let t=j.legacy[e.network][e.type],n=Buffer.alloc(1+e.hash.length);return n[0]=t,n.set(e.hash,1),dt.encode(n)}function yn(e){let t=e.network==="mainnet"?"bitcoincash":"bchtest",n=e.type==="p2pkh"?"P2PKH":"P2SH",r=new Uint8Array(e.hash);return Ee.encode(t,n,r)}import{Chain as Q,SwapKitError as Ve}from"@swapkit/helpers";import{SwapKitError as bn}from"@swapkit/helpers";import{Script as wn}from"@swapkit/utxo-signer";var Nr=1000,Le=10,ze=2,vn=10,Pn=41,_n=107;function X(e){let t=new Uint8Array(Buffer.from(e,"utf8"));return wn.encode(["RETURN",t])}var $e;((n)=>{n.P2PKH="P2PKH";n.P2WPKH="P2WPKH"})($e||={});var Ze={["P2PKH"]:148,["P2WPKH"]:68},De={["P2PKH"]:34,["P2WPKH"]:31},ye=(e)=>{if(e.startsWith("bc1")||e.startsWith("tb1")||e.startsWith("ltc1")||e.startsWith("tltc1"))return"P2WPKH";if(e.startsWith("1")||e.startsWith("m")||e.startsWith("n")||e.startsWith("bitcoincash:q")||e.startsWith("bitcoincash:p")||e.startsWith("q")||e.startsWith("p")||e.startsWith("L")||e.startsWith("M")||e.startsWith("3")||e.startsWith("D")||e.startsWith("A")||e.startsWith("9")||e.startsWith("X")||e.startsWith("7")||e.startsWith("y")||e.startsWith("t1")||e.startsWith("t3")||e.startsWith("tm"))return"P2PKH";throw new bn("toolbox_utxo_invalid_address",{address:e})},ue=({inputs:e,outputs:t,feeRate:n})=>{let r=e[0]&&"address"in e[0]&&e[0].address?ye(e[0].address):"P2PKH",o=(n?e.filter((i)=>i.value>=Ze["type"in i&&i.type?i.type:"P2PKH"]*Math.ceil(n)):e).reduce((i,p)=>i+J(p),0),d=t?.reduce((i,p)=>i+He(p),0)||De[r],a=Le+o+d;return r==="P2WPKH"?Math.ceil(a+ze/4):a},J=(e)=>{if("type"in e&&e.type)return Ze[e.type];if("address"in e&&e.address)return Ze[ye(e.address)];return Pn+_n},He=(e,t)=>{if(e?.script)return vn+e.script.length+(e.script.length>=74?2:1);if(t)return De[t];if("address"in e&&e.address)return De[ye(e.address)];return De.P2PKH};function be(e){switch(e){case Q.Bitcoin:case Q.BitcoinCash:return 550;case Q.Dash:case Q.Litecoin:return 5500;case Q.Dogecoin:return 1e5;case Q.Zcash:return 546;default:throw new Ve("toolbox_utxo_not_supported",{chain:e})}}function F({inputs:e,outputs:t,feeRate:n=1,chain:r=Q.Bitcoin,changeAddress:s="",sweep:o=!1}){let d=be(r),a=e.filter((g)=>{let y=J(g)*n;return o?g.value>Math.max(y,d):y<=g.value});if(o){let g=Math.ceil(n*ue({inputs:a,outputs:t})),y=a.reduce((S,W)=>S+W.value,0),L=y-g;if(L<=d)throw new Ve("toolbox_sweep_amount_too_low",{available:y,dustThreshold:d,fee:g});let z=t.findIndex((S)=>("address"in S)&&S.address);if(z===-1)throw new Ve("toolbox_utxo_invalid_params",{error:"Sweep requires a recipient output"});return{fee:g,inputs:a,outputs:t.map((S,W)=>W===z?{...S,value:L}:S)}}let p=(e[0]&&"address"in e[0]&&e[0].address?ye(e[0].address):"P2PKH")==="P2WPKH"?Math.ceil(ze/4):0,u=Le+p+t.reduce((g,y)=>g+He(y),0),l=t.reduce((g,y)=>g+y.value,0),h=u*n,m=0,T=[];for(let g of a){let y=J(g),L=n*y;h+=L,m+=g.value,T.push(g);let z=h+l;if(m<z)continue;let S=m-z,W=n*He({address:s,value:0});if(S>W){let Ae=W+h,Ue=m-(l+Math.ceil(Ae));if(Ue>Math.max(J({value:0})*n,be(r)))return{fee:Math.ceil(Ae),inputs:T,outputs:t.concat({address:s,value:Ue})}}return{fee:Math.ceil(h),inputs:T,outputs:t}}return{fee:Math.ceil(n*ue({inputs:e,outputs:t}))}}import{Chain as fe,SwapKitError as Pr}from"@swapkit/helpers";import{hex as Bt}from"@scure/base";import{Chain as En,derivationPathToString as Zn,FeeOption as Ln,resolveDerivationPath as zn,SwapKitError as N}from"@swapkit/helpers";import{BCHSigHash as $n,CashAddrPrefix as St,CashAddrType as kt,encodeCashAddr as Xt,NETWORKS as Vn,p2pkh as Kt,Transaction as Ft}from"@swapkit/utxo-signer";import{secp256k1 as An}from"@noble/curves/secp256k1.js";import{hex as ee}from"@scure/base";import{HDKey as Tt}from"@scure/bip32";import{mnemonicToSeedSync as je}from"@scure/bip39";import{AssetValue as qe,applyFeeMultiplier as ft,Chain as A,derivationPathToString as ve,FeeOption as D,NetworkDerivationPath as yt,SwapKitError as P,SwapKitNumber as Un,updateDerivationPath as On,warnOnce as Cn}from"@swapkit/helpers";import{Address as Bn,BCHSigHash as Je,CashAddrPrefix as Sn,CashAddrType as kn,encodeCashAddr as Xn,NETWORKS as pe,p2pkh as mt,p2wpkh as Kn,RBF_SEQUENCE as Fn,SigHash as bt,Transaction as Ge,WIF as wt}from"@swapkit/utxo-signer";import{match as vt}from"ts-pattern";import{validateZcashAddress as we}from"@swapkit/utxo-signer";function de(e){return e.replace(/(bchtest:|bitcoincash:)/,"")}function Y(e){let t=de(e);return lt(t)&&ht(t)==="mainnet"}var Re=[A.Dash,A.Dogecoin,A.Zcash,A.BitcoinCash],Ie=[A.Bitcoin];function Pt({address:e,chain:t}){return vt(t).with(A.BitcoinCash,()=>Y(e)).with(A.Zcash,()=>we(e)).otherwise(()=>{try{return Bn(C(t)).decode(e),!0}catch{return!1}})}function C(e){return vt(e).with(A.Bitcoin,()=>pe.bitcoin).with(A.BitcoinCash,()=>pe.bitcoinCash).with(A.Dash,()=>pe.dash).with(A.Dogecoin,()=>pe.dogecoin).with(A.Litecoin,()=>pe.litecoin).with(A.Zcash,()=>pe.zcash).exhaustive()}function Dn({phrase:e,derivationPath:t,network:n,seed:r}){let s=r??je(e),d=Tt.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 An.getPublicKey(e,!0)}function Pe({publicKey:e,chain:t,network:n}){if(t===A.BitcoinCash){let o=mt(e,n);if(!o.hash)throw new P("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return Xn({hash:o.hash,prefix:Sn.MAINNET,type:kn.P2PKH}).replace(/^bitcoincash:/,"")}let s=!Re.includes(t)?Kn(e,n):mt(e,n);if(!s.address)throw new P("toolbox_utxo_invalid_address",{error:"Could not derive address"});return s.address}function le({phrase:e,derivationPath:t,chain:n,wif:r,seed:s}){let o=C(n);if(r){let i=wt(o).decode(r),p=gt(i);return{privateKey:i,publicKey:p}}if(!e)throw new P("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let d=t||ve(yt[n]),a=Dn({derivationPath:d,network:o,phrase:e,seed:s}),c=gt(a);return{privateKey:a,publicKey:c}}function Hn(e,t){return wt(C(t)).encode(e)}function In({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 o=C(n),d=r??je(e),a=Tt.fromMasterSeed(d,o.bip32),c=s.slice(0,4).join("/");return a.derive(c)}function te({inputs:e,outputs:t,chain:n,tx:r,sender:s,compiledMemo:o,enableRBF:d=!1}){let a=C(n),c=!Re.includes(n),i=d?Fn:void 0,p=new Set;for(let u of e){let l=`${u.hash}:${u.index}`;if(p.has(l))throw new P("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});p.add(l);let h=typeof u.hash==="string"?ee.decode(u.hash):u.hash;if(c&&u.witnessUtxo)r.addInput({index:u.index,sequence:i,txid:h,witnessUtxo:{amount:BigInt(u.witnessUtxo.value),script:u.witnessUtxo.script}});else if(u.txHex)r.addInput({index:u.index,nonWitnessUtxo:ee.decode(u.txHex),sequence:i,txid:h,...n===A.BitcoinCash?{sighashType:Je.ALL}:{}});else throw new P("toolbox_utxo_invalid_params",{error:"Input requires either witnessUtxo or txHex for non-segwit chains"})}for(let u of t){let l="address"in u&&u.address?u.address:s;if(n===A.BitcoinCash)l=Z(l);if(u.script){if(o)r.addOutput({amount:0n,script:o})}else r.addOutputAddress(l,BigInt(u.value),a)}return{inputs:e,tx:r}}async function he(e){let t=await _(e).getSuggestedTxFee();return{[D.Average]:t,[D.Fast]:ft(t,D.Fast),[D.Fastest]:ft(t,D.Fastest)}}async function _t({assetValue:e,recipient:t,memo:n,sender:r,sweep:s,fetchTxHex:o=!1},d){let a=e.chain,c=o||Re.includes(a),i=e.getBaseValue("number"),p=s?void 0:d??(await he(a))[D.Fastest],u=s||p===void 0?void 0:Math.ceil(i+p*5000);return{inputs:await _(a).getUtxos({address:r,fetchTxHex:c,targetValue:u}),outputs:[{address:t,value:s?0:i},...n?[{address:"",script:X(n),value:0}]:[]]}}async function At({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s,fetchTxHex:o=!1,enableRBF:d=!1,sweep:a}){let c=e.chain,i=n?X(n):null,p=await _t({assetValue:e,fetchTxHex:o,memo:n,recipient:t,sender:s,sweep:a},r),{inputs:u,outputs:l}=F({...p,chain:c,feeRate:r,sweep:a});if(!(u&&l))throw new P("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let h=new Ge({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!i,version:1}),{inputs:m,tx:T}=te({chain:c,compiledMemo:i,enableRBF:d,inputs:u,outputs:l,sender:s,tx:h});return{inputs:m,tx:T,utxos:p.inputs}}async function Ut({assetValue:e,feeOptionKey:t=D.Fast,feeRate:n,memo:r,sender:s,recipient:o,sweep:d}){let a=e.chain,c,i;if(n!==void 0)c=n,i=Math.floor(n);else{let u=await he(a);c=u[D.Fastest],i=u[t]}let p=await _t({assetValue:e,memo:r,recipient:o,sender:s,sweep:d},c);return F({...p,chain:a,feeRate:i,sweep:d})}function Rn(e){return async function({from:n,memo:r,feeRate:s,feeOptionKey:o=D.Fast,recipient:d=n,recipients:a=1}){let c=s??(await he(e))[o],p=(await _(e).getUtxos({address:n,fetchTxHex:!1})).filter((T)=>T.value>Math.max(be(e),J(T)*c));if(!p.length)return qe.from({chain:e});let u=typeof a==="number"?Math.max(a,1):a.length,l=typeof a==="number"||u===0?Array.from({length:u||1},()=>({address:d,value:0})):[...a];if(r)l.push({address:n,script:X(r),value:0});let{outputs:h}=F({chain:e,feeRate:c,inputs:p,outputs:l,sweep:!0}),m=h?.[0]?.value??0;return qe.from({chain:e,value:BigInt(m)})}}function Wn(e){return async function(n){let{fee:r}=await Ut(n);return qe.from({chain:e,value:Un.fromBigInt(BigInt(r),8).getValue("string")})}}function Mn({chain:e,phrase:t,derivationPath:n,seed:r}){let s=C(e),{privateKey:o,publicKey:d}=le({chain:e,derivationPath:n,phrase:t,seed:r}),a=e===A.BitcoinCash?[Je.ALL]:[bt.ALL];return{getAddress:()=>Pe({chain:e,network:s,publicKey:d}),privateKey:o,publicKey:d,signTransaction:(c)=>(c.sign(o,a),c)}}function Nn(e,t){return async function({memo:r,recipient:s,feeOptionKey:o,feeRate:d,assetValue:a,enableRBF:c=!1,sweep:i}){let p=await t?.getAddress();if(!(t&&p))throw new P("toolbox_utxo_no_signer");if(!s)throw new P("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});Cn({condition:c&&!Ie.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 u=c&&Ie.includes(e),l=d||(await he(e))[o||D.Fast],{tx:h}=await At({assetValue:a,enableRBF:u,feeRate:l,memo:r,recipient:s,sender:p,sweep:i}),m=await t.signTransaction(h);return m.finalize(),_(e).broadcastTx(ee.encode(m.extract()))}}function Ot(e){return(t)=>Pt({address:t,chain:e})}function Ct(e){let t=C(e);return function(r){if(!r)throw new P("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return Pe({chain:e,network:t,publicKey:r.publicKey})}}function ne({chain:e,...t}){let n="phrase"in t?t.phrase:void 0,r="index"in t?t.index||0:0,s=n?je(n):void 0,o="derivationPath"in t&&t.derivationPath?t.derivationPath:On(yt[e],{index:r}),d=ve(o),a=n?Mn({chain:e,derivationPath:d,phrase:n,seed:s}):void 0,c="signer"in t?t.signer:void 0,i=a||c,p=n?le({chain:e,derivationPath:d,phrase:n,seed:s}):void 0;function u(){if(i)return i.getAddress();return Promise.resolve(void 0)}function l(f){if(!n)return;let x=G({accountIndex:f,chain:e,derivationPath:o});return In({chain:e,derivationPath:ve(x),phrase:n,seed:s})}let h=l();function m(){if(!h)return;return h.publicExtendedKey}function T({accountIndex:f}={}){let x=f===void 0?h:l(f);if(!x)return;let b=G({accountIndex:f,chain:e,derivationPath:o});return{accountIndex:ae(b),path:ve(b),xpub:x.publicExtendedKey}}function g({accountIndex:f,index:x,change:b=!1}){let w=f===void 0?h:l(f);if(!w)return;let v=xe({accountIndex:f,chain:e,change:b,derivationPath:o,index:x}),k=C(e),I=w.deriveChild(Number(b)).deriveChild(x);if(!I.publicKey)throw new P("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let B=Pe({chain:e,network:k,publicKey:I.publicKey}),E=ee.encode(I.publicKey);return{accountIndex:ae(v),address:B,change:b,index:x,path:ve(v),pubkey:E}}async function y(f){if(!Ie.includes(e))return{reason:`RBF is not supported on ${e}`,supported:!1};let x=await _(e).getTransactionDetails(f);return{canReplace:x.isRBF&&!x.confirmed,confirmed:x.confirmed,enabled:x.isRBF,fee:x.fee,sequences:x.sequences,supported:!0}}async function L({txid:f,newFeeRate:x,recipient:b,memo:w}){if(!Ie.includes(e))throw new P("toolbox_utxo_rbf_not_supported",{chain:e});let v=await _(e).getTransactionDetails(f);if(!v.isRBF)throw new P("toolbox_utxo_tx_not_replaceable",{txid:f});if(v.confirmed)throw new P("toolbox_utxo_tx_already_confirmed",{blockId:v.blockId,txid:f});let k=v.inputs.reduce((O,M)=>O+M.value,0),B=v.outputs.find((O)=>O.recipient===b)?.value||0;if(B===0)throw new P("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let E=await Promise.all(v.inputs.map(async(O)=>{let M=await _(e).getRawTx(O.transaction_hash);return{hash:O.transaction_hash,index:O.index,txHex:M,value:O.value,witnessUtxo:void 0}})),me=w?X(w):null,Oe=ue({feeRate:x,inputs:E.map((O)=>({...O,type:"P2WPKH"})),outputs:[{address:b,value:B}]}),V=Math.ceil(Oe*x);if(V<=v.fee)throw new P("toolbox_utxo_rbf_fee_too_low",{newFee:V,originalFee:v.fee});let se=V-v.fee,oe=B-se;if(oe<=0)throw new P("toolbox_utxo_rbf_insufficient_change");let q=new Ge({allowLegacyWitnessUtxo:!0,version:1}),Ce=[{address:b,value:oe},...w?[{address:"",script:X(w),value:0}]:[]],Be=k-oe-V,ge=await u();if(Be>be(e)&&ge)Ce.push({address:ge,value:Be});return te({chain:e,compiledMemo:me,inputs:E,outputs:Ce,sender:ge||b,tx:q}),{feeDelta:se,newFee:V,originalFee:v.fee,tx:q}}async function z({txid:f,newFeeRate:x,recipient:b,memo:w}){let{tx:v,originalFee:k,newFee:I}=await L({memo:w,newFeeRate:x,recipient:b,txid:f}),B=await Me(v);B.finalize();let E=await _(e).broadcastTx(ee.encode(B.extract()));return{newFee:I,originalFee:k,txid:E}}function S({accountIndex:f,index:x,change:b=!1}){R("index",x);let w=f===void 0?h:l(f);if(!w)return;return w.deriveChild(Number(b)).deriveChild(x).privateKey||void 0}function W({tx:f,inputDerivations:x}){if(!h)throw new P("toolbox_utxo_no_signer");let b=e===A.BitcoinCash?[Je.ALL]:[bt.ALL];for(let w=0;w<x.length;w++){let v=x[w];if(!v)continue;let{derivationIndex:k,isChange:I}=v,B=S({change:I,index:k});if(!B)throw new P("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${w} at index ${k}`});f.signIdx(B,w,b)}return f}async function Ae({utxos:f,recipient:x,assetValue:b,memo:w,feeRate:v,feeOptionKey:k,changeAddress:I,sweep:B}){if(B)throw new P("toolbox_utxo_invalid_params",{error:"Sweep is not supported for transfers from multiple addresses"});if(!h)throw new P("toolbox_utxo_no_signer");let E=v||(await he(e))[k||D.Fast],me=w?X(w):null,Oe=[{address:x,value:b.getBaseValue("number")}];if(me)Oe.push({address:"",script:me,value:0});let V=f.map(({hash:O,index:M,value:Se,txHex:zt,witnessUtxo:Ne})=>({hash:O,index:M,txHex:zt,value:Se,witnessUtxo:Ne?{script:Ne.script,value:Ne.value}:void 0})),{inputs:se,outputs:oe}=F({chain:e,feeRate:E,inputs:V,outputs:Oe});if(!(se&&oe))throw new P("toolbox_utxo_insufficient_balance",{assetValue:b,sender:"multiple addresses"});let q=new Ge({allowLegacyWitnessUtxo:!0,version:1}),Ce=f[0]?.address,Be=I||await u()||Ce||x;te({chain:e,compiledMemo:me,inputs:se,outputs:oe,sender:Be,tx:q});let ge=se.map((O)=>{let M=f.find((Se)=>Se.hash===O.hash&&Se.index===O.index);return M?{derivationIndex:M.derivationIndex,isChange:M.isChange}:{derivationIndex:0,isChange:!1}});return W({inputDerivations:ge,tx:q}),q.finalize(),_(e).broadcastTx(ee.encode(q.extract()))}function Ue({address:f,gapLimit:x=20}){if(!h)return;for(let b=0;b<x;b++){let w=g({change:!1,index:b}),v=g({change:!0,index:b}),k=w?.address===f?!1:v?.address===f;if(w?.address===f||v?.address===f)return{change:k,index:b}}return}function Me(f){if(!i)throw new P("toolbox_utxo_no_signer");return i.signTransaction(f)}async function Lt(f){let x=await Me(f);return x.finalize(),await _(e).broadcastTx(ee.encode(x.extract()))}return{accumulative:F,broadcastTx:(f)=>_(e).broadcastTx(f),bumpFee:z,calculateTxSize:ue,createKeysForPath:(f)=>le({...f,chain:e}),createReplacementTransaction:L,createTransaction:At,deriveAddressAtIndex:g,derivePrivateKeyAtIndex:S,estimateMaxSendableAmount:Rn(e),estimateTransactionFee:Wn(e),getAddress:u,getAddressFromKeys:Ct(e),getBalance:xt(e),getExtendedPublicKey:m,getExtendedPublicKeyInfo:T,getFeeRates:()=>he(e),getInputsOutputsFee:Ut,getNetworkForChain:()=>C(e),getPrivateKeyFromMnemonic:(f)=>Hn(le({...f,chain:e}).privateKey,e),isRBFEnabled:y,keys:p,resolveDerivationIndex:Ue,signAndBroadcastTransaction:Lt,signTransaction:Me,signTransactionWithMultipleKeys:W,transfer:Nn(e,i),transferFromMultipleAddresses:Ae,validateAddress:Ot(e)}}var H=En.BitcoinCash;function We(e){return de(Ke(e))}function qn(e){let t=C(H);function n(s){return s.sign(e.privateKey,[$n.ALL]),s}function r(){let s=Kt(e.publicKey,t);if(!s.hash)throw new N("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let o=Xt({hash:s.hash,prefix:St.MAINNET,type:kt.P2PKH});return Promise.resolve(o.replace(/^bitcoincash:/,""))}return{getAddress:r,signTransaction:n}}function Dt(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=zn({chain:H,derivationPath:r,index:n}),o=Zn(s),d=t?le({chain:H,derivationPath:o,phrase:t}):void 0,a=d?qn(d):("signer"in e)?e.signer:void 0;function c(){return Promise.resolve(a?.getAddress())}let{getBalance:i,getFeeRates:p,broadcastTx:u,...l}=ne(t?{chain:H,derivationPath:s,phrase:t}:{chain:H});function h(g,y=!0){return i(de(Ke(g)))}function m(g){if(!a)throw new N("toolbox_utxo_no_signer");return a.signTransaction(g)}async function T(g){let y=await m(g);return y.finalize(),await u(Bt.encode(y.extract()))}return{...l,broadcastTx:u,buildTx:jn,createTransaction:Ht,getAddress:c,getAddressFromKeys:Jn,getBalance:h,getFeeRates:p,signAndBroadcastTransaction:T,signTransaction:m,stripPrefix:de,stripToCashAddress:We,transfer:Gn({broadcastTx:u,getFeeRates:p,signer:a}),validateAddress:Y}}async function Ht({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s,sweep:o}){if(!Y(t))throw new N("toolbox_utxo_invalid_address",{address:t});let d=Math.ceil(e.getBaseValue("number")+r*7500),a=await _(H).getUtxos({address:We(s),fetchTxHex:!0,targetValue:o?void 0:d}),c=n?X(n):null,i=[],p=Z(t);if(i.push({address:p,value:o?0:e.getBaseValue("number")}),c)i.push({script:c,value:0});let{inputs:u,outputs:l}=F({chain:H,feeRate:r,inputs:a,outputs:i,sweep:o});if(!(u&&l))throw new N("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let h=new Ft({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!c,version:1}),m=Z(s),{inputs:T,tx:g}=te({chain:H,compiledMemo:c,inputs:u,outputs:l.map((y)=>("address"in y)&&y.address?{...y,address:Z(y.address)}:y),sender:m,tx:h});return{inputs:T,tx:g,utxos:u}}function Gn({broadcastTx:e,getFeeRates:t,signer:n}){return async function({recipient:s,assetValue:o,feeOptionKey:d=Ln.Fast,sweep:a,...c}){let i=await n?.getAddress();if(!(n&&i))throw new N("toolbox_utxo_no_signer");if(!s)throw new N("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let p=c.feeRate||(await t())[d],{tx:u}=await Ht({...c,assetValue:o,feeRate:p,recipient:s,sender:i,sweep:a}),l=await n.signTransaction(u);return l.finalize(),e(Bt.encode(l.extract()))}}async function jn({assetValue:e,recipient:t,memo:n,feeRate:r,sender:s}){let o=Ke(t);if(!Y(o))throw new N("toolbox_utxo_invalid_address",{address:o});let d=Math.ceil(e.getBaseValue("number")+r*7500),a=await _(H).getUtxos({address:We(s),fetchTxHex:!0,targetValue:d}),c=Number(r.toFixed(0)),i=n?X(n):null,p=[];if(p.push({address:Z(t),value:e.getBaseValue("number")}),i)p.push({script:i,value:0});let{inputs:u,outputs:l}=F({chain:H,feeRate:c,inputs:a,outputs:p});if(!(u&&l))throw new N("toolbox_utxo_insufficient_balance",{assetValue:e,sender:s});let h=new Ft({allowLegacyWitnessUtxo:!0,allowUnknownOutputs:!!i,version:1}),{inputs:m,tx:T}=te({chain:H,compiledMemo:i,inputs:u,outputs:l,sender:Z(s),tx:h});return{inputs:m,tx:T,utxos:a}}function Jn(e){let t=Vn.bitcoinCash,n=Kt(e.publicKey,t);if(!n.hash)throw new N("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return Xt({hash:n.hash,prefix:St.MAINNET,type:kt.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as Qn,hex as Yn}from"@scure/base";import{HDKey as Mt}from"@scure/bip32";import{mnemonicToSeedSync as Nt}from"@scure/bip39";import{Chain as _e,derivationPathToString as er,FeeOption as tr,resolveDerivationPath as nr,SKConfig as et,SwapKitError as re}from"@swapkit/helpers";import{Address as rr,createZcashTransaction as sr,getZcashConsensusBranchId as or,isTransparentZcashAddress as It,OutScript as ar,PCZT as ir,utils as Et,WIF as cr,ZCASH_NETWORK as ur,ZCASH_TEST_NETWORK as dr,ZcashConsensusBranchId as Rt,ZcashPSBT as pr,ZcashSigHash as Qe,ZcashVersionGroupId as lr}from"@swapkit/utxo-signer";import{match as hr,P as Ye}from"ts-pattern";function tt(){let{isStagenet:e}=et.get("envs");return e?dr:ur}var fr=Qn(Et.sha256);function mr(e){return fr.encode(e)}function gr({phrase:e,derivationPath:t}){let n=Nt(e),s=Mt.fromMasterSeed(n).derive(t);if(!s.privateKey||!s.publicKey)throw new re("toolbox_utxo_invalid_params");let{privateKey:o,publicKey:d}=s,a=Et.hash160(d),{isStagenet:c}=et.get("envs"),i=c?new Uint8Array([29,37]):new Uint8Array([28,184]),p=new Uint8Array(i.length+a.length);p.set(i,0),p.set(a,i.length);let u=mr(p);return{getAddress:()=>Promise.resolve(u),signTransaction:(l)=>{if(l instanceof pr){let h=l.toPCZT();return h.signAllInputs(o,d,Qe.ALL),h.finalizeAllInputs(),Promise.resolve(h.extract())}if(l instanceof ir)return l.signAllInputs(o,d,Qe.ALL),l.finalizeAllInputs(),Promise.resolve(l.extract());return l.signAllInputs(o,d,Qe.ALL),Promise.resolve(l)}}}function xr({inputs:e,outputs:t,tx:n,sender:r,compiledMemo:s}){let o=tt();for(let d of e){let a=rr(o).decode(r),c=ar.encode(a);n.addInput({index:d.index,script:c,sequence:4294967295,txid:Yn.decode(d.hash),value:BigInt(d.value)})}for(let d of t){let a="address"in d&&d.address?d.address:r,c=d.script;if(c&&!s)continue;if(c&&s)n.addOutput({amount:0n,script:s});else n.addOutputAddress(a,BigInt(d.value),o)}return{inputs:e,tx:n}}async function Tr(){let{isStagenet:e}=et.get("envs");if(e)return Rt.IRONWOOD;try{let t=await _(_e.Zcash).getBlockHeight();return or(t+1)}catch{return Rt.IRONWOOD}}async function Wt(e){let{assetValue:t,recipient:n,memo:r,feeRate:s,sender:o,fetchTxHex:d,sweep:a}=e,c=tt();if(!It(o,c))throw new re("toolbox_utxo_invalid_address",{address:o});if(!It(n,c))throw new re("toolbox_utxo_invalid_address",{address:n,error:"Zcash transaction creation currently supports transparent addresses only"});let i=r?X(r):null,p=await _(_e.Zcash).getUtxos({address:o,fetchTxHex:d!==!1}),u=[{address:n,value:a?0:Number(t.getBaseValue("string"))},...i?[{script:i,value:0}]:[]],{inputs:l,outputs:h}=F({chain:_e.Zcash,changeAddress:o,feeRate:s,inputs:p,outputs:u,sweep:a});if(!(l&&h))throw new re("toolbox_utxo_insufficient_balance",{assetValue:t,sender:o});let m=sr({consensusBranchId:await Tr(),expiryHeight:0,lockTime:0,version:4,versionGroupId:lr.SAPLING}),{tx:T,inputs:g}=xr({compiledMemo:i,inputs:l,outputs:h,sender:o,tx:m});return{inputs:g,outputs:h,tx:T}}function Zt(e){let t=hr(e).with({signer:Ye.not(Ye.nullish)},({signer:c})=>c).with({phrase:Ye.string},({phrase:c,derivationPath:i,index:p=0})=>{let u=nr({chain:_e.Zcash,derivationPath:i,index:p}),l=er(u);return gr({derivationPath:l,phrase:c})}).otherwise(()=>{return}),n=ne({chain:_e.Zcash,signer:t});async function r(c){if(!t)throw new re("toolbox_utxo_no_signer");return await t.signTransaction(c)}async function s(c){let i=await r(c);return n.broadcastTx(i.toHex())}async function o({recipient:c,assetValue:i,feeOptionKey:p=tr.Fast,sweep:u,...l}){let h=await t?.getAddress();if(!(t&&h))throw new re("toolbox_utxo_no_signer");let m=l.feeRate||(await n.getFeeRates())[p],{tx:T}=await Wt({...l,assetValue:i,feeRate:m,recipient:c,sender:h,sweep:u}),y=(await t.signTransaction(T)).toHex();return n.broadcastTx(y)}function d({phrase:c,derivationPath:i="m/44'/133'/0'/0/0"}){let p=Nt(c),l=Mt.fromMasterSeed(p).derive(i);if(!l.privateKey||!l.publicKey)throw new re("toolbox_utxo_invalid_params");return{privateKey:l.privateKey,publicKey:l.publicKey}}function a({phrase:c,derivationPath:i="m/44'/133'/0'/0/0"}){let p=d({derivationPath:i,phrase:c}),u=tt();return cr(u).encode(p.privateKey)}return{...n,createKeysForPath:d,createTransaction:Wt,getPrivateKeyFromMnemonic:a,signAndBroadcastTransaction:s,signTransaction:r,transfer:o,validateAddress:we}}import{hex as yr}from"@scure/base";import{HDKey as br}from"@scure/bip32";import{derivationPathToString as wr}from"@swapkit/helpers";function vr({xpub:e,chain:t,count:n,startIndex:r=0,accountIndex:s}){if(R("count",n),n<1)throw RangeError("count must be at least 1");R("startIndex",r);let o=C(t),d=br.fromExtendedKey(e,o.bip32),a=G({accountIndex:s,chain:t}),c=ae(a),i=[];for(let p of[!1,!0]){let u=d.deriveChild(Number(p));for(let l=0;l<n;l++){let h=r+l,m=u.deriveChild(h);if(!m.publicKey)continue;let T=xe({accountIndex:s,chain:t,change:p,index:h});i.push({accountIndex:c,address:Pe({chain:t,network:o,publicKey:m.publicKey}),change:p,index:h,path:wr(T),pubkey:yr.encode(m.publicKey)})}}return i}function Ws(e,t){switch(e){case fe.BitcoinCash:return Dt(t||{});case fe.Zcash:return Zt(t);case fe.Bitcoin:case fe.Dogecoin:case fe.Litecoin:case fe.Dash:return ne({chain:e,...t});default:throw new Pr("toolbox_utxo_not_supported",{chain:e})}}export{Ze as InputSizes,Nr as MIN_TX_FEE,vn as OP_RETURN_OVERHEAD,De as OutputSizes,ze as SEGWIT_MARKER_FLAG_WEIGHT,Le as TX_OVERHEAD,$e as UTXOScriptType,pt as UtxoNetwork,F as accumulative,te as addInputsAndOutputs,Ct as addressFromKeysGetter,R as assertDerivationIndex,ue as calculateTxSize,X as compileMemo,Dt as createBCHToolbox,Br as createCustomUtxoApi,Vt as createHDWalletHelpers,ne as createUTXOToolbox,Zt as createZcashToolbox,vr as deriveAddressesFromXpub,ht as detectAddressNetwork,be as getDustThreshold,J as getInputSize,C as getNetworkForChain,He as getOutputSize,ye as getScriptTypeForAddress,ae as getUTXOAccountIndexFromPath,G as getUTXOAccountPath,xe as getUTXOAddressPath,Ot as getUTXOAddressValidator,_ as getUtxoApi,Sr as getUtxoNetwork,Ws as getUtxoToolbox,lt as isValidAddress,Re as nonSegwitChains,de as stripPrefix,We as stripToCashAddress,Ke as toCashAddress,Z as toLegacyAddress,Y as validateBchAddress,Pt as validateUtxoAddress,we as validateZcashAddress};
|
|
1
|
+
import{fa as it,ga as vt}from"../../chunk-as9fracn.js";import"../../chunk-4428244x.js";import{NetworkDerivationPath as en}from"@swapkit/helpers";function R(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`${e} must be a non-negative integer, got: ${t}`)}function G({accountIndex:e,chain:t,derivationPath:n}){if(e!==void 0)R("accountIndex",e);let[s,r,o]=n??en[t];return[s,r,e??o]}function ye({accountIndex:e,change:t=!1,chain:n,derivationPath:s,index:r}){return R("index",r),[...G({accountIndex:e,chain:n,derivationPath:s}),Number(t),r]}function oe(e){return e[2]??0}function tn({deriveAddress:e,getBalance:t,getUtxos:n}){async function s(i){let{accountIndex:c,count:a,startIndex:l=0,change:u=!1}=i;if(R("count",a),a<1)throw RangeError("count must be at least 1");R("startIndex",l);let d=[];for(let h=0;h<a;h++){let m=await e({accountIndex:c,change:u,index:l+h});if(m)d.push(m)}return d}async function r(i){let{gapLimit:c=20,change:a=!1}=i??{},l=[],u=0,d=0;while(u<c){let h=await e({change:a,index:d});if(!h)break;if((await t(h.address)).some((x)=>x.getValue("number")>0))l.push(h),u=0;else u++;d++}return l}async function o(i=20){let[c,a]=await Promise.all([r({change:!1,gapLimit:i}),r({change:!0,gapLimit:i})]),l=[...c,...a],u=await Promise.all(l.map(async(h)=>{let g=(await t(h.address)).reduce((x,P)=>x+P.getValue("number"),0);return{...h,balance:g}})),d=u.reduce((h,m)=>h+m.balance,0);return{addresses:u,total:d}}async function p(i=20){let[c,a]=await Promise.all([r({change:!1,gapLimit:i}),r({change:!0,gapLimit:i})]),l=[...c,...a];return(await Promise.all(l.map(async(d)=>(await n(d.address)).map((m)=>({...m,address:d.address,derivationIndex:d.index,isChange:d.change}))))).flat()}return{deriveAddresses:s,getAggregatedBalance:o,getAggregatedUtxos:p,scanForAddresses:r}}import{Chain as O,getRPCUrl as nn,RequestClient as Be,SKConfig as rn,SwapKitError as X,warnOnce as sn}from"@swapkit/helpers";import{NETWORKS as ae}from"@swapkit/utxo-signer";async function on({chain:e,txHash:t}){let n=`${ie(e)}/push/transaction`,s=JSON.stringify({data:t});try{let r=await Be.post(n,{body:s,headers:{"Content-Type":"application/json"}});if(r.context.code!==200)throw new X("toolbox_utxo_broadcast_failed",{error:r.context.error||"Transaction broadcast failed"});return r.data?.transaction_hash||t}catch(r){let o=await nn(e);if(o){let p=JSON.stringify({id:it(),jsonrpc:"2.0",method:"sendrawtransaction",params:[t]}),i=await Be.post(o,{body:p,headers:{"Content-Type":"application/json"}});if(i.error)throw new X("toolbox_utxo_broadcast_failed",{error:i.error?.message});if(i.result.includes('"code":-26'))throw new X("toolbox_utxo_invalid_transaction",{error:"Transaction amount was too low"});return i.result}throw r}}function ie(e){return`https://api.blockchair.com/${an(e)}`}function ot(e){switch(e){case O.Bitcoin:return 5;case O.Dogecoin:return 1e4;case O.Litecoin:return 1;case O.Zcash:return 1;default:return 2}}function an(e){switch(e){case O.BitcoinCash:return"bitcoin-cash";case O.Litecoin:return"litecoin";case O.Dash:return"dash";case O.Dogecoin:return"dogecoin";case O.Zcash:return"zcash";case O.Polkadot:return"polkadot";default:return"bitcoin"}}async function cn(e){try{let{feePerKb:t}=await Be.get(`https://app.bitgo.com/api/v2/${e.toLowerCase()}/tx/fee`),n=t/1000;return Math.max(n,ot(e))}catch{return ot(e)}}async function be(e,t){let n=await Be.get(`${e}${t?`${e.includes("?")?"&":"?"}key=${t}`:""}`);if(!n||n.context.code!==200)throw new X("toolbox_utxo_api_error",{error:`Failed to query ${e}`});return n.data}async function un({chain:e,apiKey:t}){let n=await be(`${ie(e)}/stats`,t);if(typeof n.best_block_height!=="number")throw new X("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 X("toolbox_utxo_invalid_params",{error:"Address is required"});try{return(await be(`${ie(t)}/dashboards/address/${e}?transaction_details=true`,n))[e]}catch{return{address:{balance:0,transaction_count:0},utxo:[]}}}async function dn({address:e,chain:t,apiKey:n}){return(await ct({address:e,apiKey:n,chain:t}))?.address.balance||0}async function ut({chain:e,apiKey:t,txHash:n}){if(!n)throw new X("toolbox_utxo_invalid_params",{error:"TxHash is required"});try{return(await be(`${ie(e)}/raw/transaction/${n}`,t))?.[n]?.raw_transaction||""}catch(s){let r=s instanceof Error?s.message:String(s);return console.error(`Failed to fetch raw transaction: ${r}`),""}}var pn=4294967294;async function ln({chain:e,apiKey:t,txHash:n}){if(!n)throw new X("toolbox_utxo_invalid_params",{error:"TxHash is required"});let r=(await be(`${ie(e)}/dashboards/transaction/${n}`,t))?.[n];if(!r)throw new X("toolbox_utxo_tx_not_found",{txHash:n});let{transaction:o,inputs:p,outputs:i}=r,c=p.map((l)=>l.spending_sequence),a=o.is_rbf===!0||c.some((l)=>l<pn);return{blockId:o.block_id,confirmed:o.block_id!==-1,fee:o.fee,inputs:p,isRBF:a,outputs:i,sequences:c,size:o.size,txid:o.hash,weight:o.weight}}async function hn({chain:e,address:t,apiKey:n,offset:s=0,limit:r=30}){return(await be(`${ie(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=${r}&offset=${s}`,n)).map(({is_spent:c,script_hex:a,block_id:l,transaction_hash:u,index:d,value:h,spending_signature_hex:m})=>({hash:u,index:d,is_confirmed:l!==-1,is_spent:c,script_hex:a,txHex:m,value:h}))}function fn(e){return e.reduce((t,n)=>t+n.value,0)}function at(e,t){let n=[...e].sort((s,r)=>r.value-s.value);if(t){let s=[],r=0;for(let o of n)if(s.push(o),r+=o.value,r>=t)break;return s}return n}async function dt({chain:e,address:t,apiKey:n,targetValue:s,accumulativeValue:r=0,offset:o=0,limit:p=30}){if(!t)throw new X("toolbox_utxo_invalid_params",{error:"Address is required"});try{let i=await hn({address:t,apiKey:n,chain:e,limit:p,offset:o,targetValue:s}),a=i.length<p,l=i.filter(({is_spent:x})=>!x),u=fn(l),d=r+u,h=s&&d>=s;if(a||h)return at(l,s);let m=await dt({accumulativeValue:d,address:t,apiKey:n,chain:e,limit:p,offset:o+p,targetValue:s}),g=[...l,...m];return at(g,s)}catch(i){let c=i instanceof Error?i.message:String(i);return console.error(`Failed to fetch unspent UTXOs: ${c}`),[]}}async function mn({address:e,chain:t,apiKey:n,fetchTxHex:s=!0,targetValue:r}){let o=await dt({address:e,apiKey:n,chain:t,targetValue:r}),p=s?await Promise.all(o.map(({hash:i})=>ut({apiKey:n,chain:t,txHash:i}))):[];return o.map(({hash:i,index:c,script_hex:a,value:l},u)=>({address:e,hash:i,index:c,txHex:s?p[u]:void 0,value:l,witnessUtxo:{script:Buffer.from(a,"hex"),value:l}}))}function A(e){let t=rn.get("apiKeys").blockchair||"";return sn({condition:!t,id:"no_blockchair_api_key_warning",warning:"No Blockchair API key found. Functionality will be limited."}),{broadcastTx:(n)=>on({chain:e,txHash:n}),getAddressData:(n)=>ct({address:n,apiKey:t,chain:e}),getBalance:(n)=>dn({address:n,apiKey:t,chain:e}),getBlockHeight:()=>un({apiKey:t,chain:e}),getRawTx:(n)=>ut({apiKey:t,chain:e,txHash:n}),getSuggestedTxFee:()=>cn(e),getTransactionDetails:(n)=>ln({apiKey:t,chain:e,txHash:n}),getUtxos:(n)=>mn({...n,apiKey:t,chain:e})}}function Er(e){return e}function Mr(){return function(t){switch(t){case O.Bitcoin:return ae.bitcoin;case O.BitcoinCash:return ae.bitcoinCash;case O.Dash:return ae.dash;case O.Litecoin:return ae.litecoin;case O.Dogecoin:return ae.dogecoin;case O.Zcash:return ae.zcash;default:throw new X("toolbox_utxo_not_supported",{chain:t})}}}import{sha256 as vn}from"@noble/hashes/sha2.js";import{createBase58check as Pn}from"@scure/base";import{SwapKitError as lt}from"@swapkit/helpers";import{CashAddrType as ke,decodeCashAddr as gn,encodeCashAddr as xn}from"@swapkit/utxo-signer";var Tn={P2PKH:ke.P2PKH,P2SH:ke.P2SH},yn={[ke.P2PKH]:"P2PKH",[ke.P2SH]:"P2SH"};function bn(e,t,n){return xn({hash:n,prefix:e,type:Tn[t]})}function wn(e){let t=gn(e),n=yn[t.type];if(!n)throw Error(`Unknown CashAddr type: ${t.type}`);return{hash:t.hash,prefix:t.prefix,type:n}}var Ne={decode:wn,encode:bn};var ht=Pn(vn);var ft;((n)=>{n.Mainnet="mainnet";n.Testnet="testnet"})(ft||={});var j={["legacy"]:{["mainnet"]:{["p2pkh"]:0,["p2sh"]:5},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}},["bitpay"]:{["mainnet"]:{["p2pkh"]:28,["p2sh"]:40},["testnet"]:{["p2pkh"]:111,["p2sh"]:196}}},_n={["p2pkh"]:"pkh",["p2sh"]:"sh"};function Gr(e){return Fe(e)!==void 0}function jr(e){return Ze(e).network}function z(e){let t=Ze(e);if(t.format==="legacy")return e;return On(t)}function Xe(e){let t=Ze(e);return Cn(t)}function Fe(e){if(typeof e!=="string")return;let t=An(e)??Un(e);return t&&{...t,scriptType:_n[t.type]}}function Ze(e){let t=Fe(e);if(!t)throw new lt("toolbox_utxo_invalid_address",{address:e});return t}function An(e){try{let t=ht.decode(e);if(t.length!==21)throw new lt("toolbox_utxo_invalid_address",{address:e});let n=t[0],s=Array.prototype.slice.call(t,1);switch(n){case j.legacy.mainnet.p2pkh:return{format:"legacy",hash:s,network:"mainnet",type:"p2pkh"};case j.legacy.mainnet.p2sh:return{format:"legacy",hash:s,network:"mainnet",type:"p2sh"};case j.legacy.testnet.p2pkh:return{format:"legacy",hash:s,network:"testnet",type:"p2pkh"};case j.legacy.testnet.p2sh:return{format:"legacy",hash:s,network:"testnet",type:"p2sh"};case j.bitpay.mainnet.p2pkh:return{format:"bitpay",hash:s,network:"mainnet",type:"p2pkh"};case j.bitpay.mainnet.p2sh:return{format:"bitpay",hash:s,network:"mainnet",type:"p2sh"};default:return}}catch{return}}function Un(e){if(e.indexOf(":")!==-1)try{return pt(e)}catch{}else{let t=["bitcoincash","bchtest","bchreg"];for(let n of t)try{return pt(`${n}:${e}`)}catch{}}return}function pt(e){try{let{hash:t,prefix:n,type:s}=Ne.decode(e);return{format:"cashaddr",hash:Array.prototype.slice.call(t,0),network:n==="bitcoincash"?"mainnet":"testnet",type:s==="P2PKH"?"p2pkh":"p2sh"}}catch{return}}function On(e){let t=j.legacy[e.network][e.type],n=Buffer.alloc(1+e.hash.length);return n[0]=t,n.set(e.hash,1),ht.encode(n)}function Cn(e){let t=e.network==="mainnet"?"bitcoincash":"bchtest",n=e.type==="p2pkh"?"P2PKH":"P2SH",s=new Uint8Array(e.hash);return Ne.encode(t,n,s)}import{Chain as J,SwapKitError as Ve}from"@swapkit/helpers";import{SwapKitError as Sn,UTXO_SCRIPT_TYPE_LIST as Bn,UTXO_SCRIPT_TYPES as mt,UTXOScriptType as ce}from"@swapkit/helpers";import{Script as kn}from"@swapkit/utxo-signer";import{UTXOScriptType as Tt}from"@swapkit/helpers";var es=1000,Le=10,Xn=2,Fn=10;function F(e){let t=new Uint8Array(Buffer.from(e,"utf8"));return kn.encode(["RETURN",t])}function gt(e){return Object.fromEntries(Bn.map((t)=>[t,mt[t][e]]))}var xt=gt("inputSize"),Ke=gt("outputSize"),ze=(e)=>mt[e].witness,ve=(e)=>{if(e.startsWith("bc1")||e.startsWith("tb1")||e.startsWith("ltc1")||e.startsWith("tltc1"))return ce.P2WPKH;if(e.startsWith("1")||e.startsWith("m")||e.startsWith("n")||e.startsWith("bitcoincash:q")||e.startsWith("bitcoincash:p")||e.startsWith("q")||e.startsWith("p")||e.startsWith("L")||e.startsWith("M")||e.startsWith("3")||e.startsWith("D")||e.startsWith("A")||e.startsWith("9")||e.startsWith("X")||e.startsWith("7")||e.startsWith("y")||e.startsWith("t1")||e.startsWith("t3")||e.startsWith("tm"))return ce.P2PKH;throw new Sn("toolbox_utxo_invalid_address",{address:e})},ue=({inputs:e,outputs:t,feeRate:n})=>{let s=e[0]?we(e[0]):ce.P2PKH,r=n?e.filter((a)=>a.value>=xt["type"in a&&a.type?a.type:ce.P2PKH]*Math.ceil(n)):e,o=0,p=0;for(let a of r)if(o+=Y(a),!ze(we(a)))p++;let i=t?.reduce((a,l)=>a+De(l),0)||Ke[s],c=p<r.length;return Le+o+i+$e(c,p)},we=(e)=>{if("type"in e&&e.type)return e.type;if("address"in e&&e.address)return ve(e.address);return ce.P2PKH},Y=(e)=>xt[we(e)],$e=(e,t)=>e?Math.ceil((Xn+t)/4):0,De=(e,t)=>{if(e?.script)return Fn+e.script.length+(e.script.length>=74?2:1);if(t)return Ke[t];if("address"in e&&e.address)return Ke[ve(e.address)];return Ke[ce.P2PKH]};function Pe(e){switch(e){case J.Bitcoin:case J.BitcoinCash:return 550;case J.Dash:case J.Litecoin:return 5500;case J.Dogecoin:return 1e5;case J.Zcash:return 546;default:throw new Ve("toolbox_utxo_not_supported",{chain:e})}}function K({inputs:e,outputs:t,feeRate:n=1,chain:s=J.Bitcoin,changeAddress:r="",sweep:o=!1}){let p=Pe(s),i=e.filter((g)=>{let x=Y(g)*n;return o?g.value>Math.max(x,p):x<=g.value});if(o){let g=Math.ceil(n*ue({inputs:i,outputs:t})),x=i.reduce((B,W)=>B+W.value,0),P=x-g;if(P<=p)throw new Ve("toolbox_sweep_amount_too_low",{available:x,dustThreshold:p,fee:g});let V=t.findIndex((B)=>("address"in B)&&B.address);if(V===-1)throw new Ve("toolbox_utxo_invalid_params",{error:"Sweep requires a recipient output"});return{fee:g,inputs:i,outputs:t.map((B,W)=>W===V?{...B,value:P}:B)}}let c=Le+t.reduce((g,x)=>g+De(x),0),a=t.reduce((g,x)=>g+x.value,0),l=0,u=0,d=!1,h=0,m=[];for(let g of i){if(l+=Y(g),ze(we(g)))d=!0;else u++;h+=g.value,m.push(g);let x=(c+l+$e(d,u))*n,P=x+a;if(h<P)continue;let V=h-P,B=n*De({address:r,value:0});if(V>B){let W=B+x,me=h-(a+Math.ceil(W));if(me>Math.max(Y({value:0})*n,Pe(s)))return{fee:Math.ceil(W),inputs:m,outputs:t.concat({address:r,value:me})}}return{fee:Math.ceil(x),inputs:m,outputs:t}}return{fee:Math.ceil(n*ue({inputs:e,outputs:t}))}}import{Chain as fe,SwapKitError as Kr}from"@swapkit/helpers";import{hex as Kt}from"@scure/base";import{Chain as Qn,derivationPathToString as er,FeeOption as tr,resolveDerivationPath as nr,SwapKitError as M}from"@swapkit/helpers";import{BCHSigHash as rr,CashAddrPrefix as Dt,CashAddrType as It,encodeCashAddr as Ht,NETWORKS as sr,p2pkh as Rt,Transaction as Wt}from"@swapkit/utxo-signer";import{secp256k1 as Kn}from"@noble/curves/secp256k1.js";import{hex as Q}from"@scure/base";import{HDKey as Pt}from"@scure/bip32";import{mnemonicToSeedSync as Je}from"@scure/bip39";import{AssetValue as je,applyFeeMultiplier as yt,Chain as U,derivationPathToString as Ae,FeeOption as D,NetworkDerivationPath as _t,SwapKitError as w,SwapKitNumber as Dn,updateDerivationPath as In,warnOnce as Hn}from"@swapkit/helpers";import{BCHSigHash as Qe,CashAddrPrefix as Rn,CashAddrType as Wn,encodeCashAddr as En,getAddressScriptType as Mn,NETWORKS as pe,OutScript as Nn,p2pkh as bt,p2wpkh as Zn,RBF_SEQUENCE as Ln,SigHash as At,Transaction as Ye,WIF as Ut}from"@swapkit/utxo-signer";import{match as Ot}from"ts-pattern";import{getZcashAddressType as qe,validateZcashAddress as Ge}from"@swapkit/utxo-signer";function de(e){return e.replace(/(bchtest:|bitcoincash:)/,"")}function Ie(e){if(typeof e!=="string")return null;let t=Fe(de(e));if(!t||t.network!=="mainnet")return null;return t.scriptType}function _e(e){return Ie(e)!==null}var Re=[U.Dash,U.Dogecoin,U.Zcash,U.BitcoinCash],He=[U.Bitcoin];function et({address:e,chain:t}){return Ot(t).with(U.BitcoinCash,()=>Ie(e)).with(U.Zcash,()=>qe(e)).otherwise(()=>Mn(e,S(t)))}function Ct({address:e,chain:t}){return et({address:e,chain:t})!==null}function S(e){return Ot(e).with(U.Bitcoin,()=>pe.bitcoin).with(U.BitcoinCash,()=>pe.bitcoinCash).with(U.Dash,()=>pe.dash).with(U.Dogecoin,()=>pe.dogecoin).with(U.Litecoin,()=>pe.litecoin).with(U.Zcash,()=>pe.zcash).exhaustive()}function zn({phrase:e,derivationPath:t,network:n,seed:s}){let r=s??Je(e),p=Pt.fromMasterSeed(r,n.bip32).derive(t);if(!p.privateKey)throw new w("toolbox_utxo_invalid_params",{error:"Could not derive private key from phrase"});return p.privateKey}function wt(e){return Kn.getPublicKey(e,!0)}function Ue({publicKey:e,chain:t,network:n}){if(t===U.BitcoinCash){let o=bt(e,n);if(!o.hash)throw new w("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return En({hash:o.hash,prefix:Rn.MAINNET,type:Wn.P2PKH}).replace(/^bitcoincash:/,"")}let r=!Re.includes(t)?Zn(e,n):bt(e,n);if(!r.address)throw new w("toolbox_utxo_invalid_address",{error:"Could not derive address"});return r.address}function le({phrase:e,derivationPath:t,chain:n,wif:s,seed:r}){let o=S(n);if(s){let a=Ut(o).decode(s),l=wt(a);return{privateKey:a,publicKey:l}}if(!e)throw new w("toolbox_utxo_invalid_params",{error:"Either phrase or wif must be provided"});let p=t||Ae(_t[n]),i=zn({derivationPath:p,network:o,phrase:e,seed:r}),c=wt(i);return{privateKey:i,publicKey:c}}function $n(e,t){return Ut(S(t)).encode(e)}function Vn({phrase:e,derivationPath:t,chain:n,seed:s}){let r=t.split("/");if(r.length<4)throw new w("toolbox_utxo_invalid_params",{error:`Derivation path must have at least 4 levels (got ${r.length}): ${t}`});let o=S(n),p=s??Je(e),i=Pt.fromMasterSeed(p,o.bip32),c=r.slice(0,4).join("/");return i.derive(c)}function qn(e){try{let{type:t}=Nn.decode(e);return t==="wpkh"||t==="tr"}catch{return!1}}function ee({inputs:e,outputs:t,chain:n,tx:s,sender:r,compiledMemo:o,enableRBF:p=!1}){let i=S(n),c=!Re.includes(n),a=p?Ln:void 0,l=new Set;for(let u of e){let d=`${u.hash}:${u.index}`;if(l.has(d))throw new w("toolbox_utxo_invalid_params",{error:"Duplicate input detected"});l.add(d);let h=typeof u.hash==="string"?Q.decode(u.hash):u.hash;if(c&&u.witnessUtxo&&qn(u.witnessUtxo.script))s.addInput({index:u.index,sequence:a,txid:h,witnessUtxo:{amount:BigInt(u.witnessUtxo.value),script:u.witnessUtxo.script}});else if(u.txHex)s.addInput({index:u.index,nonWitnessUtxo:Q.decode(u.txHex),sequence:a,txid:h,...n===U.BitcoinCash?{sighashType:Qe.ALL}:{}});else throw new w("toolbox_utxo_invalid_params",{error:`Input ${d} cannot be signed from its witnessUtxo alone: it needs its previous transaction (txHex)`})}for(let u of t){let d="address"in u&&u.address?u.address:r;if(n===U.BitcoinCash)d=z(d);if(u.script)if(o)s.addOutput({amount:0n,script:o});else throw new w("toolbox_utxo_invalid_params",{error:"An output carrying a script needs the compiled memo it carries"});else s.addOutputAddress(d,BigInt(u.value),i)}return{inputs:e,tx:s}}async function he(e){let t=await A(e).getSuggestedTxFee();return{[D.Average]:t,[D.Fast]:yt(t,D.Fast),[D.Fastest]:yt(t,D.Fastest)}}async function St({assetValue:e,recipient:t,memo:n,sender:s,sweep:r,fetchTxHex:o=!1},p,{forEstimateOnly:i=!1}={}){let c=e.chain,a=Re.includes(c)||ve(s)===Tt.P2PKH,l=o||!i&&a,u=e.getBaseValue("number"),d=r?void 0:p??(await he(c))[D.Fastest],h=r||d===void 0?void 0:Math.ceil(u+d*5000);return{inputs:await A(c).getUtxos({address:s,fetchTxHex:l,targetValue:h}),outputs:[{address:t,value:r?0:u},...n?[{address:"",script:F(n),value:0}]:[]]}}async function Bt({assetValue:e,recipient:t,memo:n,feeRate:s,sender:r,fetchTxHex:o=!1,enableRBF:p=!1,sweep:i}){let c=e.chain,a=n?F(n):null,l=await St({assetValue:e,fetchTxHex:o,memo:n,recipient:t,sender:r,sweep:i},s),{inputs:u,outputs:d}=K({...l,chain:c,changeAddress:r,feeRate:s,sweep:i});if(!(u&&d))throw new w("toolbox_utxo_insufficient_balance",{assetValue:e,sender:r});let h=new Ye({allowUnknownOutputs:!!a,version:1}),{inputs:m,tx:g}=ee({chain:c,compiledMemo:a,enableRBF:p,inputs:u,outputs:d,sender:r,tx:h});return{inputs:m,tx:g,utxos:l.inputs}}async function kt({assetValue:e,feeOptionKey:t=D.Fast,feeRate:n,memo:s,sender:r,recipient:o,sweep:p}){let i=e.chain,c,a;if(n!==void 0)c=n,a=Math.floor(n);else{let u=await he(i);c=u[D.Fastest],a=u[t]}let l=await St({assetValue:e,memo:s,recipient:o,sender:r,sweep:p},c,{forEstimateOnly:!0});return K({...l,chain:i,changeAddress:r,feeRate:a,sweep:p})}function Gn(e){return async function({from:n,memo:s,feeRate:r,feeOptionKey:o=D.Fast,recipient:p=n,recipients:i=1}){let c=r??(await he(e))[o],l=(await A(e).getUtxos({address:n,fetchTxHex:!1})).filter((g)=>g.value>Math.max(Pe(e),Y(g)*c));if(!l.length)return je.from({chain:e});let u=typeof i==="number"?Math.max(i,1):i.length,d=typeof i==="number"||u===0?Array.from({length:u||1},()=>({address:p,value:0})):[...i];if(s)d.push({address:n,script:F(s),value:0});let{outputs:h}=K({chain:e,feeRate:c,inputs:l,outputs:d,sweep:!0}),m=h?.[0]?.value??0;return je.from({chain:e,value:BigInt(m)})}}function jn(e){return async function(n){let{fee:s}=await kt(n);return je.from({chain:e,value:Dn.fromBigInt(BigInt(s),8).getValue("string")})}}function Yn({chain:e,phrase:t,derivationPath:n,seed:s}){let r=S(e),{privateKey:o,publicKey:p}=le({chain:e,derivationPath:n,phrase:t,seed:s}),i=e===U.BitcoinCash?[Qe.ALL]:[At.ALL];return{getAddress:()=>Ue({chain:e,network:r,publicKey:p}),privateKey:o,publicKey:p,signTransaction:(c)=>(c.sign(o,i),c)}}function Jn(e,t){return async function({memo:s,recipient:r,feeOptionKey:o,feeRate:p,assetValue:i,enableRBF:c=!1,sweep:a}){let l=await t?.getAddress();if(!(t&&l))throw new w("toolbox_utxo_no_signer");if(!r)throw new w("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});Hn({condition:c&&!He.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 u=c&&He.includes(e),d=p||(await he(e))[o||D.Fast],{tx:h}=await Bt({assetValue:i,enableRBF:u,feeRate:d,memo:s,recipient:r,sender:l,sweep:a}),m=await t.signTransaction(h);return m.finalize(),A(e).broadcastTx(Q.encode(m.extract()))}}function Xt(e){return(t)=>Ct({address:t,chain:e})}function Ft(e){let t=S(e);return function(s){if(!s)throw new w("toolbox_utxo_invalid_params",{error:"Keys must be provided"});return Ue({chain:e,network:t,publicKey:s.publicKey})}}function te({chain:e,...t}){let n="phrase"in t?t.phrase:void 0,s="index"in t?t.index||0:0,r=n?Je(n):void 0,o="derivationPath"in t&&t.derivationPath?t.derivationPath:In(_t[e],{index:s}),p=Ae(o),i=n?Yn({chain:e,derivationPath:p,phrase:n,seed:r}):void 0,c="signer"in t?t.signer:void 0,a=i||c,l=n?le({chain:e,derivationPath:p,phrase:n,seed:r}):void 0;function u(){if(a)return a.getAddress();return Promise.resolve(void 0)}function d(f){if(!n)return;let T=G({accountIndex:f,chain:e,derivationPath:o});return Vn({chain:e,derivationPath:Ae(T),phrase:n,seed:r})}let h=d();function m(){if(!h)return;return h.publicExtendedKey}function g({accountIndex:f}={}){let T=f===void 0?h:d(f);if(!T)return;let y=G({accountIndex:f,chain:e,derivationPath:o});return{accountIndex:oe(y),path:Ae(y),xpub:T.publicExtendedKey}}function x({accountIndex:f,index:T,change:y=!1}){let v=f===void 0?h:d(f);if(!v)return;let b=ye({accountIndex:f,chain:e,change:y,derivationPath:o,index:T}),k=S(e),H=v.deriveChild(Number(y)).deriveChild(T);if(!H.publicKey)throw new w("toolbox_utxo_invalid_params",{error:"Could not derive public key"});let C=Ue({chain:e,network:k,publicKey:H.publicKey}),N=Q.encode(H.publicKey);return{accountIndex:oe(b),address:C,change:y,index:T,path:Ae(b),pubkey:N}}async function P(f){if(!He.includes(e))return{reason:`RBF is not supported on ${e}`,supported:!1};let T=await A(e).getTransactionDetails(f);return{canReplace:T.isRBF&&!T.confirmed,confirmed:T.confirmed,enabled:T.isRBF,fee:T.fee,sequences:T.sequences,supported:!0}}async function V({txid:f,newFeeRate:T,recipient:y,memo:v}){if(!He.includes(e))throw new w("toolbox_utxo_rbf_not_supported",{chain:e});let b=await A(e).getTransactionDetails(f);if(!b.isRBF)throw new w("toolbox_utxo_tx_not_replaceable",{txid:f});if(b.confirmed)throw new w("toolbox_utxo_tx_already_confirmed",{blockId:b.blockId,txid:f});let k=b.inputs.reduce((_,L)=>_+L.value,0),C=b.outputs.find((_)=>_.recipient===y)?.value||0;if(C===0)throw new w("toolbox_utxo_invalid_params",{error:"Could not determine send amount from original transaction"});let N=await Promise.all(b.inputs.map(async(_)=>{let L=await A(e).getRawTx(_.transaction_hash);return{address:_.recipient,hash:_.transaction_hash,index:_.index,txHex:L,value:_.value,witnessUtxo:void 0}})),E=v?F(v):null,ge=k-C-b.fee,xe=await u(),re=[];if(E)re.push({address:"",script:E,value:0});if(ge>Pe(e)&&xe)re.push({address:xe,value:ge});let Ce=ue({inputs:N.map((_)=>({..._,type:ve(_.address)})),outputs:[{address:y,value:C},...re]}),Z=Math.ceil(Ce*T);if(Z<=b.fee)throw new w("toolbox_utxo_rbf_fee_too_low",{newFee:Z,originalFee:b.fee});let Te=Z-b.fee,q=C-Te;if(q<=0)throw new w("toolbox_utxo_rbf_insufficient_change");let Se=new Ye({allowUnknownOutputs:!!E,version:1}),se=[{address:y,value:q},...re];return ee({chain:e,compiledMemo:E,inputs:N,outputs:se,sender:xe||y,tx:Se}),{feeDelta:Te,newFee:Z,originalFee:b.fee,tx:Se}}async function B({txid:f,newFeeRate:T,recipient:y,memo:v}){let{tx:b,originalFee:k,newFee:H}=await V({memo:v,newFeeRate:T,recipient:y,txid:f}),C=await Ee(b);C.finalize();let N=await A(e).broadcastTx(Q.encode(C.extract()));return{newFee:H,originalFee:k,txid:N}}function W({accountIndex:f,index:T,change:y=!1}){R("index",T);let v=f===void 0?h:d(f);if(!v)return;return v.deriveChild(Number(y)).deriveChild(T).privateKey||void 0}function me({tx:f,inputDerivations:T}){if(!h)throw new w("toolbox_utxo_no_signer");let y=e===U.BitcoinCash?[Qe.ALL]:[At.ALL];for(let v=0;v<T.length;v++){let b=T[v];if(!b)continue;let{derivationIndex:k,isChange:H}=b,C=W({change:H,index:k});if(!C)throw new w("toolbox_utxo_invalid_params",{error:`Could not derive private key for input ${v} at index ${k}`});f.signIdx(C,v,y)}return f}async function Gt({utxos:f,recipient:T,assetValue:y,memo:v,feeRate:b,feeOptionKey:k,changeAddress:H,sweep:C}){if(C)throw new w("toolbox_utxo_invalid_params",{error:"Sweep is not supported for transfers from multiple addresses"});if(!h)throw new w("toolbox_utxo_no_signer");let N=b||(await he(e))[k||D.Fast],E=v?F(v):null,ge=[{address:T,value:y.getBaseValue("number")}];if(E)ge.push({address:"",script:E,value:0});let xe=f.map(({address:se,hash:_,index:L,value:Jt,txHex:Qt,witnessUtxo:Me})=>({address:se,hash:_,index:L,txHex:Qt,value:Jt,witnessUtxo:Me?{script:Me.script,value:Me.value}:void 0})),re=f[0]?.address,Ce=H||await u()||re||T,{inputs:Z,outputs:Te}=K({chain:e,changeAddress:Ce,feeRate:N,inputs:xe,outputs:ge});if(!(Z&&Te))throw new w("toolbox_utxo_insufficient_balance",{assetValue:y,sender:"multiple addresses"});let q=new Ye({allowUnknownOutputs:!!E,version:1});ee({chain:e,compiledMemo:E,inputs:Z,outputs:Te,sender:Ce,tx:q});let Se=Z.map((se)=>{let _=f.find((L)=>L.hash===se.hash&&L.index===se.index);return _?{derivationIndex:_.derivationIndex,isChange:_.isChange}:{derivationIndex:0,isChange:!1}});return me({inputDerivations:Se,tx:q}),q.finalize(),A(e).broadcastTx(Q.encode(q.extract()))}function jt({address:f,gapLimit:T=20}){if(!h)return;for(let y=0;y<T;y++){let v=x({change:!1,index:y}),b=x({change:!0,index:y}),k=v?.address===f?!1:b?.address===f;if(v?.address===f||b?.address===f)return{change:k,index:y}}return}function Ee(f){if(!a)throw new w("toolbox_utxo_no_signer");return a.signTransaction(f)}async function Yt(f){let T=await Ee(f);return T.finalize(),await A(e).broadcastTx(Q.encode(T.extract()))}return{accumulative:K,broadcastTx:(f)=>A(e).broadcastTx(f),bumpFee:B,calculateTxSize:ue,createKeysForPath:(f)=>le({...f,chain:e}),createReplacementTransaction:V,createTransaction:Bt,deriveAddressAtIndex:x,derivePrivateKeyAtIndex:W,estimateMaxSendableAmount:Gn(e),estimateTransactionFee:jn(e),getAddress:u,getAddressFromKeys:Ft(e),getAddressType:(f)=>et({address:f,chain:e}),getBalance:vt(e),getExtendedPublicKey:m,getExtendedPublicKeyInfo:g,getFeeRates:()=>he(e),getInputsOutputsFee:kt,getNetworkForChain:()=>S(e),getPrivateKeyFromMnemonic:(f)=>$n(le({...f,chain:e}).privateKey,e),isRBFEnabled:P,keys:l,resolveDerivationIndex:jt,signAndBroadcastTransaction:Yt,signTransaction:Ee,signTransactionWithMultipleKeys:me,transfer:Jn(e,a),transferFromMultipleAddresses:Gt,validateAddress:Xt(e)}}var I=Qn.BitcoinCash;function We(e){return de(Xe(e))}function or(e){let t=S(I);function n(r){return r.sign(e.privateKey,[rr.ALL]),r}function s(){let r=Rt(e.publicKey,t);if(!r.hash)throw new M("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});let o=Ht({hash:r.hash,prefix:Dt.MAINNET,type:It.P2PKH});return Promise.resolve(o.replace(/^bitcoincash:/,""))}return{getAddress:s,signTransaction:n}}function Et(e){let t="phrase"in e?e.phrase:void 0,n="index"in e?e.index||0:0,s="derivationPath"in e?e.derivationPath:void 0,r=nr({chain:I,derivationPath:s,index:n}),o=er(r),p=t?le({chain:I,derivationPath:o,phrase:t}):void 0,i=p?or(p):("signer"in e)?e.signer:void 0;function c(){return Promise.resolve(i?.getAddress())}let{getBalance:a,getFeeRates:l,broadcastTx:u,...d}=te(t?{chain:I,derivationPath:r,phrase:t}:{chain:I});function h(x,P=!0){return a(de(Xe(x)))}function m(x){if(!i)throw new M("toolbox_utxo_no_signer");return i.signTransaction(x)}async function g(x){let P=await m(x);return P.finalize(),await u(Kt.encode(P.extract()))}return{...d,broadcastTx:u,buildTx:ir,createTransaction:Mt,getAddress:c,getAddressFromKeys:cr,getBalance:h,getFeeRates:l,signAndBroadcastTransaction:g,signTransaction:m,stripPrefix:de,stripToCashAddress:We,transfer:ar({broadcastTx:u,getFeeRates:l,signer:i}),validateAddress:_e}}async function Mt({assetValue:e,recipient:t,memo:n,feeRate:s,sender:r,sweep:o}){if(!_e(t))throw new M("toolbox_utxo_invalid_address",{address:t});let p=Math.ceil(e.getBaseValue("number")+s*7500),i=await A(I).getUtxos({address:We(r),fetchTxHex:!0,targetValue:o?void 0:p}),c=n?F(n):null,a=[],l=z(t);if(a.push({address:l,value:o?0:e.getBaseValue("number")}),c)a.push({script:c,value:0});let{inputs:u,outputs:d}=K({chain:I,feeRate:s,inputs:i,outputs:a,sweep:o});if(!(u&&d))throw new M("toolbox_utxo_insufficient_balance",{assetValue:e,sender:r});let h=new Wt({allowUnknownOutputs:!!c,version:1}),m=z(r),{inputs:g,tx:x}=ee({chain:I,compiledMemo:c,inputs:u,outputs:d.map((P)=>("address"in P)&&P.address?{...P,address:z(P.address)}:P),sender:m,tx:h});return{inputs:g,tx:x,utxos:u}}function ar({broadcastTx:e,getFeeRates:t,signer:n}){return async function({recipient:r,assetValue:o,feeOptionKey:p=tr.Fast,sweep:i,...c}){let a=await n?.getAddress();if(!(n&&a))throw new M("toolbox_utxo_no_signer");if(!r)throw new M("toolbox_utxo_invalid_params",{error:"Recipient address must be provided"});let l=c.feeRate||(await t())[p],{tx:u}=await Mt({...c,assetValue:o,feeRate:l,recipient:r,sender:a,sweep:i}),d=await n.signTransaction(u);return d.finalize(),e(Kt.encode(d.extract()))}}async function ir({assetValue:e,recipient:t,memo:n,feeRate:s,sender:r}){let o=Xe(t);if(!_e(o))throw new M("toolbox_utxo_invalid_address",{address:o});let p=Math.ceil(e.getBaseValue("number")+s*7500),i=await A(I).getUtxos({address:We(r),fetchTxHex:!0,targetValue:p}),c=Number(s.toFixed(0)),a=n?F(n):null,l=[];if(l.push({address:z(t),value:e.getBaseValue("number")}),a)l.push({script:a,value:0});let{inputs:u,outputs:d}=K({chain:I,feeRate:c,inputs:i,outputs:l});if(!(u&&d))throw new M("toolbox_utxo_insufficient_balance",{assetValue:e,sender:r});let h=new Wt({allowUnknownOutputs:!!a,version:1}),{inputs:m,tx:g}=ee({chain:I,compiledMemo:a,inputs:u,outputs:d,sender:z(r),tx:h});return{inputs:m,tx:g,utxos:i}}function cr(e){let t=sr.bitcoinCash,n=Rt(e.publicKey,t);if(!n.hash)throw new M("toolbox_utxo_invalid_address",{error:"Could not derive BCH address hash"});return Ht({hash:n.hash,prefix:Dt.MAINNET,type:It.P2PKH}).replace(/^bitcoincash:/,"")}import{createBase58check as ur,hex as dr}from"@scure/base";import{HDKey as zt}from"@scure/bip32";import{mnemonicToSeedSync as $t}from"@scure/bip39";import{Chain as Oe,derivationPathToString as pr,FeeOption as lr,resolveDerivationPath as hr,SKConfig as rt,SwapKitError as ne}from"@swapkit/helpers";import{Address as fr,createZcashTransaction as mr,getZcashConsensusBranchId as gr,isTransparentZcashAddress as Nt,OutScript as xr,PCZT as Tr,utils as Vt,WIF as yr,ZCASH_NETWORK as br,ZCASH_TEST_NETWORK as wr,ZcashConsensusBranchId as Zt,ZcashPSBT as vr,ZcashSigHash as tt,ZcashVersionGroupId as Pr}from"@swapkit/utxo-signer";import{match as _r,P as nt}from"ts-pattern";function st(){let{isStagenet:e}=rt.get("envs");return e?wr:br}var Ar=ur(Vt.sha256);function Ur(e){return Ar.encode(e)}function Or({phrase:e,derivationPath:t}){let n=$t(e),r=zt.fromMasterSeed(n).derive(t);if(!r.privateKey||!r.publicKey)throw new ne("toolbox_utxo_invalid_params");let{privateKey:o,publicKey:p}=r,i=Vt.hash160(p),{isStagenet:c}=rt.get("envs"),a=c?new Uint8Array([29,37]):new Uint8Array([28,184]),l=new Uint8Array(a.length+i.length);l.set(a,0),l.set(i,a.length);let u=Ur(l);return{getAddress:()=>Promise.resolve(u),signTransaction:(d)=>{if(d instanceof vr){let h=d.toPCZT();return h.signAllInputs(o,p,tt.ALL),h.finalizeAllInputs(),Promise.resolve(h.extract())}if(d instanceof Tr)return d.signAllInputs(o,p,tt.ALL),d.finalizeAllInputs(),Promise.resolve(d.extract());return d.signAllInputs(o,p,tt.ALL),Promise.resolve(d)}}}function Cr({inputs:e,outputs:t,tx:n,sender:s,compiledMemo:r}){let o=st();for(let p of e){let i=fr(o).decode(s),c=xr.encode(i);n.addInput({index:p.index,script:c,sequence:4294967295,txid:dr.decode(p.hash),value:BigInt(p.value)})}for(let p of t){let i="address"in p&&p.address?p.address:s,c=p.script;if(c&&!r)continue;if(c&&r)n.addOutput({amount:0n,script:r});else n.addOutputAddress(i,BigInt(p.value),o)}return{inputs:e,tx:n}}async function Sr(){let{isStagenet:e}=rt.get("envs");if(e)return Zt.IRONWOOD;try{let t=await A(Oe.Zcash).getBlockHeight();return gr(t+1)}catch{return Zt.IRONWOOD}}async function Lt(e){let{assetValue:t,recipient:n,memo:s,feeRate:r,sender:o,fetchTxHex:p,sweep:i}=e,c=st();if(!Nt(o,c))throw new ne("toolbox_utxo_invalid_address",{address:o});if(!Nt(n,c))throw new ne("toolbox_utxo_invalid_address",{address:n,error:"Zcash transaction creation currently supports transparent addresses only"});let a=s?F(s):null,l=await A(Oe.Zcash).getUtxos({address:o,fetchTxHex:p!==!1}),u=[{address:n,value:i?0:Number(t.getBaseValue("string"))},...a?[{script:a,value:0}]:[]],{inputs:d,outputs:h}=K({chain:Oe.Zcash,changeAddress:o,feeRate:r,inputs:l,outputs:u,sweep:i});if(!(d&&h))throw new ne("toolbox_utxo_insufficient_balance",{assetValue:t,sender:o});let m=mr({consensusBranchId:await Sr(),expiryHeight:0,lockTime:0,version:4,versionGroupId:Pr.SAPLING}),{tx:g,inputs:x}=Cr({compiledMemo:a,inputs:d,outputs:h,sender:o,tx:m});return{inputs:x,outputs:h,tx:g}}function qt(e){let t=_r(e).with({signer:nt.not(nt.nullish)},({signer:c})=>c).with({phrase:nt.string},({phrase:c,derivationPath:a,index:l=0})=>{let u=hr({chain:Oe.Zcash,derivationPath:a,index:l}),d=pr(u);return Or({derivationPath:d,phrase:c})}).otherwise(()=>{return}),n=te({chain:Oe.Zcash,signer:t});async function s(c){if(!t)throw new ne("toolbox_utxo_no_signer");return await t.signTransaction(c)}async function r(c){let a=await s(c);return n.broadcastTx(a.toHex())}async function o({recipient:c,assetValue:a,feeOptionKey:l=lr.Fast,sweep:u,...d}){let h=await t?.getAddress();if(!(t&&h))throw new ne("toolbox_utxo_no_signer");let m=d.feeRate||(await n.getFeeRates())[l],{tx:g}=await Lt({...d,assetValue:a,feeRate:m,recipient:c,sender:h,sweep:u}),P=(await t.signTransaction(g)).toHex();return n.broadcastTx(P)}function p({phrase:c,derivationPath:a="m/44'/133'/0'/0/0"}){let l=$t(c),d=zt.fromMasterSeed(l).derive(a);if(!d.privateKey||!d.publicKey)throw new ne("toolbox_utxo_invalid_params");return{privateKey:d.privateKey,publicKey:d.publicKey}}function i({phrase:c,derivationPath:a="m/44'/133'/0'/0/0"}){let l=p({derivationPath:a,phrase:c}),u=st();return yr(u).encode(l.privateKey)}return{...n,createKeysForPath:p,createTransaction:Lt,getPrivateKeyFromMnemonic:i,signAndBroadcastTransaction:r,signTransaction:s,transfer:o,validateAddress:Ge}}import{hex as Br}from"@scure/base";import{HDKey as kr}from"@scure/bip32";import{derivationPathToString as Xr}from"@swapkit/helpers";function Fr({xpub:e,chain:t,count:n,startIndex:s=0,accountIndex:r}){if(R("count",n),n<1)throw RangeError("count must be at least 1");R("startIndex",s);let o=S(t),p=kr.fromExtendedKey(e,o.bip32),i=G({accountIndex:r,chain:t}),c=oe(i),a=[];for(let l of[!1,!0]){let u=p.deriveChild(Number(l));for(let d=0;d<n;d++){let h=s+d,m=u.deriveChild(h);if(!m.publicKey)continue;let g=ye({accountIndex:r,chain:t,change:l,index:h});a.push({accountIndex:c,address:Ue({chain:t,network:o,publicKey:m.publicKey}),change:l,index:h,path:Xr(g),pubkey:Br.encode(m.publicKey)})}}return a}function Qs(e,t){switch(e){case fe.BitcoinCash:return Et(t||{});case fe.Zcash:return qt(t);case fe.Bitcoin:case fe.Dogecoin:case fe.Litecoin:case fe.Dash:return te({chain:e,...t});default:throw new Kr("toolbox_utxo_not_supported",{chain:e})}}export{xt as InputSizes,es as MIN_TX_FEE,Fn as OP_RETURN_OVERHEAD,Ke as OutputSizes,Xn as SEGWIT_MARKER_FLAG_WEIGHT,Le as TX_OVERHEAD,Tt as UTXOScriptType,ft as UtxoNetwork,K as accumulative,ee as addInputsAndOutputs,Ft as addressFromKeysGetter,R as assertDerivationIndex,ue as calculateTxSize,F as compileMemo,Et as createBCHToolbox,Er as createCustomUtxoApi,tn as createHDWalletHelpers,te as createUTXOToolbox,qt as createZcashToolbox,Fr as deriveAddressesFromXpub,jr as detectAddressNetwork,Ie as getBchAddressType,Pe as getDustThreshold,we as getInputScriptType,Y as getInputSize,S as getNetworkForChain,De as getOutputSize,ve as getScriptTypeForAddress,oe as getUTXOAccountIndexFromPath,G as getUTXOAccountPath,ye as getUTXOAddressPath,Xt as getUTXOAddressValidator,et as getUtxoAddressType,A as getUtxoApi,Mr as getUtxoNetwork,Qs as getUtxoToolbox,$e as getWitnessOverhead,qe as getZcashAddressType,ze as isSegwitScriptType,Gr as isValidAddress,Re as nonSegwitChains,de as stripPrefix,We as stripToCashAddress,Xe as toCashAddress,z as toLegacyAddress,Fe as tryDecodeAddress,_e as validateBchAddress,Ct as validateUtxoAddress,Ge as validateZcashAddress};
|
|
@@ -520,6 +520,178 @@ export declare const ARBToolbox: ({ provider, ...toolboxParams }: EVMToolboxPara
|
|
|
520
520
|
transfer: ({ assetValue, memo, recipient, feeOptionKey, sender, sweep, ...tx }: import("..").EVMTransferParams) => Promise<string>;
|
|
521
521
|
validateAddress: typeof import("./baseEVMToolbox").validateEVMAddress;
|
|
522
522
|
};
|
|
523
|
+
export declare const ARCToolbox: ({ provider, ...toolboxParams }: EVMToolboxParams) => {
|
|
524
|
+
approve: ({ assetAddress, spenderAddress, feeOptionKey, amount, gasLimitFallback, from: fromParam, nonce, }: import("..").ApproveParams) => Promise<string>;
|
|
525
|
+
approvedAmount: ({ assetAddress, spenderAddress, from }: import("..").IsApprovedParams) => Promise<bigint>;
|
|
526
|
+
broadcastTransaction: (signedTx: string) => Promise<import("ethers").TransactionResponse>;
|
|
527
|
+
call: <T>({ callProvider, contractAddress, abi, funcName, funcParams, txOverrides, feeOption, }: import("..").CallParams) => Promise<T>;
|
|
528
|
+
createApprovalTx: ({ assetAddress, spenderAddress, amount, from: fromParam, nonce, }: import("..").ApproveParams) => Promise<{
|
|
529
|
+
value: string;
|
|
530
|
+
to: string;
|
|
531
|
+
data: string;
|
|
532
|
+
from?: string;
|
|
533
|
+
type?: number;
|
|
534
|
+
nonce?: number;
|
|
535
|
+
gasLimit?: bigint;
|
|
536
|
+
gasPrice?: bigint;
|
|
537
|
+
maxPriorityFeePerGas?: bigint;
|
|
538
|
+
maxFeePerGas?: bigint;
|
|
539
|
+
chainId?: bigint;
|
|
540
|
+
accessList?: import("ethers").AccessList;
|
|
541
|
+
authorizationList?: Array<import("ethers").Authorization>;
|
|
542
|
+
customData?: any;
|
|
543
|
+
blockTag?: import("ethers").BlockTag;
|
|
544
|
+
enableCcipRead?: boolean;
|
|
545
|
+
}>;
|
|
546
|
+
createContract: (address: string, abi: readonly (import("ethers").JsonFragment | import("ethers").Fragment)[]) => import("ethers").Contract;
|
|
547
|
+
createContractTxObject: ({ contractAddress, abi, funcName, funcParams, txOverrides }: import("..").CallParams) => Promise<{
|
|
548
|
+
value: string;
|
|
549
|
+
to: string;
|
|
550
|
+
data: string;
|
|
551
|
+
from?: string;
|
|
552
|
+
type?: number;
|
|
553
|
+
nonce?: number;
|
|
554
|
+
gasLimit?: bigint;
|
|
555
|
+
gasPrice?: bigint;
|
|
556
|
+
maxPriorityFeePerGas?: bigint;
|
|
557
|
+
maxFeePerGas?: bigint;
|
|
558
|
+
chainId?: bigint;
|
|
559
|
+
accessList?: import("ethers").AccessList;
|
|
560
|
+
authorizationList?: Array<import("ethers").Authorization>;
|
|
561
|
+
customData?: any;
|
|
562
|
+
blockTag?: import("ethers").BlockTag;
|
|
563
|
+
enableCcipRead?: boolean;
|
|
564
|
+
}>;
|
|
565
|
+
createTransaction: ({ assetValue, authorizations, memo, recipient, data, feeOptionKey, gasLimit, sender: fromOverride, sweep, type, maxFeePerGas, maxPriorityFeePerGas, gasPrice, ...tx }: import("..").EVMCreateTransactionParams) => Promise<{
|
|
566
|
+
gasLimit: bigint;
|
|
567
|
+
value: string;
|
|
568
|
+
data: string;
|
|
569
|
+
from: string;
|
|
570
|
+
to: string;
|
|
571
|
+
maxFeePerGas: bigint;
|
|
572
|
+
maxPriorityFeePerGas: bigint;
|
|
573
|
+
gasPrice?: undefined;
|
|
574
|
+
type?: number | undefined;
|
|
575
|
+
nonce?: number | undefined;
|
|
576
|
+
} | {
|
|
577
|
+
gasLimit: bigint;
|
|
578
|
+
value: string;
|
|
579
|
+
data: string;
|
|
580
|
+
from: string;
|
|
581
|
+
to: string;
|
|
582
|
+
gasPrice: bigint;
|
|
583
|
+
maxFeePerGas?: undefined;
|
|
584
|
+
maxPriorityFeePerGas?: undefined;
|
|
585
|
+
type?: number | undefined;
|
|
586
|
+
nonce?: number | undefined;
|
|
587
|
+
} | {
|
|
588
|
+
value: string;
|
|
589
|
+
to: string;
|
|
590
|
+
data: string;
|
|
591
|
+
from?: string;
|
|
592
|
+
type?: number;
|
|
593
|
+
nonce?: number;
|
|
594
|
+
gasLimit?: bigint;
|
|
595
|
+
gasPrice?: bigint;
|
|
596
|
+
maxPriorityFeePerGas?: bigint;
|
|
597
|
+
maxFeePerGas?: bigint;
|
|
598
|
+
chainId?: bigint;
|
|
599
|
+
accessList?: import("ethers").AccessList;
|
|
600
|
+
authorizationList?: Array<import("ethers").Authorization>;
|
|
601
|
+
customData?: any;
|
|
602
|
+
blockTag?: import("ethers").BlockTag;
|
|
603
|
+
enableCcipRead?: boolean;
|
|
604
|
+
}>;
|
|
605
|
+
createTransferTx: ({ assetValue, authorizations, memo, recipient, data, feeOptionKey, gasLimit, sender: fromOverride, sweep, type, maxFeePerGas, maxPriorityFeePerGas, gasPrice, ...tx }: import("..").EVMCreateTransactionParams) => Promise<{
|
|
606
|
+
gasLimit: bigint;
|
|
607
|
+
value: string;
|
|
608
|
+
data: string;
|
|
609
|
+
from: string;
|
|
610
|
+
to: string;
|
|
611
|
+
maxFeePerGas: bigint;
|
|
612
|
+
maxPriorityFeePerGas: bigint;
|
|
613
|
+
gasPrice?: undefined;
|
|
614
|
+
type?: number | undefined;
|
|
615
|
+
nonce?: number | undefined;
|
|
616
|
+
} | {
|
|
617
|
+
gasLimit: bigint;
|
|
618
|
+
value: string;
|
|
619
|
+
data: string;
|
|
620
|
+
from: string;
|
|
621
|
+
to: string;
|
|
622
|
+
gasPrice: bigint;
|
|
623
|
+
maxFeePerGas?: undefined;
|
|
624
|
+
maxPriorityFeePerGas?: undefined;
|
|
625
|
+
type?: number | undefined;
|
|
626
|
+
nonce?: number | undefined;
|
|
627
|
+
} | {
|
|
628
|
+
value: string;
|
|
629
|
+
to: string;
|
|
630
|
+
data: string;
|
|
631
|
+
from?: string;
|
|
632
|
+
type?: number;
|
|
633
|
+
nonce?: number;
|
|
634
|
+
gasLimit?: bigint;
|
|
635
|
+
gasPrice?: bigint;
|
|
636
|
+
maxPriorityFeePerGas?: bigint;
|
|
637
|
+
maxFeePerGas?: bigint;
|
|
638
|
+
chainId?: bigint;
|
|
639
|
+
accessList?: import("ethers").AccessList;
|
|
640
|
+
authorizationList?: Array<import("ethers").Authorization>;
|
|
641
|
+
customData?: any;
|
|
642
|
+
blockTag?: import("ethers").BlockTag;
|
|
643
|
+
enableCcipRead?: boolean;
|
|
644
|
+
}>;
|
|
645
|
+
EIP1193SendTransaction: ({ value, ...params }: import("..").EVMTxParams | import("ethers").ContractTransaction) => Promise<string>;
|
|
646
|
+
estimateCall: ({ contractAddress, abi, funcName, funcParams, txOverrides }: import("..").EstimateCallParams) => Promise<bigint>;
|
|
647
|
+
estimateGasLimit: ({ assetValue, recipient, memo, data, sender, funcName, funcParams, txOverrides, }: import("..").EVMTransferParams & {
|
|
648
|
+
assetValue: import("@swapkit/helpers").AssetValue;
|
|
649
|
+
funcName?: string;
|
|
650
|
+
funcParams?: unknown[];
|
|
651
|
+
txOverrides?: import("..").EVMTxParams;
|
|
652
|
+
data?: string;
|
|
653
|
+
}) => Promise<bigint>;
|
|
654
|
+
estimateGasPrices: () => Promise<{
|
|
655
|
+
average: {
|
|
656
|
+
gasPrice?: bigint;
|
|
657
|
+
l1GasPrice?: bigint;
|
|
658
|
+
maxFeePerGas?: bigint;
|
|
659
|
+
maxPriorityFeePerGas?: bigint;
|
|
660
|
+
};
|
|
661
|
+
fast: {
|
|
662
|
+
gasPrice?: bigint;
|
|
663
|
+
l1GasPrice?: bigint;
|
|
664
|
+
maxFeePerGas?: bigint;
|
|
665
|
+
maxPriorityFeePerGas?: bigint;
|
|
666
|
+
};
|
|
667
|
+
fastest: {
|
|
668
|
+
gasPrice?: bigint;
|
|
669
|
+
l1GasPrice?: bigint;
|
|
670
|
+
maxFeePerGas?: bigint;
|
|
671
|
+
maxPriorityFeePerGas?: bigint;
|
|
672
|
+
};
|
|
673
|
+
}>;
|
|
674
|
+
estimateTransactionFee: ({ feeOption, ...txObject }: import("..").EIP1559TxParams & {
|
|
675
|
+
feeOption: FeeOption;
|
|
676
|
+
}) => Promise<import("@swapkit/helpers").AssetValue>;
|
|
677
|
+
getAddress: () => string | Promise<string> | undefined;
|
|
678
|
+
getBalance: (address: string, scamFilter?: boolean) => Promise<import("@swapkit/helpers").AssetValue[]>;
|
|
679
|
+
getNetworkParams: () => import("@swapkit/helpers").NetworkParams | undefined;
|
|
680
|
+
isApproved: ({ assetAddress, spenderAddress, from, amount }: import("..").IsApprovedParams) => Promise<boolean>;
|
|
681
|
+
sendTransaction: ({ feeOptionKey, sweep, ...tx }: import("..").EVMTxParams & {
|
|
682
|
+
feeOptionKey?: FeeOption;
|
|
683
|
+
sweep?: boolean;
|
|
684
|
+
}) => Promise<string>;
|
|
685
|
+
signAuthorization: ((params: {
|
|
686
|
+
address: string;
|
|
687
|
+
nonce?: number | bigint;
|
|
688
|
+
chainId?: bigint;
|
|
689
|
+
}) => Promise<import("ethers").Authorization>) | undefined;
|
|
690
|
+
signMessage: ((message: string | Uint8Array) => Promise<string>) | undefined;
|
|
691
|
+
signTypedData: (({ domain, types, value }: import("..").SignTypedDataParams) => Promise<string>) | undefined;
|
|
692
|
+
transfer: ({ assetValue, memo, recipient, feeOptionKey, sender, sweep, ...tx }: import("..").EVMTransferParams) => Promise<string>;
|
|
693
|
+
validateAddress: typeof import("./baseEVMToolbox").validateEVMAddress;
|
|
694
|
+
};
|
|
523
695
|
export declare const AURORAToolbox: ({ provider, ...toolboxParams }: EVMToolboxParams) => {
|
|
524
696
|
approve: ({ assetAddress, spenderAddress, feeOptionKey, amount, gasLimitFallback, from: fromParam, nonce, }: import("..").ApproveParams) => Promise<string>;
|
|
525
697
|
approvedAmount: ({ assetAddress, spenderAddress, from }: import("..").IsApprovedParams) => Promise<bigint>;
|
|
@@ -2,7 +2,7 @@ import type { ChainSigner, DerivationPathArray, FeeOption, GenericCreateTransact
|
|
|
2
2
|
import { Chain } from "@swapkit/helpers";
|
|
3
3
|
import type { AuthorizationLike, BigNumberish, BrowserProvider, JsonFragment, JsonRpcSigner, Provider, Signer, TransactionRequest, TypedDataField } from "ethers";
|
|
4
4
|
import type { getProvider } from "./index";
|
|
5
|
-
import type { ADIToolbox, ARBToolbox, AURORAToolbox, AVAXToolbox, BASEToolbox, BERAToolbox, BSCToolbox, COREToolbox, CORNToolbox, CROToolbox, ETHToolbox, GNOToolbox, HOODToolbox, HYPEREVMToolbox, LINEAToolbox, MATICToolbox, MEGAETHToolbox, MONADToolbox, OPToolbox, PLASMAToolbox, SONICToolbox, UNIToolbox, XLayerToolbox } from "./toolbox";
|
|
5
|
+
import type { ADIToolbox, ARBToolbox, ARCToolbox, AURORAToolbox, AVAXToolbox, BASEToolbox, BERAToolbox, BSCToolbox, COREToolbox, CORNToolbox, CROToolbox, ETHToolbox, GNOToolbox, HOODToolbox, HYPEREVMToolbox, LINEAToolbox, MATICToolbox, MEGAETHToolbox, MONADToolbox, OPToolbox, PLASMAToolbox, SONICToolbox, UNIToolbox, XLayerToolbox } from "./toolbox";
|
|
6
6
|
export declare enum EthNetwork {
|
|
7
7
|
Test = "goerli",
|
|
8
8
|
Main = "homestead"
|
|
@@ -101,6 +101,7 @@ export type EVMToolboxAsyncParams = {
|
|
|
101
101
|
export type EVMToolboxes = {
|
|
102
102
|
[Chain.Adi]: ReturnType<typeof ADIToolbox>;
|
|
103
103
|
[Chain.Arbitrum]: ReturnType<typeof ARBToolbox>;
|
|
104
|
+
[Chain.Arc]: ReturnType<typeof ARCToolbox>;
|
|
104
105
|
[Chain.Aurora]: ReturnType<typeof AURORAToolbox>;
|
|
105
106
|
[Chain.Avalanche]: ReturnType<typeof AVAXToolbox>;
|
|
106
107
|
[Chain.Base]: ReturnType<typeof BASEToolbox>;
|