@swapkit/toolboxes 5.4.2 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/{chunk-4428244x.js → chunk-exyqap7m.js} +1 -1
  3. package/dist/chunk-ncc6qmj6.js +1 -0
  4. package/dist/{chunk-as9fracn.js → chunk-xdkdc1f0.js} +1 -1
  5. package/dist/{chunk-rn33j2bm.js → chunk-ygq25ce3.js} +2 -2
  6. package/dist/src/aleo/index.js +1 -1
  7. package/dist/src/aptos/index.js +1 -1
  8. package/dist/src/cardano/index.js +1 -1
  9. package/dist/src/cosmos/index.js +1 -1
  10. package/dist/src/evm/index.js +1 -1
  11. package/dist/src/hypercore/index.js +1 -1
  12. package/dist/src/index.js +1 -1
  13. package/dist/src/near/index.js +1 -1
  14. package/dist/src/radix/index.js +1 -1
  15. package/dist/src/ripple/index.js +1 -1
  16. package/dist/src/solana/index.js +1 -1
  17. package/dist/src/starknet/index.js +1 -1
  18. package/dist/src/stellar/index.js +1 -1
  19. package/dist/src/substrate/index.js +1 -1
  20. package/dist/src/sui/index.js +1 -1
  21. package/dist/src/ton/index.js +1 -1
  22. package/dist/src/tron/index.js +1 -1
  23. package/dist/src/utxo/index.js +1 -1
  24. package/dist/types/cosmos/types.d.ts +0 -1
  25. package/dist/types/evm/toolbox/baseEVMToolbox.d.ts +1 -0
  26. package/dist/types/evm/toolbox/op.d.ts +8 -0
  27. package/dist/types/near/toolbox.d.ts +0 -2
  28. package/dist/types/near/types/toolbox.d.ts +0 -2
  29. package/dist/types/solana/index.d.ts +3 -0
  30. package/dist/types/solana/toolbox.d.ts +2 -2
  31. package/dist/types/utxo/__tests__/fixtures/utxo.d.ts +6 -5
  32. package/dist/types/utxo/helpers/addressType.d.ts +8 -0
  33. package/dist/types/utxo/helpers/network.d.ts +4 -0
  34. package/dist/types/utxo/helpers/scriptTypes.d.ts +40 -0
  35. package/dist/types/utxo/helpers/txSize.d.ts +7 -6
  36. package/dist/types/utxo/helpers/xpubDerivation.d.ts +4 -2
  37. package/dist/types/utxo/index.d.ts +1 -1
  38. package/dist/types/utxo/toolbox/bitcoinCash.d.ts +5 -8
  39. package/dist/types/utxo/toolbox/index.d.ts +3 -7
  40. package/dist/types/utxo/toolbox/params.d.ts +24 -19
  41. package/dist/types/utxo/toolbox/utxo.d.ts +51 -36
  42. package/dist/types/utxo/toolbox/validators.d.ts +1 -2
  43. package/dist/types/utxo/toolbox/zcash.d.ts +6 -8
  44. package/dist/types/utxo/types.d.ts +4 -1
  45. package/package.json +2 -2
  46. package/dist/chunk-dssawneq.js +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @swapkit/toolboxes
2
2
 
3
+ ## 6.0.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#424](https://github.com/swapkit/sdk/pull/424) [`3254bf4`](https://github.com/swapkit/sdk/commit/3254bf4d7496289307c2f22edabf627f63479611) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Solana: the payer SOL check for SPL transfers that create the recipient's associated token account is now opt-in. Pass `checkPayerBalance: true` to `createTransaction` or `transfer` to get `toolbox_solana_insufficient_balance` instead of a transaction that fails simulation; by default no extra RPC calls are made and the transaction is returned as before. The recipient token account is still created with `CreateIdempotent`.
8
+ - [#415](https://github.com/swapkit/sdk/pull/415) [`3e3dca0`](https://github.com/swapkit/sdk/commit/3e3dca0aea7625917a797c1a8183c60a47ae5574) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@6.0.1)
9
+
10
+ ## 6.0.0
11
+
12
+ ### Major Changes
13
+
14
+ - [#400](https://github.com/swapkit/sdk/pull/400) [`d64a2a7`](https://github.com/swapkit/sdk/commit/d64a2a77fe56689abc8521a4670d57131bdf2648) Thanks [@ice-chillios](https://github.com/ice-chillios)! - **The SDK targets mainnet only.** The stagenet/testnet switch and everything that backed it are gone: `SKConfig` `envs.isStagenet`, the `StagenetChain` enum with its chain configs, chain ids, node URLs, RPC entries and bech32 prefixes, the Zcash testnet paths in the toolbox, and the APIs that were already marked deprecated. Nodes and RPC endpoints stay configurable per chain through `SKConfig`; wallets always derive mainnet addresses.
15
+ - [#394](https://github.com/swapkit/sdk/pull/394) [`bece151`](https://github.com/swapkit/sdk/commit/bece151c7a6ca3402e740e5627e070cb7900d49c) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - **UTXO addresses are classified by decoding them, against the chain they belong to.**
16
+ - [#395](https://github.com/swapkit/sdk/pull/395) [`1021a3f`](https://github.com/swapkit/sdk/commit/1021a3f7dab8efc55fba573002a16ae5c0ad3a04) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - **UTXO toolboxes encode addresses by an explicit script type, and derive all four single-key standards on Bitcoin and Litecoin: legacy (BIP44, P2PKH), nested segwit (BIP49, P2SH-P2WPKH), native segwit (BIP84, P2WPKH) and taproot (BIP86, P2TR key path).**
17
+ - [#395](https://github.com/swapkit/sdk/pull/395) [`1021a3f`](https://github.com/swapkit/sdk/commit/1021a3f7dab8efc55fba573002a16ae5c0ad3a04) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - **Nested segwit (BIP49) and taproot (BIP86) inputs are built and signed on Bitcoin and Litecoin.** Deriving on them landed with the script-type contract; this release spends from them.
18
+ - [#411](https://github.com/swapkit/sdk/pull/411) [`b5d7cf0`](https://github.com/swapkit/sdk/commit/b5d7cf0ef988a475a910620d53c588990e4766ef) Thanks [@paz-ts](https://github.com/paz-ts)! - Fix EIP-1559 fees on OP-stack chains: the `Fast` and `Fastest` fee options multiplied the priority fee without raising `maxFeePerGas`. An Optimism base fee is a few hundred wei, so the priority fee is almost the whole cap and the multiplied tip ended up above it, which made ethers reject every transaction with `priorityFee cannot be more than maxFee`. Both fields now scale together, and the cap is clamped to the tip.
19
+ - [#420](https://github.com/swapkit/sdk/pull/420) [`ec0d02c`](https://github.com/swapkit/sdk/commit/ec0d02cf4f35de1542bbd6c92324704c7c944c46) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Solana: `createTransaction` now rejects an SPL token transfer that has to create the recipient's associated token account when the sender's SOL can't cover the network fee, the token account rent and its own rent-exempt reserve. It throws `toolbox_solana_insufficient_balance` (with `balance`, `required`, `fee`, `tokenAccountRent` and `rentReserve`) instead of returning a transaction that fails simulation with "Transaction results in an account (0) with insufficient funds for rent". `estimateTransactionFee` is unaffected. The recipient token account is now created with `CreateIdempotent`, so a transfer no longer fails if that account is created between building and broadcasting.
20
+ - [#421](https://github.com/swapkit/sdk/pull/421) [`f311348`](https://github.com/swapkit/sdk/commit/f311348c221764e64da368b06033f9a3c67d7a07) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Add PactSwap support: `ProviderName.PACTSWAP` is now available, and PactSwap routes resolve to the generic `swapkit` plugin for any wallet (like Flashnet and Mayan), which signs the route's prebuilt EVM or Tron transaction. (via @swapkit/helpers@6.0.0)
21
+ - [#410](https://github.com/swapkit/sdk/pull/410) [`89c5e68`](https://github.com/swapkit/sdk/commit/89c5e68d52c094aa8acc1356244060261549a18b) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Fix EVM network switching for extension wallets (Brave, Coinbase Wallet extension, …) on chains they don't ship by default, such as Arc. (via @swapkit/helpers@6.0.0)
22
+ - [#413](https://github.com/swapkit/sdk/pull/413) [`4af82d0`](https://github.com/swapkit/sdk/commit/4af82d0764c4260d0e4df5ffdd1b7809516f14f8) Thanks [@hippocampusSK](https://github.com/hippocampusSK)! - Update the default `rpcUrls` for `Chain.Arc` to three public endpoints, in fallback order: the official `https://rpc.mainnet.arc.io`, `https://arc-rpc.publicnode.com` and `https://arc.drpc.org`. (via @swapkit/helpers@6.0.0)
23
+ - [#415](https://github.com/swapkit/sdk/pull/415) [`3e3dca0`](https://github.com/swapkit/sdk/commit/3e3dca0aea7625917a797c1a8183c60a47ae5574) Thanks [@github-actions](https://github.com/apps/github-actions)! - Update generated token lists. (via @swapkit/helpers@6.0.0)
24
+
3
25
  ## 5.4.2
4
26
 
5
27
  ### Patch Changes
@@ -1,2 +1,2 @@
1
1
  var d=((a)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});
2
- export{d as ha};
2
+ export{d as ja};
@@ -0,0 +1 @@
1
+ import{$ as N,A as m,B as n,C as o,D as p,E as q,F as r,G as s,H as t,I as u,J as v,K as w,L as x,M as y,N as z,O as A,P as B,Q as C,R as D,S as E,T as F,U as G,V as H,W as I,X as J,Y as K,Z as L,_ as M,aa as O,ba as P,ca as Q,da as R,ea as S,fa as T,ga as U,o as a,p as b,q as c,r as d,s as e,t as f,u as g,v as h,w as i,x as j,y as k,z as l}from"./chunk-ygq25ce3.js";import"./chunk-xdkdc1f0.js";import"./chunk-exyqap7m.js";export{w as ADIToolbox,x as ARBToolbox,y as ARCToolbox,z as AURORAToolbox,A as AVAXToolbox,B as BASEToolbox,C as BERAToolbox,D as BSCToolbox,b as BaseEVMToolbox,E as BotanixToolbox,F as COREToolbox,G as CORNToolbox,H as CROToolbox,k as ContractAddress,v as ETHToolbox,I as GNOToolbox,J as HOODToolbox,K as HYPEREVMToolbox,L as LINEAToolbox,M as MATICToolbox,a as MAX_APPROVAL,N as MEGAETHToolbox,O as MONADToolbox,u as OPToolbox,P as PLASMAToolbox,Q as SONICToolbox,R as UNIToolbox,S as XLayerToolbox,e as createContract,t as createOPStackToolbox,j as getChecksumAddressFromAsset,f as getCreateContract,m as getCreateContractTxObject,i as getEIP1193SendTransaction,q as getEVMTxType,n as getEstimateGasPrices,T as getEvmToolbox,U as getEvmToolboxAsync,l as getTokenAddress,d as isBrowserProvider,p as isEIP1559Transaction,o as isEIP7702Transaction,g as isStateChangingCall,r as maxBigInt,s as scaleEIP1559Fees,h as toChecksumAddress,c as validateEVMAddress};
@@ -1,2 +1,2 @@
1
1
  import{AssetValue as o,getChainConfig as l}from"@swapkit/helpers";import{SwapKitApi as m}from"@swapkit/helpers/api";var d=typeof process<"u"&&process.pid?process.pid.toString(36):"",i=0;function C(){function t(){let e=Date.now(),n=i||e;return i=n,e>i?e:n+1}return d+t().toString(36)}function h(t){return async function(n,r=!0){let c=await m.getChainBalance({address:n,chain:t,scamFilter:r}),{baseDecimal:p}=l(t),s=c.map(({identifier:a,value:u,decimal:f})=>new o({decimal:f||p,identifier:a,value:u}));if(!s.some((a)=>a.isGasAsset))return[o.from({chain:t}),...s];return s}}
2
- export{C as fa,h as ga};
2
+ export{C as ha,h as ia};
@@ -1,2 +1,2 @@
1
- import{ga as Be}from"./chunk-as9fracn.js";import{ha as ye}from"./chunk-4428244x.js";import{Chain as P}from"@swapkit/helpers";import{match as Gn}from"ts-pattern";import{Chain as g,getChainConfig as J,getRPCUrl as ht,SKConfig as vt,SwapKitError as j}from"@swapkit/helpers";import{FallbackProvider as Et,getAddress as ve,Interface as _t,JsonRpcProvider as se,Network as Ct}from"ethers";import{match as Ee}from"ts-pattern";function At(e){return new se(e)}async function Sn(e,t){return At(t||await ht(e))}function _e(e){let t=vt.get("rpcUrls")[e]?.filter(Boolean)??[];if(t.length===0)throw new j("helpers_chain_no_public_or_set_rpc_url",{chain:e});let{chainId:n}=J(e),o=Ct.from(Number(n)),[a]=t;if(t.length===1)return new se(a,o,{staticNetwork:o});return new Et(t.map((r,i)=>({priority:i+1,provider:new se(r,o,{staticNetwork:o}),stallTimeout:2000})),o,{quorum:1})}function B(e){return e>0n?`0x${e.toString(16)}`:"0x0"}function Ce(e){let{explorerUrl:t,chainIdHex:n,rpcUrls:o}=J(e);return function(){return e!==g.Ethereum?{...Ft({chain:e}),blockExplorerUrls:[t],chainId:n,rpcUrls:o}:void 0}}function Ae(e){return![g.Adi,g.Arbitrum,g.BinanceSmartChain,g.Robinhood].includes(e)}function Ft({chain:e}){let{name:t,nativeCurrency:n,baseDecimal:o}=J(e);return Ee(e).with(g.Arbitrum,()=>({chainName:"Arbitrum One",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Aurora,()=>({chainName:"Aurora Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Avalanche,()=>({chainName:"Avalanche Network",nativeCurrency:{decimals:o,name:"Avalanche",symbol:e}})).with(g.Base,()=>({chainName:"Base Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Berachain,()=>({chainName:"Berachain",nativeCurrency:{decimals:o,name:"Berachain",symbol:"BERA"}})).with(g.XLayer,()=>({chainName:"X Layer",nativeCurrency:{decimals:o,name:"OKB",symbol:"OKB"}})).with(g.BinanceSmartChain,()=>({chainName:"BNB Smart Chain Mainnet",nativeCurrency:{decimals:o,name:"Binance Coin",symbol:"BNB"}})).with(g.Gnosis,()=>({chainName:"Gnosis",nativeCurrency:{decimals:o,name:"xDAI",symbol:"XDAI"}})).with(g.Optimism,()=>({chainName:"OP Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Polygon,()=>({chainName:"Polygon Mainnet",nativeCurrency:{decimals:o,name:"Polygon",symbol:g.Polygon}})).with(g.Robinhood,()=>({chainName:"Robinhood Chain",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).otherwise(()=>({chainName:t,nativeCurrency:{decimals:o,name:n,symbol:n}}))}async function Fe(e,t){if(!("authorize"in e))throw Error("Signer does not support EIP-7702 authorization. Requires ethers.js v6.14+");let n={...t,nonce:t.nonce!==void 0?BigInt(t.nonce):void 0};return await e.authorize(n)}var he=(e)=>typeof e==="string"&&/^0x[a-fA-F0-9]{64}$/.test(e),Mt=(e)=>{try{return typeof e==="string"&&!!ve(e)}catch{return!1}};function Gt(e,t){let n=t!==void 0?`index ${t}: `:"",o=(a,r)=>{throw new j({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:a,message:`${n}${r}`}})};Ee(e).when(({chainId:a})=>typeof a!=="bigint",()=>o("chainId","chainId must be a bigint")).when(({address:a})=>!Mt(a),()=>o("address","address must be a valid checksummed address")).when(({nonce:a})=>typeof a!=="bigint"||a<0n,()=>o("nonce","nonce must be a non-negative bigint")).when(({signature:a})=>!a,()=>o("signature","signature is required")).when(({signature:a})=>typeof a?.yParity!=="number"||![0,1].includes(a.yParity),()=>o("signature.yParity","yParity must be 0 or 1")).when(({signature:a})=>!he(a?.r),()=>o("signature.r","r must be a 32-byte hex string")).when(({signature:a})=>!he(a?.s),()=>o("signature.s","s must be a 32-byte hex string")).otherwise(()=>{})}function Bt(e){return[{key:"name",type:"string"},{key:"version",type:"string"},{key:"chainId",type:"uint256"},{key:"verifyingContract",type:"address"},{key:"salt",type:"bytes32"}].filter(({key:t})=>e[t]!=null).map(({key:t,type:n})=>({name:t,type:n}))}function ce(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ue(e,t){if(e.isTuple()&&e.components){let n=ce(e.name);return t[n]=e.components.map((o)=>({name:o.name,type:ue(o,t)})),n}if(e.isArray()){let n=e.arrayChildren;if(n?.isTuple()&&n.components){let o=ce(e.name.replace(/s$/,""));return t[o]=n.components.map((a)=>({name:a.name,type:ue(a,t)})),`${o}[]`}return`${n?.type??"bytes"}[]`}return e.type}function le(e,t){if(typeof e==="bigint")return e;if(t?.isTuple()&&typeof e?.toObject==="function"){let n=e.toObject(),o={};for(let[a,r]of(t.components??[]).entries())o[r.name]=le(n[r.name]??e[a],r);return o}if(Array.isArray(e)){let n=t?.arrayChildren;return e.map((o)=>le(o,n??void 0))}return e}function Rn({chain:e,abi:t,data:n,to:o}){let r=new _t(t).parseTransaction({data:n});if(!r)throw new j({errorKey:"toolbox_evm_invalid_params",info:{error:"Could not decode calldata"}});let i={},s=ce(r.name);i[s]=r.fragment.inputs.map((p)=>({name:p.name,type:ue(p,i)}));let c={};for(let[p,y]of r.fragment.inputs.entries())c[y.name]=le(r.args[p],y);let{chainId:l}=J(e),u={chainId:Number(l),verifyingContract:ve(o)},b=Bt(u);return{domain:u,message:c,primaryType:s,types:{EIP712Domain:b,...i}}}function Me(e,t){if(!Array.isArray(e)||e.length===0)throw new j({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{message:"EIP-7702 transactions require at least one authorization"}});for(let[n,o]of e.entries())if(Gt(o,n),t!==void 0&&o.chainId!==t)throw new j({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:"chainId",message:`index ${n}: authorization chainId (${o.chainId}) does not match transaction chainId (${t})`}})}import{Chain as T,derivationPathToString as En,FeeOption as _n,resolveDerivationPath as Cn}from"@swapkit/helpers";import{HDNodeWallet as An}from"ethers";import{match as Fn,P as Ze}from"ts-pattern";var Ge=[{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"aggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes[]",name:"returnData",type:"bytes[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"blockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"getBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getBlockNumber",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockCoinbase",outputs:[{internalType:"address",name:"coinbase",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockDifficulty",outputs:[{internalType:"uint256",name:"difficulty",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockGasLimit",outputs:[{internalType:"uint256",name:"gaslimit",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"addr",type:"address"}],name:"getEthBalance",outputs:[{internalType:"uint256",name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLastBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryAggregate",outputs:[{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryBlockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"}];import{AssetValue as Ot,applyFeeMultiplierToBigInt as M,Chain as O,EVMChains as It,FeeOption as d,isGasAsset as Vt,SwapKitError as m,SwapKitNumber as Q}from"@swapkit/helpers";import{erc20ABI as z}from"@swapkit/helpers/contracts";import{BrowserProvider as St,Contract as Ve,getAddress as ee,getBytes as Rt,Interface as Se,isError as U,resolveAddress as Nt,Transaction as pe}from"ethers";import{match as Re}from"ts-pattern";function Y(e){return{getBalance:Be(e)}}function Dn(e){return e}var be=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function te({chain:e=O.Ethereum,provider:t,signer:n,isEIP1559Compatible:o=!0,estimateGasPrices:a,estimateAdditionalFee:r}){let i=a??X({chain:e,isEIP1559Compatible:o,provider:t}),s=qe({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n});return{approve:Yt({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),approvedAmount:Ue({chain:e,provider:t}),broadcastTransaction:(c)=>t.broadcastTransaction(c),call:ae({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),createApprovalTx:mn({chain:e,provider:t,signer:n}),createContract:Lt({chain:e,provider:t}),createContractTxObject:W({chain:e,provider:t}),createTransaction:s,createTransferTx:s,EIP1193SendTransaction:oe(t),estimateCall:He({provider:t,signer:n}),estimateGasLimit:Zt({chain:e,provider:t,signer:n}),estimateGasPrices:i,estimateTransactionFee:pn({chain:e,isEIP1559Compatible:o,provider:t}),getAddress:()=>n?n.getAddress():void 0,getBalance:Y(e).getBalance,getNetworkParams:Ce(e),isApproved:Jt({chain:e,provider:t}),sendTransaction:Ke({chain:e,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),signAuthorization:en({signer:n}),signMessage:n?(c)=>n.signMessage(c):void 0,signTypedData:n?({domain:c,types:l,value:u})=>n.signTypedData(c,l,u):void 0,transfer:Qt({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),validateAddress:kt}}function kt(e){try{return ee(e),!0}catch{return!1}}function ne(e){return e instanceof St}function ge(e,t,n){return new Ve(e,Se.from(t),n)}function Lt({provider:e}){return function(n,o){return new Ve(n,Se.from(o),e)}}var Dt=["payable","nonpayable"];function Ut({abi:e,funcName:t}){let n=e.find((o)=>o.name===t);if(!n)throw new m("toolbox_evm_no_abi_fragment",{funcName:t});return n.stateMutability&&Dt.includes(n.stateMutability)}function Xn(e){return ee(e)}var Ht=30000,Oe=new WeakMap,Ie=()=>{};function zt(e,t,n){let o=Date.now();for(let[r,i]of e)if(i.held===0&&o-i.at>Ht)e.delete(r);let a=e.get(t);if(!a||n>=a.next){let r={at:o,held:1,next:n+1,released:new Set};return e.set(t,r),{floor:r,nonce:n}}a.held+=1;for(let r of[...a.released].sort((i,s)=>i-s))if(a.released.delete(r),r>=n)return{floor:a,nonce:r};return{floor:a,nonce:a.next++}}async function Ne({address:e,nonce:t,provider:n}){if(t!==void 0&&t!==null)return{nonce:t,release:Ie,settle:Ie};let{chainId:o}=await n.getNetwork(),a=Oe.get(n)??new Map;Oe.set(n,a);let r=`${o}:${e.toLowerCase()}`,i=await n.getTransactionCount(e,"pending"),{floor:s,nonce:c}=zt(a,r,i),l=!1,u=(b)=>{if(l)return;if(l=!0,s.held-=1,s.at=Date.now(),b)s.released.add(c)};return{nonce:c,release:()=>u(!0),settle:()=>u(!1)}}function Z(e,t=0){if(!e||t>3)return"";if(typeof e==="string")return e.toLowerCase();if(typeof e!=="object")return"";let{error:n,info:o,message:a,shortMessage:r}=e;return[(typeof r==="string"?r:typeof a==="string"?a:"").toLowerCase(),Z(n,t+1),Z(o?.error,t+1)].filter(Boolean).join(" ")}function fe(e){if(U(e,"NONCE_EXPIRED")||U(e,"REPLACEMENT_UNDERPRICED"))return!0;let t=Z(e);return/nonce (?:is )?too low/.test(t)||t.includes("replacement transaction underpriced")}function de(e){let t=Z(e);return t.includes("already known")||t.includes("known transaction")||t.includes("already imported")}function ke(e){return U(e,"NETWORK_ERROR")||U(e,"SERVER_ERROR")||U(e,"TIMEOUT")}function Kt(e){return ke(e)||U(e,"UNSUPPORTED_OPERATION")}function Le(e){return ke(e)||de(e)}function De(e,t){return e.getTransaction(t).then((n)=>n!==null,()=>!1)}async function qt({provider:e,signer:t,txObject:n}){try{let o=pe.from(await t.signTransaction(n)).hash;return o&&await De(e,o)?o:null}catch{return null}}function oe(e,t=!1){return function({value:o,...a}){if(!ne(e))throw new m("toolbox_evm_provider_not_eip1193_compatible");let r={...a,gasPrice:"gasPrice"in a?a.gasPrice:void 0,maxFeePerGas:"maxFeePerGas"in a?a.maxFeePerGas:void 0,maxPriorityFeePerGas:"maxPriorityFeePerGas"in a?a.maxPriorityFeePerGas:void 0},{gasLimit:i,gasPrice:s,maxFeePerGas:c,maxPriorityFeePerGas:l,...u}=r,b={...u,...t&&i!==void 0&&{gas:B(BigInt(i))},...t&&s!==void 0&&{gasPrice:B(BigInt(s))},...t&&c!==void 0&&{maxFeePerGas:B(BigInt(c))},...t&&l!==void 0&&{maxPriorityFeePerGas:B(BigInt(l))},value:B(BigInt(o||0))};return e.send("eth_sendTransaction",[b])}}function $n(e,t){let n=Pe(e,t);if(n)return ee(n.toLowerCase());throw new m("toolbox_evm_invalid_gas_asset_address")}var jt=It.reduce((e,t)=>(e[t]="0x0000000000000000000000000000000000000000",e),{}),Wt={...jt,[O.Optimism]:"0x4200000000000000000000000000000000000042",[O.Polygon]:"0x0000000000000000000000000000000000001010"},Xt=[O.Arbitrum,O.Aurora,O.Base,O.Optimism,O.Robinhood];function Pe({chain:e,symbol:t,ticker:n},o){try{let a=e===O.BinanceSmartChain&&t==="BNB"&&n==="BNB",r=e===O.Hyperevm&&t==="HYPE"&&n==="HYPE",i=e===o&&t===o&&n===o,s=Xt.includes(e)&&t==="ETH"&&n==="ETH",c=e===O.Arc&&t==="USDC"&&n==="USDC";if(i||a||r||s||c)return Wt[o];return ee(t.slice(n.length+1).replace(/^0X/,""))}catch{return null}}function W({provider:e}){return async({contractAddress:t,abi:n,funcName:o,funcParams:a=[],txOverrides:r})=>{let i=await ge(t,n,e).getFunction(o).populateTransaction(...a.concat(r).filter((s)=>typeof s<"u"));return{...i,value:B(BigInt(i.value||0))}}}function X({chain:e,provider:t,isEIP1559Compatible:n=!0}){return Re(e).with(O.Gnosis,()=>async function(){try{let{gasPrice:a,maxPriorityFeePerGas:r}=await t.getFeeData();if(!a||r===null)throw new m("toolbox_evm_no_fee_data");return{[d.Average]:{maxFeePerGas:M(a,d.Average),maxPriorityFeePerGas:M(r,d.Average)},[d.Fast]:{maxFeePerGas:M(a,d.Fast),maxPriorityFeePerGas:M(r,d.Fast)},[d.Fastest]:{maxFeePerGas:M(a,d.Fastest),maxPriorityFeePerGas:M(r,d.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).with(O.Arbitrum,()=>async function(){try{let{gasPrice:a}=await t.getFeeData();if(!a)throw new m("toolbox_evm_no_fee_data");let r=a*12n/10n;return{[d.Average]:{gasPrice:r},[d.Fast]:{gasPrice:M(r,d.Fast)},[d.Fastest]:{gasPrice:M(r,d.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).otherwise(()=>async function(){try{let{maxFeePerGas:a,maxPriorityFeePerGas:r,gasPrice:i}=await t.getFeeData();if(n){if(a===null||r===null)throw new m("toolbox_evm_no_fee_data");return{[d.Average]:{maxFeePerGas:a,maxPriorityFeePerGas:r},[d.Fast]:{maxFeePerGas:M(a,d.Fast),maxPriorityFeePerGas:M(r,d.Fast)},[d.Fastest]:{maxFeePerGas:M(a,d.Fastest),maxPriorityFeePerGas:M(r,d.Fastest)}}}if(!i)throw new m("toolbox_evm_no_gas_price");return{[d.Average]:{gasPrice:i},[d.Fast]:{gasPrice:M(i,d.Fast)},[d.Fastest]:{gasPrice:M(i,d.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}})}async function $t({chain:e,contract:t,contractProvider:n,feeOption:o,funcName:a,funcParams:r,isEIP1559Compatible:i,provider:s,signer:c,txOverrides:l}){let u=l?.from||await c.getAddress();if(!u)throw new m("toolbox_evm_no_signer_address");let b=t.connect(c),p=X({chain:e,isEIP1559Compatible:i,provider:s}),[{maxFeePerGas:y,maxPriorityFeePerGas:f,gasPrice:x},F]=await Promise.all([p().then((_)=>_[o]),t.getFunction(a).estimateGas(...r,l)]),C=typeof u==="string"?u:await Nt(u,n),{nonce:G,release:R,settle:k}=await Ne({address:C,nonce:l?.nonce,provider:c.provider??s});try{let _=await b[a](...r,{...l,gasLimit:F,gasPrice:x,maxFeePerGas:y,maxPriorityFeePerGas:f,nonce:G});return typeof _?.hash==="string"?_?.hash:_}catch(_){if(fe(_)){let E=l?.nonce!=null?"caller":"pending",w={address:C,error:_,nonce:G,nonceSource:E};throw new m({errorKey:"toolbox_evm_nonce_conflict",info:w},w)}if(!Le(_))R();throw _}finally{k()}}function ae({provider:e,isEIP1559Compatible:t,signer:n,chain:o}){return async function({callProvider:r,contractAddress:i,abi:s,funcName:c,funcParams:l=[],txOverrides:u={},feeOption:b=d.Fast}){let p=r||e;if(!i)throw new m("toolbox_evm_invalid_params",{error:"contractAddress must be provided"});let y=Ut({abi:s,funcName:c});if(y&&ne(p)&&n){let F=W({chain:o,provider:p}),C=u?.from||await n?.getAddress(),G=await F({abi:s,contractAddress:i,funcName:c,funcParams:l,txOverrides:{...u,from:C}});return oe(p)(G)}let f=ge(i,s,p);if(y){if(!n)throw new m("toolbox_evm_no_signer");return $t({chain:o,contract:f,contractProvider:p,feeOption:b,funcName:c,funcParams:l,isEIP1559Compatible:t,provider:e,signer:n,txOverrides:u})}let x=await f[c]?.(...l);return typeof x?.hash==="string"?x?.hash:x}}function Ue({provider:e,chain:t}){return function({assetAddress:o,spenderAddress:a,from:r}){return ae({chain:t,isEIP1559Compatible:!0,provider:e})({abi:z,contractAddress:o,funcName:"allowance",funcParams:[r,a]})}}function Jt({provider:e,chain:t}){return async function({assetAddress:o,spenderAddress:a,from:r,amount:i=be}){let s=await Ue({chain:t,provider:e})({assetAddress:o,from:r,spenderAddress:a});return Q.fromBigInt(s).gte(Q.fromBigInt(BigInt(i)))}}function Yt({signer:e,isEIP1559Compatible:t=!0,provider:n,chain:o}){return async function({assetAddress:r,spenderAddress:i,feeOptionKey:s=d.Fast,amount:c,gasLimitFallback:l,from:u,nonce:b}){let p=[i,BigInt(c||be)],y=await e?.getAddress()||u,f={abi:z,contractAddress:r,funcName:"approve",funcParams:p,signer:e,txOverrides:{from:y}};if(ne(n)){let F=W({chain:o,provider:n}),C=oe(n),G=await F(f);return C(G)}return ae({chain:o,isEIP1559Compatible:t,provider:n,signer:e})({...f,feeOption:s,funcParams:p,txOverrides:{from:y,gasLimit:l?BigInt(l.toString()):void 0,nonce:b}})}}function Qt({chain:e,estimateGasPrices:t,estimateAdditionalFee:n,signer:o,isEIP1559Compatible:a=!0,provider:r}){return async function({assetValue:s,memo:c,recipient:l,feeOptionKey:u=d.Fast,sender:b,sweep:p,...y}){let f=b||await o?.getAddress(),x=Ke({chain:e,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o});if(!f)throw new m("toolbox_evm_no_from_address");let F=await qe({chain:e,estimateAdditionalFee:n,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o})({assetValue:s,feeOptionKey:u,memo:c,recipient:l,sender:f,sweep:p,...y});return x({...F,feeOptionKey:u,sweep:p})}}function He({provider:e,signer:t}){return function({contractAddress:o,abi:a,funcName:r,funcParams:i=[],txOverrides:s}){if(!o)throw new m("toolbox_evm_no_contract_address");let c=ge(o,a,e);return t?c.connect(t).getFunction(r).estimateGas(...i,s):c.getFunction(r).estimateGas(...i,s)}}function Zt({provider:e,signer:t}){return async function({assetValue:o,recipient:a,memo:r,data:i,sender:s,funcName:c,funcParams:l,txOverrides:u}){let b=o.bigIntValue,p=o.isGasAsset?null:Pe(o,o.chain);if(p&&c)return He({provider:e,signer:t})({abi:z,contractAddress:p,funcName:c,funcParams:l,txOverrides:u});let{hexlify:y,toUtf8Bytes:f}=await import("ethers");return e.estimateGas({data:i?i:r?y(f(r)):void 0,from:s,to:a,value:b})}}function en({signer:e}){if(!e)return;return(t)=>Fe(e,t)}var ze=(e)=>e.type===4||(e.authorizations?.length??0)>0,tn=(e)=>!ze(e)&&(e.type===2||!!e.maxFeePerGas||!!e.maxPriorityFeePerGas),nn=(e,t=!0)=>{if(ze(e))return"eip7702";if(tn(e)||t)return"eip1559";return"legacy"};function on(e,t){if(e==="legacy"){if(t.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{gasPrice:B(t.gasPrice)}}if(t.maxFeePerGas===void 0||t.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{maxFeePerGas:B(t.maxFeePerGas),maxPriorityFeePerGas:B(t.maxPriorityFeePerGas)}}function Ke({chain:e,estimateGasPrices:t,provider:n,signer:o,isEIP1559Compatible:a=!0}){return async function({feeOptionKey:i=d.Fast,sweep:s,...c}){let{from:l,to:u,data:b,value:p,...y}=c;if(!o)throw new m("toolbox_evm_no_signer");if(!u)throw new m("toolbox_evm_no_to_address");let f={...y,data:b||"0x",from:l,to:u,value:BigInt(p||0)};if(ne(n))return oe(n,s)(f);let x=l||await o.getAddress(),{chainId:F}=await n.getNetwork(),C=o.provider??n,{nonce:G,release:R,settle:k}=await Ne({address:x,nonce:c.nonce,provider:C}),_=async()=>{let E=nn(f,a);if(E==="eip7702")Me(f.authorizations||[],F);let w=Re(E).with("eip7702",()=>4).with("eip1559",()=>2).otherwise(()=>0),V={...f,chainId:F,nonce:G,type:w,...E==="eip7702"&&{authorizationList:f.authorizations}},A=t??X({chain:e,isEIP1559Compatible:a,provider:n}),S=(E==="legacy"?f.gasPrice!==void 0:f.maxFeePerGas!==void 0&&f.maxPriorityFeePerGas!==void 0)?{}:on(E,(await A())[i]),h;try{h=B(f.gasLimit?BigInt(f.gasLimit):await n.estimateGas(V)*11n/10n)}catch(I){throw new m("toolbox_evm_error_estimating_gas_limit",{error:I})}return{...V,gasLimit:h,...S}};try{let E=await _().catch((w)=>{throw R(),w});try{return(await o.sendTransaction(E)).hash}catch(w){let V=c.nonce!=null?"caller":"pending",A={address:x,error:w,nonce:G,nonceSource:V};if(fe(w))throw new m({errorKey:"toolbox_evm_nonce_conflict",info:A},A);if(de(w)){let h=await qt({provider:C,signer:o,txObject:{...E,from:x}});if(h)return h;throw new m({errorKey:"toolbox_evm_tx_already_known",info:A},A)}if(!Kt(w))throw R(),new m({errorKey:"toolbox_evm_error_sending_transaction",info:A},A);let L=U(w,"UNSUPPORTED_OPERATION"),S;try{S=await o.signTransaction({...E,from:x})}catch(h){if(L)R();let I={...A,fallbackError:h};throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:I},I)}try{return(await C.broadcastTransaction(S)).hash}catch(h){let I={...A,fallbackError:h};if(de(h)){let H=pe.from(S).hash;if(H)return H}if(fe(h)){let H=pe.from(S).hash;if(H&&await De(C,H))return H;throw new m({errorKey:"toolbox_evm_nonce_conflict",info:I},I)}if(L&&!Le(h))R();throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:I},I)}}}finally{k()}}}function D(e,t){throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{balance:e.toString(),fee:t.toString()}})}function an(e,t){if(t){if(e.maxFeePerGas===void 0||e.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{feeFields:{maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas},feePerGas:e.maxFeePerGas}}if(e.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{feeFields:{gasPrice:e.gasPrice},feePerGas:e.gasPrice}}function rn(e,t){if(e>t)return e;return t}function sn(e){return Rt(e).reduce((t,n)=>t+(n===0?4n:16n),21000n)}function me(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("insufficient funds")||n.includes("insufficient balance")||n.includes("gas required exceeds allowance")}async function cn({balance:e,estimateAdditionalFee:t,feeOptionKey:n,l2Reserve:o,sweepTx:a,valueBeforeL1Fee:r}){if(!t)return 0n;let i=await t({...a,value:r})??0n,s=M(i,n),c=r-s;if(c<=0n)D(e,o+s);let l=await t({...a,value:c})??i;return M(rn(i,l),n)}async function un({chain:e,data:t,estimateGasPrices:n,estimateAdditionalFee:o,feeOptionKey:a,from:r,isEIP1559Compatible:i,provider:s,recipient:c,transaction:l}){let u=await s.getBalance(r),b=n??X({chain:e,isEIP1559Compatible:i,provider:s}),{feeFields:p,feePerGas:y}=an((await b())[a],i),f={...l,...p,data:t,from:r,to:c},x=sn(t)*y;if(u-x<=0n)D(u,x);let F=(u-x)/2n,C;try{C=await s.estimateGas({...f,value:F})}catch(h){if(!me(h))throw h;try{C=await s.estimateGas({...f,value:0n})}catch(I){if(me(I))D(u,x);throw I}}let G=C*y;if(u-G<=0n)D(u,G);let _=C*11n/10n*y,E=u>_?u-_:0n,w;try{w=await s.estimateGas({...f,value:E})}catch(h){if(!me(h))throw h;D(u,_)}let V=w*y,A=u-V;if(A<=0n)D(u,V);let L=await cn({balance:u,estimateAdditionalFee:o,feeOptionKey:a,l2Reserve:V,sweepTx:{...f,gasLimit:w},valueBeforeL1Fee:A}),S=A-L;if(S<=0n)D(u,V+L);return{...f,gasLimit:w,value:B(S)}}async function ln({chain:e,contractAddress:t,from:n,provider:o}){let a=await ae({chain:e,provider:o})({abi:z,contractAddress:t,funcName:"balanceOf",funcParams:[n]});if(typeof a!=="bigint")throw new m({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid ERC20 balance"}});return a}function qe({chain:e,estimateAdditionalFee:t,estimateGasPrices:n,isEIP1559Compatible:o=!0,provider:a,signer:r}){return async function({assetValue:s,authorizations:c,memo:l,recipient:u,data:b,feeOptionKey:p=d.Fast,gasLimit:y,sender:f,sweep:x,type:F,maxFeePerGas:C,maxPriorityFeePerGas:G,gasPrice:R,...k}){let _=s.getBaseValue("bigint"),E=f||await r?.getAddress();if(!E)throw new m("toolbox_evm_no_from_address");if(x&&(F===4||(c?.length??0)>0))throw new m({errorKey:"toolbox_not_supported",info:{chain:e,reason:"EIP-7702 sweep transactions are not supported"}});if(Vt(s)){let{hexlify:L,toUtf8Bytes:S}=await import("ethers"),h=b||L(S(l||""));if(!x)return{...k,...c!==void 0&&{authorizations:c},data:h,from:E,...y!==void 0&&{gasLimit:y},to:u,...F!==void 0&&{type:F},value:B(_)};return un({chain:e,data:h,estimateAdditionalFee:t,estimateGasPrices:n,feeOptionKey:p,from:E,isEIP1559Compatible:o,provider:a,recipient:u,transaction:{nonce:k.nonce,type:F}})}let w=Pe(s,e);if(!w)throw new m("toolbox_evm_no_contract_address");let V=W({chain:e,provider:a}),A=x?await ln({chain:e,contractAddress:w,from:E,provider:a}):_;if(x&&A<=0n)throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{asset:s.toString(),balance:A.toString()}});return V({abi:z,contractAddress:w,funcName:"transfer",funcParams:[u,A],txOverrides:{from:E,gasLimit:y,gasPrice:R,maxFeePerGas:C,maxPriorityFeePerGas:G,nonce:k.nonce}})}}function mn({provider:e,signer:t,chain:n}){return async function({assetAddress:a,spenderAddress:r,amount:i,from:s,nonce:c}){let l=await t?.getAddress()||s,u=W({chain:n,provider:e}),b=["bigint","number"].includes(typeof i)?i:i||be;return await u({abi:z,contractAddress:a,funcName:"approve",funcParams:[r,BigInt(b)],txOverrides:{from:l,nonce:c}})}}function pn({provider:e,isEIP1559Compatible:t=!0,chain:n}){return async function({feeOption:a=d.Fast,...r}){let s=await X({chain:n,isEIP1559Compatible:t,provider:e})(),c=await e.estimateGas(r),l=Ot.from({chain:n}),{gasPrice:u,maxFeePerGas:b,maxPriorityFeePerGas:p}=s[a];if(!t&&u)return l.set(Q.fromBigInt(u*c,l.decimal));if(b&&p){let y=(b+p)*c;return l.set(Q.fromBigInt(y,l.decimal))}throw new m("toolbox_evm_no_gas_price")}}import{applyFeeMultiplierToBigInt as K,Chain as Xe,derivationPathToString as fn,FeeOption as N,getChainConfig as dn,resolveDerivationPath as yn,SwapKitError as q}from"@swapkit/helpers";import{Contract as bn,HDNodeWallet as gn}from"ethers";import{match as Pn,P as We}from"ts-pattern";var je=[{inputs:[{internalType:"address",name:"_owner",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"DecimalsUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"GasPriceUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"L1BaseFeeUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"OverheadUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"ScalarUpdated",type:"event"},{inputs:[],name:"decimals",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"gasPrice",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1Fee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1GasUsed",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_gasUsed",type:"uint256"}],name:"getOperatorFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"l1BaseFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"overhead",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"scalar",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_decimals",type:"uint256"}],name:"setDecimals",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_gasPrice",type:"uint256"}],name:"setGasPrice",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_baseFee",type:"uint256"}],name:"setL1BaseFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_overhead",type:"uint256"}],name:"setOverhead",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_scalar",type:"uint256"}],name:"setScalar",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"}];var xn="0x420000000000000000000000000000000000000f";function re(e){return new bn(xn,je,e)}function $e(e){return async function(){let n=re(e);if(n&&"l1BaseFee"in n)return await n?.l1BaseFee();return}}function Je(e){return async function({from:n,to:o,nonce:a,...r}){let{Transaction:i}=await import("ethers");if(!o)throw new q("toolbox_evm_invalid_transaction",{error:"Missing to address"});return i.from({...r,authorizationList:r.authorizationList,nonce:a??(n?await e.getTransactionCount(n,"pending"):0),to:o}).unsignedSerialized}}function xe(e,t){return async function(o){let a=re(e),r=o.chainId??t??(await e.getNetwork()).chainId,i=await Je(e)({...o,chainId:r});if(a&&"getL1Fee"in a){let s=await a.getL1Fee(i);if(typeof s!=="bigint")throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack L1 fee"}});return s}return}}function Te(e){return async function(n){let o=re(e);if(o&&"getOperatorFee"in o){let a=await o.getOperatorFee(n);if(typeof a!=="bigint")throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack operator fee"}});return a}return 0n}}function Tn(e,t){let n=xe(e,t),o=Te(e);return async function(r){if(r.gasLimit===void 0||r.gasLimit===null)throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Missing gas limit for OP-stack fee estimation"}});let[i,s]=await Promise.all([n(r),o(BigInt(r.gasLimit.toString()))]);return(i??0n)+s}}function Ye(e){return async function(n){let a=(await e.getFeeData()).gasPrice??0n,r=await e.estimateGas(n);return a*r}}function wn(e){return async function(n){let o=await xe(e)(n)??0n,a=await Ye(e)(n),r=n.gasLimit??await e.estimateGas(n),i=await Te(e)(BigInt(r.toString()));return o+a+i}}function hn(e){return async function(n){let o=re(e),a=await Je(e)(n);if(o&&"getL1GasUsed"in o)return o.getL1GasUsed(a)}}function vn(e){return async function(){try{let{maxFeePerGas:n,maxPriorityFeePerGas:o,gasPrice:a}=await e.getFeeData(),r=await $e(e)(),i=a;if(!(n&&o))throw new q("toolbox_evm_no_fee_data");return{[N.Average]:{gasPrice:i,l1GasPrice:r,maxFeePerGas:n,maxPriorityFeePerGas:o},[N.Fast]:{gasPrice:K(i,N.Fast),l1GasPrice:K(r||0n,N.Fast),maxFeePerGas:n,maxPriorityFeePerGas:K(o,N.Fast)},[N.Fastest]:{gasPrice:K(i,N.Fastest),l1GasPrice:K(r||0n,N.Fastest),maxFeePerGas:n,maxPriorityFeePerGas:K(o,N.Fastest)}}}catch(n){throw new q("toolbox_evm_gas_estimation_error",{error:n.msg??n.toString()})}}}function ie(e){return function({provider:n,...o}){let a=Pn(o).with({phrase:We.string},({phrase:p,derivationPath:y,index:f=0})=>gn.fromPhrase(p,void 0,fn(yn({chain:e,derivationPath:y,index:f}))).connect(n)).with({signer:We.any},({signer:p})=>p).otherwise(()=>{return}),r=$e(n),i=BigInt(dn(e).chainId),s=xe(n,i),c=Tn(n,i),l=Te(n),u=e===Xe.Optimism?vn(n):void 0;return{...te({chain:e,estimateAdditionalFee:c,estimateGasPrices:u,provider:n,signer:a}),estimateL1Gas:hn(n),estimateL1GasCost:s,estimateL2GasCost:Ye(n),estimateOperatorFee:l,estimateTotalGasCost:wn(n),getBalance:Y(e).getBalance,getL1GasPrice:r}}}var Qe=ie(Xe.Optimism);function et(e){let t=v(T.Ethereum)(e);async function n(o,a="0x5ba1e12693dc8f9c48aad8770482f4739beed696",r="aggregate",i=_n.Fast){let s=await t.createContractTxObject({abi:Ge,contractAddress:a,funcName:r,funcParams:[o]});return t.sendTransaction({...s,feeOptionKey:i})}return{...t,multicall:n}}var tt=v(T.Adi),nt=v(T.Arbitrum),ot=v(T.Arc),at=v(T.Aurora),rt=v(T.Avalanche),it=ie(T.Base),st=v(T.Berachain),ct=v(T.BinanceSmartChain),po=v(T.Botanix),ut=v(T.Core),lt=v(T.Corn),mt=v(T.Cronos),pt=v(T.Gnosis),ft=v(T.Robinhood),dt=v(T.Hyperevm),yt=v(T.Linea),bt=v(T.Polygon),gt=v(T.MegaETH),Pt=v(T.Monad),xt=v(T.Plasma),we=v(T.Sonic),Tt=ie(T.Unichain),wt=v(T.XLayer);function v(e){return function({provider:n,...o}){let a=Ae(e),r=Fn(o).with({phrase:Ze.string},({phrase:s,derivationPath:c,index:l=0})=>An.fromPhrase(s,void 0,En(Cn({chain:e,derivationPath:c,index:l}))).connect(n)).with({signer:Ze.any},({signer:s})=>s).otherwise(()=>{return});return te({chain:e,isEIP1559Compatible:a,provider:n,signer:r})}}function Bn(e,t){return Gn(e).with(P.Adi,()=>tt(t)).with(P.Arbitrum,()=>nt(t)).with(P.Arc,()=>ot(t)).with(P.Aurora,()=>at(t)).with(P.Avalanche,()=>rt(t)).with(P.Base,()=>it(t)).with(P.Berachain,()=>st(t)).with(P.BinanceSmartChain,()=>ct(t)).with(P.Botanix,()=>we(t)).with(P.Core,()=>ut(t)).with(P.Corn,()=>lt(t)).with(P.Cronos,()=>mt(t)).with(P.Ethereum,()=>et(t)).with(P.Gnosis,()=>pt(t)).with(P.Hyperevm,()=>dt(t)).with(P.Linea,()=>yt(t)).with(P.MegaETH,()=>gt(t)).with(P.Monad,()=>Pt(t)).with(P.Optimism,()=>Qe(t)).with(P.Plasma,()=>xt(t)).with(P.Polygon,()=>bt(t)).with(P.Robinhood,()=>ft(t)).with(P.Sonic,()=>we(t)).with(P.Unichain,()=>Tt(t)).with(P.XLayer,()=>wt(t)).exhaustive()}async function Po(e,t){let n={...t,provider:t?.provider||_e(e)};return Bn(e,n)}
2
- export{Y as b,Dn as c,At as d,Sn as e,_e as f,B as g,Ce as h,Ae as i,Fe as j,Gt as k,Bt as l,Rn as m,Me as n,be as o,te as p,kt as q,ne as r,ge as s,Lt as t,Ut as u,Xn as v,oe as w,$n as x,Wt as y,Pe as z,W as A,X as B,ze as C,tn as D,nn as E,ie as F,Qe as G,et as H,tt as I,nt as J,ot as K,at as L,rt as M,it as N,st as O,ct as P,po as Q,ut as R,lt as S,mt as T,pt as U,ft as V,dt as W,yt as X,bt as Y,gt as Z,Pt as _,xt as $,we as aa,Tt as ba,wt as ca,Bn as da,Po as ea};
1
+ import{ia as Ie}from"./chunk-xdkdc1f0.js";import{ja as ye}from"./chunk-exyqap7m.js";import{Chain as x}from"@swapkit/helpers";import{match as Bn}from"ts-pattern";import{Chain as g,getChainConfig as J,getRPCUrl as Et,SKConfig as _t,SwapKitError as j}from"@swapkit/helpers";import{FallbackProvider as Ct,getAddress as _e,Interface as Ft,JsonRpcProvider as se,Network as At}from"ethers";import{match as Ce}from"ts-pattern";function Mt(e){return new se(e)}async function Rn(e,t){return Mt(t||await Et(e))}function Fe(e){let t=_t.get("rpcUrls")[e]?.filter(Boolean)??[];if(t.length===0)throw new j("helpers_chain_no_public_or_set_rpc_url",{chain:e});let{chainId:n}=J(e),o=At.from(Number(n)),[a]=t;if(t.length===1)return new se(a,o,{staticNetwork:o});return new Ct(t.map((r,i)=>({priority:i+1,provider:new se(r,o,{staticNetwork:o}),stallTimeout:2000})),o,{quorum:1})}function B(e){return e>0n?`0x${e.toString(16)}`:"0x0"}function Ae(e){let{explorerUrl:t,chainIdHex:n,rpcUrls:o}=J(e);return function(){return e!==g.Ethereum?{...Gt({chain:e}),blockExplorerUrls:[t],chainId:n,rpcUrls:o}:void 0}}function Me(e){return![g.Adi,g.Arbitrum,g.BinanceSmartChain,g.Robinhood].includes(e)}function Gt({chain:e}){let{name:t,nativeCurrency:n,baseDecimal:o}=J(e);return Ce(e).with(g.Arbitrum,()=>({chainName:"Arbitrum One",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Aurora,()=>({chainName:"Aurora Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Avalanche,()=>({chainName:"Avalanche Network",nativeCurrency:{decimals:o,name:"Avalanche",symbol:e}})).with(g.Base,()=>({chainName:"Base Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Berachain,()=>({chainName:"Berachain",nativeCurrency:{decimals:o,name:"Berachain",symbol:"BERA"}})).with(g.XLayer,()=>({chainName:"X Layer",nativeCurrency:{decimals:o,name:"OKB",symbol:"OKB"}})).with(g.BinanceSmartChain,()=>({chainName:"BNB Smart Chain Mainnet",nativeCurrency:{decimals:o,name:"Binance Coin",symbol:"BNB"}})).with(g.Gnosis,()=>({chainName:"Gnosis",nativeCurrency:{decimals:o,name:"xDAI",symbol:"XDAI"}})).with(g.Optimism,()=>({chainName:"OP Mainnet",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).with(g.Polygon,()=>({chainName:"Polygon Mainnet",nativeCurrency:{decimals:o,name:"Polygon",symbol:g.Polygon}})).with(g.Robinhood,()=>({chainName:"Robinhood Chain",nativeCurrency:{decimals:o,name:"Ethereum",symbol:g.Ethereum}})).otherwise(()=>({chainName:t,nativeCurrency:{decimals:o,name:n,symbol:n}}))}async function Ge(e,t){if(!("authorize"in e))throw Error("Signer does not support EIP-7702 authorization. Requires ethers.js v6.14+");let n={...t,nonce:t.nonce!==void 0?BigInt(t.nonce):void 0};return await e.authorize(n)}var Ee=(e)=>typeof e==="string"&&/^0x[a-fA-F0-9]{64}$/.test(e),Bt=(e)=>{try{return typeof e==="string"&&!!_e(e)}catch{return!1}};function Ot(e,t){let n=t!==void 0?`index ${t}: `:"",o=(a,r)=>{throw new j({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:a,message:`${n}${r}`}})};Ce(e).when(({chainId:a})=>typeof a!=="bigint",()=>o("chainId","chainId must be a bigint")).when(({address:a})=>!Bt(a),()=>o("address","address must be a valid checksummed address")).when(({nonce:a})=>typeof a!=="bigint"||a<0n,()=>o("nonce","nonce must be a non-negative bigint")).when(({signature:a})=>!a,()=>o("signature","signature is required")).when(({signature:a})=>typeof a?.yParity!=="number"||![0,1].includes(a.yParity),()=>o("signature.yParity","yParity must be 0 or 1")).when(({signature:a})=>!Ee(a?.r),()=>o("signature.r","r must be a 32-byte hex string")).when(({signature:a})=>!Ee(a?.s),()=>o("signature.s","s must be a 32-byte hex string")).otherwise(()=>{})}function It(e){return[{key:"name",type:"string"},{key:"version",type:"string"},{key:"chainId",type:"uint256"},{key:"verifyingContract",type:"address"},{key:"salt",type:"bytes32"}].filter(({key:t})=>e[t]!=null).map(({key:t,type:n})=>({name:t,type:n}))}function ce(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ue(e,t){if(e.isTuple()&&e.components){let n=ce(e.name);return t[n]=e.components.map((o)=>({name:o.name,type:ue(o,t)})),n}if(e.isArray()){let n=e.arrayChildren;if(n?.isTuple()&&n.components){let o=ce(e.name.replace(/s$/,""));return t[o]=n.components.map((a)=>({name:a.name,type:ue(a,t)})),`${o}[]`}return`${n?.type??"bytes"}[]`}return e.type}function le(e,t){if(typeof e==="bigint")return e;if(t?.isTuple()&&typeof e?.toObject==="function"){let n=e.toObject(),o={};for(let[a,r]of(t.components??[]).entries())o[r.name]=le(n[r.name]??e[a],r);return o}if(Array.isArray(e)){let n=t?.arrayChildren;return e.map((o)=>le(o,n??void 0))}return e}function Nn({chain:e,abi:t,data:n,to:o}){let r=new Ft(t).parseTransaction({data:n});if(!r)throw new j({errorKey:"toolbox_evm_invalid_params",info:{error:"Could not decode calldata"}});let i={},s=ce(r.name);i[s]=r.fragment.inputs.map((p)=>({name:p.name,type:ue(p,i)}));let c={};for(let[p,y]of r.fragment.inputs.entries())c[y.name]=le(r.args[p],y);let{chainId:l}=J(e),u={chainId:Number(l),verifyingContract:_e(o)},b=It(u);return{domain:u,message:c,primaryType:s,types:{EIP712Domain:b,...i}}}function Be(e,t){if(!Array.isArray(e)||e.length===0)throw new j({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{message:"EIP-7702 transactions require at least one authorization"}});for(let[n,o]of e.entries())if(Ot(o,n),t!==void 0&&o.chainId!==t)throw new j({errorKey:"toolbox_evm_invalid_eip7702_authorization",info:{field:"chainId",message:`index ${n}: authorization chainId (${o.chainId}) does not match transaction chainId (${t})`}})}import{Chain as T,derivationPathToString as _n,FeeOption as Cn,resolveDerivationPath as Fn}from"@swapkit/helpers";import{HDNodeWallet as An}from"ethers";import{match as Mn,P as tt}from"ts-pattern";var Oe=[{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"aggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes[]",name:"returnData",type:"bytes[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"blockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],name:"getBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"getBlockNumber",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockCoinbase",outputs:[{internalType:"address",name:"coinbase",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockDifficulty",outputs:[{internalType:"uint256",name:"difficulty",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockGasLimit",outputs:[{internalType:"uint256",name:"gaslimit",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCurrentBlockTimestamp",outputs:[{internalType:"uint256",name:"timestamp",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"addr",type:"address"}],name:"getEthBalance",outputs:[{internalType:"uint256",name:"balance",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLastBlockHash",outputs:[{internalType:"bytes32",name:"blockHash",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryAggregate",outputs:[{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bool",name:"requireSuccess",type:"bool"},{components:[{internalType:"address",name:"target",type:"address"},{internalType:"bytes",name:"callData",type:"bytes"}],internalType:"struct Multicall2.Call[]",name:"calls",type:"tuple[]"}],name:"tryBlockAndAggregate",outputs:[{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"bytes32",name:"blockHash",type:"bytes32"},{components:[{internalType:"bool",name:"success",type:"bool"},{internalType:"bytes",name:"returnData",type:"bytes"}],internalType:"struct Multicall2.Result[]",name:"returnData",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"}];import{AssetValue as Vt,applyFeeMultiplierToBigInt as M,Chain as O,EVMChains as St,FeeOption as d,isGasAsset as Rt,SwapKitError as m,SwapKitNumber as Q}from"@swapkit/helpers";import{erc20ABI as z}from"@swapkit/helpers/contracts";import{BrowserProvider as Nt,Contract as Re,getAddress as ee,getBytes as kt,Interface as Ne,isError as U,resolveAddress as Lt,Transaction as pe}from"ethers";import{match as ke}from"ts-pattern";function Y(e){return{getBalance:Ie(e)}}function Un(e){return e}var be=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function te({chain:e=O.Ethereum,provider:t,signer:n,isEIP1559Compatible:o=!0,estimateGasPrices:a,estimateAdditionalFee:r}){let i=a??X({chain:e,isEIP1559Compatible:o,provider:t}),s=We({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n});return{approve:Zt({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),approvedAmount:ze({chain:e,provider:t}),broadcastTransaction:(c)=>t.broadcastTransaction(c),call:ae({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),createApprovalTx:pn({chain:e,provider:t,signer:n}),createContract:Ut({chain:e,provider:t}),createContractTxObject:W({chain:e,provider:t}),createTransaction:s,createTransferTx:s,EIP1193SendTransaction:oe(t),estimateCall:Ke({provider:t,signer:n}),estimateGasLimit:tn({chain:e,provider:t,signer:n}),estimateGasPrices:i,estimateTransactionFee:fn({chain:e,isEIP1559Compatible:o,provider:t}),getAddress:()=>n?n.getAddress():void 0,getBalance:Y(e).getBalance,getNetworkParams:Ae(e),isApproved:Qt({chain:e,provider:t}),sendTransaction:je({chain:e,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),signAuthorization:nn({signer:n}),signMessage:n?(c)=>n.signMessage(c):void 0,signTypedData:n?({domain:c,types:l,value:u})=>n.signTypedData(c,l,u):void 0,transfer:en({chain:e,estimateAdditionalFee:r,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),validateAddress:Dt}}function Dt(e){try{return ee(e),!0}catch{return!1}}function ne(e){return e instanceof Nt}function ge(e,t,n){return new Re(e,Ne.from(t),n)}function Ut({provider:e}){return function(n,o){return new Re(n,Ne.from(o),e)}}var Ht=["payable","nonpayable"];function zt({abi:e,funcName:t}){let n=e.find((o)=>o.name===t);if(!n)throw new m("toolbox_evm_no_abi_fragment",{funcName:t});return n.stateMutability&&Ht.includes(n.stateMutability)}function $n(e){return ee(e)}var Kt=30000,Ve=new WeakMap,Se=()=>{};function qt(e,t,n){let o=Date.now();for(let[r,i]of e)if(i.held===0&&o-i.at>Kt)e.delete(r);let a=e.get(t);if(!a||n>=a.next){let r={at:o,held:1,next:n+1,released:new Set};return e.set(t,r),{floor:r,nonce:n}}a.held+=1;for(let r of[...a.released].sort((i,s)=>i-s))if(a.released.delete(r),r>=n)return{floor:a,nonce:r};return{floor:a,nonce:a.next++}}async function Le({address:e,nonce:t,provider:n}){if(t!==void 0&&t!==null)return{nonce:t,release:Se,settle:Se};let{chainId:o}=await n.getNetwork(),a=Ve.get(n)??new Map;Ve.set(n,a);let r=`${o}:${e.toLowerCase()}`,i=await n.getTransactionCount(e,"pending"),{floor:s,nonce:c}=qt(a,r,i),l=!1,u=(b)=>{if(l)return;if(l=!0,s.held-=1,s.at=Date.now(),b)s.released.add(c)};return{nonce:c,release:()=>u(!0),settle:()=>u(!1)}}function Z(e,t=0){if(!e||t>3)return"";if(typeof e==="string")return e.toLowerCase();if(typeof e!=="object")return"";let{error:n,info:o,message:a,shortMessage:r}=e;return[(typeof r==="string"?r:typeof a==="string"?a:"").toLowerCase(),Z(n,t+1),Z(o?.error,t+1)].filter(Boolean).join(" ")}function fe(e){if(U(e,"NONCE_EXPIRED")||U(e,"REPLACEMENT_UNDERPRICED"))return!0;let t=Z(e);return/nonce (?:is )?too low/.test(t)||t.includes("replacement transaction underpriced")}function de(e){let t=Z(e);return t.includes("already known")||t.includes("known transaction")||t.includes("already imported")}function De(e){return U(e,"NETWORK_ERROR")||U(e,"SERVER_ERROR")||U(e,"TIMEOUT")}function jt(e){return De(e)||U(e,"UNSUPPORTED_OPERATION")}function Ue(e){return De(e)||de(e)}function He(e,t){return e.getTransaction(t).then((n)=>n!==null,()=>!1)}async function Wt({provider:e,signer:t,txObject:n}){try{let o=pe.from(await t.signTransaction(n)).hash;return o&&await He(e,o)?o:null}catch{return null}}function oe(e,t=!1){return function({value:o,...a}){if(!ne(e))throw new m("toolbox_evm_provider_not_eip1193_compatible");let r={...a,gasPrice:"gasPrice"in a?a.gasPrice:void 0,maxFeePerGas:"maxFeePerGas"in a?a.maxFeePerGas:void 0,maxPriorityFeePerGas:"maxPriorityFeePerGas"in a?a.maxPriorityFeePerGas:void 0},{gasLimit:i,gasPrice:s,maxFeePerGas:c,maxPriorityFeePerGas:l,...u}=r,b={...u,...t&&i!==void 0&&{gas:B(BigInt(i))},...t&&s!==void 0&&{gasPrice:B(BigInt(s))},...t&&c!==void 0&&{maxFeePerGas:B(BigInt(c))},...t&&l!==void 0&&{maxPriorityFeePerGas:B(BigInt(l))},value:B(BigInt(o||0))};return e.send("eth_sendTransaction",[b])}}function Jn(e,t){let n=xe(e,t);if(n)return ee(n.toLowerCase());throw new m("toolbox_evm_invalid_gas_asset_address")}var Xt=St.reduce((e,t)=>(e[t]="0x0000000000000000000000000000000000000000",e),{}),$t={...Xt,[O.Optimism]:"0x4200000000000000000000000000000000000042",[O.Polygon]:"0x0000000000000000000000000000000000001010"},Jt=[O.Arbitrum,O.Aurora,O.Base,O.Optimism,O.Robinhood];function xe({chain:e,symbol:t,ticker:n},o){try{let a=e===O.BinanceSmartChain&&t==="BNB"&&n==="BNB",r=e===O.Hyperevm&&t==="HYPE"&&n==="HYPE",i=e===o&&t===o&&n===o,s=Jt.includes(e)&&t==="ETH"&&n==="ETH",c=e===O.Arc&&t==="USDC"&&n==="USDC";if(i||a||r||s||c)return $t[o];return ee(t.slice(n.length+1).replace(/^0X/,""))}catch{return null}}function W({provider:e}){return async({contractAddress:t,abi:n,funcName:o,funcParams:a=[],txOverrides:r})=>{let i=await ge(t,n,e).getFunction(o).populateTransaction(...a.concat(r).filter((s)=>typeof s<"u"));return{...i,value:B(BigInt(i.value||0))}}}function X({chain:e,provider:t,isEIP1559Compatible:n=!0}){return ke(e).with(O.Gnosis,()=>async function(){try{let{gasPrice:a,maxPriorityFeePerGas:r}=await t.getFeeData();if(!a||r===null)throw new m("toolbox_evm_no_fee_data");return{[d.Average]:{maxFeePerGas:M(a,d.Average),maxPriorityFeePerGas:M(r,d.Average)},[d.Fast]:{maxFeePerGas:M(a,d.Fast),maxPriorityFeePerGas:M(r,d.Fast)},[d.Fastest]:{maxFeePerGas:M(a,d.Fastest),maxPriorityFeePerGas:M(r,d.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).with(O.Arbitrum,()=>async function(){try{let{gasPrice:a}=await t.getFeeData();if(!a)throw new m("toolbox_evm_no_fee_data");let r=a*12n/10n;return{[d.Average]:{gasPrice:r},[d.Fast]:{gasPrice:M(r,d.Fast)},[d.Fastest]:{gasPrice:M(r,d.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}}).otherwise(()=>async function(){try{let{maxFeePerGas:a,maxPriorityFeePerGas:r,gasPrice:i}=await t.getFeeData();if(n){if(a===null||r===null)throw new m("toolbox_evm_no_fee_data");return{[d.Average]:{maxFeePerGas:a,maxPriorityFeePerGas:r},[d.Fast]:{maxFeePerGas:M(a,d.Fast),maxPriorityFeePerGas:M(r,d.Fast)},[d.Fastest]:{maxFeePerGas:M(a,d.Fastest),maxPriorityFeePerGas:M(r,d.Fastest)}}}if(!i)throw new m("toolbox_evm_no_gas_price");return{[d.Average]:{gasPrice:i},[d.Fast]:{gasPrice:M(i,d.Fast)},[d.Fastest]:{gasPrice:M(i,d.Fastest)}}}catch(a){throw new m("toolbox_evm_gas_estimation_error",{error:a.msg??a.toString()})}})}async function Yt({chain:e,contract:t,contractProvider:n,feeOption:o,funcName:a,funcParams:r,isEIP1559Compatible:i,provider:s,signer:c,txOverrides:l}){let u=l?.from||await c.getAddress();if(!u)throw new m("toolbox_evm_no_signer_address");let b=t.connect(c),p=X({chain:e,isEIP1559Compatible:i,provider:s}),[{maxFeePerGas:y,maxPriorityFeePerGas:f,gasPrice:P},A]=await Promise.all([p().then((_)=>_[o]),t.getFunction(a).estimateGas(...r,l)]),C=typeof u==="string"?u:await Lt(u,n),{nonce:G,release:R,settle:k}=await Le({address:C,nonce:l?.nonce,provider:c.provider??s});try{let _=await b[a](...r,{...l,gasLimit:A,gasPrice:P,maxFeePerGas:y,maxPriorityFeePerGas:f,nonce:G});return typeof _?.hash==="string"?_?.hash:_}catch(_){if(fe(_)){let E=l?.nonce!=null?"caller":"pending",w={address:C,error:_,nonce:G,nonceSource:E};throw new m({errorKey:"toolbox_evm_nonce_conflict",info:w},w)}if(!Ue(_))R();throw _}finally{k()}}function ae({provider:e,isEIP1559Compatible:t,signer:n,chain:o}){return async function({callProvider:r,contractAddress:i,abi:s,funcName:c,funcParams:l=[],txOverrides:u={},feeOption:b=d.Fast}){let p=r||e;if(!i)throw new m("toolbox_evm_invalid_params",{error:"contractAddress must be provided"});let y=zt({abi:s,funcName:c});if(y&&ne(p)&&n){let A=W({chain:o,provider:p}),C=u?.from||await n?.getAddress(),G=await A({abi:s,contractAddress:i,funcName:c,funcParams:l,txOverrides:{...u,from:C}});return oe(p)(G)}let f=ge(i,s,p);if(y){if(!n)throw new m("toolbox_evm_no_signer");return Yt({chain:o,contract:f,contractProvider:p,feeOption:b,funcName:c,funcParams:l,isEIP1559Compatible:t,provider:e,signer:n,txOverrides:u})}let P=await f[c]?.(...l);return typeof P?.hash==="string"?P?.hash:P}}function ze({provider:e,chain:t}){return function({assetAddress:o,spenderAddress:a,from:r}){return ae({chain:t,isEIP1559Compatible:!0,provider:e})({abi:z,contractAddress:o,funcName:"allowance",funcParams:[r,a]})}}function Qt({provider:e,chain:t}){return async function({assetAddress:o,spenderAddress:a,from:r,amount:i=be}){let s=await ze({chain:t,provider:e})({assetAddress:o,from:r,spenderAddress:a});return Q.fromBigInt(s).gte(Q.fromBigInt(BigInt(i)))}}function Zt({signer:e,isEIP1559Compatible:t=!0,provider:n,chain:o}){return async function({assetAddress:r,spenderAddress:i,feeOptionKey:s=d.Fast,amount:c,gasLimitFallback:l,from:u,nonce:b}){let p=[i,BigInt(c||be)],y=await e?.getAddress()||u,f={abi:z,contractAddress:r,funcName:"approve",funcParams:p,signer:e,txOverrides:{from:y}};if(ne(n)){let A=W({chain:o,provider:n}),C=oe(n),G=await A(f);return C(G)}return ae({chain:o,isEIP1559Compatible:t,provider:n,signer:e})({...f,feeOption:s,funcParams:p,txOverrides:{from:y,gasLimit:l?BigInt(l.toString()):void 0,nonce:b}})}}function en({chain:e,estimateGasPrices:t,estimateAdditionalFee:n,signer:o,isEIP1559Compatible:a=!0,provider:r}){return async function({assetValue:s,memo:c,recipient:l,feeOptionKey:u=d.Fast,sender:b,sweep:p,...y}){let f=b||await o?.getAddress(),P=je({chain:e,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o});if(!f)throw new m("toolbox_evm_no_from_address");let A=await We({chain:e,estimateAdditionalFee:n,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o})({assetValue:s,feeOptionKey:u,memo:c,recipient:l,sender:f,sweep:p,...y});return P({...A,feeOptionKey:u,sweep:p})}}function Ke({provider:e,signer:t}){return function({contractAddress:o,abi:a,funcName:r,funcParams:i=[],txOverrides:s}){if(!o)throw new m("toolbox_evm_no_contract_address");let c=ge(o,a,e);return t?c.connect(t).getFunction(r).estimateGas(...i,s):c.getFunction(r).estimateGas(...i,s)}}function tn({provider:e,signer:t}){return async function({assetValue:o,recipient:a,memo:r,data:i,sender:s,funcName:c,funcParams:l,txOverrides:u}){let b=o.bigIntValue,p=o.isGasAsset?null:xe(o,o.chain);if(p&&c)return Ke({provider:e,signer:t})({abi:z,contractAddress:p,funcName:c,funcParams:l,txOverrides:u});let{hexlify:y,toUtf8Bytes:f}=await import("ethers");return e.estimateGas({data:i?i:r?y(f(r)):void 0,from:s,to:a,value:b})}}function nn({signer:e}){if(!e)return;return(t)=>Ge(e,t)}var qe=(e)=>e.type===4||(e.authorizations?.length??0)>0,on=(e)=>!qe(e)&&(e.type===2||!!e.maxFeePerGas||!!e.maxPriorityFeePerGas),an=(e,t=!0)=>{if(qe(e))return"eip7702";if(on(e)||t)return"eip1559";return"legacy"};function rn(e,t){if(e==="legacy"){if(t.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{gasPrice:B(t.gasPrice)}}if(t.maxFeePerGas===void 0||t.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{maxFeePerGas:B(t.maxFeePerGas),maxPriorityFeePerGas:B(t.maxPriorityFeePerGas)}}function je({chain:e,estimateGasPrices:t,provider:n,signer:o,isEIP1559Compatible:a=!0}){return async function({feeOptionKey:i=d.Fast,sweep:s,...c}){let{from:l,to:u,data:b,value:p,...y}=c;if(!o)throw new m("toolbox_evm_no_signer");if(!u)throw new m("toolbox_evm_no_to_address");let f={...y,data:b||"0x",from:l,to:u,value:BigInt(p||0)};if(ne(n))return oe(n,s)(f);let P=l||await o.getAddress(),{chainId:A}=await n.getNetwork(),C=o.provider??n,{nonce:G,release:R,settle:k}=await Le({address:P,nonce:c.nonce,provider:C}),_=async()=>{let E=an(f,a);if(E==="eip7702")Be(f.authorizations||[],A);let w=ke(E).with("eip7702",()=>4).with("eip1559",()=>2).otherwise(()=>0),V={...f,chainId:A,nonce:G,type:w,...E==="eip7702"&&{authorizationList:f.authorizations}},F=t??X({chain:e,isEIP1559Compatible:a,provider:n}),S=(E==="legacy"?f.gasPrice!==void 0:f.maxFeePerGas!==void 0&&f.maxPriorityFeePerGas!==void 0)?{}:rn(E,(await F())[i]),h;try{h=B(f.gasLimit?BigInt(f.gasLimit):await n.estimateGas(V)*11n/10n)}catch(I){throw new m("toolbox_evm_error_estimating_gas_limit",{error:I})}return{...V,gasLimit:h,...S}};try{let E=await _().catch((w)=>{throw R(),w});try{return(await o.sendTransaction(E)).hash}catch(w){let V=c.nonce!=null?"caller":"pending",F={address:P,error:w,nonce:G,nonceSource:V};if(fe(w))throw new m({errorKey:"toolbox_evm_nonce_conflict",info:F},F);if(de(w)){let h=await Wt({provider:C,signer:o,txObject:{...E,from:P}});if(h)return h;throw new m({errorKey:"toolbox_evm_tx_already_known",info:F},F)}if(!jt(w))throw R(),new m({errorKey:"toolbox_evm_error_sending_transaction",info:F},F);let L=U(w,"UNSUPPORTED_OPERATION"),S;try{S=await o.signTransaction({...E,from:P})}catch(h){if(L)R();let I={...F,fallbackError:h};throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:I},I)}try{return(await C.broadcastTransaction(S)).hash}catch(h){let I={...F,fallbackError:h};if(de(h)){let H=pe.from(S).hash;if(H)return H}if(fe(h)){let H=pe.from(S).hash;if(H&&await He(C,H))return H;throw new m({errorKey:"toolbox_evm_nonce_conflict",info:I},I)}if(L&&!Ue(h))R();throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:I},I)}}}finally{k()}}}function D(e,t){throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{balance:e.toString(),fee:t.toString()}})}function sn(e,t){if(t){if(e.maxFeePerGas===void 0||e.maxPriorityFeePerGas===void 0)throw new m("toolbox_evm_no_fee_data");return{feeFields:{maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas},feePerGas:e.maxFeePerGas}}if(e.gasPrice===void 0)throw new m("toolbox_evm_no_fee_data");return{feeFields:{gasPrice:e.gasPrice},feePerGas:e.gasPrice}}function Pe(e,t){if(e>t)return e;return t}function cn(e){return kt(e).reduce((t,n)=>t+(n===0?4n:16n),21000n)}function me(e){let n=(e instanceof Error?e.message:String(e)).toLowerCase();return n.includes("insufficient funds")||n.includes("insufficient balance")||n.includes("gas required exceeds allowance")}async function un({balance:e,estimateAdditionalFee:t,feeOptionKey:n,l2Reserve:o,sweepTx:a,valueBeforeL1Fee:r}){if(!t)return 0n;let i=await t({...a,value:r})??0n,s=M(i,n),c=r-s;if(c<=0n)D(e,o+s);let l=await t({...a,value:c})??i;return M(Pe(i,l),n)}async function ln({chain:e,data:t,estimateGasPrices:n,estimateAdditionalFee:o,feeOptionKey:a,from:r,isEIP1559Compatible:i,provider:s,recipient:c,transaction:l}){let u=await s.getBalance(r),b=n??X({chain:e,isEIP1559Compatible:i,provider:s}),{feeFields:p,feePerGas:y}=sn((await b())[a],i),f={...l,...p,data:t,from:r,to:c},P=cn(t)*y;if(u-P<=0n)D(u,P);let A=(u-P)/2n,C;try{C=await s.estimateGas({...f,value:A})}catch(h){if(!me(h))throw h;try{C=await s.estimateGas({...f,value:0n})}catch(I){if(me(I))D(u,P);throw I}}let G=C*y;if(u-G<=0n)D(u,G);let _=C*11n/10n*y,E=u>_?u-_:0n,w;try{w=await s.estimateGas({...f,value:E})}catch(h){if(!me(h))throw h;D(u,_)}let V=w*y,F=u-V;if(F<=0n)D(u,V);let L=await un({balance:u,estimateAdditionalFee:o,feeOptionKey:a,l2Reserve:V,sweepTx:{...f,gasLimit:w},valueBeforeL1Fee:F}),S=F-L;if(S<=0n)D(u,V+L);return{...f,gasLimit:w,value:B(S)}}async function mn({chain:e,contractAddress:t,from:n,provider:o}){let a=await ae({chain:e,provider:o})({abi:z,contractAddress:t,funcName:"balanceOf",funcParams:[n]});if(typeof a!=="bigint")throw new m({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid ERC20 balance"}});return a}function We({chain:e,estimateAdditionalFee:t,estimateGasPrices:n,isEIP1559Compatible:o=!0,provider:a,signer:r}){return async function({assetValue:s,authorizations:c,memo:l,recipient:u,data:b,feeOptionKey:p=d.Fast,gasLimit:y,sender:f,sweep:P,type:A,maxFeePerGas:C,maxPriorityFeePerGas:G,gasPrice:R,...k}){let _=s.getBaseValue("bigint"),E=f||await r?.getAddress();if(!E)throw new m("toolbox_evm_no_from_address");if(P&&(A===4||(c?.length??0)>0))throw new m({errorKey:"toolbox_not_supported",info:{chain:e,reason:"EIP-7702 sweep transactions are not supported"}});if(Rt(s)){let{hexlify:L,toUtf8Bytes:S}=await import("ethers"),h=b||L(S(l||""));if(!P)return{...k,...c!==void 0&&{authorizations:c},data:h,from:E,...y!==void 0&&{gasLimit:y},to:u,...A!==void 0&&{type:A},value:B(_)};return ln({chain:e,data:h,estimateAdditionalFee:t,estimateGasPrices:n,feeOptionKey:p,from:E,isEIP1559Compatible:o,provider:a,recipient:u,transaction:{nonce:k.nonce,type:A}})}let w=xe(s,e);if(!w)throw new m("toolbox_evm_no_contract_address");let V=W({chain:e,provider:a}),F=P?await mn({chain:e,contractAddress:w,from:E,provider:a}):_;if(P&&F<=0n)throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{asset:s.toString(),balance:F.toString()}});return V({abi:z,contractAddress:w,funcName:"transfer",funcParams:[u,F],txOverrides:{from:E,gasLimit:y,gasPrice:R,maxFeePerGas:C,maxPriorityFeePerGas:G,nonce:k.nonce}})}}function pn({provider:e,signer:t,chain:n}){return async function({assetAddress:a,spenderAddress:r,amount:i,from:s,nonce:c}){let l=await t?.getAddress()||s,u=W({chain:n,provider:e}),b=["bigint","number"].includes(typeof i)?i:i||be;return await u({abi:z,contractAddress:a,funcName:"approve",funcParams:[r,BigInt(b)],txOverrides:{from:l,nonce:c}})}}function fn({provider:e,isEIP1559Compatible:t=!0,chain:n}){return async function({feeOption:a=d.Fast,...r}){let s=await X({chain:n,isEIP1559Compatible:t,provider:e})(),c=await e.estimateGas(r),l=Vt.from({chain:n}),{gasPrice:u,maxFeePerGas:b,maxPriorityFeePerGas:p}=s[a];if(!t&&u)return l.set(Q.fromBigInt(u*c,l.decimal));if(b&&p){let y=(b+p)*c;return l.set(Q.fromBigInt(y,l.decimal))}throw new m("toolbox_evm_no_gas_price")}}import{applyFeeMultiplierToBigInt as K,Chain as Je,derivationPathToString as dn,FeeOption as N,getChainConfig as yn,resolveDerivationPath as bn,SwapKitError as q}from"@swapkit/helpers";import{Contract as gn,HDNodeWallet as xn}from"ethers";import{match as Pn,P as $e}from"ts-pattern";var Xe=[{inputs:[{internalType:"address",name:"_owner",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"DecimalsUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"GasPriceUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"L1BaseFeeUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"OverheadUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint256",name:"",type:"uint256"}],name:"ScalarUpdated",type:"event"},{inputs:[],name:"decimals",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"gasPrice",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1Fee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes",name:"_data",type:"bytes"}],name:"getL1GasUsed",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_gasUsed",type:"uint256"}],name:"getOperatorFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"l1BaseFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"overhead",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"scalar",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_decimals",type:"uint256"}],name:"setDecimals",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_gasPrice",type:"uint256"}],name:"setGasPrice",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_baseFee",type:"uint256"}],name:"setL1BaseFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_overhead",type:"uint256"}],name:"setOverhead",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"_scalar",type:"uint256"}],name:"setScalar",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"}];var Tn="0x420000000000000000000000000000000000000f";function re(e){return new gn(Tn,Xe,e)}function Ye(e){return async function(){let n=re(e);if(n&&"l1BaseFee"in n)return await n?.l1BaseFee();return}}function Qe(e){return async function({from:n,to:o,nonce:a,...r}){let{Transaction:i}=await import("ethers");if(!o)throw new q("toolbox_evm_invalid_transaction",{error:"Missing to address"});return i.from({...r,authorizationList:r.authorizationList,nonce:a??(n?await e.getTransactionCount(n,"pending"):0),to:o}).unsignedSerialized}}function we(e,t){return async function(o){let a=re(e),r=o.chainId??t??(await e.getNetwork()).chainId,i=await Qe(e)({...o,chainId:r});if(a&&"getL1Fee"in a){let s=await a.getL1Fee(i);if(typeof s!=="bigint")throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack L1 fee"}});return s}return}}function he(e){return async function(n){let o=re(e);if(o&&"getOperatorFee"in o){let a=await o.getOperatorFee(n);if(typeof a!=="bigint")throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Invalid OP-stack operator fee"}});return a}return 0n}}function wn(e,t){let n=we(e,t),o=he(e);return async function(r){if(r.gasLimit===void 0||r.gasLimit===null)throw new q({errorKey:"toolbox_evm_invalid_transaction",info:{error:"Missing gas limit for OP-stack fee estimation"}});let[i,s]=await Promise.all([n(r),o(BigInt(r.gasLimit.toString()))]);return(i??0n)+s}}function Ze(e){return async function(n){let a=(await e.getFeeData()).gasPrice??0n,r=await e.estimateGas(n);return a*r}}function hn(e){return async function(n){let o=await we(e)(n)??0n,a=await Ze(e)(n),r=n.gasLimit??await e.estimateGas(n),i=await he(e)(BigInt(r.toString()));return o+a+i}}function vn(e){return async function(n){let o=re(e),a=await Qe(e)(n);if(o&&"getL1GasUsed"in o)return o.getL1GasUsed(a)}}function Te({feeOption:e,maxFeePerGas:t,maxPriorityFeePerGas:n}){let o=K(t,e),a=K(n,e);return{maxFeePerGas:Pe(o,a),maxPriorityFeePerGas:a}}function En(e){return async function(){try{let{maxFeePerGas:n,maxPriorityFeePerGas:o,gasPrice:a}=await e.getFeeData(),r=await Ye(e)(),i=a;if(!(n&&o))throw new q("toolbox_evm_no_fee_data");return{[N.Average]:{gasPrice:i,l1GasPrice:r,...Te({feeOption:N.Average,maxFeePerGas:n,maxPriorityFeePerGas:o})},[N.Fast]:{gasPrice:K(i,N.Fast),l1GasPrice:K(r||0n,N.Fast),...Te({feeOption:N.Fast,maxFeePerGas:n,maxPriorityFeePerGas:o})},[N.Fastest]:{gasPrice:K(i,N.Fastest),l1GasPrice:K(r||0n,N.Fastest),...Te({feeOption:N.Fastest,maxFeePerGas:n,maxPriorityFeePerGas:o})}}}catch(n){throw new q("toolbox_evm_gas_estimation_error",{error:n.msg??n.toString()})}}}function ie(e){return function({provider:n,...o}){let a=Pn(o).with({phrase:$e.string},({phrase:p,derivationPath:y,index:f=0})=>xn.fromPhrase(p,void 0,dn(bn({chain:e,derivationPath:y,index:f}))).connect(n)).with({signer:$e.any},({signer:p})=>p).otherwise(()=>{return}),r=Ye(n),i=BigInt(yn(e).chainId),s=we(n,i),c=wn(n,i),l=he(n),u=e===Je.Optimism?En(n):void 0;return{...te({chain:e,estimateAdditionalFee:c,estimateGasPrices:u,provider:n,signer:a}),estimateL1Gas:vn(n),estimateL1GasCost:s,estimateL2GasCost:Ze(n),estimateOperatorFee:l,estimateTotalGasCost:hn(n),getBalance:Y(e).getBalance,getL1GasPrice:r}}}var et=ie(Je.Optimism);function nt(e){let t=v(T.Ethereum)(e);async function n(o,a="0x5ba1e12693dc8f9c48aad8770482f4739beed696",r="aggregate",i=Cn.Fast){let s=await t.createContractTxObject({abi:Oe,contractAddress:a,funcName:r,funcParams:[o]});return t.sendTransaction({...s,feeOptionKey:i})}return{...t,multicall:n}}var ot=v(T.Adi),at=v(T.Arbitrum),rt=v(T.Arc),it=v(T.Aurora),st=v(T.Avalanche),ct=ie(T.Base),ut=v(T.Berachain),lt=v(T.BinanceSmartChain),fo=v(T.Botanix),mt=v(T.Core),pt=v(T.Corn),ft=v(T.Cronos),dt=v(T.Gnosis),yt=v(T.Robinhood),bt=v(T.Hyperevm),gt=v(T.Linea),xt=v(T.Polygon),Pt=v(T.MegaETH),Tt=v(T.Monad),wt=v(T.Plasma),ve=v(T.Sonic),ht=ie(T.Unichain),vt=v(T.XLayer);function v(e){return function({provider:n,...o}){let a=Me(e),r=Mn(o).with({phrase:tt.string},({phrase:s,derivationPath:c,index:l=0})=>An.fromPhrase(s,void 0,_n(Fn({chain:e,derivationPath:c,index:l}))).connect(n)).with({signer:tt.any},({signer:s})=>s).otherwise(()=>{return});return te({chain:e,isEIP1559Compatible:a,provider:n,signer:r})}}function On(e,t){return Bn(e).with(x.Adi,()=>ot(t)).with(x.Arbitrum,()=>at(t)).with(x.Arc,()=>rt(t)).with(x.Aurora,()=>it(t)).with(x.Avalanche,()=>st(t)).with(x.Base,()=>ct(t)).with(x.Berachain,()=>ut(t)).with(x.BinanceSmartChain,()=>lt(t)).with(x.Botanix,()=>ve(t)).with(x.Core,()=>mt(t)).with(x.Corn,()=>pt(t)).with(x.Cronos,()=>ft(t)).with(x.Ethereum,()=>nt(t)).with(x.Gnosis,()=>dt(t)).with(x.Hyperevm,()=>bt(t)).with(x.Linea,()=>gt(t)).with(x.MegaETH,()=>Pt(t)).with(x.Monad,()=>Tt(t)).with(x.Optimism,()=>et(t)).with(x.Plasma,()=>wt(t)).with(x.Polygon,()=>xt(t)).with(x.Robinhood,()=>yt(t)).with(x.Sonic,()=>ve(t)).with(x.Unichain,()=>ht(t)).with(x.XLayer,()=>vt(t)).exhaustive()}async function Po(e,t){let n={...t,provider:t?.provider||Fe(e)};return On(e,n)}
2
+ export{Y as b,Un as c,Mt as d,Rn as e,Fe as f,B as g,Ae as h,Me as i,Ge as j,Ot as k,It as l,Nn as m,Be as n,be as o,te as p,Dt as q,ne as r,ge as s,Ut as t,zt as u,$n as v,oe as w,Jn as x,$t as y,xe as z,W as A,X as B,qe as C,on as D,an as E,Pe as F,Te as G,ie as H,et as I,nt as J,ot as K,at as L,rt as M,it as N,st as O,ct as P,ut as Q,lt as R,fo as S,mt as T,pt as U,ft as V,dt as W,yt as X,bt as Y,gt as Z,xt as _,Pt as $,Tt as aa,wt as ba,ve as ca,ht as da,vt as ea,On as fa,Po as ga};
@@ -1 +1 @@
1
- import{ga as it}from"../../chunk-as9fracn.js";import{ha as x}from"../../chunk-4428244x.js";import{hmac as Y}from"@noble/hashes/hmac.js";import{sha512 as J}from"@noble/hashes/sha2.js";import{Chain as F,getChainConfig as gt,SKConfig as At,SwapKitError as w}from"@swapkit/helpers";var mt=/^aleo1[ac-hj-np-z02-9]{58}$/,pt=/^[a-z0-9_]+\.aleo$/,v=/^at1[ac-hj-np-z02-9]+$/,ht=new TextEncoder().encode("bls12_377 seed"),H=2147483648,O=1e6,E="credits.aleo",U="transfer_public",Q=1e6,Z=2000000;function tt(t,n){if(!m(t))return[];let r=m(t.transaction)?t.transaction:t,s=r.execution,a=m(r.fee)?r.fee.transition:void 0;return[...m(s)&&Array.isArray(s.transitions)?s.transitions:[],...m(a)?[a]:[]].flatMap((y)=>{if(!m(y)||!Array.isArray(y.outputs))return[];if(n&&y.program!==n)return[];return y.outputs.flatMap((h)=>m(h)&&h.type==="record"&&typeof h.value==="string"?[h.value]:[])})}function et(t){return t.reduce((n,r)=>r.spent?n:n+r.microcredits,0n)}function p(t,n){return n instanceof w&&n.errorKey.startsWith("toolbox_aleo_")?n:new w(t,n)}function xt(...t){let n=t.reduce((a,_)=>a+_.length,0),r=new Uint8Array(n),s=0;for(let a of t)r.set(a,s),s+=a.length;return r}function yt(t){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t,!1),n}function bt(t){let n=Y(J,ht,t);return{chainCode:n.slice(32),key:n.slice(0,32)}}function Tt(t,n){if(!Number.isSafeInteger(n)||n<0||n>=H)throw new w("toolbox_aleo_wasm_init_failed",{index:n});let r=n+H,s=xt(Uint8Array.of(0),t.key,yt(r)),a=Y(J,t.chainCode,s);return{chainCode:a.slice(32),key:a.slice(0,32)}}function nt(t,n){let r=t.split("/");if(r.shift()!=="m"||r.length===0)throw new w("toolbox_aleo_wasm_init_failed",{path:t});return r.reduce((s,a)=>{if(!/^\d+'$/.test(a))throw new w("toolbox_aleo_wasm_init_failed",{path:t,segment:a});return Tt(s,Number.parseInt(a.slice(0,-1),10))},bt(n))}function B(t){return typeof t==="string"&&mt.test(t)}async function ot(t){if(!B(t))return!1;try{let{Account:n}=await import("@provablehq/sdk/mainnet.js");return n.isValidAddress(t)}catch{return!1}}function Et(t){return pt.test(t)}function rt(t,n){if(t===null)return 0n;if(typeof t!=="string")throw new w("toolbox_aleo_balance_error",{integerType:n,value:t});let r=t.match(new RegExp(`^(\\d+)${n}$`));if(!r?.[1])throw new w("toolbox_aleo_balance_error",{integerType:n,value:t});return BigInt(r[1])}function M(t){if(t.chain!==F.Aleo)throw new w("toolbox_aleo_unsupported_token",{asset:t.toString()});let n=t.getBaseValue("bigint");if(t.isGasAsset)return{amount:`${n}u64`,functionName:U,isTokenTransfer:!1,programName:E};if(!t.address||!Et(t.address))throw new w("toolbox_aleo_unsupported_token",{asset:t.toString()});return{amount:`${n}u128`,functionName:U,isTokenTransfer:!0,programName:t.address}}function R(){let t=[...new Set([...At.get("rpcUrls")[F.Aleo],...gt(F.Aleo).rpcUrls])].filter(Boolean);if(t.length===0)throw new w("toolbox_aleo_no_rpc_urls");return t}function L(t){if(typeof t==="object"&&t!==null&&"status"in t&&t.status===404)return!0;return t instanceof Error&&t.message.includes("404")}function m(t){return typeof t==="object"&&t!==null}function Rt(t){if(!m(t))return!1;return[t.transaction,t.rejected].some((n)=>{if(!m(n)||!m(n.execution))return!1;let{transitions:r}=n.execution;return Array.isArray(r)&&r.some((s)=>m(s)&&s.function===U&&typeof s.program==="string"&&s.program!==E)})}function Pt(t,n){if(!m(t)||typeof t.status!=="string")throw new w("toolbox_aleo_transaction_failed",{response:t,transactionId:n});let r=t.status.toLowerCase();if(r==="rejected"){let s=Rt(t)?"toolbox_aleo_token_transfer_rejected":"toolbox_aleo_transaction_failed";throw new w(s,{transactionId:n})}return r==="accepted"?"accepted":"pending"}async function kt(t){if(!v.test(t))throw new w("toolbox_aleo_transaction_failed",{transactionId:t});let n,r=!0;for(let s of R())try{let{AleoNetworkClient:a}=await import("@provablehq/sdk/mainnet.js"),_=await new a(s).getConfirmedTransaction(t);return Pt(_,t)}catch(a){if(a instanceof w)throw a;n=a,r=r&&L(a)}if(r)return"pending";throw p("toolbox_aleo_transaction_failed",n)}async function K(t,{intervalMs:n=5000,timeoutMs:r=60000}={}){let s=Date.now();while(Date.now()-s<r){let a=await kt(t);if(a==="accepted")return a;await new Promise((_)=>setTimeout(_,n))}throw new w("toolbox_aleo_transaction_failed",{reason:"confirmation_timeout",transactionId:t})}import{AssetValue as C,Chain as P,derivationPathToString as Nt,NetworkDerivationPath as Ct,SwapKitError as d}from"@swapkit/helpers";async function st(t,n){try{let{Account:r}=await import("@provablehq/sdk/mainnet.js"),{mnemonicToSeedSync:s}=await import("@scure/bip39"),a=Nt(n||Ct[P.Aleo],{allHardened:!0}),{key:_}=nt(a,s(t));return new r({seed:_})}catch(r){throw p("toolbox_aleo_wasm_init_failed",r)}}function at(t,n){let r,s=()=>(r??=st(t,n),r);return{getAddress:async()=>(await s()).address().to_string(),signTransaction:async(a)=>{let _=await s();if(a.sender!==_.address().to_string())throw new d("toolbox_aleo_invalid_address",{address:a.sender});let y;for(let h of R())try{let{ProgramManager:b}=await import("@provablehq/sdk/mainnet.js"),N=new b(h);return N.setAccount(_),await N.buildExecutionTransaction({functionName:a.functionName,inputs:a.inputs,priorityFee:a.priorityFee/O,privateFee:!1,programName:a.programName})}catch(b){y=b}throw y}}}function St(t={}){if("phrase"in t&&t.phrase&&"signer"in t&&t.signer)throw new d("toolbox_aleo_conflicting_signers");let n;async function r(){if(n)return n;let o="phrase"in t?t.phrase:void 0;if(!o)throw new d("toolbox_aleo_no_signer");let e="derivationPath"in t?t.derivationPath:void 0;return n=await st(o,e),n}let s;function a(){let o="signer"in t?t.signer:void 0;if(o)return o;let e="phrase"in t?t.phrase:void 0;if(!e)throw new d("toolbox_aleo_no_signer");return s??=at(e,"derivationPath"in t?t.derivationPath:void 0),s}async function _(o){let e;for(let c of R())try{let{AleoNetworkClient:i}=await import("@provablehq/sdk/mainnet.js");return await o(new i(c))}catch(i){e=i}throw e}async function y(o){let e;for(let c of R())try{let{AleoNetworkClient:i}=await import("@provablehq/sdk/mainnet.js");return await new i(c).getTransitionId(o),!0}catch(i){if(L(i))return!1;e=i}throw e}async function h(){let o=a();try{return await o.getAddress()}catch(e){throw p("toolbox_aleo_wasm_init_failed",e)}}async function b(o){let e=await _((c)=>c.getProgramMappingValue(E,"account",o));return rt(e,"u64")}async function N(o){try{let e=await b(o);return[C.from({chain:P.Aleo,fromBaseDecimal:6,value:e})]}catch(e){throw p("toolbox_aleo_balance_error",e)}}let j=it(P.Aleo);async function G(o,e=!0){try{return await j(o,e)}catch{return N(o)}}async function ct(){return G(await h())}async function S({transactionIds:o}){try{let e=await r(),c=[];for(let i of o){if(!v.test(i))throw new d("toolbox_aleo_transaction_failed",{transactionId:i});let g=await _((u)=>u.getTransaction(i));for(let u of tt(g,E)){if(!e.ownsRecordCiphertext(u))continue;let{RecordPlaintext:f}=await import("@provablehq/sdk/mainnet.js"),l=e.decryptRecord(u).toString(),A=f.fromString(l),k=A.microcredits();if(k===0n)continue;let I=e.generateRecordViewKey(u).toString(),T=A.serialNumberString(e.privateKey(),E,"credits",I);c.push({microcredits:k,plaintext:l,spent:await y(T),transactionId:i})}}return c}catch(e){throw p("toolbox_aleo_balance_error",e)}}async function lt({transactionIds:o}){let e=await S({transactionIds:o});return C.from({chain:P.Aleo,fromBaseDecimal:6,value:et(e)})}async function ut(o,e){if(!Number.isSafeInteger(e)||e<=0)throw new d("toolbox_aleo_insufficient_fee_balance",{feeRecordCredits:e});let c=await r();if(!o||o.microcredits<=BigInt(e)*BigInt(O))throw new d("toolbox_aleo_insufficient_fee_balance",{available:o?.microcredits.toString(),required:`${e} credits fee record`});let{ProgramManager:i,RecordPlaintext:g}=await import("@provablehq/sdk/mainnet.js"),u;for(let f of R())try{let l=new i(f);return l.setAccount(c),await l.split(e,g.fromString(o.plaintext))}catch(l){u=l}throw u}async function ft(o,e,c){let i=await r(),{ProgramManager:g,RecordPlaintext:u}=await import("@provablehq/sdk/mainnet.js"),f;for(let l of R())try{let A=new g(l);return A.setAccount(i),await A.buildExecutionTransaction({feeRecord:u.fromString(e.plaintext),functionName:"transfer_private_to_public",inputs:[o.plaintext,c,`${o.microcredits}u64`],priorityFee:0,privateFee:!0,programName:E})}catch(A){f=A}throw f}async function V(o,e,c){let i;try{let u=(await r()).address().to_string(),f=o.filter((T)=>!T.spent);if(f.length===0)throw new d("toolbox_aleo_no_unspent_records",{transactionId:c});if(f.length===1){if(i=await ut(f[0],e),await K(i),f=(await S({transactionIds:[i]})).filter((T)=>!T.spent),f.length<2)throw new d("toolbox_aleo_transaction_failed",{transactionId:i})}let l=[...f].sort((T,wt)=>T.microcredits<wt.microcredits?-1:1),A=l[0],k=l[l.length-1];if(!A||!k||A===k)throw new d("toolbox_aleo_no_unspent_records",{transactionId:c});let I=await D(await ft(k,A,u));return await K(I),{publicBalance:C.from({chain:P.Aleo,fromBaseDecimal:6,value:await b(u)}),splitTransactionId:i,unshieldTransactionId:I}}catch(g){if(i)throw new d("toolbox_aleo_transaction_failed",{error:g,splitTransactionId:i});throw p("toolbox_aleo_transaction_failed",g)}}async function dt(o){try{if("records"in o&&o.records)return await V(o.records,o.feeRecordCredits??4);let e=await S({transactionIds:[o.transactionId]});return await V(e,o.feeRecordCredits??4,o.transactionId)}catch(e){throw p("toolbox_aleo_transaction_failed",e)}}function W({assetValue:o,priorityFee:e=0}){try{if(!Number.isSafeInteger(e)||e<0)throw new d("toolbox_aleo_fee_estimation_failed",{priorityFee:e});let i=M(o).isTokenTransfer?Z:Q;return C.from({chain:P.Aleo,fromBaseDecimal:6,value:BigInt(i)+BigInt(e)})}catch(c){throw p("toolbox_aleo_fee_estimation_failed",c)}}async function z({assetValue:o,priorityFee:e=0,recipient:c,sender:i}){if(!await ot(c))throw new d("toolbox_aleo_invalid_address",{address:c});let g=i||await h();if(!B(g))throw new d("toolbox_aleo_invalid_address",{address:g});let u=M(o),f=await W({assetValue:o,priorityFee:e,recipient:c});try{let l=await b(g);if(C.from({chain:P.Aleo,fromBaseDecimal:6,value:l}).lt(f))throw new d("toolbox_aleo_insufficient_fee_balance",{available:l.toString(),required:f.getBaseValue("string")});return{functionName:u.functionName,inputs:[c,u.amount],priorityFee:e,programName:u.programName,sender:g}}catch(l){throw p("toolbox_aleo_transaction_failed",l)}}async function X(o){try{return await a().signTransaction(o)}catch(e){throw p("toolbox_aleo_transaction_failed",e)}}async function q(o){return D(await X(o))}async function D(o){try{let e=typeof o==="string"?o:o.toString(),c=await _((i)=>i.submitTransaction(e));if(!v.test(c))throw new d("toolbox_aleo_broadcast_error",{transactionId:c});return c}catch(e){throw p("toolbox_aleo_broadcast_error",e)}}async function _t(o){let e=await z({...o,sender:await h()});return q(e)}return{broadcastTransaction:D,createSigner:at,createTransaction:z,estimateTransactionFee:W,getAddress:h,getBalance:j,getBalanceFromRpc:N,getBalances:ct,getBalanceWithFallback:G,getRecords:S,getShieldedBalance:lt,signAndBroadcastTransaction:q,signTransaction:X,transfer:_t,unshield:dt,validateAddress:B}}export{mt as ALEO_ADDRESS_REGEX,ht as ALEO_HD_KEY,pt as ALEO_PROGRAM_ID_REGEX,Z as ALEO_TOKEN_TRANSFER_PUBLIC_FEE,v as ALEO_TRANSACTION_ID_REGEX,Q as ALEO_TRANSFER_PUBLIC_FEE,H as HARDENED_OFFSET,O as MICRO_CREDITS_PER_CREDIT,E as NATIVE_PROGRAM_ID,U as TRANSFER_PUBLIC_FUNCTION,Tt as deriveAleoChildKey,nt as deriveAleoPath,tt as extractAleoRecordCiphertexts,p as getAleoError,bt as getAleoMasterSeed,St as getAleoToolbox,kt as getAleoTransactionStatus,M as getAleoTransferRoute,R as getConfiguredAleoUrls,Rt as isAleoTokenTransferResponse,L as isNotFoundError,m as isRecord,rt as parseAleoMappingValue,Pt as parseAleoTransactionStatus,et as sumUnspentRecords,B as validateAleoAddress,ot as validateAleoAddressWithChecksum,Et as validateAleoProgramId,K as waitForAleoTransaction};
1
+ import{ia as it}from"../../chunk-xdkdc1f0.js";import{ja as x}from"../../chunk-exyqap7m.js";import{hmac as Y}from"@noble/hashes/hmac.js";import{sha512 as J}from"@noble/hashes/sha2.js";import{Chain as F,getChainConfig as gt,SKConfig as At,SwapKitError as w}from"@swapkit/helpers";var mt=/^aleo1[ac-hj-np-z02-9]{58}$/,pt=/^[a-z0-9_]+\.aleo$/,v=/^at1[ac-hj-np-z02-9]+$/,ht=new TextEncoder().encode("bls12_377 seed"),H=2147483648,O=1e6,E="credits.aleo",U="transfer_public",Q=1e6,Z=2000000;function tt(t,n){if(!m(t))return[];let r=m(t.transaction)?t.transaction:t,s=r.execution,a=m(r.fee)?r.fee.transition:void 0;return[...m(s)&&Array.isArray(s.transitions)?s.transitions:[],...m(a)?[a]:[]].flatMap((y)=>{if(!m(y)||!Array.isArray(y.outputs))return[];if(n&&y.program!==n)return[];return y.outputs.flatMap((h)=>m(h)&&h.type==="record"&&typeof h.value==="string"?[h.value]:[])})}function et(t){return t.reduce((n,r)=>r.spent?n:n+r.microcredits,0n)}function p(t,n){return n instanceof w&&n.errorKey.startsWith("toolbox_aleo_")?n:new w(t,n)}function xt(...t){let n=t.reduce((a,_)=>a+_.length,0),r=new Uint8Array(n),s=0;for(let a of t)r.set(a,s),s+=a.length;return r}function yt(t){let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t,!1),n}function bt(t){let n=Y(J,ht,t);return{chainCode:n.slice(32),key:n.slice(0,32)}}function Tt(t,n){if(!Number.isSafeInteger(n)||n<0||n>=H)throw new w("toolbox_aleo_wasm_init_failed",{index:n});let r=n+H,s=xt(Uint8Array.of(0),t.key,yt(r)),a=Y(J,t.chainCode,s);return{chainCode:a.slice(32),key:a.slice(0,32)}}function nt(t,n){let r=t.split("/");if(r.shift()!=="m"||r.length===0)throw new w("toolbox_aleo_wasm_init_failed",{path:t});return r.reduce((s,a)=>{if(!/^\d+'$/.test(a))throw new w("toolbox_aleo_wasm_init_failed",{path:t,segment:a});return Tt(s,Number.parseInt(a.slice(0,-1),10))},bt(n))}function B(t){return typeof t==="string"&&mt.test(t)}async function ot(t){if(!B(t))return!1;try{let{Account:n}=await import("@provablehq/sdk/mainnet.js");return n.isValidAddress(t)}catch{return!1}}function Et(t){return pt.test(t)}function rt(t,n){if(t===null)return 0n;if(typeof t!=="string")throw new w("toolbox_aleo_balance_error",{integerType:n,value:t});let r=t.match(new RegExp(`^(\\d+)${n}$`));if(!r?.[1])throw new w("toolbox_aleo_balance_error",{integerType:n,value:t});return BigInt(r[1])}function M(t){if(t.chain!==F.Aleo)throw new w("toolbox_aleo_unsupported_token",{asset:t.toString()});let n=t.getBaseValue("bigint");if(t.isGasAsset)return{amount:`${n}u64`,functionName:U,isTokenTransfer:!1,programName:E};if(!t.address||!Et(t.address))throw new w("toolbox_aleo_unsupported_token",{asset:t.toString()});return{amount:`${n}u128`,functionName:U,isTokenTransfer:!0,programName:t.address}}function R(){let t=[...new Set([...At.get("rpcUrls")[F.Aleo],...gt(F.Aleo).rpcUrls])].filter(Boolean);if(t.length===0)throw new w("toolbox_aleo_no_rpc_urls");return t}function L(t){if(typeof t==="object"&&t!==null&&"status"in t&&t.status===404)return!0;return t instanceof Error&&t.message.includes("404")}function m(t){return typeof t==="object"&&t!==null}function Rt(t){if(!m(t))return!1;return[t.transaction,t.rejected].some((n)=>{if(!m(n)||!m(n.execution))return!1;let{transitions:r}=n.execution;return Array.isArray(r)&&r.some((s)=>m(s)&&s.function===U&&typeof s.program==="string"&&s.program!==E)})}function Pt(t,n){if(!m(t)||typeof t.status!=="string")throw new w("toolbox_aleo_transaction_failed",{response:t,transactionId:n});let r=t.status.toLowerCase();if(r==="rejected"){let s=Rt(t)?"toolbox_aleo_token_transfer_rejected":"toolbox_aleo_transaction_failed";throw new w(s,{transactionId:n})}return r==="accepted"?"accepted":"pending"}async function kt(t){if(!v.test(t))throw new w("toolbox_aleo_transaction_failed",{transactionId:t});let n,r=!0;for(let s of R())try{let{AleoNetworkClient:a}=await import("@provablehq/sdk/mainnet.js"),_=await new a(s).getConfirmedTransaction(t);return Pt(_,t)}catch(a){if(a instanceof w)throw a;n=a,r=r&&L(a)}if(r)return"pending";throw p("toolbox_aleo_transaction_failed",n)}async function K(t,{intervalMs:n=5000,timeoutMs:r=60000}={}){let s=Date.now();while(Date.now()-s<r){let a=await kt(t);if(a==="accepted")return a;await new Promise((_)=>setTimeout(_,n))}throw new w("toolbox_aleo_transaction_failed",{reason:"confirmation_timeout",transactionId:t})}import{AssetValue as C,Chain as P,derivationPathToString as Nt,NetworkDerivationPath as Ct,SwapKitError as d}from"@swapkit/helpers";async function st(t,n){try{let{Account:r}=await import("@provablehq/sdk/mainnet.js"),{mnemonicToSeedSync:s}=await import("@scure/bip39"),a=Nt(n||Ct[P.Aleo],{allHardened:!0}),{key:_}=nt(a,s(t));return new r({seed:_})}catch(r){throw p("toolbox_aleo_wasm_init_failed",r)}}function at(t,n){let r,s=()=>(r??=st(t,n),r);return{getAddress:async()=>(await s()).address().to_string(),signTransaction:async(a)=>{let _=await s();if(a.sender!==_.address().to_string())throw new d("toolbox_aleo_invalid_address",{address:a.sender});let y;for(let h of R())try{let{ProgramManager:b}=await import("@provablehq/sdk/mainnet.js"),N=new b(h);return N.setAccount(_),await N.buildExecutionTransaction({functionName:a.functionName,inputs:a.inputs,priorityFee:a.priorityFee/O,privateFee:!1,programName:a.programName})}catch(b){y=b}throw y}}}function St(t={}){if("phrase"in t&&t.phrase&&"signer"in t&&t.signer)throw new d("toolbox_aleo_conflicting_signers");let n;async function r(){if(n)return n;let o="phrase"in t?t.phrase:void 0;if(!o)throw new d("toolbox_aleo_no_signer");let e="derivationPath"in t?t.derivationPath:void 0;return n=await st(o,e),n}let s;function a(){let o="signer"in t?t.signer:void 0;if(o)return o;let e="phrase"in t?t.phrase:void 0;if(!e)throw new d("toolbox_aleo_no_signer");return s??=at(e,"derivationPath"in t?t.derivationPath:void 0),s}async function _(o){let e;for(let c of R())try{let{AleoNetworkClient:i}=await import("@provablehq/sdk/mainnet.js");return await o(new i(c))}catch(i){e=i}throw e}async function y(o){let e;for(let c of R())try{let{AleoNetworkClient:i}=await import("@provablehq/sdk/mainnet.js");return await new i(c).getTransitionId(o),!0}catch(i){if(L(i))return!1;e=i}throw e}async function h(){let o=a();try{return await o.getAddress()}catch(e){throw p("toolbox_aleo_wasm_init_failed",e)}}async function b(o){let e=await _((c)=>c.getProgramMappingValue(E,"account",o));return rt(e,"u64")}async function N(o){try{let e=await b(o);return[C.from({chain:P.Aleo,fromBaseDecimal:6,value:e})]}catch(e){throw p("toolbox_aleo_balance_error",e)}}let j=it(P.Aleo);async function G(o,e=!0){try{return await j(o,e)}catch{return N(o)}}async function ct(){return G(await h())}async function S({transactionIds:o}){try{let e=await r(),c=[];for(let i of o){if(!v.test(i))throw new d("toolbox_aleo_transaction_failed",{transactionId:i});let g=await _((u)=>u.getTransaction(i));for(let u of tt(g,E)){if(!e.ownsRecordCiphertext(u))continue;let{RecordPlaintext:f}=await import("@provablehq/sdk/mainnet.js"),l=e.decryptRecord(u).toString(),A=f.fromString(l),k=A.microcredits();if(k===0n)continue;let I=e.generateRecordViewKey(u).toString(),T=A.serialNumberString(e.privateKey(),E,"credits",I);c.push({microcredits:k,plaintext:l,spent:await y(T),transactionId:i})}}return c}catch(e){throw p("toolbox_aleo_balance_error",e)}}async function lt({transactionIds:o}){let e=await S({transactionIds:o});return C.from({chain:P.Aleo,fromBaseDecimal:6,value:et(e)})}async function ut(o,e){if(!Number.isSafeInteger(e)||e<=0)throw new d("toolbox_aleo_insufficient_fee_balance",{feeRecordCredits:e});let c=await r();if(!o||o.microcredits<=BigInt(e)*BigInt(O))throw new d("toolbox_aleo_insufficient_fee_balance",{available:o?.microcredits.toString(),required:`${e} credits fee record`});let{ProgramManager:i,RecordPlaintext:g}=await import("@provablehq/sdk/mainnet.js"),u;for(let f of R())try{let l=new i(f);return l.setAccount(c),await l.split(e,g.fromString(o.plaintext))}catch(l){u=l}throw u}async function ft(o,e,c){let i=await r(),{ProgramManager:g,RecordPlaintext:u}=await import("@provablehq/sdk/mainnet.js"),f;for(let l of R())try{let A=new g(l);return A.setAccount(i),await A.buildExecutionTransaction({feeRecord:u.fromString(e.plaintext),functionName:"transfer_private_to_public",inputs:[o.plaintext,c,`${o.microcredits}u64`],priorityFee:0,privateFee:!0,programName:E})}catch(A){f=A}throw f}async function V(o,e,c){let i;try{let u=(await r()).address().to_string(),f=o.filter((T)=>!T.spent);if(f.length===0)throw new d("toolbox_aleo_no_unspent_records",{transactionId:c});if(f.length===1){if(i=await ut(f[0],e),await K(i),f=(await S({transactionIds:[i]})).filter((T)=>!T.spent),f.length<2)throw new d("toolbox_aleo_transaction_failed",{transactionId:i})}let l=[...f].sort((T,wt)=>T.microcredits<wt.microcredits?-1:1),A=l[0],k=l[l.length-1];if(!A||!k||A===k)throw new d("toolbox_aleo_no_unspent_records",{transactionId:c});let I=await D(await ft(k,A,u));return await K(I),{publicBalance:C.from({chain:P.Aleo,fromBaseDecimal:6,value:await b(u)}),splitTransactionId:i,unshieldTransactionId:I}}catch(g){if(i)throw new d("toolbox_aleo_transaction_failed",{error:g,splitTransactionId:i});throw p("toolbox_aleo_transaction_failed",g)}}async function dt(o){try{if("records"in o&&o.records)return await V(o.records,o.feeRecordCredits??4);let e=await S({transactionIds:[o.transactionId]});return await V(e,o.feeRecordCredits??4,o.transactionId)}catch(e){throw p("toolbox_aleo_transaction_failed",e)}}function W({assetValue:o,priorityFee:e=0}){try{if(!Number.isSafeInteger(e)||e<0)throw new d("toolbox_aleo_fee_estimation_failed",{priorityFee:e});let i=M(o).isTokenTransfer?Z:Q;return C.from({chain:P.Aleo,fromBaseDecimal:6,value:BigInt(i)+BigInt(e)})}catch(c){throw p("toolbox_aleo_fee_estimation_failed",c)}}async function z({assetValue:o,priorityFee:e=0,recipient:c,sender:i}){if(!await ot(c))throw new d("toolbox_aleo_invalid_address",{address:c});let g=i||await h();if(!B(g))throw new d("toolbox_aleo_invalid_address",{address:g});let u=M(o),f=await W({assetValue:o,priorityFee:e,recipient:c});try{let l=await b(g);if(C.from({chain:P.Aleo,fromBaseDecimal:6,value:l}).lt(f))throw new d("toolbox_aleo_insufficient_fee_balance",{available:l.toString(),required:f.getBaseValue("string")});return{functionName:u.functionName,inputs:[c,u.amount],priorityFee:e,programName:u.programName,sender:g}}catch(l){throw p("toolbox_aleo_transaction_failed",l)}}async function X(o){try{return await a().signTransaction(o)}catch(e){throw p("toolbox_aleo_transaction_failed",e)}}async function q(o){return D(await X(o))}async function D(o){try{let e=typeof o==="string"?o:o.toString(),c=await _((i)=>i.submitTransaction(e));if(!v.test(c))throw new d("toolbox_aleo_broadcast_error",{transactionId:c});return c}catch(e){throw p("toolbox_aleo_broadcast_error",e)}}async function _t(o){let e=await z({...o,sender:await h()});return q(e)}return{broadcastTransaction:D,createSigner:at,createTransaction:z,estimateTransactionFee:W,getAddress:h,getBalance:j,getBalanceFromRpc:N,getBalances:ct,getBalanceWithFallback:G,getRecords:S,getShieldedBalance:lt,signAndBroadcastTransaction:q,signTransaction:X,transfer:_t,unshield:dt,validateAddress:B}}export{mt as ALEO_ADDRESS_REGEX,ht as ALEO_HD_KEY,pt as ALEO_PROGRAM_ID_REGEX,Z as ALEO_TOKEN_TRANSFER_PUBLIC_FEE,v as ALEO_TRANSACTION_ID_REGEX,Q as ALEO_TRANSFER_PUBLIC_FEE,H as HARDENED_OFFSET,O as MICRO_CREDITS_PER_CREDIT,E as NATIVE_PROGRAM_ID,U as TRANSFER_PUBLIC_FUNCTION,Tt as deriveAleoChildKey,nt as deriveAleoPath,tt as extractAleoRecordCiphertexts,p as getAleoError,bt as getAleoMasterSeed,St as getAleoToolbox,kt as getAleoTransactionStatus,M as getAleoTransferRoute,R as getConfiguredAleoUrls,Rt as isAleoTokenTransferResponse,L as isNotFoundError,m as isRecord,rt as parseAleoMappingValue,Pt as parseAleoTransactionStatus,et as sumUnspentRecords,B as validateAleoAddress,ot as validateAleoAddressWithChecksum,Et as validateAleoProgramId,K as waitForAleoTransaction};
@@ -1 +1 @@
1
- import{ha as B}from"../../chunk-4428244x.js";import{AssetValue as b,Chain as A,derivationPathToString as tt,getChainConfig as v,getRPCUrlSync as W,NetworkDerivationPath as nt,SwapKitError as s}from"@swapkit/helpers";import{match as j,P as R}from"ts-pattern";var w={COIN_TYPE:"0x1::aptos_coin::AptosCoin",FUNGIBLE_ASSET_METADATA:"0x1::fungible_asset::Metadata",FUNGIBLE_STORE_TRANSFER:"0x1::primary_fungible_store::transfer",TRANSFER:"0x1::aptos_account::transfer"},st=2000,at=/^[0-9a-fA-F]+$/;function x(e){if(!e||typeof e!=="string"||!e.startsWith("0x"))return!1;let i=e.slice(2);if(i.length===0||i.length>64)return!1;return at.test(i)}function Y(e,i,d){if(e<=0n)throw new s({errorKey:"toolbox_sweep_amount_too_low",info:{amount:e.toString(),asset:i.toString(),...d}});return e}async function ot({aptos:e,assetValue:i,senderAddress:d}){let c=i.address;if(!c)throw new s("toolbox_aptos_missing_asset_type");let[y]=await e.getCurrentFungibleAssetBalances({options:{limit:1,where:{asset_type:{_eq:c},is_primary:{_eq:!0},owner_address:{_eq:d}}}});return Y(BigInt(y?.amount??0),i)}function et({derivationPath:e,provider:i,...d}={}){let c,y=tt(e||nt[A.Aptos],{allHardened:!0});async function T(){if(c)return c;return c=await j(d).with({phrase:R.string},async({phrase:n})=>{let{Ed25519Account:t}=await import("@aptos-labs/ts-sdk");return t.fromDerivationPath({mnemonic:n,path:y})}).with({signer:R.any},({signer:n})=>n).otherwise(()=>{return}),c}async function _(){let{Aptos:n,AptosConfig:t,Network:a}=await import("@aptos-labs/ts-sdk"),r=new t({clientConfig:{http2:!1},fullnode:i||W(A.Aptos),network:a.MAINNET});return new n(r)}async function S(){return(await T())?.accountAddress.toString()||""}async function G(n){let t=n||await S();if(!t)throw new s("toolbox_aptos_address_required");let{baseDecimal:a,chain:r}=v(A.Aptos);try{let u=await _(),p=await u.getAccountAPTAmount({accountAddress:t}),g=[b.from({chain:r,fromBaseDecimal:a,value:p.toString()})],f=await u.getCurrentFungibleAssetBalances({options:{where:{owner_address:{_eq:t}}}});for(let o of f){if(o.asset_type===w.COIN_TYPE||Number(o.amount)<=0)continue;let m=o.asset_type;if(m){let l=("metadata"in o&&typeof o.metadata==="object"&&o.metadata!==null?o.metadata:void 0)?.decimals??a;g.push(b.from({asset:`${A.Aptos}.APT-${m}`,fromBaseDecimal:l,value:String(o.amount)}))}}return g}catch{return[b.from({chain:r})]}}async function H(n){if(!n){let{baseDecimal:g}=v(A.Aptos),f=i||W(A.Aptos),o=await fetch(`${f}/estimate_gas_price`),{gas_estimate:m}=await o.json();return b.from({chain:A.Aptos,fromBaseDecimal:g,value:String(m)})}let t=await N(n),a=await _(),[r]=await a.transaction.simulate.simple({transaction:t});if(!r)throw new s("toolbox_aptos_transaction_creation_error");let u=BigInt(r.gas_used)*BigInt(r.gas_unit_price),{baseDecimal:p}=v(A.Aptos);return b.from({chain:A.Aptos,fromBaseDecimal:p,value:u.toString()})}async function N({recipient:n,assetValue:t,maxGasAmount:a,sender:r,accountSequenceNumber:u,gasUnitPrice:p,sweep:g}){if(!x(n))throw new s("core_transaction_invalid_recipient_address");let f=r||await S();if(!f)throw new s("toolbox_aptos_no_sender");let{AccountAddress:o}=await import("@aptos-labs/ts-sdk"),m=await _(),C=o.from(f);try{let l=t.isGasAsset?w.TRANSFER:w.FUNGIBLE_STORE_TRANSFER,z=t.address,E=(P,O)=>{let k=j({address:z,isGasAsset:t.isGasAsset}).with({isGasAsset:!0},()=>[o.from(n),P]).with({address:R.string},({address:V})=>[o.from(V),o.from(n),P]).otherwise(()=>null);if(!k)throw new s("toolbox_aptos_missing_asset_type");let q=O?.maxGasAmount??a,K=O?.gasUnitPrice??p;return m.transaction.build.simple({data:{function:l,functionArguments:k,typeArguments:t.isGasAsset?[]:[w.FUNGIBLE_ASSET_METADATA]},options:q!==void 0||K!==void 0||u!==void 0?{accountSequenceNumber:u,gasUnitPrice:K,maxGasAmount:q}:void 0,sender:C})};if(!g)return E(t.getBaseValue("bigint"));if(!t.isGasAsset){let P=await ot({aptos:m,assetValue:t,senderAddress:f});return E(P)}let U=BigInt(await m.getAccountAPTAmount({accountAddress:f})),J=await E(1n,{maxGasAmount:a??st}),[h]=await m.transaction.simulate.simple({options:{estimateMaxGasAmount:a===void 0},transaction:J});if(!h)throw new s("toolbox_aptos_transaction_creation_error");if(!h.success)throw new s({errorKey:"toolbox_aptos_transaction_creation_error",info:{vmStatus:h.vm_status}});let D=BigInt(h.gas_used),M=D>0n?(D*6n+4n)/5n:1n,L=M*BigInt(h.gas_unit_price),Z=Y(U-L,t,{balance:U.toString(),fee:L.toString()});return E(Z,{gasUnitPrice:Number(h.gas_unit_price),maxGasAmount:Number(M)})}catch(l){if(l instanceof s)throw l;throw new s("toolbox_aptos_transaction_creation_error",l)}}async function F(n){let t=await T();if(!t)throw new s("toolbox_aptos_no_signer");return(await _()).transaction.sign({signer:t,transaction:n})}async function Q({assetValue:n,maxGasAmount:t,recipient:a,sweep:r}){let u=await T();if(!u)throw new s("toolbox_aptos_no_signer");if(!x(a))throw new s("core_transaction_invalid_recipient_address");try{let p=u.accountAddress.toString(),g=await N({assetValue:n,maxGasAmount:t,recipient:a,sender:p,sweep:r});return(await(await _()).signAndSubmitTransaction({signer:u,transaction:g})).hash}catch(p){if(p instanceof s)throw p;throw new s("toolbox_aptos_transaction_creation_error",p)}}async function I({senderAuthenticator:n,transaction:t}){try{return(await(await _()).transaction.submit.simple({senderAuthenticator:n,transaction:t})).hash}catch(a){throw new s("toolbox_aptos_broadcast_error",a)}}async function X(n){let t=await F(n);return I({senderAuthenticator:t,transaction:n})}return{broadcastTransaction:I,createTransaction:N,estimateTransactionFee:H,getAddress:S,getBalance:G,signAndBroadcastTransaction:X,signTransaction:F,transfer:Q,validateAddress:x}}function rt({provider:e}){return async function({assetValue:d,recipient:c,sweep:y}){if(y)throw new s({errorKey:"toolbox_not_supported",info:{chain:A.Aptos,feature:"extension_provider_sweep",reason:"Aptos extension providers cannot query balances or simulate transactions"}});if(!x(c))throw new s("core_transaction_invalid_recipient_address");let{AccountAddress:T}=await import("@aptos-labs/ts-sdk");if(d.isGasAsset)return(await e.signAndSubmitTransaction({arguments:[T.from(c).toString(),d.getBaseValue("string")],function:w.TRANSFER,type:"entry_function_payload",type_arguments:[]})).hash;let _=d.address;if(!_)throw new s("toolbox_aptos_missing_asset_type");return(await e.signAndSubmitTransaction({arguments:[_,T.from(c).toString(),d.getBaseValue("string")],function:w.FUNGIBLE_STORE_TRANSFER,type:"entry_function_payload",type_arguments:[w.FUNGIBLE_ASSET_METADATA]})).hash}}export{rt as createAptosExtensionTransfer,et as getAptosToolbox,x as validateAptosAddress};
1
+ import{ja as B}from"../../chunk-exyqap7m.js";import{AssetValue as b,Chain as A,derivationPathToString as tt,getChainConfig as v,getRPCUrlSync as W,NetworkDerivationPath as nt,SwapKitError as s}from"@swapkit/helpers";import{match as j,P as R}from"ts-pattern";var w={COIN_TYPE:"0x1::aptos_coin::AptosCoin",FUNGIBLE_ASSET_METADATA:"0x1::fungible_asset::Metadata",FUNGIBLE_STORE_TRANSFER:"0x1::primary_fungible_store::transfer",TRANSFER:"0x1::aptos_account::transfer"},st=2000,at=/^[0-9a-fA-F]+$/;function x(e){if(!e||typeof e!=="string"||!e.startsWith("0x"))return!1;let i=e.slice(2);if(i.length===0||i.length>64)return!1;return at.test(i)}function Y(e,i,d){if(e<=0n)throw new s({errorKey:"toolbox_sweep_amount_too_low",info:{amount:e.toString(),asset:i.toString(),...d}});return e}async function ot({aptos:e,assetValue:i,senderAddress:d}){let c=i.address;if(!c)throw new s("toolbox_aptos_missing_asset_type");let[y]=await e.getCurrentFungibleAssetBalances({options:{limit:1,where:{asset_type:{_eq:c},is_primary:{_eq:!0},owner_address:{_eq:d}}}});return Y(BigInt(y?.amount??0),i)}function et({derivationPath:e,provider:i,...d}={}){let c,y=tt(e||nt[A.Aptos],{allHardened:!0});async function T(){if(c)return c;return c=await j(d).with({phrase:R.string},async({phrase:n})=>{let{Ed25519Account:t}=await import("@aptos-labs/ts-sdk");return t.fromDerivationPath({mnemonic:n,path:y})}).with({signer:R.any},({signer:n})=>n).otherwise(()=>{return}),c}async function _(){let{Aptos:n,AptosConfig:t,Network:a}=await import("@aptos-labs/ts-sdk"),r=new t({clientConfig:{http2:!1},fullnode:i||W(A.Aptos),network:a.MAINNET});return new n(r)}async function S(){return(await T())?.accountAddress.toString()||""}async function G(n){let t=n||await S();if(!t)throw new s("toolbox_aptos_address_required");let{baseDecimal:a,chain:r}=v(A.Aptos);try{let u=await _(),p=await u.getAccountAPTAmount({accountAddress:t}),g=[b.from({chain:r,fromBaseDecimal:a,value:p.toString()})],f=await u.getCurrentFungibleAssetBalances({options:{where:{owner_address:{_eq:t}}}});for(let o of f){if(o.asset_type===w.COIN_TYPE||Number(o.amount)<=0)continue;let m=o.asset_type;if(m){let l=("metadata"in o&&typeof o.metadata==="object"&&o.metadata!==null?o.metadata:void 0)?.decimals??a;g.push(b.from({asset:`${A.Aptos}.APT-${m}`,fromBaseDecimal:l,value:String(o.amount)}))}}return g}catch{return[b.from({chain:r})]}}async function H(n){if(!n){let{baseDecimal:g}=v(A.Aptos),f=i||W(A.Aptos),o=await fetch(`${f}/estimate_gas_price`),{gas_estimate:m}=await o.json();return b.from({chain:A.Aptos,fromBaseDecimal:g,value:String(m)})}let t=await N(n),a=await _(),[r]=await a.transaction.simulate.simple({transaction:t});if(!r)throw new s("toolbox_aptos_transaction_creation_error");let u=BigInt(r.gas_used)*BigInt(r.gas_unit_price),{baseDecimal:p}=v(A.Aptos);return b.from({chain:A.Aptos,fromBaseDecimal:p,value:u.toString()})}async function N({recipient:n,assetValue:t,maxGasAmount:a,sender:r,accountSequenceNumber:u,gasUnitPrice:p,sweep:g}){if(!x(n))throw new s("core_transaction_invalid_recipient_address");let f=r||await S();if(!f)throw new s("toolbox_aptos_no_sender");let{AccountAddress:o}=await import("@aptos-labs/ts-sdk"),m=await _(),C=o.from(f);try{let l=t.isGasAsset?w.TRANSFER:w.FUNGIBLE_STORE_TRANSFER,z=t.address,E=(P,O)=>{let k=j({address:z,isGasAsset:t.isGasAsset}).with({isGasAsset:!0},()=>[o.from(n),P]).with({address:R.string},({address:V})=>[o.from(V),o.from(n),P]).otherwise(()=>null);if(!k)throw new s("toolbox_aptos_missing_asset_type");let q=O?.maxGasAmount??a,K=O?.gasUnitPrice??p;return m.transaction.build.simple({data:{function:l,functionArguments:k,typeArguments:t.isGasAsset?[]:[w.FUNGIBLE_ASSET_METADATA]},options:q!==void 0||K!==void 0||u!==void 0?{accountSequenceNumber:u,gasUnitPrice:K,maxGasAmount:q}:void 0,sender:C})};if(!g)return E(t.getBaseValue("bigint"));if(!t.isGasAsset){let P=await ot({aptos:m,assetValue:t,senderAddress:f});return E(P)}let U=BigInt(await m.getAccountAPTAmount({accountAddress:f})),J=await E(1n,{maxGasAmount:a??st}),[h]=await m.transaction.simulate.simple({options:{estimateMaxGasAmount:a===void 0},transaction:J});if(!h)throw new s("toolbox_aptos_transaction_creation_error");if(!h.success)throw new s({errorKey:"toolbox_aptos_transaction_creation_error",info:{vmStatus:h.vm_status}});let D=BigInt(h.gas_used),M=D>0n?(D*6n+4n)/5n:1n,L=M*BigInt(h.gas_unit_price),Z=Y(U-L,t,{balance:U.toString(),fee:L.toString()});return E(Z,{gasUnitPrice:Number(h.gas_unit_price),maxGasAmount:Number(M)})}catch(l){if(l instanceof s)throw l;throw new s("toolbox_aptos_transaction_creation_error",l)}}async function F(n){let t=await T();if(!t)throw new s("toolbox_aptos_no_signer");return(await _()).transaction.sign({signer:t,transaction:n})}async function Q({assetValue:n,maxGasAmount:t,recipient:a,sweep:r}){let u=await T();if(!u)throw new s("toolbox_aptos_no_signer");if(!x(a))throw new s("core_transaction_invalid_recipient_address");try{let p=u.accountAddress.toString(),g=await N({assetValue:n,maxGasAmount:t,recipient:a,sender:p,sweep:r});return(await(await _()).signAndSubmitTransaction({signer:u,transaction:g})).hash}catch(p){if(p instanceof s)throw p;throw new s("toolbox_aptos_transaction_creation_error",p)}}async function I({senderAuthenticator:n,transaction:t}){try{return(await(await _()).transaction.submit.simple({senderAuthenticator:n,transaction:t})).hash}catch(a){throw new s("toolbox_aptos_broadcast_error",a)}}async function X(n){let t=await F(n);return I({senderAuthenticator:t,transaction:n})}return{broadcastTransaction:I,createTransaction:N,estimateTransactionFee:H,getAddress:S,getBalance:G,signAndBroadcastTransaction:X,signTransaction:F,transfer:Q,validateAddress:x}}function rt({provider:e}){return async function({assetValue:d,recipient:c,sweep:y}){if(y)throw new s({errorKey:"toolbox_not_supported",info:{chain:A.Aptos,feature:"extension_provider_sweep",reason:"Aptos extension providers cannot query balances or simulate transactions"}});if(!x(c))throw new s("core_transaction_invalid_recipient_address");let{AccountAddress:T}=await import("@aptos-labs/ts-sdk");if(d.isGasAsset)return(await e.signAndSubmitTransaction({arguments:[T.from(c).toString(),d.getBaseValue("string")],function:w.TRANSFER,type:"entry_function_payload",type_arguments:[]})).hash;let _=d.address;if(!_)throw new s("toolbox_aptos_missing_asset_type");return(await e.signAndSubmitTransaction({arguments:[_,T.from(c).toString(),d.getBaseValue("string")],function:w.FUNGIBLE_STORE_TRANSFER,type:"entry_function_payload",type_arguments:[w.FUNGIBLE_ASSET_METADATA]})).hash}}export{rt as createAptosExtensionTransfer,et as getAptosToolbox,x as validateAptosAddress};
@@ -1 +1 @@
1
- import{ha as R}from"../../chunk-4428244x.js";import{bech32 as ne}from"@scure/base";import{mnemonicToEntropy as re}from"@scure/bip39";import{wordlist as oe}from"@scure/bip39/wordlists/english.js";import{AssetValue as S,Chain as w,getChainConfig as se,SwapKitError as h}from"@swapkit/helpers";import m from"bignumber.js";var X="mainnet3YT7XK6NidLPlkHxxyBB5V0WzXUOTIJS",J="https://cardano-mainnet.blockfrost.io/api/v0",U=2147483648,W=0;async function z(e,t){let o=await fetch(`${J}${e}`,{...t,headers:{project_id:X,...t?.headers}});if(!o.ok)throw Error(`Blockfrost API error: ${o.status} ${o.statusText}`);return o.json()}async function Q(e){try{return await z(`/addresses/${e}/utxos`)}catch{return[]}}async function ae(){return(await z("/blocks/latest")).slot}async function ie(){let e=await z("/epochs/latest/parameters"),t={PlutusScriptV1:e.cost_models.PlutusV1?Object.values(e.cost_models.PlutusV1):[],PlutusScriptV2:e.cost_models.PlutusV2?Object.values(e.cost_models.PlutusV2):[],PlutusScriptV3:e.cost_models.PlutusV3?Object.values(e.cost_models.PlutusV3):[]};return{collateralPercent:new m(e.collateral_percent),languageView:t,maxValueSize:Number.parseInt(e.max_val_size,10),minFeeA:new m(e.min_fee_a),minFeeB:new m(e.min_fee_b),minFeeRefScriptCostPerByte:new m(15),priceMem:new m(e.price_mem),priceSteps:new m(e.price_step),stakeKeyDeposit:new m(2000000),utxoCostPerByte:new m(e.coins_per_utxo_size)}}async function Y(e){let t=await fetch(`${J}/tx/submit`,{body:Buffer.from(e,"hex"),headers:{"Content-Type":"application/cbor",project_id:X},method:"POST"});if(!t.ok){let o=await t.text();throw Error(`Transaction submission failed: ${o}`)}return t.json()}function ce(e,t){return e.map((o)=>{let c=o.amount.find((r)=>r.unit==="lovelace"),a=c?new m(c.quantity):new m(0),u=o.amount.filter((r)=>r.unit!=="lovelace").map((r)=>({amount:new m(r.quantity),assetName:r.unit.slice(56),policyId:r.unit.slice(0,56)}));return{address:t,amount:a,index:o.output_index,tokens:u,txId:o.tx_hash}})}function ue({TransactionConstructor:e,auxiliaryData:t,bufferedParams:o,currentSlot:c,inputs:a,recipientAddress:u}){let r=a.reduce((n,s)=>n.plus(s.amount),new m(0));if(!r.isPositive())throw new h({errorKey:"toolbox_sweep_amount_too_low",info:{available:r.toString()}});let i=new e({protocolParams:o});for(let n of a)i.addInput(n);if(i.addOutput({address:u,amount:r,tokens:[]}),i.setTTL(c+3600),t)i.setAuxiliaryData(t);i.setFee(i.calculateFee());let y=i.getFee(),d=r.minus(y),p={address:u,amount:d,tokens:[]},P=i.calculateMinUtxoAmountBabbage(p);if(!d.isPositive()||d.lt(P))throw new h({errorKey:"toolbox_sweep_amount_too_low",info:{available:r.toString(),fee:y.toString(),minimumOutput:P.toString()}});return new e({protocolParams:o}).paymentTransaction({auxiliaryData:t,changeAddress:u,inputs:a,outputs:[p],ttl:c+3600})}async function de(e){try{let t=await Q(e),o=0n,c=new Map;for(let r of t){if(!r.amount||!Array.isArray(r.amount))continue;for(let i of r.amount){let{unit:y,quantity:d}=i;if(y==="lovelace")o+=BigInt(d);else{let p=c.get(y)||0n;c.set(y,p+BigInt(d))}}}let a=[],{baseDecimal:u}=se(w.Cardano);if(o>0n)a.push(S.from({chain:w.Cardano,fromBaseDecimal:u,value:o.toString()}));for(let[r,i]of c)a.push(S.from({asset:`${w.Cardano}.${r}`,value:i.toString()}));if(a.length===0)return[S.from({chain:w.Cardano})];return a}catch(t){let o=t instanceof Error?t.message:String(t);return console.error(`Cardano balance fetch error: ${o}`),[S.from({chain:w.Cardano})]}}function le(e){if(!e||typeof e!=="string")return!1;try{let t=ne.decode(e,120);return t.prefix==="addr"||t.prefix==="addr_test"}catch{return!1}}async function me(e,t=0,o=0){let{Bip32PrivateKey:c}=await import("@stricahq/bip32ed25519"),{types:a,address:u,crypto:r}=await import("@stricahq/typhonjs"),i=re(e,oe),d=(await c.fromEntropy(Buffer.from(Array.from(i)))).derive(U+1852).derive(U+1815).derive(U+t),p=d.derive(0).derive(o),P=p.toBip32PublicKey().toPublicKey().toBytes(),A=r.hash28(P),s=d.derive(2).derive(0).toBip32PublicKey().toPublicKey().toBytes(),l=r.hash28(s),_={hash:A,type:a.HashType.ADDRESS},T={hash:l,type:a.HashType.ADDRESS},C=new u.BaseAddress(a.NetworkId.MAINNET,_,T).getBech32(),B=p.toPrivateKey();return{getAddress:()=>C,publicKey:P,publicKeyHash:A,signTransaction:async(k)=>{try{let b=await import("@stricahq/cbors"),I=Buffer.from(k,"hex"),K=b.Decoder.decode(I),[D,O,L,V]=K.value,F=b.Encoder.encode(D),H=r.hash32(F),E=B.sign(H),v=O instanceof Map?O:new Map,M=v.get(W)||[];M.push([P,E]),v.set(W,M);let j=[D,v,L,V];return b.Encoder.encode(j).toString("hex")}catch(b){throw new h("toolbox_cardano_sign_transaction_failed",{message:String(b)})}}}}function we(e){let t,o,c;async function a(){if(!c)c=await ie();return c}async function u(){if(t!==void 0)return t;if(e&&"phrase"in e&&e.phrase){let{derivationPath:n}=e;if(n&&(n.length!==5||n[3]!==0||n[4]===void 0))throw new h("toolbox_derivation_slot_unsupported",{chain:w.Cardano,derivationPath:n});let s=n?.[2]??0,l=n?.[4]??e.index??0;return t=await me(e.phrase,s,l),t}if(e&&"signer"in e&&e.signer)return t=e.signer,t;return}async function r(){if(o)return o;let n=await u();if(!n)return"";if("getAddress"in n)return o=await n.getAddress(),o;return""}async function i(n){let s=n||await r();if(!s)throw new h("core_wallet_connection_not_found");return de(s)}async function y(n){if(n)try{let{tx:T}=await d(n),x=T.getFee();return S.from({chain:w.Cardano,fromBaseDecimal:6,value:x.toString()})}catch{}let s=await a(),l=400,_=s.minFeeB.plus(s.minFeeA.times(l));return S.from({chain:w.Cardano,fromBaseDecimal:6,value:_.toString()})}async function d({sender:n="",recipient:s,assetValue:l,memo:_,pureLovelaceOnly:T=!1,sweep:x=!1}){let{Transaction:C,utils:B}=await import("@stricahq/typhonjs"),k=n||await r();if(!k)throw new h("core_wallet_connection_not_found");let[b,I,K]=await Promise.all([Q(k),ae(),a()]);if(x&&!l.isGasAsset)throw new h({errorKey:"toolbox_not_supported",info:{asset:l.toString(),chain:w.Cardano,feature:"token_sweep"}});let D=x&&l.isGasAsset,O=T||D,L=b.filter((f)=>O?f.amount.some((g)=>g.unit==="lovelace")&&f.amount.every((g)=>g.unit==="lovelace"):f.amount.some((g)=>g.unit==="lovelace")).sort((f,g)=>{let G=f.amount.some((N)=>N.unit!=="lovelace"),te=g.amount.some((N)=>N.unit!=="lovelace");if(G===te)return 0;return G?1:-1}),V=B.getAddressFromString(k),F=B.getAddressFromString(s),H=ce(L,V),E;if(_){let f=new Map;f.set("msg",[_]),E={metadata:[{data:f,label:674}]}}let v={...K,minFeeB:K.minFeeB.plus(K.minFeeA.times(4))};if(D){let f=ue({auxiliaryData:E,bufferedParams:v,currentSlot:I,inputs:H,recipientAddress:F,TransactionConstructor:C}),{payload:g}=f.buildTransaction();return{tx:f,unsignedTx:g}}let M=new m(l.getBaseValue("string")),j=[{address:F,amount:M,tokens:[]}],q=new C({protocolParams:v}).paymentTransaction({auxiliaryData:E,changeAddress:V,inputs:H,outputs:j,ttl:I+3600}),{payload:ee}=q.buildTransaction();return{tx:q,unsignedTx:ee}}async function p(n){let s=await u();if(!s||!("signTransaction"in s))throw new h("core_wallet_connection_not_found");return s.signTransaction(n)}async function P({recipient:n,assetValue:s,memo:l,sweep:_}){let T=await u();if(!T||!("signTransaction"in T))throw new h("core_wallet_connection_not_found");let{unsignedTx:x}=await d({assetValue:s,memo:l,recipient:n,sender:await r(),sweep:_}),C=await p(x);return await Y(C)}async function A(n){let s=await p(n);return await Y(s)}return{createTransaction:d,estimateTransactionFee:y,getAddress:r,getBalance:i,signAndBroadcastTransaction:A,signTransaction:p,transfer:P,validateAddress:le}}export{we as getCardanoToolbox,le as validateCardanoAddress};
1
+ import{ja as R}from"../../chunk-exyqap7m.js";import{bech32 as ne}from"@scure/base";import{mnemonicToEntropy as re}from"@scure/bip39";import{wordlist as oe}from"@scure/bip39/wordlists/english.js";import{AssetValue as S,Chain as w,getChainConfig as se,SwapKitError as h}from"@swapkit/helpers";import m from"bignumber.js";var X="mainnet3YT7XK6NidLPlkHxxyBB5V0WzXUOTIJS",J="https://cardano-mainnet.blockfrost.io/api/v0",U=2147483648,W=0;async function z(e,t){let o=await fetch(`${J}${e}`,{...t,headers:{project_id:X,...t?.headers}});if(!o.ok)throw Error(`Blockfrost API error: ${o.status} ${o.statusText}`);return o.json()}async function Q(e){try{return await z(`/addresses/${e}/utxos`)}catch{return[]}}async function ae(){return(await z("/blocks/latest")).slot}async function ie(){let e=await z("/epochs/latest/parameters"),t={PlutusScriptV1:e.cost_models.PlutusV1?Object.values(e.cost_models.PlutusV1):[],PlutusScriptV2:e.cost_models.PlutusV2?Object.values(e.cost_models.PlutusV2):[],PlutusScriptV3:e.cost_models.PlutusV3?Object.values(e.cost_models.PlutusV3):[]};return{collateralPercent:new m(e.collateral_percent),languageView:t,maxValueSize:Number.parseInt(e.max_val_size,10),minFeeA:new m(e.min_fee_a),minFeeB:new m(e.min_fee_b),minFeeRefScriptCostPerByte:new m(15),priceMem:new m(e.price_mem),priceSteps:new m(e.price_step),stakeKeyDeposit:new m(2000000),utxoCostPerByte:new m(e.coins_per_utxo_size)}}async function Y(e){let t=await fetch(`${J}/tx/submit`,{body:Buffer.from(e,"hex"),headers:{"Content-Type":"application/cbor",project_id:X},method:"POST"});if(!t.ok){let o=await t.text();throw Error(`Transaction submission failed: ${o}`)}return t.json()}function ce(e,t){return e.map((o)=>{let c=o.amount.find((r)=>r.unit==="lovelace"),a=c?new m(c.quantity):new m(0),u=o.amount.filter((r)=>r.unit!=="lovelace").map((r)=>({amount:new m(r.quantity),assetName:r.unit.slice(56),policyId:r.unit.slice(0,56)}));return{address:t,amount:a,index:o.output_index,tokens:u,txId:o.tx_hash}})}function ue({TransactionConstructor:e,auxiliaryData:t,bufferedParams:o,currentSlot:c,inputs:a,recipientAddress:u}){let r=a.reduce((n,s)=>n.plus(s.amount),new m(0));if(!r.isPositive())throw new h({errorKey:"toolbox_sweep_amount_too_low",info:{available:r.toString()}});let i=new e({protocolParams:o});for(let n of a)i.addInput(n);if(i.addOutput({address:u,amount:r,tokens:[]}),i.setTTL(c+3600),t)i.setAuxiliaryData(t);i.setFee(i.calculateFee());let y=i.getFee(),d=r.minus(y),p={address:u,amount:d,tokens:[]},P=i.calculateMinUtxoAmountBabbage(p);if(!d.isPositive()||d.lt(P))throw new h({errorKey:"toolbox_sweep_amount_too_low",info:{available:r.toString(),fee:y.toString(),minimumOutput:P.toString()}});return new e({protocolParams:o}).paymentTransaction({auxiliaryData:t,changeAddress:u,inputs:a,outputs:[p],ttl:c+3600})}async function de(e){try{let t=await Q(e),o=0n,c=new Map;for(let r of t){if(!r.amount||!Array.isArray(r.amount))continue;for(let i of r.amount){let{unit:y,quantity:d}=i;if(y==="lovelace")o+=BigInt(d);else{let p=c.get(y)||0n;c.set(y,p+BigInt(d))}}}let a=[],{baseDecimal:u}=se(w.Cardano);if(o>0n)a.push(S.from({chain:w.Cardano,fromBaseDecimal:u,value:o.toString()}));for(let[r,i]of c)a.push(S.from({asset:`${w.Cardano}.${r}`,value:i.toString()}));if(a.length===0)return[S.from({chain:w.Cardano})];return a}catch(t){let o=t instanceof Error?t.message:String(t);return console.error(`Cardano balance fetch error: ${o}`),[S.from({chain:w.Cardano})]}}function le(e){if(!e||typeof e!=="string")return!1;try{let t=ne.decode(e,120);return t.prefix==="addr"||t.prefix==="addr_test"}catch{return!1}}async function me(e,t=0,o=0){let{Bip32PrivateKey:c}=await import("@stricahq/bip32ed25519"),{types:a,address:u,crypto:r}=await import("@stricahq/typhonjs"),i=re(e,oe),d=(await c.fromEntropy(Buffer.from(Array.from(i)))).derive(U+1852).derive(U+1815).derive(U+t),p=d.derive(0).derive(o),P=p.toBip32PublicKey().toPublicKey().toBytes(),A=r.hash28(P),s=d.derive(2).derive(0).toBip32PublicKey().toPublicKey().toBytes(),l=r.hash28(s),_={hash:A,type:a.HashType.ADDRESS},T={hash:l,type:a.HashType.ADDRESS},C=new u.BaseAddress(a.NetworkId.MAINNET,_,T).getBech32(),B=p.toPrivateKey();return{getAddress:()=>C,publicKey:P,publicKeyHash:A,signTransaction:async(k)=>{try{let b=await import("@stricahq/cbors"),I=Buffer.from(k,"hex"),K=b.Decoder.decode(I),[D,O,L,V]=K.value,F=b.Encoder.encode(D),H=r.hash32(F),E=B.sign(H),v=O instanceof Map?O:new Map,M=v.get(W)||[];M.push([P,E]),v.set(W,M);let j=[D,v,L,V];return b.Encoder.encode(j).toString("hex")}catch(b){throw new h("toolbox_cardano_sign_transaction_failed",{message:String(b)})}}}}function we(e){let t,o,c;async function a(){if(!c)c=await ie();return c}async function u(){if(t!==void 0)return t;if(e&&"phrase"in e&&e.phrase){let{derivationPath:n}=e;if(n&&(n.length!==5||n[3]!==0||n[4]===void 0))throw new h("toolbox_derivation_slot_unsupported",{chain:w.Cardano,derivationPath:n});let s=n?.[2]??0,l=n?.[4]??e.index??0;return t=await me(e.phrase,s,l),t}if(e&&"signer"in e&&e.signer)return t=e.signer,t;return}async function r(){if(o)return o;let n=await u();if(!n)return"";if("getAddress"in n)return o=await n.getAddress(),o;return""}async function i(n){let s=n||await r();if(!s)throw new h("core_wallet_connection_not_found");return de(s)}async function y(n){if(n)try{let{tx:T}=await d(n),x=T.getFee();return S.from({chain:w.Cardano,fromBaseDecimal:6,value:x.toString()})}catch{}let s=await a(),l=400,_=s.minFeeB.plus(s.minFeeA.times(l));return S.from({chain:w.Cardano,fromBaseDecimal:6,value:_.toString()})}async function d({sender:n="",recipient:s,assetValue:l,memo:_,pureLovelaceOnly:T=!1,sweep:x=!1}){let{Transaction:C,utils:B}=await import("@stricahq/typhonjs"),k=n||await r();if(!k)throw new h("core_wallet_connection_not_found");let[b,I,K]=await Promise.all([Q(k),ae(),a()]);if(x&&!l.isGasAsset)throw new h({errorKey:"toolbox_not_supported",info:{asset:l.toString(),chain:w.Cardano,feature:"token_sweep"}});let D=x&&l.isGasAsset,O=T||D,L=b.filter((f)=>O?f.amount.some((g)=>g.unit==="lovelace")&&f.amount.every((g)=>g.unit==="lovelace"):f.amount.some((g)=>g.unit==="lovelace")).sort((f,g)=>{let G=f.amount.some((N)=>N.unit!=="lovelace"),te=g.amount.some((N)=>N.unit!=="lovelace");if(G===te)return 0;return G?1:-1}),V=B.getAddressFromString(k),F=B.getAddressFromString(s),H=ce(L,V),E;if(_){let f=new Map;f.set("msg",[_]),E={metadata:[{data:f,label:674}]}}let v={...K,minFeeB:K.minFeeB.plus(K.minFeeA.times(4))};if(D){let f=ue({auxiliaryData:E,bufferedParams:v,currentSlot:I,inputs:H,recipientAddress:F,TransactionConstructor:C}),{payload:g}=f.buildTransaction();return{tx:f,unsignedTx:g}}let M=new m(l.getBaseValue("string")),j=[{address:F,amount:M,tokens:[]}],q=new C({protocolParams:v}).paymentTransaction({auxiliaryData:E,changeAddress:V,inputs:H,outputs:j,ttl:I+3600}),{payload:ee}=q.buildTransaction();return{tx:q,unsignedTx:ee}}async function p(n){let s=await u();if(!s||!("signTransaction"in s))throw new h("core_wallet_connection_not_found");return s.signTransaction(n)}async function P({recipient:n,assetValue:s,memo:l,sweep:_}){let T=await u();if(!T||!("signTransaction"in T))throw new h("core_wallet_connection_not_found");let{unsignedTx:x}=await d({assetValue:s,memo:l,recipient:n,sender:await r(),sweep:_}),C=await p(x);return await Y(C)}async function A(n){let s=await p(n);return await Y(s)}return{createTransaction:d,estimateTransactionFee:y,getAddress:r,getBalance:i,signAndBroadcastTransaction:A,signTransaction:p,transfer:P,validateAddress:le}}export{we as getCardanoToolbox,le as validateCardanoAddress};