@swapkit/toolboxes 5.3.0 → 5.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/{chunk-k50sjysj.js → chunk-4428244x.js} +1 -1
  3. package/dist/{chunk-s1528ghz.js → chunk-as9fracn.js} +1 -1
  4. package/dist/chunk-dssawneq.js +1 -0
  5. package/dist/chunk-rn33j2bm.js +2 -0
  6. package/dist/src/aleo/index.js +1 -1
  7. package/dist/src/aptos/index.js +1 -1
  8. package/dist/src/cardano/index.js +1 -1
  9. package/dist/src/cosmos/index.js +1 -1
  10. package/dist/src/evm/index.js +1 -1
  11. package/dist/src/hypercore/index.js +1 -1
  12. package/dist/src/index.js +1 -1
  13. package/dist/src/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/evm/toolbox/evm.d.ts +172 -0
  25. package/dist/types/evm/types.d.ts +2 -1
  26. package/dist/types/utxo/__tests__/fixtures/utxo.d.ts +178 -0
  27. package/dist/types/utxo/helpers/bchaddrjs.d.ts +17 -1
  28. package/dist/types/utxo/helpers/txSize.d.ts +7 -5
  29. package/dist/types/utxo/index.d.ts +1 -1
  30. package/dist/types/utxo/toolbox/bitcoinCash.d.ts +1 -0
  31. package/dist/types/utxo/toolbox/index.d.ts +1 -1
  32. package/dist/types/utxo/toolbox/utxo.d.ts +6 -0
  33. package/dist/types/utxo/toolbox/validators.d.ts +2 -1
  34. package/dist/types/utxo/toolbox/zcash.d.ts +1 -0
  35. package/package.json +2 -2
  36. package/dist/chunk-1ma8fv42.js +0 -2
  37. package/dist/chunk-z8n8qjs5.js +0 -1
@@ -0,0 +1,178 @@
1
+ import { type DerivationPathArray } from "@swapkit/helpers";
2
+ import { Transaction } from "@swapkit/utxo-signer";
3
+ export declare const TEST_PHRASE = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
4
+ export declare const RECIPIENT = "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu";
5
+ export declare const CHANGE_ADDRESS = "bc1qnjg0jd8228aq7egyzacy8cys3knf9xvrerkf9g";
6
+ export declare const HASH = "0000000000000000000000000000000000000000000000000000000000000001";
7
+ export type FlowScriptType = "legacy" | "segwit";
8
+ export declare const PATHS: Record<FlowScriptType, DerivationPathArray>;
9
+ export declare const ADDRESSES: Record<FlowScriptType, string>;
10
+ export declare function previousTransaction(script: Uint8Array, value: number, salt?: number): string;
11
+ export declare function txidOf(rawTx: string): string;
12
+ export declare function installMockApi(utxos: {
13
+ address: string;
14
+ script: Uint8Array;
15
+ value: number;
16
+ }[]): {
17
+ api: {
18
+ broadcastTx: import("bun:test").Mock<() => Promise<string>>;
19
+ getBalance: import("bun:test").Mock<() => Promise<number>>;
20
+ getRawTx: import("bun:test").Mock<() => Promise<string>>;
21
+ getSuggestedTxFee: import("bun:test").Mock<() => Promise<number>>;
22
+ getUtxos: import("bun:test").Mock<({ fetchTxHex }: {
23
+ fetchTxHex?: boolean;
24
+ }) => Promise<{
25
+ address: string;
26
+ hash: string;
27
+ index: number;
28
+ txHex: string | undefined;
29
+ value: number;
30
+ witnessUtxo: {
31
+ script: Uint8Array<ArrayBufferLike>;
32
+ value: number;
33
+ };
34
+ }[]>>;
35
+ };
36
+ rawTxs: string[];
37
+ };
38
+ export declare function scriptFor(scriptType: FlowScriptType, publicKey: Uint8Array): import("@swapkit/utxo-signer/utils").Bytes;
39
+ export declare function toolboxFor(scriptType: FlowScriptType): {
40
+ address: string;
41
+ publicKey: Uint8Array<ArrayBufferLike>;
42
+ script: import("@swapkit/utxo-signer/utils").Bytes;
43
+ toolbox: {
44
+ accumulative: typeof import("../..").accumulative;
45
+ broadcastTx: (txHash: string) => Promise<string>;
46
+ bumpFee: ({ txid, newFeeRate, recipient, memo }: import("../..").RBFTransactionParams) => Promise<{
47
+ newFee: number;
48
+ originalFee: number;
49
+ txid: string;
50
+ }>;
51
+ calculateTxSize: ({ inputs, outputs, feeRate }: import("../..").UTXOCalculateTxSizeParams) => number;
52
+ createKeysForPath: (params: {
53
+ wif?: string;
54
+ phrase?: string;
55
+ derivationPath?: string;
56
+ }) => {
57
+ privateKey: import("@swapkit/utxo-signer/utils").Bytes;
58
+ publicKey: Uint8Array<ArrayBufferLike> & Uint8Array<ArrayBuffer>;
59
+ };
60
+ createReplacementTransaction: ({ txid, newFeeRate, recipient, memo, }: import("../..").RBFTransactionParams) => Promise<import("../../toolbox/utxo").ReplacementTransactionResult>;
61
+ createTransaction: ({ assetValue, recipient, memo, feeRate, sender, fetchTxHex, enableRBF, sweep, }: import("../..").UTXOBuildTxParams) => Promise<{
62
+ inputs: import("../..").UTXOType[];
63
+ tx: Transaction;
64
+ utxos: {
65
+ address: string;
66
+ hash: string;
67
+ index: number;
68
+ txHex: string | undefined;
69
+ value: number;
70
+ witnessUtxo: {
71
+ script: Buffer<ArrayBuffer>;
72
+ value: number;
73
+ };
74
+ }[];
75
+ }>;
76
+ deriveAddressAtIndex: ({ accountIndex, index, change }: import("../..").DeriveAddressParams) => {
77
+ accountIndex: number;
78
+ address: string;
79
+ change: boolean;
80
+ index: number;
81
+ path: string;
82
+ pubkey: string;
83
+ } | undefined;
84
+ derivePrivateKeyAtIndex: ({ accountIndex, index, change }: import("../..").DeriveAddressParams) => Uint8Array<ArrayBufferLike> | undefined;
85
+ estimateMaxSendableAmount: ({ from, memo, feeRate, feeOptionKey, recipient, recipients, }: {
86
+ from: string;
87
+ memo?: string;
88
+ feeRate?: number;
89
+ feeOptionKey?: import("@swapkit/helpers").FeeOption;
90
+ recipient?: string;
91
+ recipients?: number | import("../..").TargetOutput[];
92
+ }) => Promise<import("@swapkit/helpers").AssetValue>;
93
+ estimateTransactionFee: (params: {
94
+ assetValue: import("@swapkit/helpers").AssetValue;
95
+ recipient: string;
96
+ sender: string;
97
+ memo?: string;
98
+ feeOptionKey?: import("@swapkit/helpers").FeeOption;
99
+ feeRate?: number;
100
+ fetchTxHex?: boolean;
101
+ }) => Promise<import("@swapkit/helpers").AssetValue>;
102
+ getAddress: () => string | Promise<string> | Promise<undefined>;
103
+ getAddressFromKeys: (keys: {
104
+ publicKey: Uint8Array;
105
+ }) => string;
106
+ getAddressType: (address: string) => "pkh" | "sh" | "sprout" | "sapling" | "unified" | "wpkh" | "wsh" | "tr" | null;
107
+ getBalance: (address: string, scamFilter?: boolean) => Promise<import("@swapkit/helpers").AssetValue[]>;
108
+ getExtendedPublicKey: () => string | undefined;
109
+ getExtendedPublicKeyInfo: ({ accountIndex }?: {
110
+ accountIndex?: number;
111
+ }) => {
112
+ accountIndex: number;
113
+ path: string;
114
+ xpub: string;
115
+ } | undefined;
116
+ getFeeRates: () => Promise<{
117
+ average: number;
118
+ fast: number;
119
+ fastest: number;
120
+ }>;
121
+ getInputsOutputsFee: ({ assetValue, feeOptionKey, feeRate, memo, sender, recipient, sweep, }: Omit<import("../..").UTXOBuildTxParams, "feeRate"> & {
122
+ feeOptionKey?: import("@swapkit/helpers").FeeOption;
123
+ feeRate?: number;
124
+ }) => Promise<{
125
+ fee: number;
126
+ inputs: {
127
+ address: string;
128
+ hash: string;
129
+ index: number;
130
+ txHex: string | undefined;
131
+ value: number;
132
+ witnessUtxo: {
133
+ script: Buffer<ArrayBuffer>;
134
+ value: number;
135
+ };
136
+ }[];
137
+ outputs: import("../..").TargetOutput[];
138
+ } | {
139
+ fee: number;
140
+ inputs?: undefined;
141
+ outputs?: undefined;
142
+ }>;
143
+ getNetworkForChain: () => import("@swapkit/utxo-signer").BTCNetwork;
144
+ getPrivateKeyFromMnemonic: (params: {
145
+ phrase: string;
146
+ derivationPath: string;
147
+ }) => string;
148
+ isRBFEnabled: (txid: string) => Promise<import("../../toolbox/utxo").RBFStatusResult>;
149
+ keys: {
150
+ privateKey: import("@swapkit/utxo-signer/utils").Bytes;
151
+ publicKey: Uint8Array<ArrayBufferLike> & Uint8Array<ArrayBuffer>;
152
+ } | undefined;
153
+ resolveDerivationIndex: ({ address, gapLimit }: import("../..").ResolveDerivationParams) => {
154
+ change: boolean;
155
+ index: number;
156
+ } | undefined;
157
+ signAndBroadcastTransaction: (tx: InstanceType<typeof Transaction>) => Promise<string>;
158
+ signTransaction: (tx: InstanceType<typeof Transaction>) => Transaction | Promise<Transaction>;
159
+ signTransactionWithMultipleKeys: ({ tx, inputDerivations, }: {
160
+ tx: InstanceType<typeof Transaction>;
161
+ inputDerivations: import("../..").InputDerivation[];
162
+ }) => Transaction;
163
+ transfer: ({ memo, recipient, feeOptionKey, feeRate, assetValue, enableRBF, sweep, }: import("../..").UTXOTransferParams & {
164
+ enableRBF?: boolean;
165
+ }) => Promise<string>;
166
+ transferFromMultipleAddresses: ({ utxos, recipient, assetValue, memo, feeRate, feeOptionKey, changeAddress, sweep, }: {
167
+ utxos: import("../..").UTXOForMultiAddressTransfer[];
168
+ recipient: string;
169
+ assetValue: import("@swapkit/helpers").AssetValue;
170
+ memo?: string;
171
+ feeRate?: number;
172
+ feeOptionKey?: import("@swapkit/helpers").FeeOption;
173
+ changeAddress?: string;
174
+ sweep?: boolean;
175
+ }) => Promise<string>;
176
+ validateAddress: (address: string) => boolean;
177
+ };
178
+ };
@@ -1,9 +1,25 @@
1
+ declare enum Format {
2
+ Legacy = "legacy",
3
+ Bitpay = "bitpay",
4
+ Cashaddr = "cashaddr"
5
+ }
1
6
  declare enum UtxoNetwork {
2
7
  Mainnet = "mainnet",
3
8
  Testnet = "testnet"
4
9
  }
10
+ declare enum Type {
11
+ P2PKH = "p2pkh",
12
+ P2SH = "p2sh"
13
+ }
5
14
  declare function isValidAddress(input: any): boolean;
6
15
  declare function detectAddressNetwork(address: string): UtxoNetwork;
7
16
  declare function toLegacyAddress(address: string): string;
8
17
  declare function toCashAddress(address: string): string;
9
- export { detectAddressNetwork, isValidAddress, toCashAddress, toLegacyAddress, UtxoNetwork };
18
+ declare function tryDecodeAddress(address: unknown): {
19
+ scriptType: "pkh" | "sh";
20
+ format: Format;
21
+ hash: any[];
22
+ network: UtxoNetwork;
23
+ type: Type;
24
+ } | undefined;
25
+ export { detectAddressNetwork, isValidAddress, toCashAddress, toLegacyAddress, tryDecodeAddress, UtxoNetwork };
@@ -1,3 +1,4 @@
1
+ import { UTXOScriptType } from "@swapkit/helpers";
1
2
  import type { TargetOutput, UTXOCalculateTxSizeParams, UTXOInputWithScriptType, UTXOSizeInput, UTXOType } from "../types";
2
3
  /**
3
4
  * Minimum transaction fee
@@ -9,13 +10,14 @@ export declare const TX_OVERHEAD: number;
9
10
  export declare const SEGWIT_MARKER_FLAG_WEIGHT = 2;
10
11
  export declare const OP_RETURN_OVERHEAD: number;
11
12
  export declare function compileMemo(memo: string): Uint8Array;
12
- export declare enum UTXOScriptType {
13
- P2PKH = "P2PKH",// legacy
14
- P2WPKH = "P2WPKH"
15
- }
13
+ export { UTXOScriptType } from "@swapkit/helpers";
16
14
  export declare const InputSizes: Record<UTXOScriptType, number>;
17
15
  export declare const OutputSizes: Record<UTXOScriptType, number>;
18
- export declare const getScriptTypeForAddress: (address: string) => UTXOScriptType;
16
+ export declare const isSegwitScriptType: (scriptType: UTXOScriptType) => boolean;
17
+ export declare const getScriptTypeForAddress: (address: string) => UTXOScriptType.P2PKH | UTXOScriptType.P2WPKH;
19
18
  export declare const calculateTxSize: ({ inputs, outputs, feeRate }: UTXOCalculateTxSizeParams) => number;
19
+ export declare const getInputScriptType: (input: UTXOInputWithScriptType | UTXOType | UTXOSizeInput) => UTXOScriptType;
20
20
  export declare const getInputSize: (input: UTXOInputWithScriptType | UTXOType | UTXOSizeInput) => number;
21
+ /** BIP-141: marker/flag plus one empty witness-stack byte for each legacy input in a witness transaction. */
22
+ export declare const getWitnessOverhead: (hasWitness: boolean, legacyInputCount: number) => number;
21
23
  export declare const getOutputSize: (output: TargetOutput, scriptType?: UTXOScriptType) => number;
@@ -2,6 +2,6 @@ export * from "./hdWallet";
2
2
  export * from "./helpers";
3
3
  export * from "./toolbox";
4
4
  export * from "./toolbox/bitcoinCash";
5
- export { addInputsAndOutputs, addressFromKeysGetter, createUTXOToolbox, getNetworkForChain, getUTXOAddressValidator, nonSegwitChains, validateUtxoAddress, } from "./toolbox/utxo";
5
+ export { addInputsAndOutputs, addressFromKeysGetter, createUTXOToolbox, getNetworkForChain, getUTXOAddressValidator, getUtxoAddressType, nonSegwitChains, type UtxoAddressType, validateUtxoAddress, } from "./toolbox/utxo";
6
6
  export * from "./toolbox/zcash";
7
7
  export * from "./types";
@@ -69,6 +69,7 @@ export declare function createBCHToolbox<T extends typeof Chain.BitcoinCash>(too
69
69
  feeRate?: number;
70
70
  fetchTxHex?: boolean;
71
71
  }) => Promise<import("@swapkit/helpers").AssetValue>;
72
+ getAddressType: (address: string) => "pkh" | "sh" | "sprout" | "sapling" | "unified" | "wpkh" | "wsh" | "tr" | null;
72
73
  getExtendedPublicKey: () => string | undefined;
73
74
  getExtendedPublicKeyInfo: ({ accountIndex }?: {
74
75
  accountIndex?: number;
@@ -26,4 +26,4 @@ export { assertDerivationIndex, type CreateHDWalletHelpersParams, createHDWallet
26
26
  export { type DeriveAddressesFromXpubParams, deriveAddressesFromXpub } from "../helpers/xpubDerivation";
27
27
  export { stripToCashAddress } from "./bitcoinCash";
28
28
  export * from "./params";
29
- export { stripPrefix, validateBchAddress, validateZcashAddress } from "./validators";
29
+ export { getBchAddressType, getZcashAddressType, stripPrefix, validateBchAddress, validateZcashAddress, } from "./validators";
@@ -5,6 +5,11 @@ import type { DeriveAddressParams, InputDerivation, RBFTransactionParams, Resolv
5
5
  import type { UtxoToolboxParams } from "./params";
6
6
  export declare const nonSegwitChains: UTXOChain[];
7
7
  export declare const rbfSupportedChains: UTXOChain[];
8
+ export declare function getUtxoAddressType({ address, chain }: {
9
+ address: string;
10
+ chain: UTXOChain;
11
+ }): "pkh" | "sh" | "sprout" | "sapling" | "unified" | "wpkh" | "wsh" | "tr" | null;
12
+ export type UtxoAddressType = NonNullable<ReturnType<typeof getUtxoAddressType>>;
8
13
  export declare function validateUtxoAddress({ address, chain }: {
9
14
  address: string;
10
15
  chain: UTXOChain;
@@ -155,6 +160,7 @@ export declare function createUTXOToolbox<T extends UTXOChain>({ chain, ...toolb
155
160
  getAddressFromKeys: (keys: {
156
161
  publicKey: Uint8Array;
157
162
  }) => string;
163
+ getAddressType: (address: string) => "pkh" | "sh" | "sprout" | "sapling" | "unified" | "wpkh" | "wsh" | "tr" | null;
158
164
  getBalance: (address: string, scamFilter?: boolean) => Promise<AssetValue[]>;
159
165
  getExtendedPublicKey: () => string | undefined;
160
166
  getExtendedPublicKeyInfo: ({ accountIndex }?: {
@@ -1,3 +1,4 @@
1
- export { validateZcashAddress } from "@swapkit/utxo-signer";
1
+ export { getZcashAddressType, validateZcashAddress } from "@swapkit/utxo-signer";
2
2
  export declare function stripPrefix(address: string): string;
3
+ export declare function getBchAddressType(address: string): "pkh" | "sh" | null;
3
4
  export declare function validateBchAddress(address: string): boolean;
@@ -71,6 +71,7 @@ export declare function createZcashToolbox(toolboxParams: {
71
71
  getAddressFromKeys: (keys: {
72
72
  publicKey: Uint8Array;
73
73
  }) => string;
74
+ getAddressType: (address: string) => "pkh" | "sh" | "sprout" | "sapling" | "unified" | "wpkh" | "wsh" | "tr" | null;
74
75
  getBalance: (address: string, scamFilter?: boolean) => Promise<import("@swapkit/helpers").AssetValue[]>;
75
76
  getExtendedPublicKey: () => string | undefined;
76
77
  getExtendedPublicKeyInfo: ({ accountIndex }?: {
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "dependencies": { "@swapkit/helpers": "5.3.0", "@swapkit/utxo-signer": "3.0.0" },
2
+ "dependencies": { "@swapkit/helpers": "5.4.0", "@swapkit/utxo-signer": "3.1.0" },
3
3
  "description": "SwapKit - Toolboxes",
4
4
  "devDependencies": {
5
5
  "@aptos-labs/ts-sdk": "7.0.1",
@@ -131,5 +131,5 @@
131
131
  "type-check:go": "tsgo"
132
132
  },
133
133
  "type": "module",
134
- "version": "5.3.0"
134
+ "version": "5.4.0"
135
135
  }
@@ -1,2 +0,0 @@
1
- import{fa as Be}from"./chunk-s1528ghz.js";import{ga as ye}from"./chunk-k50sjysj.js";import{Chain as x}from"@swapkit/helpers";import{match as Mn}from"ts-pattern";import{Chain as g,getChainConfig as J,getRPCUrl as wt,SKConfig as ht,SwapKitError as j}from"@swapkit/helpers";import{FallbackProvider as vt,getAddress as ve,Interface as Et,JsonRpcProvider as se,Network as _t}from"ethers";import{match as Ee}from"ts-pattern";function Ct(e){return new se(e)}async function Vn(e,t){return Ct(t||await wt(e))}function _e(e){let t=ht.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=_t.from(Number(n)),[a]=t;if(t.length===1)return new se(a,o,{staticNetwork:o});return new vt(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 Fe(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 Ae(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),At=(e)=>{try{return typeof e==="string"&&!!ve(e)}catch{return!1}};function Mt(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})=>!At(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 Gt(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 Sn({chain:e,abi:t,data:n,to:o}){let r=new Et(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=Gt(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(Mt(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 vn,FeeOption as En,resolveDerivationPath as _n}from"@swapkit/helpers";import{HDNodeWallet as Cn}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 Bt,applyFeeMultiplierToBigInt as M,Chain as I,EVMChains as Ot,FeeOption as d,isGasAsset as It,SwapKitError as m,SwapKitNumber as Q}from"@swapkit/helpers";import{erc20ABI as z}from"@swapkit/helpers/contracts";import{BrowserProvider as Vt,Contract as Ve,getAddress as ee,getBytes as St,Interface as Se,isError as H,resolveAddress as Rt,Transaction as pe}from"ethers";import{match as Re}from"ts-pattern";function Y(e){return{getBalance:Be(e)}}function Ln(e){return e}var be=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function te({chain:e=I.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:Jt({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),approvedAmount:He({chain:e,provider:t}),broadcastTransaction:(c)=>t.broadcastTransaction(c),call:ae({chain:e,isEIP1559Compatible:o,provider:t,signer:n}),createApprovalTx:ln({chain:e,provider:t,signer:n}),createContract:Nt({chain:e,provider:t}),createContractTxObject:W({chain:e,provider:t}),createTransaction:s,createTransferTx:s,EIP1193SendTransaction:oe(t),estimateCall:Ue({provider:t,signer:n}),estimateGasLimit:Qt({chain:e,provider:t,signer:n}),estimateGasPrices:i,estimateTransactionFee:mn({chain:e,isEIP1559Compatible:o,provider:t}),getAddress:()=>n?n.getAddress():void 0,getBalance:Y(e).getBalance,getNetworkParams:Ce(e),isApproved:$t({chain:e,provider:t}),sendTransaction:Ke({chain:e,estimateGasPrices:i,isEIP1559Compatible:o,provider:t,signer:n}),signAuthorization:Zt({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:Yt({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 Vt}function ge(e,t,n){return new Ve(e,Se.from(t),n)}function Nt({provider:e}){return function(n,o){return new Ve(n,Se.from(o),e)}}var Lt=["payable","nonpayable"];function Dt({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&&Lt.includes(n.stateMutability)}function Wn(e){return ee(e)}var Ht=30000,Oe=new WeakMap,Ie=()=>{};function Ut(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 ke({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}=Ut(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(H(e,"NONCE_EXPIRED")||H(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 Ne(e){return H(e,"NETWORK_ERROR")||H(e,"SERVER_ERROR")||H(e,"TIMEOUT")}function zt(e){return Ne(e)||H(e,"UNSUPPORTED_OPERATION")}function Le(e){return Ne(e)||de(e)}function De(e,t){return e.getTransaction(t).then((n)=>n!==null,()=>!1)}async function Kt({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 Xn(e,t){let n=Pe(e,t);if(n)return ee(n.toLowerCase());throw new m("toolbox_evm_invalid_gas_asset_address")}var qt=Ot.reduce((e,t)=>(e[t]="0x0000000000000000000000000000000000000000",e),{}),jt={...qt,[I.Optimism]:"0x4200000000000000000000000000000000000042",[I.Polygon]:"0x0000000000000000000000000000000000001010"},Wt=[I.Arbitrum,I.Aurora,I.Base,I.Optimism,I.Robinhood];function Pe({chain:e,symbol:t,ticker:n},o){try{let a=e===I.BinanceSmartChain&&t==="BNB"&&n==="BNB",r=e===I.Hyperevm&&t==="HYPE"&&n==="HYPE",i=e===o&&t===o&&n===o,s=Wt.includes(e)&&t==="ETH"&&n==="ETH";if(i||a||r||s)return jt[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(I.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(I.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 Xt({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 Rt(u,n),{nonce:G,release:R,settle:N}=await ke({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(!Le(_))R();throw _}finally{N()}}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=Dt({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 Xt({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 He({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 $t({provider:e,chain:t}){return async function({assetAddress:o,spenderAddress:a,from:r,amount:i=be}){let s=await He({chain:t,provider:e})({assetAddress:o,from:r,spenderAddress:a});return Q.fromBigInt(s).gte(Q.fromBigInt(BigInt(i)))}}function Jt({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 Yt({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=Ke({chain:e,estimateGasPrices:t,isEIP1559Compatible:a,provider:r,signer:o});if(!f)throw new m("toolbox_evm_no_from_address");let A=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 P({...A,feeOptionKey:u,sweep:p})}}function Ue({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 Qt({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 Ue({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 Zt({signer:e}){if(!e)return;return(t)=>Ae(e,t)}var ze=(e)=>e.type===4||(e.authorizations?.length??0)>0,en=(e)=>!ze(e)&&(e.type===2||!!e.maxFeePerGas||!!e.maxPriorityFeePerGas),tn=(e,t=!0)=>{if(ze(e))return"eip7702";if(en(e)||t)return"eip1559";return"legacy"};function nn(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 P=l||await o.getAddress(),{chainId:A}=await n.getNetwork(),C=o.provider??n,{nonce:G,release:R,settle:N}=await ke({address:P,nonce:c.nonce,provider:C}),_=async()=>{let E=tn(f,a);if(E==="eip7702")Me(f.authorizations||[],A);let w=Re(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)?{}:nn(E,(await F())[i]),h;try{h=B(f.gasLimit?BigInt(f.gasLimit):await n.estimateGas(V)*11n/10n)}catch(O){throw new m("toolbox_evm_error_estimating_gas_limit",{error:O})}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 Kt({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(!zt(w))throw R(),new m({errorKey:"toolbox_evm_error_sending_transaction",info:F},F);let L=H(w,"UNSUPPORTED_OPERATION"),S;try{S=await o.signTransaction({...E,from:P})}catch(h){if(L)R();let O={...F,fallbackError:h};throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:O},O)}try{return(await C.broadcastTransaction(S)).hash}catch(h){let O={...F,fallbackError:h};if(de(h)){let U=pe.from(S).hash;if(U)return U}if(fe(h)){let U=pe.from(S).hash;if(U&&await De(C,U))return U;throw new m({errorKey:"toolbox_evm_nonce_conflict",info:O},O)}if(L&&!Le(h))R();throw new m({errorKey:"toolbox_evm_error_sending_transaction",info:O},O)}}}finally{N()}}}function D(e,t){throw new m({errorKey:"toolbox_sweep_amount_too_low",info:{balance:e.toString(),fee:t.toString()}})}function on(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 an(e,t){if(e>t)return e;return t}function rn(e){return St(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 sn({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(an(i,l),n)}async function cn({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}=on((await b())[a],i),f={...l,...p,data:t,from:r,to:c},P=rn(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(O){if(me(O))D(u,P);throw O}}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 sn({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 un({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:P,type:A,maxFeePerGas:C,maxPriorityFeePerGas:G,gasPrice:R,...N}){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(It(s)){let{hexlify:L,toUtf8Bytes:S}=await import("ethers"),h=b||L(S(l||""));if(!P)return{...N,...c!==void 0&&{authorizations:c},data:h,from:E,...y!==void 0&&{gasLimit:y},to:u,...A!==void 0&&{type:A},value:B(_)};return cn({chain:e,data:h,estimateAdditionalFee:t,estimateGasPrices:n,feeOptionKey:p,from:E,isEIP1559Compatible:o,provider:a,recipient:u,transaction:{nonce:N.nonce,type:A}})}let w=Pe(s,e);if(!w)throw new m("toolbox_evm_no_contract_address");let V=W({chain:e,provider:a}),F=P?await un({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:N.nonce}})}}function ln({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 mn({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=Bt.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 pn,FeeOption as k,getChainConfig as fn,resolveDerivationPath as dn,SwapKitError as q}from"@swapkit/helpers";import{Contract as yn,HDNodeWallet as bn}from"ethers";import{match as gn,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 Pn="0x420000000000000000000000000000000000000f";function re(e){return new yn(Pn,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 xn(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 Tn(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 wn(e){return async function(n){let o=re(e),a=await Je(e)(n);if(o&&"getL1GasUsed"in o)return o.getL1GasUsed(a)}}function hn(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{[k.Average]:{gasPrice:i,l1GasPrice:r,maxFeePerGas:n,maxPriorityFeePerGas:o},[k.Fast]:{gasPrice:K(i,k.Fast),l1GasPrice:K(r||0n,k.Fast),maxFeePerGas:n,maxPriorityFeePerGas:K(o,k.Fast)},[k.Fastest]:{gasPrice:K(i,k.Fastest),l1GasPrice:K(r||0n,k.Fastest),maxFeePerGas:n,maxPriorityFeePerGas:K(o,k.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=gn(o).with({phrase:We.string},({phrase:p,derivationPath:y,index:f=0})=>bn.fromPhrase(p,void 0,pn(dn({chain:e,derivationPath:y,index:f}))).connect(n)).with({signer:We.any},({signer:p})=>p).otherwise(()=>{return}),r=$e(n),i=BigInt(fn(e).chainId),s=xe(n,i),c=xn(n,i),l=Te(n),u=e===Xe.Optimism?hn(n):void 0;return{...te({chain:e,estimateAdditionalFee:c,estimateGasPrices:u,provider:n,signer:a}),estimateL1Gas:wn(n),estimateL1GasCost:s,estimateL2GasCost:Ye(n),estimateOperatorFee:l,estimateTotalGasCost:Tn(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=En.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.Aurora),at=v(T.Avalanche),rt=ie(T.Base),it=v(T.Berachain),st=v(T.BinanceSmartChain),mo=v(T.Botanix),ct=v(T.Core),ut=v(T.Corn),lt=v(T.Cronos),mt=v(T.Gnosis),pt=v(T.Robinhood),ft=v(T.Hyperevm),dt=v(T.Linea),yt=v(T.Polygon),bt=v(T.MegaETH),gt=v(T.Monad),Pt=v(T.Plasma),we=v(T.Sonic),xt=ie(T.Unichain),Tt=v(T.XLayer);function v(e){return function({provider:n,...o}){let a=Fe(e),r=Fn(o).with({phrase:Ze.string},({phrase:s,derivationPath:c,index:l=0})=>Cn.fromPhrase(s,void 0,vn(_n({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 Gn(e,t){return Mn(e).with(x.Adi,()=>tt(t)).with(x.Arbitrum,()=>nt(t)).with(x.Aurora,()=>ot(t)).with(x.Avalanche,()=>at(t)).with(x.Base,()=>rt(t)).with(x.Berachain,()=>it(t)).with(x.BinanceSmartChain,()=>st(t)).with(x.Botanix,()=>we(t)).with(x.Core,()=>ct(t)).with(x.Corn,()=>ut(t)).with(x.Cronos,()=>lt(t)).with(x.Ethereum,()=>et(t)).with(x.Gnosis,()=>mt(t)).with(x.Hyperevm,()=>ft(t)).with(x.Linea,()=>dt(t)).with(x.MegaETH,()=>bt(t)).with(x.Monad,()=>gt(t)).with(x.Optimism,()=>Qe(t)).with(x.Plasma,()=>Pt(t)).with(x.Polygon,()=>yt(t)).with(x.Robinhood,()=>pt(t)).with(x.Sonic,()=>we(t)).with(x.Unichain,()=>xt(t)).with(x.XLayer,()=>Tt(t)).exhaustive()}async function go(e,t){let n={...t,provider:t?.provider||_e(e)};return Gn(e,n)}
2
- export{Y as b,Ln as c,Ct as d,Vn as e,_e as f,B as g,Ce as h,Fe as i,Ae as j,Mt as k,Gt as l,Sn as m,Me as n,be as o,te as p,kt as q,ne as r,ge as s,Nt as t,Dt as u,Wn as v,oe as w,Xn as x,jt as y,Pe as z,W as A,X as B,ze as C,en as D,tn 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,mo as P,ct 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 _,we as $,xt as aa,Tt as ba,Gn as ca,go as da};
@@ -1 +0,0 @@
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,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-1ma8fv42.js";import"./chunk-s1528ghz.js";import"./chunk-k50sjysj.js";export{u as ADIToolbox,v as ARBToolbox,w as AURORAToolbox,x as AVAXToolbox,y as BASEToolbox,z as BERAToolbox,A as BSCToolbox,b as BaseEVMToolbox,B as BotanixToolbox,C as COREToolbox,D as CORNToolbox,E as CROToolbox,k as ContractAddress,t as ETHToolbox,F as GNOToolbox,G as HOODToolbox,H as HYPEREVMToolbox,I as LINEAToolbox,J as MATICToolbox,a as MAX_APPROVAL,K as MEGAETHToolbox,L as MONADToolbox,s as OPToolbox,M as PLASMAToolbox,N as SONICToolbox,O as UNIToolbox,P as XLayerToolbox,e as createContract,r as createOPStackToolbox,j as getChecksumAddressFromAsset,f as getCreateContract,m as getCreateContractTxObject,i as getEIP1193SendTransaction,q as getEVMTxType,n as getEstimateGasPrices,Q as getEvmToolbox,R as getEvmToolboxAsync,l as getTokenAddress,d as isBrowserProvider,p as isEIP1559Transaction,o as isEIP7702Transaction,g as isStateChangingCall,h as toChecksumAddress,c as validateEVMAddress};