@bitzy-app/bitzy-sdk 0.0.7 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,25 @@
1
+ ## [0.1.1](https://github.com/bitzy-app/bitzy-sdk/compare/v0.1.0...v0.1.1) (2026-01-15)
2
+
3
+
4
+
5
+ # [0.1.0](https://github.com/bitzy-app/bitzy-sdk/compare/v0.0.8...v0.1.0) (2026-01-15)
6
+
7
+
8
+ ### Bug Fixes
9
+
10
+ * build setup ([53a9fed](https://github.com/bitzy-app/bitzy-sdk/commit/53a9fed4774a36c8d5f14d2699873c48d2daae68))
11
+
12
+
13
+
14
+ ## [0.0.8](https://github.com/bitzy-app/bitzy-sdk/compare/v0.0.7...v0.0.8) (2026-01-15)
15
+
16
+
17
+ ### Features
18
+
19
+ * add automatic publicClient creation and RPC configuration ([4376ec3](https://github.com/bitzy-app/bitzy-sdk/commit/4376ec33161e18133126ea49835bcb4f19200a57))
20
+
21
+
22
+
1
23
  ## [0.0.7](https://github.com/bitzy-app/bitzy-sdk/compare/v0.0.6...v0.0.7) (2025-09-17)
2
24
 
3
25
 
package/README.md CHANGED
@@ -63,6 +63,56 @@ console.log('Amount out:', result.amountOutBN.toFixed());
63
63
  console.log('Distributions:', result.distributions);
64
64
  ```
65
65
 
66
+ **With Custom PublicClient (Optional):**
67
+
68
+ ```typescript
69
+ import { fetchSwapRoute } from '@bitzy-app/bitzy-sdk';
70
+ import { createPublicClient, http, defineChain } from 'viem';
71
+
72
+ // Create your own PublicClient (e.g., from wagmi, or custom RPC)
73
+ const publicClient = createPublicClient({
74
+ chain: defineChain({
75
+ id: 3637,
76
+ name: 'Botanix Mainnet',
77
+ network: 'botanix-mainnet',
78
+ nativeCurrency: {
79
+ name: 'Bitcoin',
80
+ symbol: 'BTC',
81
+ decimals: 18,
82
+ },
83
+ rpcUrls: {
84
+ default: { http: ['https://rpc.botanixlabs.com'] },
85
+ },
86
+ }),
87
+ transport: http(),
88
+ });
89
+
90
+ // Use your custom PublicClient for better performance and connection reuse
91
+ const result = await fetchSwapRoute(
92
+ {
93
+ amountIn: '1.5',
94
+ srcToken: btcToken,
95
+ dstToken: usdcToken,
96
+ chainId: 3637,
97
+ },
98
+ {
99
+ publicClient: publicClient, // Optional: inject your own client
100
+ headers: {
101
+ 'authen-key': 'your-api-key', // Optional: API key for authentication
102
+ },
103
+ }
104
+ );
105
+ ```
106
+
107
+ **Note:** If you don't provide `publicClient`, the SDK will automatically create one using default RPC endpoints:
108
+ - **Botanix Mainnet (3637)**: `https://rpc.botanixlabs.com`
109
+ - **Botanix Testnet (3636)**: `https://node.botanixlabs.dev`
110
+
111
+ Injecting your own client is useful when:
112
+ - You already have a `PublicClient` instance (e.g., from wagmi's `useAccount()`)
113
+ - You want to reuse connections for better performance
114
+ - You need to use a custom RPC endpoint
115
+
66
116
  ### **1.2 `fetchBatchSwapRoutes()` - Batch Route Aggregation**
67
117
 
68
118
  ```typescript
@@ -679,6 +729,8 @@ Main function for aggregating swap routes across multiple DEXs in any environmen
679
729
 
680
730
  **Returns:** `Promise<SwapResult>`
681
731
 
732
+ **Note:** The `publicClient` is automatically created using default RPC endpoints if not provided. You can optionally inject your own `PublicClient` instance (e.g., from wagmi) for better performance and connection reuse.
733
+
682
734
  #### **`fetchBatchSwapRoutes(requests)`**
683
735
  Aggregate multiple routes simultaneously across different token pairs.
684
736
 
@@ -749,6 +801,7 @@ interface FetchSwapRouteConfig {
749
801
  timeout?: number; // Optional: Request timeout (defaults to 30000)
750
802
  headers?: Record<string, string>; // Optional: Custom HTTP headers (defaults to {})
751
803
  forcePartCount?: number; // Optional: Force specific partCount, overriding intelligent calculation
804
+ publicClient?: PublicClient; // Optional: Viem PublicClient instance (auto-created if not provided)
752
805
  }
753
806
  ```
754
807
 
@@ -882,6 +935,9 @@ When no config is provided, the aggregator SDK uses these sensible defaults:
882
935
  - **API URL**: `https://api-public.bitzy.app` (from `DEFAULT_API_BASE_URL`)
883
936
  - **API Key**: From `NEXT_PUBLIC_BITZY_API_KEY` environment variable or fallback
884
937
  - **Addresses**: Network-specific defaults from `CONTRACT_ADDRESSES`
938
+ - **RPC Endpoints**:
939
+ - Botanix Mainnet (3637): `https://rpc.botanixlabs.com`
940
+ - Botanix Testnet (3636): `https://node.botanixlabs.dev`
885
941
  - **PartCount**: `5` for high-value pairs, `1` for others
886
942
  - **Timeout**: `30` seconds
887
943
  - **Refresh**: `10` seconds
@@ -28,6 +28,7 @@ export declare class APIClient {
28
28
  private request;
29
29
  /**
30
30
  * Get V3 path for swap routing
31
+ * Uses URLSearchParams for single encoding (avoids double-encoding on iOS).
31
32
  */
32
33
  getPathV3(srcToken: Token, dstToken: Token, amountIn: string, types: number[], enabledSources: number[]): Promise<PathV3Response>;
33
34
  /**
@@ -35,9 +36,5 @@ export declare class APIClient {
35
36
  * Returns minimum amounts for tokens to use multiple routes
36
37
  */
37
38
  getAssetMinimum(): Promise<any>;
38
- /**
39
- * Build query string from parameters
40
- */
41
- private buildQueryString;
42
39
  }
43
40
  //# sourceMappingURL=Client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Client.d.ts","sourceRoot":"","sources":["../../src/api/Client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAmB,cAAc,EAAE,MAAM,UAAU,CAAC;AAIlE,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAED,qBAAa,SAAS;IACpB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAA0B;IACjD,OAAO,CAAC,MAAM,CAAkB;IAEhC,OAAO;IAIP;;;;;;;;OAQG;IACH,MAAM,CAAC,WAAW,CAAC,MAAM,EAAE,eAAe,GAAG,SAAS;IAqBtD;;OAEG;IACH,MAAM,CAAC,aAAa,IAAI,IAAI;IAI5B;;OAEG;YACW,OAAO;IAoDrB;;OAEG;IACG,SAAS,CACb,QAAQ,EAAE,KAAK,EACf,QAAQ,EAAE,KAAK,EACf,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EAAE,EACf,cAAc,EAAE,MAAM,EAAE,GACvB,OAAO,CAAC,cAAc,CAAC;IAgB1B;;;OAGG;IACG,eAAe,IAAI,OAAO,CAAC,GAAG,CAAC;IAMrC;;OAEG;IACH,OAAO,CAAC,gBAAgB;CAczB"}
1
+ {"version":3,"file":"Client.d.ts","sourceRoot":"","sources":["../../src/api/Client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAmB,cAAc,EAAE,MAAM,UAAU,CAAC;AAIlE,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAED,qBAAa,SAAS;IACpB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAA0B;IACjD,OAAO,CAAC,MAAM,CAAkB;IAEhC,OAAO;IAIP;;;;;;;;OAQG;IACH,MAAM,CAAC,WAAW,CAAC,MAAM,EAAE,eAAe,GAAG,SAAS;IAoBtD;;OAEG;IACH,MAAM,CAAC,aAAa,IAAI,IAAI;IAI5B;;OAEG;YACW,OAAO;IAoDrB;;;OAGG;IACG,SAAS,CACb,QAAQ,EAAE,KAAK,EACf,QAAQ,EAAE,KAAK,EACf,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EAAE,EACf,cAAc,EAAE,MAAM,EAAE,GACvB,OAAO,CAAC,cAAc,CAAC;IAa1B;;;OAGG;IACG,eAAe,IAAI,OAAO,CAAC,GAAG,CAAC;CAKtC"}
@@ -14,6 +14,13 @@ export interface FetchSwapRouteConfig {
14
14
  * - Low-value tokens (meme tokens, small caps): partCount = 1 (simpler routing)
15
15
  */
16
16
  forcePartCount?: number;
17
+ /**
18
+ * Optional PublicClient from viem
19
+ * - If provided, will be used for contract calls
20
+ * - If not provided, SDK will automatically create one using RPC_CONFIG
21
+ * - Useful when you already have a PublicClient instance (e.g., from wagmi)
22
+ */
23
+ publicClient?: PublicClient;
17
24
  }
18
25
  /**
19
26
  * Common function to fetch swap routes
@@ -1 +1 @@
1
- {"version":3,"file":"FetchSwapRoute.d.ts","sourceRoot":"","sources":["../../src/common/FetchSwapRoute.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,WAAW,EAAuB,MAAM,UAAU,CAAC;AAS/E,OAAO,EAAE,YAAY,EAAE,MAAM,MAAM,CAAC;AAEpC,MAAM,WAAW,oBAAoB;IACnC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC/B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAClC,OAAO,EAAE,WAAW,EACpB,MAAM,GAAE,oBAAyB,GAChC,OAAO,CAAC,UAAU,CAAC,CAoCrB;AAED;;GAEG;AACH,wBAAsB,oBAAoB,CACxC,KAAK,EAAE,KAAK,CAAC;IAAE,OAAO,EAAE,WAAW,CAAC;IAAC,MAAM,EAAE,oBAAoB,CAAA;CAAE,CAAC,GACnE,OAAO,CAAC,KAAK,CAAC;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,IAAI,CAAC,EAAE,UAAU,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC,CAyBzE;AAED;;GAEG;AACH,wBAAsB,YAAY,CAChC,QAAQ,EAAE,KAAK,EACf,QAAQ,EAAE,KAAK,EACf,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,MAAM,GAAE,oBAAyB,GAChC,OAAO,CAAC;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CAehD;AAED,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,KAAK,CAAC;IAChB,QAAQ,EAAE,KAAK,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,YAAY,CAAC,EAAE,YAAY,CAAC;CAC7B;AAED;;;GAGG;AACH,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,qBAAqB,EAC9B,MAAM,GAAE,oBAAyB,GAChC,OAAO,CAAC,UAAU,CAAC,CAcrB;AAGD,eAAe,cAAc,CAAC"}
1
+ {"version":3,"file":"FetchSwapRoute.d.ts","sourceRoot":"","sources":["../../src/common/FetchSwapRoute.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,WAAW,EAAuB,MAAM,UAAU,CAAC;AAS/E,OAAO,EAAE,YAAY,EAAE,MAAM,MAAM,CAAC;AAEpC,MAAM,WAAW,oBAAoB;IACnC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC/B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;;;OAKG;IACH,YAAY,CAAC,EAAE,YAAY,CAAC;CAC7B;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAClC,OAAO,EAAE,WAAW,EACpB,MAAM,GAAE,oBAAyB,GAChC,OAAO,CAAC,UAAU,CAAC,CAsCrB;AAED;;GAEG;AACH,wBAAsB,oBAAoB,CACxC,KAAK,EAAE,KAAK,CAAC;IAAE,OAAO,EAAE,WAAW,CAAC;IAAC,MAAM,EAAE,oBAAoB,CAAA;CAAE,CAAC,GACnE,OAAO,CAAC,KAAK,CAAC;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,IAAI,CAAC,EAAE,UAAU,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC,CAyBzE;AAED;;GAEG;AACH,wBAAsB,YAAY,CAChC,QAAQ,EAAE,KAAK,EACf,QAAQ,EAAE,KAAK,EACf,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,MAAM,EACf,MAAM,GAAE,oBAAyB,GAChC,OAAO,CAAC;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CAehD;AAED,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,KAAK,CAAC;IAChB,QAAQ,EAAE,KAAK,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,YAAY,CAAC,EAAE,YAAY,CAAC;CAC7B;AAED;;;GAGG;AACH,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,qBAAqB,EAC9B,MAAM,GAAE,oBAAyB,GAChC,OAAO,CAAC,UAAU,CAAC,CAcrB;AAGD,eAAe,cAAc,CAAC"}
@@ -24,6 +24,15 @@ export declare const CONTRACT_ADDRESSES: ChainWrap<{
24
24
  nativeAddress: Address;
25
25
  gasLimit: bigint;
26
26
  }>;
27
+ export declare const RPC_CONFIG: ChainWrap<{
28
+ rpcUrls: string[];
29
+ name: string;
30
+ nativeCurrency: {
31
+ name: string;
32
+ symbol: string;
33
+ decimals: number;
34
+ };
35
+ }>;
27
36
  export declare const LIQUIDITY_SOURCES: ChainWrap<LiquiditySourcesConfig>;
28
37
  export declare const getLiquiditySources: (chainId: number) => LiquiditySourcesConfig;
29
38
  export declare const getContractAddresses: (chainId: number) => {
@@ -41,6 +50,15 @@ export declare const getContractAddresses: (chainId: number) => {
41
50
  gasLimit: bigint;
42
51
  };
43
52
  export declare const getDexRouters: (chainId: number) => Record<string, `0x${string}`>;
53
+ export declare const getRpcConfig: (chainId: number) => {
54
+ rpcUrls: string[];
55
+ name: string;
56
+ nativeCurrency: {
57
+ name: string;
58
+ symbol: string;
59
+ decimals: number;
60
+ };
61
+ };
44
62
  export declare const DEFAULT_NETWORKS: ChainWrap<{
45
63
  factoryAddress: Address;
46
64
  v3FactoryAddress: Address;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/constants/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAG7D,eAAO,MAAM,aAAa;;;CAGhB,CAAC;AAGX,eAAO,MAAM,WAAW,EAAE,OACoB,CAAC;AAC/C,eAAO,MAAM,aAAa,EAAE,OACkB,CAAC;AAG/C,eAAO,MAAM,kBAAkB,IAAI,CAAC;AACpC,eAAO,MAAM,eAAe,QAAQ,CAAC;AAGrC,eAAO,MAAM,oBAAoB,iCAAiC,CAAC;AAGnE,eAAO,MAAM,WAAW,EAAE,SAAS,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAa1D,CAAC;AAGF,eAAO,MAAM,kBAAkB,EAAE,SAAS,CAAC;IACzC,cAAc,EAAE,OAAO,CAAC;IACxB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,wBAAwB,EAAE,OAAO,CAAC;IAClC,qBAAqB,EAAE,OAAO,CAAC;IAC/B,aAAa,EAAE,OAAO,CAAC;IACvB,iBAAiB,EAAE,OAAO,CAAC;IAC3B,UAAU,EAAE,OAAO,CAAC;IACpB,kBAAkB,EAAE,OAAO,CAAC;IAC5B,iBAAiB,EAAE,OAAO,CAAC;IAC3B,cAAc,EAAE,OAAO,CAAC;IACxB,aAAa,EAAE,OAAO,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;CAClB,CA+BA,CAAC;AAGF,eAAO,MAAM,iBAAiB,EAAE,SAAS,CAAC,sBAAsB,CAW/D,CAAC;AAGF,eAAO,MAAM,mBAAmB,GAC9B,SAAS,MAAM,KACd,sBAEF,CAAC;AAEF,eAAO,MAAM,oBAAoB,GAAI,SAAS,MAAM;oBAlElC,OAAO;sBACL,OAAO;8BACC,OAAO;2BACV,OAAO;mBACf,OAAO;uBACH,OAAO;gBACd,OAAO;wBACC,OAAO;uBACR,OAAO;oBACV,OAAO;mBACR,OAAO;cACZ,MAAM;CAyDjB,CAAC;AAEF,eAAO,MAAM,aAAa,GAAI,SAAS,MAAM,kCAE5C,CAAC;AAGF,eAAO,MAAM,gBAAgB;oBA3EX,OAAO;sBACL,OAAO;8BACC,OAAO;2BACV,OAAO;mBACf,OAAO;uBACH,OAAO;gBACd,OAAO;wBACC,OAAO;uBACR,OAAO;oBACV,OAAO;mBACR,OAAO;cACZ,MAAM;EAgEgC,CAAC;AACnD,eAAO,MAAM,UAAU,+BAA0B,CAAC;AAGlD,eAAO,MAAM,aAAa;;;CAGhB,CAAC;AAGX,eAAO,MAAM,WAAW;;;;;;;CAOd,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/constants/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAG7D,eAAO,MAAM,aAAa;;;CAGhB,CAAC;AAGX,eAAO,MAAM,WAAW,EAAE,OACoB,CAAC;AAC/C,eAAO,MAAM,aAAa,EAAE,OACkB,CAAC;AAG/C,eAAO,MAAM,kBAAkB,IAAI,CAAC;AACpC,eAAO,MAAM,eAAe,QAAQ,CAAC;AAGrC,eAAO,MAAM,oBAAoB,iCAAiC,CAAC;AAGnE,eAAO,MAAM,WAAW,EAAE,SAAS,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAa1D,CAAC;AAGF,eAAO,MAAM,kBAAkB,EAAE,SAAS,CAAC;IACzC,cAAc,EAAE,OAAO,CAAC;IACxB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,wBAAwB,EAAE,OAAO,CAAC;IAClC,qBAAqB,EAAE,OAAO,CAAC;IAC/B,aAAa,EAAE,OAAO,CAAC;IACvB,iBAAiB,EAAE,OAAO,CAAC;IAC3B,UAAU,EAAE,OAAO,CAAC;IACpB,kBAAkB,EAAE,OAAO,CAAC;IAC5B,iBAAiB,EAAE,OAAO,CAAC;IAC3B,cAAc,EAAE,OAAO,CAAC;IACxB,aAAa,EAAE,OAAO,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;CAClB,CA+BA,CAAC;AAGF,eAAO,MAAM,UAAU,EAAE,SAAS,CAAC;IACjC,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,cAAc,EAAE;QACd,IAAI,EAAE,MAAM,CAAC;QACb,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,MAAM,CAAC;KAClB,CAAC;CACH,CAqBA,CAAC;AAGF,eAAO,MAAM,iBAAiB,EAAE,SAAS,CAAC,sBAAsB,CAW/D,CAAC;AAGF,eAAO,MAAM,mBAAmB,GAC9B,SAAS,MAAM,KACd,sBAEF,CAAC;AAEF,eAAO,MAAM,oBAAoB,GAAI,SAAS,MAAM;oBAlGlC,OAAO;sBACL,OAAO;8BACC,OAAO;2BACV,OAAO;mBACf,OAAO;uBACH,OAAO;gBACd,OAAO;wBACC,OAAO;uBACR,OAAO;oBACV,OAAO;mBACR,OAAO;cACZ,MAAM;CAyFjB,CAAC;AAEF,eAAO,MAAM,aAAa,GAAI,SAAS,MAAM,kCAE5C,CAAC;AAEF,eAAO,MAAM,YAAY,GAAI,SAAS,MAAM;aA3DjC,MAAM,EAAE;UACX,MAAM;oBACI;QACd,IAAI,EAAE,MAAM,CAAC;QACb,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,MAAM,CAAC;KAClB;CAuDF,CAAC;AAGF,eAAO,MAAM,gBAAgB;oBA/GX,OAAO;sBACL,OAAO;8BACC,OAAO;2BACV,OAAO;mBACf,OAAO;uBACH,OAAO;gBACd,OAAO;wBACC,OAAO;uBACR,OAAO;oBACV,OAAO;mBACR,OAAO;cACZ,MAAM;EAoGgC,CAAC;AACnD,eAAO,MAAM,UAAU,+BAA0B,CAAC;AAGlD,eAAO,MAAM,aAAa;;;CAGhB,CAAC;AAGX,eAAO,MAAM,WAAW;;;;;;;CAOd,CAAC"}
package/dist/index.d.ts CHANGED
@@ -274,6 +274,13 @@ interface FetchSwapRouteConfig {
274
274
  * - Low-value tokens (meme tokens, small caps): partCount = 1 (simpler routing)
275
275
  */
276
276
  forcePartCount?: number;
277
+ /**
278
+ * Optional PublicClient from viem
279
+ * - If provided, will be used for contract calls
280
+ * - If not provided, SDK will automatically create one using RPC_CONFIG
281
+ * - Useful when you already have a PublicClient instance (e.g., from wagmi)
282
+ */
283
+ publicClient?: PublicClient;
277
284
  }
278
285
  /**
279
286
  * Common function to fetch swap routes
@@ -445,6 +452,7 @@ declare class APIClient {
445
452
  private request;
446
453
  /**
447
454
  * Get V3 path for swap routing
455
+ * Uses URLSearchParams for single encoding (avoids double-encoding on iOS).
448
456
  */
449
457
  getPathV3(srcToken: Token, dstToken: Token, amountIn: string, types: number[], enabledSources: number[]): Promise<PathV3Response>;
450
458
  /**
@@ -452,10 +460,6 @@ declare class APIClient {
452
460
  * Returns minimum amounts for tokens to use multiple routes
453
461
  */
454
462
  getAssetMinimum(): Promise<any>;
455
- /**
456
- * Build query string from parameters
457
- */
458
- private buildQueryString;
459
463
  }
460
464
 
461
465
  interface SwapV3ServiceConfig {
@@ -467,6 +471,11 @@ interface SwapV3ServiceConfig {
467
471
  declare class SwapV3Service {
468
472
  private config;
469
473
  constructor(config: SwapV3ServiceConfig);
474
+ /**
475
+ * Get or create publicClient for the given chainId
476
+ * Returns existing publicClient if provided, otherwise creates a default one
477
+ */
478
+ private getPublicClient;
470
479
  /**
471
480
  * Fetch swap routes for V3 swaps
472
481
  * This is the core function extracted from the React hook
package/dist/index.esm.js CHANGED
@@ -1,4 +1,2 @@
1
- import{useMemo as e,useEffect as t,useState as n,useCallback as r}from"react";var s=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,i=Math.ceil,o=Math.floor,a="[BigNumber Error] ",c=a+"Number primitive has more than 15 significant digits: ",u=1e14,l=14,f=9007199254740991,d=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],h=1e7,p=1e9;function g(e){var t=0|e;return e>0||e===t?t:t-1}function m(e){for(var t,n,r=1,s=e.length,i=e[0]+"";r<s;){for(t=e[r++]+"",n=l-t.length;n--;t="0"+t);i+=t}for(s=i.length;48===i.charCodeAt(--s););return i.slice(0,s+1||1)}function y(e,t){var n,r,s=e.c,i=t.c,o=e.s,a=t.s,c=e.e,u=t.e;if(!o||!a)return null;if(n=s&&!s[0],r=i&&!i[0],n||r)return n?r?0:-a:o;if(o!=a)return o;if(n=o<0,r=c==u,!s||!i)return r?0:!s^n?1:-1;if(!r)return c>u^n?1:-1;for(a=(c=s.length)<(u=i.length)?c:u,o=0;o<a;o++)if(s[o]!=i[o])return s[o]>i[o]^n?1:-1;return c==u?0:c>u^n?1:-1}function b(e,t,n,r){if(e<t||e>n||e!==o(e))throw Error(a+(r||"Argument")+("number"==typeof e?e<t||e>n?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function w(e){var t=e.c.length-1;return g(e.e/l)==t&&e.c[t]%2!=0}function A(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function E(e,t,n){var r,s;if(t<0){for(s=n+".";++t;s+=n);e=s+e}else if(++t>(r=e.length)){for(s=n,t-=r;--t;s+=n);e+=s}else t<r&&(e=e.slice(0,t)+"."+e.slice(t));return e}var v=function e(t){var n,r,v,I,x,C,P,O,B,N,$=W.prototype={constructor:W,toString:null,valueOf:null},z=new W(1),D=20,S=4,T=-7,U=21,R=-1e7,F=1e7,L=!1,_=1,k=0,M={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:" ",suffix:""},V="0123456789abcdefghijklmnopqrstuvwxyz",j=!0;function W(e,t){var n,i,a,u,d,h,p,g,m=this;if(!(m instanceof W))return new W(e,t);if(null==t){if(e&&!0===e._isBigNumber)return m.s=e.s,void(!e.c||e.e>F?m.c=m.e=null:e.e<R?m.c=[m.e=0]:(m.e=e.e,m.c=e.c.slice()));if((h="number"==typeof e)&&0*e==0){if(m.s=1/e<0?(e=-e,-1):1,e===~~e){for(u=0,d=e;d>=10;d/=10,u++);return void(u>F?m.c=m.e=null:(m.e=u,m.c=[e]))}g=String(e)}else{if(!s.test(g=String(e)))return v(m,g,h);m.s=45==g.charCodeAt(0)?(g=g.slice(1),-1):1}(u=g.indexOf("."))>-1&&(g=g.replace(".","")),(d=g.search(/e/i))>0?(u<0&&(u=d),u+=+g.slice(d+1),g=g.substring(0,d)):u<0&&(u=g.length)}else{if(b(t,2,V.length,"Base"),10==t&&j)return q(m=new W(e),D+m.e+1,S);if(g=String(e),h="number"==typeof e){if(0*e!=0)return v(m,g,h,t);if(m.s=1/e<0?(g=g.slice(1),-1):1,W.DEBUG&&g.replace(/^0\.0*|\./,"").length>15)throw Error(c+e)}else m.s=45===g.charCodeAt(0)?(g=g.slice(1),-1):1;for(n=V.slice(0,t),u=d=0,p=g.length;d<p;d++)if(n.indexOf(i=g.charAt(d))<0){if("."==i){if(d>u){u=p;continue}}else if(!a&&(g==g.toUpperCase()&&(g=g.toLowerCase())||g==g.toLowerCase()&&(g=g.toUpperCase()))){a=!0,d=-1,u=0;continue}return v(m,String(e),h,t)}h=!1,(u=(g=r(g,t,10,m.s)).indexOf("."))>-1?g=g.replace(".",""):u=g.length}for(d=0;48===g.charCodeAt(d);d++);for(p=g.length;48===g.charCodeAt(--p););if(g=g.slice(d,++p)){if(p-=d,h&&W.DEBUG&&p>15&&(e>f||e!==o(e)))throw Error(c+m.s*e);if((u=u-d-1)>F)m.c=m.e=null;else if(u<R)m.c=[m.e=0];else{if(m.e=u,m.c=[],d=(u+1)%l,u<0&&(d+=l),d<p){for(d&&m.c.push(+g.slice(0,d)),p-=l;d<p;)m.c.push(+g.slice(d,d+=l));d=l-(g=g.slice(d)).length}else d-=p;for(;d--;g+="0");m.c.push(+g)}}else m.c=[m.e=0]}function G(e,t,n,r){var s,i,o,a,c;if(null==n?n=S:b(n,0,8),!e.c)return e.toString();if(s=e.c[0],o=e.e,null==t)c=m(e.c),c=1==r||2==r&&(o<=T||o>=U)?A(c,o):E(c,o,"0");else if(i=(e=q(new W(e),t,n)).e,a=(c=m(e.c)).length,1==r||2==r&&(t<=i||i<=T)){for(;a<t;c+="0",a++);c=A(c,i)}else if(t-=o+(2===r&&i>o),c=E(c,i,"0"),i+1>a){if(--t>0)for(c+=".";t--;c+="0");}else if((t+=i-a)>0)for(i+1==a&&(c+=".");t--;c+="0");return e.s<0&&s?"-"+c:c}function Q(e,t){for(var n,r,s=1,i=new W(e[0]);s<e.length;s++)(!(r=new W(e[s])).s||(n=y(i,r))===t||0===n&&i.s===t)&&(i=r);return i}function Y(e,t,n){for(var r=1,s=t.length;!t[--s];t.pop());for(s=t[0];s>=10;s/=10,r++);return(n=r+n*l-1)>F?e.c=e.e=null:n<R?e.c=[e.e=0]:(e.e=n,e.c=t),e}function q(e,t,n,r){var s,a,c,f,h,p,g,m=e.c,y=d;if(m){e:{for(s=1,f=m[0];f>=10;f/=10,s++);if((a=t-s)<0)a+=l,c=t,h=m[p=0],g=o(h/y[s-c-1]%10);else if((p=i((a+1)/l))>=m.length){if(!r)break e;for(;m.length<=p;m.push(0));h=g=0,s=1,c=(a%=l)-l+1}else{for(h=f=m[p],s=1;f>=10;f/=10,s++);g=(c=(a%=l)-l+s)<0?0:o(h/y[s-c-1]%10)}if(r=r||t<0||null!=m[p+1]||(c<0?h:h%y[s-c-1]),r=n<4?(g||r)&&(0==n||n==(e.s<0?3:2)):g>5||5==g&&(4==n||r||6==n&&(a>0?c>0?h/y[s-c]:0:m[p-1])%10&1||n==(e.s<0?8:7)),t<1||!m[0])return m.length=0,r?(t-=e.e+1,m[0]=y[(l-t%l)%l],e.e=-t||0):m[0]=e.e=0,e;if(0==a?(m.length=p,f=1,p--):(m.length=p+1,f=y[l-a],m[p]=c>0?o(h/y[s-c]%y[c])*f:0),r)for(;;){if(0==p){for(a=1,c=m[0];c>=10;c/=10,a++);for(c=m[0]+=f,f=1;c>=10;c/=10,f++);a!=f&&(e.e++,m[0]==u&&(m[0]=1));break}if(m[p]+=f,m[p]!=u)break;m[p--]=0,f=1}for(a=m.length;0===m[--a];m.pop());}e.e>F?e.c=e.e=null:e.e<R&&(e.c=[e.e=0])}return e}function K(e){var t,n=e.e;return null===n?e.toString():(t=m(e.c),t=n<=T||n>=U?A(t,n):E(t,n,"0"),e.s<0?"-"+t:t)}return W.clone=e,W.ROUND_UP=0,W.ROUND_DOWN=1,W.ROUND_CEIL=2,W.ROUND_FLOOR=3,W.ROUND_HALF_UP=4,W.ROUND_HALF_DOWN=5,W.ROUND_HALF_EVEN=6,W.ROUND_HALF_CEIL=7,W.ROUND_HALF_FLOOR=8,W.EUCLID=9,W.config=W.set=function(e){var t,n;if(null!=e){if("object"!=typeof e)throw Error(a+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(b(n=e[t],0,p,t),D=n),e.hasOwnProperty(t="ROUNDING_MODE")&&(b(n=e[t],0,8,t),S=n),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((n=e[t])&&n.pop?(b(n[0],-p,0,t),b(n[1],0,p,t),T=n[0],U=n[1]):(b(n,-p,p,t),T=-(U=n<0?-n:n))),e.hasOwnProperty(t="RANGE"))if((n=e[t])&&n.pop)b(n[0],-p,-1,t),b(n[1],1,p,t),R=n[0],F=n[1];else{if(b(n,-p,p,t),!n)throw Error(a+t+" cannot be zero: "+n);R=-(F=n<0?-n:n)}if(e.hasOwnProperty(t="CRYPTO")){if((n=e[t])!==!!n)throw Error(a+t+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw L=!n,Error(a+"crypto unavailable");L=n}else L=n}if(e.hasOwnProperty(t="MODULO_MODE")&&(b(n=e[t],0,9,t),_=n),e.hasOwnProperty(t="POW_PRECISION")&&(b(n=e[t],0,p,t),k=n),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(n=e[t]))throw Error(a+t+" not an object: "+n);M=n}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(n=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(n))throw Error(a+t+" invalid: "+n);j="0123456789"==n.slice(0,10),V=n}}return{DECIMAL_PLACES:D,ROUNDING_MODE:S,EXPONENTIAL_AT:[T,U],RANGE:[R,F],CRYPTO:L,MODULO_MODE:_,POW_PRECISION:k,FORMAT:M,ALPHABET:V}},W.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!W.DEBUG)return!0;var t,n,r=e.c,s=e.e,i=e.s;e:if("[object Array]"=={}.toString.call(r)){if((1===i||-1===i)&&s>=-p&&s<=p&&s===o(s)){if(0===r[0]){if(0===s&&1===r.length)return!0;break e}if((t=(s+1)%l)<1&&(t+=l),String(r[0]).length==t){for(t=0;t<r.length;t++)if((n=r[t])<0||n>=u||n!==o(n))break e;if(0!==n)return!0}}}else if(null===r&&null===s&&(null===i||1===i||-1===i))return!0;throw Error(a+"Invalid BigNumber: "+e)},W.maximum=W.max=function(){return Q(arguments,-1)},W.minimum=W.min=function(){return Q(arguments,1)},W.random=(I=9007199254740992,x=Math.random()*I&2097151?function(){return o(Math.random()*I)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,n,r,s,c,u=0,f=[],h=new W(z);if(null==e?e=D:b(e,0,p),s=i(e/l),L)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(s*=2));u<s;)(c=131072*t[u]+(t[u+1]>>>11))>=9e15?(n=crypto.getRandomValues(new Uint32Array(2)),t[u]=n[0],t[u+1]=n[1]):(f.push(c%1e14),u+=2);u=s/2}else{if(!crypto.randomBytes)throw L=!1,Error(a+"crypto unavailable");for(t=crypto.randomBytes(s*=7);u<s;)(c=281474976710656*(31&t[u])+1099511627776*t[u+1]+4294967296*t[u+2]+16777216*t[u+3]+(t[u+4]<<16)+(t[u+5]<<8)+t[u+6])>=9e15?crypto.randomBytes(7).copy(t,u):(f.push(c%1e14),u+=7);u=s/7}if(!L)for(;u<s;)(c=x())<9e15&&(f[u++]=c%1e14);for(s=f[--u],e%=l,s&&e&&(c=d[l-e],f[u]=o(s/c)*c);0===f[u];f.pop(),u--);if(u<0)f=[r=0];else{for(r=-1;0===f[0];f.splice(0,1),r-=l);for(u=1,c=f[0];c>=10;c/=10,u++);u<l&&(r-=l-u)}return h.e=r,h.c=f,h}),W.sum=function(){for(var e=1,t=arguments,n=new W(t[0]);e<t.length;)n=n.plus(t[e++]);return n},r=function(){var e="0123456789";function t(e,t,n,r){for(var s,i,o=[0],a=0,c=e.length;a<c;){for(i=o.length;i--;o[i]*=t);for(o[0]+=r.indexOf(e.charAt(a++)),s=0;s<o.length;s++)o[s]>n-1&&(null==o[s+1]&&(o[s+1]=0),o[s+1]+=o[s]/n|0,o[s]%=n)}return o.reverse()}return function(r,s,i,o,a){var c,u,l,f,d,h,p,g,y=r.indexOf("."),b=D,w=S;for(y>=0&&(f=k,k=0,r=r.replace(".",""),h=(g=new W(s)).pow(r.length-y),k=f,g.c=t(E(m(h.c),h.e,"0"),10,i,e),g.e=g.c.length),l=f=(p=t(r,s,i,a?(c=V,e):(c=e,V))).length;0==p[--f];p.pop());if(!p[0])return c.charAt(0);if(y<0?--l:(h.c=p,h.e=l,h.s=o,p=(h=n(h,g,b,w,i)).c,d=h.r,l=h.e),y=p[u=l+b+1],f=i/2,d=d||u<0||null!=p[u+1],d=w<4?(null!=y||d)&&(0==w||w==(h.s<0?3:2)):y>f||y==f&&(4==w||d||6==w&&1&p[u-1]||w==(h.s<0?8:7)),u<1||!p[0])r=d?E(c.charAt(1),-b,c.charAt(0)):c.charAt(0);else{if(p.length=u,d)for(--i;++p[--u]>i;)p[u]=0,u||(++l,p=[1].concat(p));for(f=p.length;!p[--f];);for(y=0,r="";y<=f;r+=c.charAt(p[y++]));r=E(r,l,c.charAt(0))}return r}}(),n=function(){function e(e,t,n){var r,s,i,o,a=0,c=e.length,u=t%h,l=t/h|0;for(e=e.slice();c--;)a=((s=u*(i=e[c]%h)+(r=l*i+(o=e[c]/h|0)*u)%h*h+a)/n|0)+(r/h|0)+l*o,e[c]=s%n;return a&&(e=[a].concat(e)),e}function t(e,t,n,r){var s,i;if(n!=r)i=n>r?1:-1;else for(s=i=0;s<n;s++)if(e[s]!=t[s]){i=e[s]>t[s]?1:-1;break}return i}function n(e,t,n,r){for(var s=0;n--;)e[n]-=s,s=e[n]<t[n]?1:0,e[n]=s*r+e[n]-t[n];for(;!e[0]&&e.length>1;e.splice(0,1));}return function(r,s,i,a,c){var f,d,h,p,m,y,b,w,A,E,v,I,x,C,P,O,B,N=r.s==s.s?1:-1,$=r.c,z=s.c;if(!($&&$[0]&&z&&z[0]))return new W(r.s&&s.s&&($?!z||$[0]!=z[0]:z)?$&&0==$[0]||!z?0*N:N/0:NaN);for(A=(w=new W(N)).c=[],N=i+(d=r.e-s.e)+1,c||(c=u,d=g(r.e/l)-g(s.e/l),N=N/l|0),h=0;z[h]==($[h]||0);h++);if(z[h]>($[h]||0)&&d--,N<0)A.push(1),p=!0;else{for(C=$.length,O=z.length,h=0,N+=2,(m=o(c/(z[0]+1)))>1&&(z=e(z,m,c),$=e($,m,c),O=z.length,C=$.length),x=O,v=(E=$.slice(0,O)).length;v<O;E[v++]=0);B=z.slice(),B=[0].concat(B),P=z[0],z[1]>=c/2&&P++;do{if(m=0,(f=t(z,E,O,v))<0){if(I=E[0],O!=v&&(I=I*c+(E[1]||0)),(m=o(I/P))>1)for(m>=c&&(m=c-1),b=(y=e(z,m,c)).length,v=E.length;1==t(y,E,b,v);)m--,n(y,O<b?B:z,b,c),b=y.length,f=1;else 0==m&&(f=m=1),b=(y=z.slice()).length;if(b<v&&(y=[0].concat(y)),n(E,y,v,c),v=E.length,-1==f)for(;t(z,E,O,v)<1;)m++,n(E,O<v?B:z,v,c),v=E.length}else 0===f&&(m++,E=[0]);A[h++]=m,E[0]?E[v++]=$[x]||0:(E=[$[x]],v=1)}while((x++<C||null!=E[0])&&N--);p=null!=E[0],A[0]||A.splice(0,1)}if(c==u){for(h=1,N=A[0];N>=10;N/=10,h++);q(w,i+(w.e=h+d*l-1)+1,a,p)}else w.e=d,w.r=+p;return w}}(),C=/^(-?)0([xbo])(?=\w[\w.]*$)/i,P=/^([^.]+)\.$/,O=/^\.([^.]+)$/,B=/^-?(Infinity|NaN)$/,N=/^\s*\+(?=[\w.])|^\s+|\s+$/g,v=function(e,t,n,r){var s,i=n?t:t.replace(N,"");if(B.test(i))e.s=isNaN(i)?null:i<0?-1:1;else{if(!n&&(i=i.replace(C,function(e,t,n){return s="x"==(n=n.toLowerCase())?16:"b"==n?2:8,r&&r!=s?e:t}),r&&(s=r,i=i.replace(P,"$1").replace(O,"0.$1")),t!=i))return new W(i,s);if(W.DEBUG)throw Error(a+"Not a"+(r?" base "+r:"")+" number: "+t);e.s=null}e.c=e.e=null},$.absoluteValue=$.abs=function(){var e=new W(this);return e.s<0&&(e.s=1),e},$.comparedTo=function(e,t){return y(this,new W(e,t))},$.decimalPlaces=$.dp=function(e,t){var n,r,s,i=this;if(null!=e)return b(e,0,p),null==t?t=S:b(t,0,8),q(new W(i),e+i.e+1,t);if(!(n=i.c))return null;if(r=((s=n.length-1)-g(this.e/l))*l,s=n[s])for(;s%10==0;s/=10,r--);return r<0&&(r=0),r},$.dividedBy=$.div=function(e,t){return n(this,new W(e,t),D,S)},$.dividedToIntegerBy=$.idiv=function(e,t){return n(this,new W(e,t),0,1)},$.exponentiatedBy=$.pow=function(e,t){var n,r,s,c,u,f,d,h,p=this;if((e=new W(e)).c&&!e.isInteger())throw Error(a+"Exponent not an integer: "+K(e));if(null!=t&&(t=new W(t)),u=e.e>14,!p.c||!p.c[0]||1==p.c[0]&&!p.e&&1==p.c.length||!e.c||!e.c[0])return h=new W(Math.pow(+K(p),u?e.s*(2-w(e)):+K(e))),t?h.mod(t):h;if(f=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new W(NaN);(r=!f&&p.isInteger()&&t.isInteger())&&(p=p.mod(t))}else{if(e.e>9&&(p.e>0||p.e<-1||(0==p.e?p.c[0]>1||u&&p.c[1]>=24e7:p.c[0]<8e13||u&&p.c[0]<=9999975e7)))return c=p.s<0&&w(e)?-0:0,p.e>-1&&(c=1/c),new W(f?1/c:c);k&&(c=i(k/l+2))}for(u?(n=new W(.5),f&&(e.s=1),d=w(e)):d=(s=Math.abs(+K(e)))%2,h=new W(z);;){if(d){if(!(h=h.times(p)).c)break;c?h.c.length>c&&(h.c.length=c):r&&(h=h.mod(t))}if(s){if(0===(s=o(s/2)))break;d=s%2}else if(q(e=e.times(n),e.e+1,1),e.e>14)d=w(e);else{if(0===(s=+K(e)))break;d=s%2}p=p.times(p),c?p.c&&p.c.length>c&&(p.c.length=c):r&&(p=p.mod(t))}return r?h:(f&&(h=z.div(h)),t?h.mod(t):c?q(h,k,S,undefined):h)},$.integerValue=function(e){var t=new W(this);return null==e?e=S:b(e,0,8),q(t,t.e+1,e)},$.isEqualTo=$.eq=function(e,t){return 0===y(this,new W(e,t))},$.isFinite=function(){return!!this.c},$.isGreaterThan=$.gt=function(e,t){return y(this,new W(e,t))>0},$.isGreaterThanOrEqualTo=$.gte=function(e,t){return 1===(t=y(this,new W(e,t)))||0===t},$.isInteger=function(){return!!this.c&&g(this.e/l)>this.c.length-2},$.isLessThan=$.lt=function(e,t){return y(this,new W(e,t))<0},$.isLessThanOrEqualTo=$.lte=function(e,t){return-1===(t=y(this,new W(e,t)))||0===t},$.isNaN=function(){return!this.s},$.isNegative=function(){return this.s<0},$.isPositive=function(){return this.s>0},$.isZero=function(){return!!this.c&&0==this.c[0]},$.minus=function(e,t){var n,r,s,i,o=this,a=o.s;if(t=(e=new W(e,t)).s,!a||!t)return new W(NaN);if(a!=t)return e.s=-t,o.plus(e);var c=o.e/l,f=e.e/l,d=o.c,h=e.c;if(!c||!f){if(!d||!h)return d?(e.s=-t,e):new W(h?o:NaN);if(!d[0]||!h[0])return h[0]?(e.s=-t,e):new W(d[0]?o:3==S?-0:0)}if(c=g(c),f=g(f),d=d.slice(),a=c-f){for((i=a<0)?(a=-a,s=d):(f=c,s=h),s.reverse(),t=a;t--;s.push(0));s.reverse()}else for(r=(i=(a=d.length)<(t=h.length))?a:t,a=t=0;t<r;t++)if(d[t]!=h[t]){i=d[t]<h[t];break}if(i&&(s=d,d=h,h=s,e.s=-e.s),(t=(r=h.length)-(n=d.length))>0)for(;t--;d[n++]=0);for(t=u-1;r>a;){if(d[--r]<h[r]){for(n=r;n&&!d[--n];d[n]=t);--d[n],d[r]+=u}d[r]-=h[r]}for(;0==d[0];d.splice(0,1),--f);return d[0]?Y(e,d,f):(e.s=3==S?-1:1,e.c=[e.e=0],e)},$.modulo=$.mod=function(e,t){var r,s,i=this;return e=new W(e,t),!i.c||!e.s||e.c&&!e.c[0]?new W(NaN):!e.c||i.c&&!i.c[0]?new W(i):(9==_?(s=e.s,e.s=1,r=n(i,e,0,3),e.s=s,r.s*=s):r=n(i,e,0,_),(e=i.minus(r.times(e))).c[0]||1!=_||(e.s=i.s),e)},$.multipliedBy=$.times=function(e,t){var n,r,s,i,o,a,c,f,d,p,m,y,b,w,A,E=this,v=E.c,I=(e=new W(e,t)).c;if(!(v&&I&&v[0]&&I[0]))return!E.s||!e.s||v&&!v[0]&&!I||I&&!I[0]&&!v?e.c=e.e=e.s=null:(e.s*=E.s,v&&I?(e.c=[0],e.e=0):e.c=e.e=null),e;for(r=g(E.e/l)+g(e.e/l),e.s*=E.s,(c=v.length)<(p=I.length)&&(b=v,v=I,I=b,s=c,c=p,p=s),s=c+p,b=[];s--;b.push(0));for(w=u,A=h,s=p;--s>=0;){for(n=0,m=I[s]%A,y=I[s]/A|0,i=s+(o=c);i>s;)n=((f=m*(f=v[--o]%A)+(a=y*f+(d=v[o]/A|0)*m)%A*A+b[i]+n)/w|0)+(a/A|0)+y*d,b[i--]=f%w;b[i]=n}return n?++r:b.splice(0,1),Y(e,b,r)},$.negated=function(){var e=new W(this);return e.s=-e.s||null,e},$.plus=function(e,t){var n,r=this,s=r.s;if(t=(e=new W(e,t)).s,!s||!t)return new W(NaN);if(s!=t)return e.s=-t,r.minus(e);var i=r.e/l,o=e.e/l,a=r.c,c=e.c;if(!i||!o){if(!a||!c)return new W(s/0);if(!a[0]||!c[0])return c[0]?e:new W(a[0]?r:0*s)}if(i=g(i),o=g(o),a=a.slice(),s=i-o){for(s>0?(o=i,n=c):(s=-s,n=a),n.reverse();s--;n.push(0));n.reverse()}for((s=a.length)-(t=c.length)<0&&(n=c,c=a,a=n,t=s),s=0;t;)s=(a[--t]=a[t]+c[t]+s)/u|0,a[t]=u===a[t]?0:a[t]%u;return s&&(a=[s].concat(a),++o),Y(e,a,o)},$.precision=$.sd=function(e,t){var n,r,s,i=this;if(null!=e&&e!==!!e)return b(e,1,p),null==t?t=S:b(t,0,8),q(new W(i),e,t);if(!(n=i.c))return null;if(r=(s=n.length-1)*l+1,s=n[s]){for(;s%10==0;s/=10,r--);for(s=n[0];s>=10;s/=10,r++);}return e&&i.e+1>r&&(r=i.e+1),r},$.shiftedBy=function(e){return b(e,-9007199254740991,f),this.times("1e"+e)},$.squareRoot=$.sqrt=function(){var e,t,r,s,i,o=this,a=o.c,c=o.s,u=o.e,l=D+4,f=new W("0.5");if(1!==c||!a||!a[0])return new W(!c||c<0&&(!a||a[0])?NaN:a?o:1/0);if(0==(c=Math.sqrt(+K(o)))||c==1/0?(((t=m(a)).length+u)%2==0&&(t+="0"),c=Math.sqrt(+t),u=g((u+1)/2)-(u<0||u%2),r=new W(t=c==1/0?"5e"+u:(t=c.toExponential()).slice(0,t.indexOf("e")+1)+u)):r=new W(c+""),r.c[0])for((c=(u=r.e)+l)<3&&(c=0);;)if(i=r,r=f.times(i.plus(n(o,i,l,1))),m(i.c).slice(0,c)===(t=m(r.c)).slice(0,c)){if(r.e<u&&--c,"9999"!=(t=t.slice(c-3,c+1))&&(s||"4999"!=t)){+t&&(+t.slice(1)||"5"!=t.charAt(0))||(q(r,r.e+D+2,1),e=!r.times(r).eq(o));break}if(!s&&(q(i,i.e+D+2,0),i.times(i).eq(o))){r=i;break}l+=4,c+=4,s=1}return q(r,r.e+D+1,S,e)},$.toExponential=function(e,t){return null!=e&&(b(e,0,p),e++),G(this,e,t,1)},$.toFixed=function(e,t){return null!=e&&(b(e,0,p),e=e+this.e+1),G(this,e,t)},$.toFormat=function(e,t,n){var r,s=this;if(null==n)null!=e&&t&&"object"==typeof t?(n=t,t=null):e&&"object"==typeof e?(n=e,e=t=null):n=M;else if("object"!=typeof n)throw Error(a+"Argument not an object: "+n);if(r=s.toFixed(e,t),s.c){var i,o=r.split("."),c=+n.groupSize,u=+n.secondaryGroupSize,l=n.groupSeparator||"",f=o[0],d=o[1],h=s.s<0,p=h?f.slice(1):f,g=p.length;if(u&&(i=c,c=u,u=i,g-=i),c>0&&g>0){for(i=g%c||c,f=p.substr(0,i);i<g;i+=c)f+=l+p.substr(i,c);u>0&&(f+=l+p.slice(i)),h&&(f="-"+f)}r=d?f+(n.decimalSeparator||"")+((u=+n.fractionGroupSize)?d.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+(n.fractionGroupSeparator||"")):d):f}return(n.prefix||"")+r+(n.suffix||"")},$.toFraction=function(e){var t,r,s,i,o,c,u,f,h,p,g,y,b=this,w=b.c;if(null!=e&&(!(u=new W(e)).isInteger()&&(u.c||1!==u.s)||u.lt(z)))throw Error(a+"Argument "+(u.isInteger()?"out of range: ":"not an integer: ")+K(u));if(!w)return new W(b);for(t=new W(z),h=r=new W(z),s=f=new W(z),y=m(w),o=t.e=y.length-b.e-1,t.c[0]=d[(c=o%l)<0?l+c:c],e=!e||u.comparedTo(t)>0?o>0?t:h:u,c=F,F=1/0,u=new W(y),f.c[0]=0;p=n(u,t,0,1),1!=(i=r.plus(p.times(s))).comparedTo(e);)r=s,s=i,h=f.plus(p.times(i=h)),f=i,t=u.minus(p.times(i=t)),u=i;return i=n(e.minus(r),s,0,1),f=f.plus(i.times(h)),r=r.plus(i.times(s)),f.s=h.s=b.s,g=n(h,s,o*=2,S).minus(b).abs().comparedTo(n(f,r,o,S).minus(b).abs())<1?[h,s]:[f,r],F=c,g},$.toNumber=function(){return+K(this)},$.toPrecision=function(e,t){return null!=e&&b(e,1,p),G(this,e,t,2)},$.toString=function(e){var t,n=this,s=n.s,i=n.e;return null===i?s?(t="Infinity",s<0&&(t="-"+t)):t="NaN":(null==e?t=i<=T||i>=U?A(m(n.c),i):E(m(n.c),i,"0"):10===e&&j?t=E(m((n=q(new W(n),D+i+1,S)).c),n.e,"0"):(b(e,2,V.length,"Base"),t=r(E(m(n.c),i,"0"),10,e,s,!0)),s<0&&n.c[0]&&(t="-"+t)),t},$.valueOf=$.toJSON=function(){return K(this)},$._isBigNumber=!0,$[Symbol.toStringTag]="BigNumber",$[Symbol.for("nodejs.util.inspect.custom")]=$.valueOf,null!=t&&W.set(t),W}();const I=/^tuple(?<array>(\[(\d*)\])*)$/;function x(e){let t=e.type;if(I.test(e.type)&&"components"in e){t="(";const n=e.components.length;for(let r=0;r<n;r++){t+=x(e.components[r]),r<n-1&&(t+=", ")}const r=function(e,t){const n=e.exec(t);return n?.groups}(I,e.type);return t+=`)${r?.array??""}`,x({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}function C(e){let t="";const n=e.length;for(let r=0;r<n;r++){t+=x(e[r]),r!==n-1&&(t+=", ")}return t}function P(e,{includeName:t=!1}={}){if("function"!==e.type&&"event"!==e.type&&"error"!==e.type)throw new Q(e.type);return`${e.name}(${O(e.inputs,{includeName:t})})`}function O(e,{includeName:t=!1}={}){return e?e.map(e=>function(e,{includeName:t}){if(e.type.startsWith("tuple"))return`(${O(e.components,{includeName:t})})${e.type.slice(5)}`;return e.type+(t&&e.name?` ${e.name}`:"")}(e,{includeName:t})).join(t?", ":","):""}function B(e,{strict:t=!0}={}){return!!e&&("string"==typeof e&&(t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")))}function N(e){return B(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}const $="2.36.0";let z=({docsBaseUrl:e,docsPath:t="",docsSlug:n})=>t?`${e??"https://viem.sh"}${t}${n?`#${n}`:""}`:void 0,D=`viem@${$}`;class S extends Error{constructor(e,t={}){const n=t.cause instanceof S?t.cause.details:t.cause?.message?t.cause.message:t.details,r=t.cause instanceof S&&t.cause.docsPath||t.docsPath,s=z?.({...t,docsPath:r});super([e||"An error occurred.","",...t.metaMessages?[...t.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...n?[`Details: ${n}`]:[],...D?[`Version: ${D}`]:[]].join("\n"),t.cause?{cause:t.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=r,this.metaMessages=t.metaMessages,this.name=t.name??this.name,this.shortMessage=e,this.version=$}walk(e){return T(this,e)}}function T(e,t){return t?.(e)?e:e&&"object"==typeof e&&"cause"in e&&void 0!==e.cause?T(e.cause,t):t?null:e}class U extends S{constructor({data:e,params:t,size:n}){super([`Data size of ${n} bytes is too small for given parameters.`].join("\n"),{metaMessages:[`Params: (${O(t,{includeName:!0})})`,`Data: ${e} (${n} bytes)`],name:"AbiDecodingDataSizeTooSmallError"}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"params",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"size",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.data=e,this.params=t,this.size=n}}class R extends S{constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{name:"AbiDecodingZeroDataError"})}}class F extends S{constructor({expectedLength:e,givenLength:t,type:n}){super([`ABI encoding array length mismatch for type ${n}.`,`Expected length: ${e}`,`Given length: ${t}`].join("\n"),{name:"AbiEncodingArrayLengthMismatchError"})}}class L extends S{constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" (bytes${N(t)}) does not match expected size (bytes${e}).`,{name:"AbiEncodingBytesSizeMismatchError"})}}class _ extends S{constructor({expectedLength:e,givenLength:t}){super(["ABI encoding params/values length mismatch.",`Expected length (params): ${e}`,`Given length (values): ${t}`].join("\n"),{name:"AbiEncodingLengthMismatchError"})}}class k extends S{constructor(e,{docsPath:t}={}){super([`Function ${e?`"${e}" `:""}not found on ABI.`,"Make sure you are using the correct ABI and that the function exists on it."].join("\n"),{docsPath:t,name:"AbiFunctionNotFoundError"})}}class M extends S{constructor(e,{docsPath:t}){super([`Function "${e}" does not contain any \`outputs\` on ABI.`,"Cannot decode function result without knowing what the parameter types are.","Make sure you are using the correct ABI and that the function exists on it."].join("\n"),{docsPath:t,name:"AbiFunctionOutputsNotFoundError"})}}class V extends S{constructor(e,t){super("Found ambiguous types in overloaded ABI items.",{metaMessages:[`\`${e.type}\` in \`${P(e.abiItem)}\`, and`,`\`${t.type}\` in \`${P(t.abiItem)}\``,"","These types encode differently and cannot be distinguished at runtime.","Remove one of the ambiguous items in the ABI."],name:"AbiItemAmbiguityError"})}}class j extends S{constructor(e,{docsPath:t}){super([`Type "${e}" is not a valid encoding type.`,"Please provide a valid ABI type."].join("\n"),{docsPath:t,name:"InvalidAbiEncodingType"})}}class W extends S{constructor(e,{docsPath:t}){super([`Type "${e}" is not a valid decoding type.`,"Please provide a valid ABI type."].join("\n"),{docsPath:t,name:"InvalidAbiDecodingType"})}}class G extends S{constructor(e){super([`Value "${e}" is not a valid array.`].join("\n"),{name:"InvalidArrayError"})}}class Q extends S{constructor(e){super([`"${e}" is not a valid definition type.`,'Valid types: "function", "event", "error"'].join("\n"),{name:"InvalidDefinitionTypeError"})}}class Y extends S{constructor({offset:e,position:t,size:n}){super(`Slice ${"start"===t?"starting":"ending"} at offset "${e}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}}class q extends S{constructor({size:e,targetSize:t,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${t}).`,{name:"SizeExceedsPaddingSizeError"})}}function K(e,{dir:t,size:n=32}={}){return"string"==typeof e?H(e,{dir:t,size:n}):function(e,{dir:t,size:n=32}={}){if(null===n)return e;if(e.length>n)throw new q({size:e.length,targetSize:n,type:"bytes"});const r=new Uint8Array(n);for(let s=0;s<n;s++){const i="right"===t;r[i?s:n-s-1]=e[i?s:e.length-s-1]}return r}(e,{dir:t,size:n})}function H(e,{dir:t,size:n=32}={}){if(null===n)return e;const r=e.replace("0x","");if(r.length>2*n)throw new q({size:Math.ceil(r.length/2),targetSize:n,type:"hex"});return`0x${r["right"===t?"padEnd":"padStart"](2*n,"0")}`}class X extends S{constructor({max:e,min:t,signed:n,size:r,value:s}){super(`Number "${s}" is not in safe ${r?`${8*r}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${t} to ${e})`:`(above ${t})`}`,{name:"IntegerOutOfRangeError"})}}class Z extends S{constructor(e){super(`Bytes value "${e}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`,{name:"InvalidBytesBooleanError"})}}class J extends S{constructor({givenSize:e,maxSize:t}){super(`Size cannot exceed ${t} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function ee(e,{dir:t="left"}={}){let n="string"==typeof e?e.replace("0x",""):e,r=0;for(let e=0;e<n.length-1&&"0"===n["left"===t?e:n.length-e-1].toString();e++)r++;return n="left"===t?n.slice(r):n.slice(0,n.length-r),"string"==typeof e?(1===n.length&&"right"===t&&(n=`${n}0`),`0x${n.length%2==1?`0${n}`:n}`):n}function te(e,{size:t}){if(N(e)>t)throw new J({givenSize:N(e),maxSize:t})}function ne(e,t={}){const{signed:n}=t;t.size&&te(e,{size:t.size});const r=BigInt(e);if(!n)return r;const s=(e.length-2)/2;return r<=(1n<<8n*BigInt(s)-1n)-1n?r:r-BigInt(`0x${"f".padStart(2*s,"f")}`)-1n}const re=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function se(e,t={}){const n=`0x${Number(e)}`;return"number"==typeof t.size?(te(n,{size:t.size}),K(n,{size:t.size})):n}function ie(e,t={}){let n="";for(let t=0;t<e.length;t++)n+=re[e[t]];const r=`0x${n}`;return"number"==typeof t.size?(te(r,{size:t.size}),K(r,{dir:"right",size:t.size})):r}function oe(e,t={}){const{signed:n,size:r}=t,s=BigInt(e);let i;r?i=n?(1n<<8n*BigInt(r)-1n)-1n:2n**(8n*BigInt(r))-1n:"number"==typeof e&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o="bigint"==typeof i&&n?-i-1n:0;if(i&&s>i||s<o){const t="bigint"==typeof e?"n":"";throw new X({max:i?`${i}${t}`:void 0,min:`${o}${t}`,signed:n,size:r,value:`${e}${t}`})}const a=`0x${(n&&s<0?(1n<<BigInt(8*r))+BigInt(s):s).toString(16)}`;return r?K(a,{size:r}):a}const ae=new TextEncoder;function ce(e,t={}){return ie(ae.encode(e),t)}const ue=new TextEncoder;function le(e,t={}){return"number"==typeof e||"bigint"==typeof e?function(e,t){const n=oe(e,t);return he(n)}(e,t):"boolean"==typeof e?function(e,t={}){const n=new Uint8Array(1);if(n[0]=Number(e),"number"==typeof t.size)return te(n,{size:t.size}),K(n,{size:t.size});return n}(e,t):B(e)?he(e,t):pe(e,t)}const fe={zero:48,nine:57,A:65,F:70,a:97,f:102};function de(e){return e>=fe.zero&&e<=fe.nine?e-fe.zero:e>=fe.A&&e<=fe.F?e-(fe.A-10):e>=fe.a&&e<=fe.f?e-(fe.a-10):void 0}function he(e,t={}){let n=e;t.size&&(te(n,{size:t.size}),n=K(n,{dir:"right",size:t.size}));let r=n.slice(2);r.length%2&&(r=`0${r}`);const s=r.length/2,i=new Uint8Array(s);for(let e=0,t=0;e<s;e++){const n=de(r.charCodeAt(t++)),s=de(r.charCodeAt(t++));if(void 0===n||void 0===s)throw new S(`Invalid byte sequence ("${r[t-2]}${r[t-1]}" in "${r}").`);i[e]=16*n+s}return i}function pe(e,t={}){const n=ue.encode(e);return"number"==typeof t.size?(te(n,{size:t.size}),K(n,{dir:"right",size:t.size})):n}const ge=BigInt(2**32-1),me=BigInt(32);function ye(e,t=!1){return t?{h:Number(e&ge),l:Number(e>>me&ge)}:{h:0|Number(e>>me&ge),l:0|Number(e&ge)}}function be(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function we(e,...t){if(!((n=e)instanceof Uint8Array||ArrayBuffer.isView(n)&&"Uint8Array"===n.constructor.name))throw new Error("Uint8Array expected");
2
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3
- var n;if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Ae(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ee(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function ve(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const Ie=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])()?e=>e:function(e){for(let t=0;t<e.length;t++)e[t]=ve(e[t]);return e};function xe(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),we(e),e}class Ce{}const Pe=BigInt(0),Oe=BigInt(1),Be=BigInt(2),Ne=BigInt(7),$e=BigInt(256),ze=BigInt(113),De=[],Se=[],Te=[];for(let e=0,t=Oe,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],De.push(2*(5*r+n)),Se.push((e+1)*(e+2)/2%64);let s=Pe;for(let e=0;e<7;e++)t=(t<<Oe^(t>>Ne)*ze)%$e,t&Be&&(s^=Oe<<(Oe<<BigInt(e))-Oe);Te.push(s)}const Ue=function(e,t=!1){const n=e.length;let r=new Uint32Array(n),s=new Uint32Array(n);for(let i=0;i<n;i++){const{h:n,l:o}=ye(e[i],t);[r[i],s[i]]=[n,o]}return[r,s]}(Te,!0),Re=Ue[0],Fe=Ue[1],Le=(e,t,n)=>n>32?((e,t,n)=>t<<n-32|e>>>64-n)(e,t,n):((e,t,n)=>e<<n|t>>>32-n)(e,t,n),_e=(e,t,n)=>n>32?((e,t,n)=>e<<n-32|t>>>64-n)(e,t,n):((e,t,n)=>t<<n|e>>>32-n)(e,t,n);class ke extends Ce{constructor(e,t,n,r=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=s,be(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");var i;this.state=new Uint8Array(200),this.state32=(i=this.state,new Uint32Array(i.buffer,i.byteOffset,Math.floor(i.byteLength/4)))}clone(){return this._cloneInto()}keccak(){Ie(this.state32),function(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let t=0;t<10;t++)n[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const r=(t+8)%10,s=(t+2)%10,i=n[s],o=n[s+1],a=Le(i,o,1)^n[r],c=_e(i,o,1)^n[r+1];for(let n=0;n<50;n+=10)e[t+n]^=a,e[t+n+1]^=c}let t=e[2],s=e[3];for(let n=0;n<24;n++){const r=Se[n],i=Le(t,s,r),o=_e(t,s,r),a=De[n];t=e[a],s=e[a+1],e[a]=i,e[a+1]=o}for(let t=0;t<50;t+=10){for(let r=0;r<10;r++)n[r]=e[t+r];for(let r=0;r<10;r++)e[t+r]^=~n[(r+2)%10]&n[(r+4)%10]}e[0]^=Re[r],e[1]^=Fe[r]}Ee(n)}(this.state32,this.rounds),Ie(this.state32),this.posOut=0,this.pos=0}update(e){Ae(this),we(e=xe(e));const{blockLen:t,state:n}=this,r=e.length;for(let s=0;s<r;){const i=Math.min(t-this.pos,r-s);for(let t=0;t<i;t++)n[this.pos++]^=e[s++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,128&t&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){Ae(this,!1),we(e),this.finish();const t=this.state,{blockLen:n}=this;for(let r=0,s=e.length;r<s;){this.posOut>=n&&this.keccak();const i=Math.min(n-this.posOut,s-r);e.set(t.subarray(this.posOut,this.posOut+i),r),this.posOut+=i,r+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return be(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(function(e,t){we(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Ee(this.state)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:r,rounds:s,enableXOF:i}=this;return e||(e=new ke(t,n,r,i,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=r,e.enableXOF=i,e.destroyed=this.destroyed,e}}const Me=(e,t,n)=>function(e){const t=t=>e().update(xe(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}(()=>new ke(t,e,n)),Ve=(()=>Me(1,136,32))();function je(e,t){const n=t||"hex",r=Ve(B(e,{strict:!1})?le(e):e);return"bytes"===n?r:function(e,t={}){return"number"==typeof e||"bigint"==typeof e?oe(e,t):"string"==typeof e?ce(e,t):"boolean"==typeof e?se(e,t):ie(e,t)}(r)}function We(e){return je(le(e))}const Ge=e=>{var t;return function(e){let t=!0,n="",r=0,s="",i=!1;for(let o=0;o<e.length;o++){const a=e[o];if(["(",")",","].includes(a)&&(t=!0),"("===a&&r++,")"===a&&r--,t)if(0!==r)" "!==a?(s+=a,n+=a):","!==e[o-1]&&","!==n&&",("!==n&&(n="",t=!1);else if(" "===a&&["event","function",""].includes(s))s="";else if(s+=a,")"===a){i=!0;break}}if(!i)throw new S("Unable to normalize signature.");return s}("string"==typeof e?e:"function"===(t=e).type?`function ${t.name}(${C(t.inputs)})${t.stateMutability&&"nonpayable"!==t.stateMutability?` ${t.stateMutability}`:""}${t.outputs?.length?` returns (${C(t.outputs)})`:""}`:"event"===t.type?`event ${t.name}(${C(t.inputs)})`:"error"===t.type?`error ${t.name}(${C(t.inputs)})`:"constructor"===t.type?`constructor(${C(t.inputs)})${"payable"===t.stateMutability?" payable":""}`:"fallback"===t.type?"fallback() external"+("payable"===t.stateMutability?" payable":""):"receive() external payable")};function Qe(e){return We(Ge(e))}const Ye=Qe;class qe extends S{constructor({address:e}){super(`Address "${e}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}class Ke extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const t=super.get(e);return super.has(e)&&void 0!==t&&(this.delete(e),super.set(e,t)),t}set(e,t){if(super.set(e,t),this.maxSize&&this.size>this.maxSize){const e=this.keys().next().value;e&&this.delete(e)}return this}}const He=new Ke(8192);function Xe(e,t){if(He.has(`${e}.${t}`))return He.get(`${e}.${t}`);const n=e.substring(2).toLowerCase(),r=je(pe(n),"bytes"),s=n.split("");for(let e=0;e<40;e+=2)r[e>>1]>>4>=8&&s[e]&&(s[e]=s[e].toUpperCase()),(15&r[e>>1])>=8&&s[e+1]&&(s[e+1]=s[e+1].toUpperCase());const i=`0x${s.join("")}`;return He.set(`${e}.${t}`,i),i}const Ze=/^0x[a-fA-F0-9]{40}$/,Je=new Ke(8192);function et(e,t){const{strict:n=!0}=t??{},r=`${e}.${n}`;if(Je.has(r))return Je.get(r);const s=!(!Ze.test(e)||e.toLowerCase()!==e&&n&&Xe(e)!==e);return Je.set(r,s),s}function tt(e){return"string"==typeof e[0]?nt(e):function(e){let t=0;for(const n of e)t+=n.length;const n=new Uint8Array(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return n}(e)}function nt(e){return`0x${e.reduce((e,t)=>e+t.replace("0x",""),"")}`}function rt(e,t,n,{strict:r}={}){return B(e,{strict:!1})?function(e,t,n,{strict:r}={}){st(e,t);const s=`0x${e.replace("0x","").slice(2*(t??0),2*(n??e.length))}`;r&&it(s,t,n);return s}(e,t,n,{strict:r}):ot(e,t,n,{strict:r})}function st(e,t){if("number"==typeof t&&t>0&&t>N(e)-1)throw new Y({offset:t,position:"start",size:N(e)})}function it(e,t,n){if("number"==typeof t&&"number"==typeof n&&N(e)!==n-t)throw new Y({offset:n,position:"end",size:N(e)})}function ot(e,t,n,{strict:r}={}){st(e,t);const s=e.slice(t,n);return r&&it(s,t,n),s}const at=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;function ct(e,t){if(e.length!==t.length)throw new _({expectedLength:e.length,givenLength:t.length});const n=function({params:e,values:t}){const n=[];for(let r=0;r<e.length;r++)n.push(ut({param:e[r],value:t[r]}));return n}({params:e,values:t}),r=lt(n);return 0===r.length?"0x":r}function ut({param:e,value:t}){const n=ft(e.type);if(n){const[r,s]=n;return function(e,{length:t,param:n}){const r=null===t;if(!Array.isArray(e))throw new G(e);if(!r&&e.length!==t)throw new F({expectedLength:t,givenLength:e.length,type:`${n.type}[${t}]`});let s=!1;const i=[];for(let t=0;t<e.length;t++){const r=ut({param:n,value:e[t]});r.dynamic&&(s=!0),i.push(r)}if(r||s){const e=lt(i);if(r){const t=oe(i.length,{size:32});return{dynamic:!0,encoded:i.length>0?tt([t,e]):t}}if(s)return{dynamic:!0,encoded:e}}return{dynamic:!1,encoded:tt(i.map(({encoded:e})=>e))}}(t,{length:r,param:{...e,type:s}})}if("tuple"===e.type)return function(e,{param:t}){let n=!1;const r=[];for(let s=0;s<t.components.length;s++){const i=t.components[s],o=ut({param:i,value:e[Array.isArray(e)?s:i.name]});r.push(o),o.dynamic&&(n=!0)}return{dynamic:n,encoded:n?lt(r):tt(r.map(({encoded:e})=>e))}}(t,{param:e});if("address"===e.type)return function(e){if(!et(e))throw new qe({address:e});return{dynamic:!1,encoded:H(e.toLowerCase())}}(t);if("bool"===e.type)return function(e){if("boolean"!=typeof e)throw new S(`Invalid boolean value: "${e}" (type: ${typeof e}). Expected: \`true\` or \`false\`.`);return{dynamic:!1,encoded:H(se(e))}}(t);if(e.type.startsWith("uint")||e.type.startsWith("int")){const n=e.type.startsWith("int"),[,,r="256"]=at.exec(e.type)??[];return function(e,{signed:t,size:n=256}){if("number"==typeof n){const r=2n**(BigInt(n)-(t?1n:0n))-1n,s=t?-r-1n:0n;if(e>r||e<s)throw new X({max:r.toString(),min:s.toString(),signed:t,size:n/8,value:e.toString()})}return{dynamic:!1,encoded:oe(e,{size:32,signed:t})}}(t,{signed:n,size:Number(r)})}if(e.type.startsWith("bytes"))return function(e,{param:t}){const[,n]=t.type.split("bytes"),r=N(e);if(!n){let t=e;return r%32!=0&&(t=H(t,{dir:"right",size:32*Math.ceil((e.length-2)/2/32)})),{dynamic:!0,encoded:tt([H(oe(r,{size:32})),t])}}if(r!==Number.parseInt(n,10))throw new L({expectedSize:Number.parseInt(n,10),value:e});return{dynamic:!1,encoded:H(e,{dir:"right"})}}(t,{param:e});if("string"===e.type)return function(e){const t=ce(e),n=Math.ceil(N(t)/32),r=[];for(let e=0;e<n;e++)r.push(H(rt(t,32*e,32*(e+1)),{dir:"right"}));return{dynamic:!0,encoded:tt([H(oe(N(t),{size:32})),...r])}}(t);throw new j(e.type,{docsPath:"/docs/contract/encodeAbiParameters"})}function lt(e){let t=0;for(let n=0;n<e.length;n++){const{dynamic:r,encoded:s}=e[n];t+=r?32:N(s)}const n=[],r=[];let s=0;for(let i=0;i<e.length;i++){const{dynamic:o,encoded:a}=e[i];o?(n.push(oe(t+s,{size:32})),r.push(a),s+=N(a)):n.push(a)}return tt([...n,...r])}function ft(e){const t=e.match(/^(.*)\[(\d+)?\]$/);return t?[t[2]?Number(t[2]):null,t[1]]:void 0}const dt=e=>rt(Qe(e),0,4);function ht(e){const{abi:t,args:n=[],name:r}=e,s=B(r,{strict:!1}),i=t.filter(e=>s?"function"===e.type?dt(e)===r:"event"===e.type&&Ye(e)===r:"name"in e&&e.name===r);if(0===i.length)return;if(1===i.length)return i[0];let o;for(const e of i){if(!("inputs"in e))continue;if(!n||0===n.length){if(!e.inputs||0===e.inputs.length)return e;continue}if(!e.inputs)continue;if(0===e.inputs.length)continue;if(e.inputs.length!==n.length)continue;if(n.every((t,n)=>{const r="inputs"in e&&e.inputs[n];return!!r&&pt(t,r)})){if(o&&"inputs"in o&&o.inputs){const t=gt(e.inputs,o.inputs,n);if(t)throw new V({abiItem:e,type:t[0]},{abiItem:o,type:t[1]})}o=e}}return o||i[0]}function pt(e,t){const n=typeof e,r=t.type;switch(r){case"address":return et(e,{strict:!1});case"bool":return"boolean"===n;case"function":case"string":return"string"===n;default:return"tuple"===r&&"components"in t?Object.values(t.components).every((t,n)=>pt(Object.values(e)[n],t)):/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(r)?"number"===n||"bigint"===n:/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(r)?"string"===n||e instanceof Uint8Array:!!/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(r)&&(Array.isArray(e)&&e.every(e=>pt(e,{...t,type:r.replace(/(\[[0-9]{0,}\])$/,"")})))}}function gt(e,t,n){for(const r in e){const s=e[r],i=t[r];if("tuple"===s.type&&"tuple"===i.type&&"components"in s&&"components"in i)return gt(s.components,i.components,n[r]);const o=[s.type,i.type];if((()=>!(!o.includes("address")||!o.includes("bytes20"))||(o.includes("address")&&o.includes("string")||!(!o.includes("address")||!o.includes("bytes")))&&et(n[r],{strict:!1}))())return o}}const mt="/docs/contract/encodeFunctionData";function yt(e){const{args:t}=e,{abi:n,functionName:r}=1===e.abi.length&&e.functionName?.startsWith("0x")?e:function(e){const{abi:t,args:n,functionName:r}=e;let s=t[0];if(r){const e=ht({abi:t,args:n,name:r});if(!e)throw new k(r,{docsPath:mt});s=e}if("function"!==s.type)throw new k(void 0,{docsPath:mt});return{abi:[s],functionName:dt(P(s))}}(e),s=n[0];return nt([r,("inputs"in s&&s.inputs?ct(s.inputs,t??[]):void 0)??"0x"])}class bt extends S{constructor({offset:e}){super(`Offset \`${e}\` cannot be negative.`,{name:"NegativeOffsetError"})}}class wt extends S{constructor({length:e,position:t}){super(`Position \`${t}\` is out of bounds (\`0 < position < ${e}\`).`,{name:"PositionOutOfBoundsError"})}}class At extends S{constructor({count:e,limit:t}){super(`Recursive read limit of \`${t}\` exceeded (recursive read count: \`${e}\`).`,{name:"RecursiveReadLimitExceededError"})}}const Et={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new At({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new wt({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new bt({offset:e});const t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new bt({offset:e});const t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){const n=t??this.position;return this.assertPosition(n+e-1),this.bytes.subarray(n,n+e)},inspectUint8(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){const t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){const t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){const t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,255&e),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();const n=this.inspectBytes(e);return this.position+=t??e,n},readUint8(){this.assertReadLimit(),this._touch();const e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();const e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();const e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();const e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){const t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function vt(e,t={}){void 0!==t.size&&te(e,{size:t.size});return ne(ie(e,t),t)}function It(e,t={}){let n=e;if(void 0!==t.size&&(te(n,{size:t.size}),n=ee(n)),n.length>1||n[0]>1)throw new Z(n);return Boolean(n[0])}function xt(e,t={}){void 0!==t.size&&te(e,{size:t.size});return function(e,t={}){return Number(ne(e,t))}(ie(e,t),t)}function Ct(e,t){const n="string"==typeof t?he(t):t,r=function(e,{recursiveReadLimit:t=8192}={}){const n=Object.create(Et);return n.bytes=e,n.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),n.positionReadCount=new Map,n.recursiveReadLimit=t,n}(n);if(0===N(n)&&e.length>0)throw new R;if(N(t)&&N(t)<32)throw new U({data:"string"==typeof t?t:ie(t),params:e,size:N(t)});let s=0;const i=[];for(let t=0;t<e.length;++t){const n=e[t];r.setPosition(s);const[o,a]=Pt(r,n,{staticPosition:0});s+=a,i.push(o)}return i}function Pt(e,t,{staticPosition:n}){const r=ft(t.type);if(r){const[s,i]=r;return function(e,t,{length:n,staticPosition:r}){if(!n){const n=r+xt(e.readBytes(Bt)),s=n+Ot;e.setPosition(n);const i=xt(e.readBytes(Ot)),o=Nt(t);let a=0;const c=[];for(let n=0;n<i;++n){e.setPosition(s+(o?32*n:a));const[r,i]=Pt(e,t,{staticPosition:s});a+=i,c.push(r)}return e.setPosition(r+32),[c,32]}if(Nt(t)){const s=r+xt(e.readBytes(Bt)),i=[];for(let r=0;r<n;++r){e.setPosition(s+32*r);const[n]=Pt(e,t,{staticPosition:s});i.push(n)}return e.setPosition(r+32),[i,32]}let s=0;const i=[];for(let o=0;o<n;++o){const[n,o]=Pt(e,t,{staticPosition:r+s});s+=o,i.push(n)}return[i,s]}(e,{...t,type:i},{length:s,staticPosition:n})}if("tuple"===t.type)return function(e,t,{staticPosition:n}){const r=0===t.components.length||t.components.some(({name:e})=>!e),s=r?[]:{};let i=0;if(Nt(t)){const o=n+xt(e.readBytes(Bt));for(let n=0;n<t.components.length;++n){const a=t.components[n];e.setPosition(o+i);const[c,u]=Pt(e,a,{staticPosition:o});i+=u,s[r?n:a?.name]=c}return e.setPosition(n+32),[s,32]}for(let o=0;o<t.components.length;++o){const a=t.components[o],[c,u]=Pt(e,a,{staticPosition:n});s[r?o:a?.name]=c,i+=u}return[s,i]}(e,t,{staticPosition:n});if("address"===t.type)return function(e){const t=e.readBytes(32);return[Xe(ie(ot(t,-20))),32]}(e);if("bool"===t.type)return function(e){return[It(e.readBytes(32),{size:32}),32]}(e);if(t.type.startsWith("bytes"))return function(e,t,{staticPosition:n}){const[r,s]=t.type.split("bytes");if(!s){const t=xt(e.readBytes(32));e.setPosition(n+t);const r=xt(e.readBytes(32));if(0===r)return e.setPosition(n+32),["0x",32];const s=e.readBytes(r);return e.setPosition(n+32),[ie(s),32]}const i=ie(e.readBytes(Number.parseInt(s,10),32));return[i,32]}(e,t,{staticPosition:n});if(t.type.startsWith("uint")||t.type.startsWith("int"))return function(e,t){const n=t.type.startsWith("int"),r=Number.parseInt(t.type.split("int")[1]||"256",10),s=e.readBytes(32);return[r>48?vt(s,{signed:n}):xt(s,{signed:n}),32]}(e,t);if("string"===t.type)return function(e,{staticPosition:t}){const n=xt(e.readBytes(32)),r=t+n;e.setPosition(r);const s=xt(e.readBytes(32));if(0===s)return e.setPosition(t+32),["",32];const i=e.readBytes(s,32),o=function(e,t={}){let n=e;return void 0!==t.size&&(te(n,{size:t.size}),n=ee(n,{dir:"right"})),(new TextDecoder).decode(n)}(ee(i));return e.setPosition(t+32),[o,32]}(e,{staticPosition:n});throw new W(t.type,{docsPath:"/docs/contract/decodeAbiParameters"})}const Ot=32,Bt=32;function Nt(e){const{type:t}=e;if("string"===t)return!0;if("bytes"===t)return!0;if(t.endsWith("[]"))return!0;if("tuple"===t)return e.components?.some(Nt);const n=ft(e.type);return!(!n||!Nt({...e,type:n[1]}))}const $t="/docs/contract/decodeFunctionResult";const zt="0x0000000000000000000000000000000000000000",Dt=e=>e instanceof v?e:new v(e),St=e=>e instanceof v;class Tt extends Error{constructor(e){super(e.message),this.name="SwapError",this.code=e.code,this.details=e.details,Error.captureStackTrace&&Error.captureStackTrace(this,Tt)}}const Ut={V2:0,V3:1},Rt="0x0000000000000000000000000000000000000001",Ft="0x0000000000000000000000000000000000000000",Lt=5,_t=3e4,kt="https://api-public.bitzy.app",Mt={3637:{BITZY_V3:"0xA5E0AE4e5103dc71cA290AA3654830442357A489",BITZY_V2:"0x07c49Ade88b40f1Ac05707f236d7706f834F6BDB",AVOCADO_V2:"0xA4B4cDeC4fE2839d3D3a49Ad5E20c21c01A31091"},3636:{BITZY_V3:"0xA5E0AE4e5103dc71cA290AA3654830442357A489",BITZY_V2:"0x07c49Ade88b40f1Ac05707f236d7706f834F6BDB",AVOCADO_V2:"0xA4B4cDeC4fE2839d3D3a49Ad5E20c21c01A31091"}},Vt={3637:{factoryAddress:"0xDF2CA43f59fd92874e6C1ef887f7E14cb1f354dD",v3FactoryAddress:"0xa8C00286d8d37131c1d033dEeE2F754148932800",v3PositionManagerAddress:"0x76F3e7e326479Ef559996Cf5ab0aCB79Be4626FD",v3WalletHelperAddress:"0xd9Db96Aa882Da764feFff3eE427701B0337e8Ae7",routerAddress:"0x41207Eadf1932966Ff75bdc35e55D2C6734E47D4",aggregatorAddress:"0x5a0690AC82AAAA2e25bC130E900CD31eE9B67DB8",otcAddress:"0xe97ED77EB36A09c37B57D69A5000d8831167A854",memeTokenGenerator:"0x1cb880329265c7A5deDaD6301b1fbd2684CDd200",bitzyQueryAddress:"0x5b5079587501Bd85d3CDf5bFDf299f4eaAe98c23",wrappedAddress:"0x0D2437F93Fed6EA64Ef01cCde385FB1263910C56",nativeAddress:"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",gasLimit:BigInt(5e10)},3636:{factoryAddress:"0x472F9A40F47e0e0F770b224AeC2DD093cf5783aC",v3FactoryAddress:"0xc89e6aD4aD42Eeb82dfBA4c301CDaEDfd794A778",v3PositionManagerAddress:"0xA05E35Fa8997852E6a4A073461E36db1AA725D39",v3WalletHelperAddress:"0x232182B50E1d3c037b3E0bdbd89226d7730cFe0e",routerAddress:"0x07c49Ade88b40f1Ac05707f236d7706f834F6BDB",aggregatorAddress:"0x33B1Ed34c11910F767B15eBAbAB782D61FB2C5Ea",otcAddress:"0xB582f4B568f13F29Bba7696Fc352E293952D4b7E",memeTokenGenerator:"0xc76b4a09BecA8b34D94dE8BA27AeeF652FA3D2fC",bitzyQueryAddress:"0x2ad4b8912fb4Fe93f79BbCb3Aa6B8C39025FdfCC",wrappedAddress:"0x233631132FD56c8f86D1FC97F0b82420a8d20af3",nativeAddress:"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",gasLimit:BigInt(5e10)}},jt={3637:{types:[1,2],enabledSources:[1]},3636:{types:[1,2],enabledSources:[1]}},Wt=e=>jt[e]||{types:[1,2],enabledSources:[1]},Gt=e=>Vt[e],Qt=e=>Mt[e]||{},Yt=Vt,qt=Mt[3637]||{},Kt={PATH_V3:"/api/sdk/bestpath/split",ASSET_MINIMUM:"/api/sdk/asset/minimum"},Ht={INVALID_TOKENS:"INVALID_TOKENS",INVALID_AMOUNT:"INVALID_AMOUNT",NETWORK_NOT_SUPPORTED:"NETWORK_NOT_SUPPORTED",API_ERROR:"API_ERROR",QUERY_ERROR:"QUERY_ERROR",INSUFFICIENT_LIQUIDITY:"INSUFFICIENT_LIQUIDITY"};class Xt{constructor(e){this.config=e}static getInstance(e){if(!Xt.instance){console.log(3232,process.env.NEXT_PUBLIC_BITZY_API_KEY);const t={...e,headers:{...process.env.NEXT_PUBLIC_BITZY_API_KEY&&{"authen-key":process.env.NEXT_PUBLIC_BITZY_API_KEY},...e.headers}};Xt.instance=new Xt(t)}return Xt.instance}static resetInstance(){Xt.instance=null}async request(e,t={}){const n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeout);try{const s=await fetch(`${this.config.baseUrl}${e}`,{...t,signal:n.signal,headers:{"Content-Type":"application/json",...this.config.headers,...t.headers}});if(clearTimeout(r),!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);return await s.json()}catch(t){if(clearTimeout(r),t instanceof Error){if("AbortError"===t.name)throw new Tt({message:"Request timeout",code:Ht.API_ERROR,details:{endpoint:e,timeout:this.config.timeout}});throw new Tt({message:t.message,code:Ht.API_ERROR,details:{endpoint:e,originalError:t}})}throw new Tt({message:"Unknown API error",code:Ht.API_ERROR,details:{endpoint:e,originalError:t}})}}async getPathV3(e,t,n,r,s){const i={src:e.address,dest:t.address,amount:n,typeId:r,sourceId:s},o=this.buildQueryString(i);return this.request(`${Kt.PATH_V3}?${o}`,{method:"GET"})}async getAssetMinimum(){return this.request(Kt.ASSET_MINIMUM,{method:"GET"})}buildQueryString(e){return Object.keys(e).reduce((t,n)=>[...t,`${n}=${Array.isArray(e[n])?'["'+e[n].map(e=>e).join('","')+'"]':e[n]}`],[]).join("&")}}Xt.instance=null;let Zt=null;function Jt(){Zt=null,console.log("Minimum amounts cache cleared")}const en={3637:["0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE","0x0D2437F93Fed6EA64Ef01cCde385FB1263910C56","0x29eE6138DD4C9815f46D34a4A1ed48F46758A402","0x9BC574a6f1170e90D80826D86a6126d59198A3Ef","0xA0b86a33E6441b8c4C8C0C4C0C4C0C4C0C4C0C4C","0xdAC17F958D2ee523a2206206994597C13D831ec7"],3636:["0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE","0x233631132FD56c8f86D1FC97F0b82420a8d20af3","0xA0b86a33E6441b8c4C8C0C4C0C4C0C4C0C4C0C4C","0xdAC17F958D2ee523a2206206994597C13D831ec7"]};function tn(e,t){if(!e?.address)return!1;const n=en[t];return!!n&&n.some(t=>t.toLowerCase()===e.address.toLowerCase())}function nn(e,t,n,r=5){const s=tn(e,n),i=tn(t,n);return s&&i?r:1}async function rn(e,t,n,r,s,i,o=5){try{console.log("Fetching online partCount data...");const a=await async function(e,t){const n=Date.now();if(Zt&&n<Zt.expiresAt)return console.log("Using cached minimum amounts data"),Zt.data;console.log("Fetching fresh minimum amounts data from API");const r=Xt.getInstance({baseUrl:e,timeout:5e3,headers:{...t&&{"authen-key":t}}}),s=await r.getAssetMinimum();if(!s.success)throw new Error(`API request failed: ${s.error||"Unknown error"}`);return Zt={data:s.data||[],timestamp:n,expiresAt:n+3e5},Zt.data}(s,i),c=a.find(t=>t.token?.toLowerCase()===e.address.toLowerCase()),u=a.find(e=>e.token?.toLowerCase()===t.address.toLowerCase()),l=new v(n);return c&&u&&l.gte(c.minimumAmount)&&l.gte(u.minimumAmount)?(console.log("Amount meets minimum threshold for both tokens, using partCount = 5"),5):(console.log("Amount below minimum threshold or missing data, falling back to offline logic"),nn(e,t,r,o))}catch(n){return console.warn("Failed to fetch online partCount data:",n),console.log("Falling back to offline partCount logic"),nn(e,t,r,o)}}async function sn(e,t,n,r,s,i=5,o){try{return await rn(e,t,n,r,s,o,i)}catch(e){return console.warn("Online partCount failed, using offline fallback:",e),i}}function on(e,t,n){if(0===t)return 1/0;return e/n/t*100}function an(e,t,n=5){return on(e,t,5)>n?1:5}function cn(e,t){return!e||isNaN(Number(e))?new v(0):new v(e).times(new v(10).pow(t))}function un(e,t){return new v(e).dividedBy(new v(10).pow(t)).toString()}function ln(e,t){return e.address.toLowerCase()===t.toLowerCase()}function fn(e,t){return e.address.toLowerCase()===t.toLowerCase()}function dn(e,t){return e&&t&&e.address&&t.address&&e.address!==t.address&&e.chainId===t.chainId}function hn(e){if(!e||isNaN(Number(e)))return!1;const t=new v(e);return t.gt(0)&&t.isFinite()}function pn(e,t,n=10){return new v(e).times(t).lt(1)?1:n}function gn(e){return"string"==typeof e?e:e?.message?e.message:e?.error?e.error:"Unknown error occurred"}function mn(e,t){let n;const r=(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)};return r.cancel=()=>{clearTimeout(n)},r}const yn=[{inputs:[{internalType:"uint256",name:"srcAmount",type:"uint256"},{internalType:"bytes",name:"encodedRoutes",type:"bytes"},{internalType:"uint256",name:"parts",type:"uint256"}],name:"splitQuery",outputs:[{components:[{internalType:"uint256",name:"amountOut",type:"uint256"},{internalType:"uint256",name:"bestIndex",type:"uint256"}],internalType:"struct BitzyQueryV2.OneRoute",name:"",type:"tuple"},{components:[{internalType:"uint256[]",name:"distribution",type:"uint256[]"},{internalType:"uint256",name:"amountOut",type:"uint256"}],internalType:"struct BitzyQueryV2.SplitRoute",name:"",type:"tuple"}],stateMutability:"nonpayable",type:"function"}];class bn{constructor(e){this.config=e}async fetchRoute(e){const{amountIn:t,srcToken:n,dstToken:r,chainId:s,partCount:i,forcePartCount:o}=e,a=o||i||this.getPartCount(n,r,s,this.config.defaultPartCount);if(!dn(n,r))throw new Tt({message:"Invalid tokens provided",code:Ht.INVALID_TOKENS,details:{srcToken:n,dstToken:r}});if(!hn(t))throw new Tt({message:"Invalid amount provided",code:Ht.INVALID_AMOUNT,details:{amountIn:t}});const c=cn(t,n.decimals),{routerAddress:u,bitzyQueryAddress:l,wrappedAddress:f,nativeAddress:d}=this.config.config,h=ln(n,d),p=ln(r,d);if(h&&fn(r,f)||p&&fn(n,f)){const e=h?"wrap":"unwrap",t=c;return{routes:[[{routerAddress:u,lpAddress:zt,fromToken:n.address,toToken:r.address,from:n.address,to:r.address,part:"100000000",amountAfterFee:"10000",dexInterface:0}]],distributions:[a],amountOutRoutes:[t],amountOutBN:t,amountInParts:[c],isAmountOutError:!1,isWrap:e}}const g=h?{...n,address:f}:n,m=p?{...r,address:f}:r;try{const t=await this.config.apiClient.getPathV3(g,m,c.toFixed(0),e.types||[1,2],e.enabledSources||[1]),{hops:n,validPath:r}=t.data;if(0===n.length)return console.log("SDK: No hops found"),{routes:[],distributions:[],amountOutRoutes:[],amountOutBN:new v(0),amountInParts:[],isAmountOutError:!0};console.log("SDK: hops.length =",n.length),console.log("SDK: validPath.length =",r.length),console.log("SDK: partCount =",a);const s=ct([{type:"tuple[][]",components:[{type:"address",name:"src"},{type:"address",name:"dest"},{type:"uint8",name:"typeId"},{type:"uint8",name:"sourceId"},{type:"bytes",name:"path"}]}],[n]);let i=new v(0),o=[],u=[];if(this.config.publicClient)try{console.log("SDK: Calling splitQuery with:",{bitzyQueryAddress:l,amountIn:c.toFixed(0),partCount:a,encodedRoutesLength:s.length});const e=yt({abi:yn,functionName:"splitQuery",args:[c.toFixed(0),s,a]}),t=await this.config.publicClient.call({to:l,data:e,gas:50000000000n,gasPrice:void 0});if(console.log("SDK: Contract call result:",t),t.data){const e=function(e){const{abi:t,args:n,functionName:r,data:s}=e;let i=t[0];if(r){const e=ht({abi:t,args:n,name:r});if(!e)throw new k(r,{docsPath:$t});i=e}if("function"!==i.type)throw new k(void 0,{docsPath:$t});if(!i.outputs)throw new M(i.name,{docsPath:$t});const o=Ct(i.outputs,s);return o&&o.length>1?o:o&&1===o.length?o[0]:void 0}({abi:yn,functionName:"splitQuery",data:t.data}),n=e[1];if(n&&n.amountOut){i=new v(n.amountOut.toString());let e=n.distribution.map(e=>new v(e.toString()).toNumber());u=r.reduce((t,n,r)=>(e[r]>0&&t.push(n.map((e,t,n)=>({routerAddress:qt[e.source+"_"+e.type]||zt,lpAddress:e.pool||zt,fromToken:e.src,toToken:e.dest,from:t>0||"V3"===e.type||e.src===f.toLowerCase()?Ft:Rt,to:t<n.length-1||t===n.length-1&&e.dest===f.toLowerCase()?Ft:Rt,part:"100000000",amountAfterFee:new v(1e4).minus(new v(e.fee||0).dividedBy(100)).toFixed(),dexInterface:Ut[e.type]||0}))),t),[]),o=e.filter(e=>e>0)}}}catch(e){console.error("SDK: splitQuery contract call failed:",e),i=new v(0),o=[],u=[]}else console.error("SDK: No publicClient available - this is the problem!"),i=new v(0),o=[],u=[];const d=o.map(e=>i.times(e).dividedBy(a).dp(0,v.ROUND_DOWN)),h=o.map(e=>c.times(e).dividedBy(a).dp(0,v.ROUND_DOWN));return{routes:u,distributions:o,amountOutRoutes:d,amountOutBN:i,amountInParts:h,isAmountOutError:!1}}catch(t){throw new Tt({message:"Failed to fetch swap route",code:Ht.API_ERROR,details:{originalError:t,options:e}})}}getSupportedNetworks(){return Object.keys(Yt).map(Number)}getNetworkConfig(e){return this.config.config}getPartCount(e,t,n,r){return nn(e,t,n,r)}}async function wn(e,t={}){const{apiBaseUrl:n=kt,defaultPartCount:r=Lt,timeout:s=3e4,headers:i={}}=t,o=e.chainId,a=Gt(o);if(!a)throw new Error(`Unsupported network: ${o}`);const c=Xt.getInstance({baseUrl:n,timeout:s,headers:i});return new bn({config:{routerAddress:a.routerAddress,bitzyQueryAddress:a.bitzyQueryAddress,wrappedAddress:a.wrappedAddress,nativeAddress:a.nativeAddress},defaultPartCount:r,apiClient:c}).fetchRoute(e)}async function An(e){return(await Promise.allSettled(e.map(async({options:e,config:t})=>{try{return{success:!0,data:await wn(e,t)}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}))).map(e=>"fulfilled"===e.status?e.value:{success:!1,error:e.reason?.message||"Unknown error"})}async function En(e,t,n,r,s={}){const i=await wn({amountIn:n,srcToken:e,dstToken:t,chainId:r},s);return{amountOut:i.amountOutBN.toFixed(0),routes:i.routes.length}}async function vn(e,t={}){const{types:n,enabledSources:r}=Wt(e.chainId);return wn({...e,types:n,enabledSources:r},{...t,forcePartCount:t.forcePartCount})}const In=(s,i,o,a,c={})=>{const u=e(()=>({}),[]),l=e(()=>({routerAddress:zt,bitzyQueryAddress:zt,wrappedAddress:zt,nativeAddress:zt}),[]),{apiBaseUrl:f,addressConfig:d,defaultPartCount:h,timeout:p,headers:g,refreshInterval:m,publicClient:y,configTypes:b,configEnabledSources:w,forcePartCount:A,useOnlinePartCount:E}=e(()=>{const{apiBaseUrl:e=kt,config:t=l,defaultPartCount:n=5,timeout:r=3e4,headers:s=u,refreshInterval:i=1e4,publicClient:o,types:a,enabledSources:f,forcePartCount:d,useOnlinePartCount:h=!1}=c;return{apiBaseUrl:e,addressConfig:t,defaultPartCount:n,timeout:r,headers:s,refreshInterval:i,publicClient:o,configTypes:a,configEnabledSources:f,forcePartCount:d,useOnlinePartCount:h}},[c,u,l]),I=e(()=>Wt(a),[a]),x=e(()=>b??I.types,[b,I.types]),C=e(()=>w??I.enabledSources,[w,I.enabledSources]);t(()=>{console.log("config",c)},[c]),t(()=>{console.log("srcToken",s)},[s]),t(()=>{console.log("dstToken",i)},[i]),t(()=>{console.log("amountIn",o)},[o]),t(()=>{console.log("chainId",a)},[a]),t(()=>{console.log("apiBaseUrl",f)},[f]),t(()=>{console.log("addressConfig",d)},[d]),t(()=>{console.log("defaultPartCount",h)},[h]),t(()=>{console.log("timeout",p)},[p]),t(()=>{console.log("headers",g)},[g]),t(()=>{console.log("types",x)},[x]),t(()=>{console.log("enabledSources",C)},[C]);const[P,O]=n(new v(0)),[B,N]=n([]),[$,z]=n([]),[D,S]=n([]),[T,U]=n([]),[R,F]=n(!1),[L,_]=n(!1),[k,M]=n(),[V,j]=n(!1),[W,G]=n(null),[Q,Y]=n(null),q=e(()=>(console.log("partCount",0,E),E?null!==Q?Q:nn(s,i,a,h):(console.log("partCount",1,A),void 0!==A?A:(console.log("partCount",2,h),nn(s,i,a,h)))),[h,A,E,Q,s,i,a]);t(()=>{if(!(E&&s&&i&&o))return void Y(null);(async()=>{try{const e=await sn(s,i,o,a,f,h);Y(e)}catch(e){console.warn("Failed to fetch online partCount:",e),Y(null)}})()},[E,s,i,o,a,f,h]);const K=e(()=>{const e=Gt(a),t=d&&Object.keys(d).length>0?d:{routerAddress:e?.routerAddress||"0x0000000000000000000000000000000000000000",bitzyQueryAddress:e?.bitzyQueryAddress||"0x0000000000000000000000000000000000000000",wrappedAddress:e?.wrappedAddress||"0x0000000000000000000000000000000000000000",nativeAddress:e?.nativeAddress||"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"},n=Xt.getInstance({baseUrl:f,timeout:p,headers:g});return new bn({config:t,defaultPartCount:h,apiClient:n,publicClient:y})},[d,h,f,p,g,y,a]),H=r(()=>{G(null)},[]),X=r(async()=>{if(!s||!i||!o||"0"===o)return O(new v(0)),N([]),z([]),S([]),U([]),_(!1),j(!1),void G(null);F(!0),G(null);try{const e={amountIn:o,srcToken:s,dstToken:i,chainId:a,partCount:q,types:x,enabledSources:C},t=await K.fetchRoute(e);O(t.amountOutBN),N(t.routes),z(t.distributions),S(t.amountOutRoutes),U(t.amountInParts),_(t.isAmountOutError),M(t.isWrap),j(!0)}catch(e){const t=e instanceof Error?e.message:"Unknown error occurred";G(t),console.error("Error fetching route:",e),O(new v(0)),N([]),z([]),S([]),U([]),_(!0),j(!1)}finally{F(!1)}},[K,s,i,o,a,q,x,C]),Z=e(()=>mn(X,300),[X]);return t(()=>{if(!o||"0"===o)return O(new v(0)),N([]),z([]),S([]),U([]),_(!1),j(!1),void G(null);Z();const e=setInterval(()=>{Z()},m);return()=>{clearInterval(e),"function"==typeof Z.cancel&&Z.cancel()}},[o,s?.address,i?.address,Z,m]),t(()=>{V&&X()},[X,V,K]),{routes:B,distributions:$,amountOutRoutes:D,amountOutBN:P,amountInParts:T,fetchRoute:X,isLoading:R,isAmountOutError:L,isFirstFetch:V,isWrap:k,error:W,clearError:H}};export{Xt as APIClient,Kt as API_ENDPOINTS,yn as BITZY_QUERY_ABI,Vt as CONTRACT_ADDRESSES,Yt as DEFAULT_NETWORKS,Lt as DEFAULT_PART_COUNT,_t as DEFAULT_TIMEOUT,Ut as DEX_INTERFACE,qt as DEX_ROUTER,Mt as DEX_ROUTERS,Ht as ERROR_CODES,en as HIGH_VALUE_TOKENS,jt as LIQUIDITY_SOURCES,Ft as ROUTER_TARGET,bn as SwapV3Service,Rt as USER_TARGET,pn as calculatePartCount,on as calculatePriceImpact,Jt as clearMinimumAmountsCache,mn as debounce,Dt as ensureBigNumber,An as fetchBatchSwapRoutes,wn as fetchSwapRoute,vn as fetchSwapRouteSimple,gn as formatError,cn as fromTokenAmount,Gt as getContractAddresses,Qt as getDexRouters,Wt as getLiquiditySources,an as getOptimalPartCount,nn as getPartCountOffline,rn as getPartCountOnline,sn as getPartCountWithFallback,En as getSwapQuote,wn as getSwapRoute,St as isBigNumber,tn as isHighValueToken,ln as isNativeToken,fn as isWrappedToken,un as toTokenAmount,In as useSwapRoutes,In as useSwapV3Routes,hn as validateAmount,dn as validateTokens};
1
+ import e from"bignumber.js";import{defineChain as t,createPublicClient as n,http as r,zeroAddress as s,encodeAbiParameters as o,encodeFunctionData as a,decodeFunctionResult as i}from"viem";import{useMemo as d,useEffect as c,useState as u,useCallback as l}from"react";const f=t=>t instanceof e?t:new e(t),p=t=>t instanceof e;class m extends Error{constructor(e){super(e.message),this.name="SwapError",this.code=e.code,this.details=e.details,Error.captureStackTrace&&Error.captureStackTrace(this,m)}}const E={V2:0,V3:1},A="0x0000000000000000000000000000000000000001",C="0x0000000000000000000000000000000000000000",g=5,y=3e4,b="https://api-public.bitzy.app",h={3637:{BITZY_V3:"0xA5E0AE4e5103dc71cA290AA3654830442357A489",BITZY_V2:"0x07c49Ade88b40f1Ac05707f236d7706f834F6BDB",AVOCADO_V2:"0xA4B4cDeC4fE2839d3D3a49Ad5E20c21c01A31091"},3636:{BITZY_V3:"0xA5E0AE4e5103dc71cA290AA3654830442357A489",BITZY_V2:"0x07c49Ade88b40f1Ac05707f236d7706f834F6BDB",AVOCADO_V2:"0xA4B4cDeC4fE2839d3D3a49Ad5E20c21c01A31091"}},w={3637:{factoryAddress:"0xDF2CA43f59fd92874e6C1ef887f7E14cb1f354dD",v3FactoryAddress:"0xa8C00286d8d37131c1d033dEeE2F754148932800",v3PositionManagerAddress:"0x76F3e7e326479Ef559996Cf5ab0aCB79Be4626FD",v3WalletHelperAddress:"0xd9Db96Aa882Da764feFff3eE427701B0337e8Ae7",routerAddress:"0x41207Eadf1932966Ff75bdc35e55D2C6734E47D4",aggregatorAddress:"0x5a0690AC82AAAA2e25bC130E900CD31eE9B67DB8",otcAddress:"0xe97ED77EB36A09c37B57D69A5000d8831167A854",memeTokenGenerator:"0x1cb880329265c7A5deDaD6301b1fbd2684CDd200",bitzyQueryAddress:"0x5b5079587501Bd85d3CDf5bFDf299f4eaAe98c23",wrappedAddress:"0x0D2437F93Fed6EA64Ef01cCde385FB1263910C56",nativeAddress:"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",gasLimit:BigInt(5e10)},3636:{factoryAddress:"0x472F9A40F47e0e0F770b224AeC2DD093cf5783aC",v3FactoryAddress:"0xc89e6aD4aD42Eeb82dfBA4c301CDaEDfd794A778",v3PositionManagerAddress:"0xA05E35Fa8997852E6a4A073461E36db1AA725D39",v3WalletHelperAddress:"0x232182B50E1d3c037b3E0bdbd89226d7730cFe0e",routerAddress:"0x07c49Ade88b40f1Ac05707f236d7706f834F6BDB",aggregatorAddress:"0x33B1Ed34c11910F767B15eBAbAB782D61FB2C5Ea",otcAddress:"0xB582f4B568f13F29Bba7696Fc352E293952D4b7E",memeTokenGenerator:"0xc76b4a09BecA8b34D94dE8BA27AeeF652FA3D2fC",bitzyQueryAddress:"0x2ad4b8912fb4Fe93f79BbCb3Aa6B8C39025FdfCC",wrappedAddress:"0x233631132FD56c8f86D1FC97F0b82420a8d20af3",nativeAddress:"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE",gasLimit:BigInt(5e10)}},I={3637:{rpcUrls:["https://rpc.botanixlabs.com"],name:"Botanix Mainnet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:18}},3636:{rpcUrls:["https://node.botanixlabs.dev"],name:"Botanix Testnet",nativeCurrency:{name:"Bitcoin",symbol:"BTC",decimals:18}}},T={3637:{types:[1,2],enabledSources:[1]},3636:{types:[1,2],enabledSources:[1]}},D=e=>T[e]||{types:[1,2],enabledSources:[1]},B=e=>w[e],O=e=>h[e]||{},x=w,F=h[3637]||{},P={PATH_V3:"/api/sdk/bestpath/split",ASSET_MINIMUM:"/api/sdk/asset/minimum"},N={INVALID_TOKENS:"INVALID_TOKENS",INVALID_AMOUNT:"INVALID_AMOUNT",NETWORK_NOT_SUPPORTED:"NETWORK_NOT_SUPPORTED",API_ERROR:"API_ERROR",QUERY_ERROR:"QUERY_ERROR",INSUFFICIENT_LIQUIDITY:"INSUFFICIENT_LIQUIDITY"};class R{constructor(e){this.config=e}static getInstance(e){if(!R.instance){const t={...e,headers:{...process.env.NEXT_PUBLIC_BITZY_API_KEY&&{"authen-key":process.env.NEXT_PUBLIC_BITZY_API_KEY},...e.headers}};R.instance=new R(t)}return R.instance}static resetInstance(){R.instance=null}async request(e,t={}){const n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeout);try{const s=await fetch(`${this.config.baseUrl}${e}`,{...t,signal:n.signal,headers:{"Content-Type":"application/json",...this.config.headers,...t.headers}});if(clearTimeout(r),!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);return await s.json()}catch(t){if(clearTimeout(r),t instanceof Error){if("AbortError"===t.name)throw new m({message:"Request timeout",code:N.API_ERROR,details:{endpoint:e,timeout:this.config.timeout}});throw new m({message:t.message,code:N.API_ERROR,details:{endpoint:e,originalError:t}})}throw new m({message:"Unknown API error",code:N.API_ERROR,details:{endpoint:e,originalError:t}})}}async getPathV3(e,t,n,r,s){const o=new URLSearchParams;return o.set("src",e.address),o.set("dest",t.address),o.set("amount",n),o.set("typeId",JSON.stringify(r)),o.set("sourceId",JSON.stringify(s)),this.request(`${P.PATH_V3}?${o.toString()}`,{method:"GET"})}async getAssetMinimum(){return this.request(P.ASSET_MINIMUM,{method:"GET"})}}R.instance=null;let _=null;function k(){_=null,console.log("Minimum amounts cache cleared")}const v={3637:["0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE","0x0D2437F93Fed6EA64Ef01cCde385FB1263910C56","0x29eE6138DD4C9815f46D34a4A1ed48F46758A402","0x9BC574a6f1170e90D80826D86a6126d59198A3Ef","0xA0b86a33E6441b8c4C8C0C4C0C4C0C4C0C4C0C4C","0xdAC17F958D2ee523a2206206994597C13D831ec7"],3636:["0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE","0x233631132FD56c8f86D1FC97F0b82420a8d20af3","0xA0b86a33E6441b8c4C8C0C4C0C4C0C4C0C4C0C4C","0xdAC17F958D2ee523a2206206994597C13D831ec7"]};function U(e,t){if(!e?.address)return!1;const n=v[t];return!!n&&n.some(t=>t.toLowerCase()===e.address.toLowerCase())}function S(e,t,n,r=5){const s=U(e,n),o=U(t,n);return s&&o?r:1}async function L(t,n,r,s,o,a,i=5){try{console.log("Fetching online partCount data...");const d=await async function(e,t){const n=Date.now();if(_&&n<_.expiresAt)return console.log("Using cached minimum amounts data"),_.data;console.log("Fetching fresh minimum amounts data from API");const r=R.getInstance({baseUrl:e,timeout:5e3,headers:{...t&&{"authen-key":t}}}),s=await r.getAssetMinimum();if(!s.success)throw new Error(`API request failed: ${s.error||"Unknown error"}`);return _={data:s.data||[],timestamp:n,expiresAt:n+3e5},_.data}(o,a),c=d.find(e=>e.token?.toLowerCase()===t.address.toLowerCase()),u=d.find(e=>e.token?.toLowerCase()===n.address.toLowerCase()),l=new e(r);return c&&u&&l.gte(c.minimumAmount)&&l.gte(u.minimumAmount)?(console.log("Amount meets minimum threshold for both tokens, using partCount = 5"),5):(console.log("Amount below minimum threshold or missing data, falling back to offline logic"),S(t,n,s,i))}catch(e){return console.warn("Failed to fetch online partCount data:",e),console.log("Falling back to offline partCount logic"),S(t,n,s,i)}}async function V(e,t,n,r,s,o=5,a){try{return await L(e,t,n,r,s,a,o)}catch(e){return console.warn("Online partCount failed, using offline fallback:",e),o}}function Q(e,t,n){if(0===t)return 1/0;return e/n/t*100}function M(e,t,n=5){return Q(e,t,5)>n?1:5}function Y(t,n){return!t||isNaN(Number(t))?new e(0):new e(t).times(new e(10).pow(n))}function z(t,n){return new e(t).dividedBy(new e(10).pow(n)).toString()}function W(e,t){return e.address.toLowerCase()===t.toLowerCase()}function $(e,t){return e.address.toLowerCase()===t.toLowerCase()}function K(e,t){return e&&t&&e.address&&t.address&&e.address!==t.address&&e.chainId===t.chainId}function Z(t){if(!t||isNaN(Number(t)))return!1;const n=new e(t);return n.gt(0)&&n.isFinite()}function j(t,n,r=10){return new e(t).times(n).lt(1)?1:r}function q(e){return"string"==typeof e?e:e?.message?e.message:e?.error?e.error:"Unknown error occurred"}function H(e,t){let n;const r=(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)};return r.cancel=()=>{clearTimeout(n)},r}const G=[{inputs:[{internalType:"uint256",name:"srcAmount",type:"uint256"},{internalType:"bytes",name:"encodedRoutes",type:"bytes"},{internalType:"uint256",name:"parts",type:"uint256"}],name:"splitQuery",outputs:[{components:[{internalType:"uint256",name:"amountOut",type:"uint256"},{internalType:"uint256",name:"bestIndex",type:"uint256"}],internalType:"struct BitzyQueryV2.OneRoute",name:"",type:"tuple"},{components:[{internalType:"uint256[]",name:"distribution",type:"uint256[]"},{internalType:"uint256",name:"amountOut",type:"uint256"}],internalType:"struct BitzyQueryV2.SplitRoute",name:"",type:"tuple"}],stateMutability:"nonpayable",type:"function"}];class J{constructor(e){this.config=e}getPublicClient(e){if(this.config.publicClient)return this.config.publicClient;const s=(e=>I[e])(e);if(!s)throw new m({message:`Unsupported chainId: ${e}`,code:N.NETWORK_NOT_SUPPORTED,details:{chainId:e}});const o=t({id:e,name:s.name,network:s.name.toLowerCase().replace(/\s+/g,"-"),nativeCurrency:s.nativeCurrency,rpcUrls:{default:{http:s.rpcUrls},public:{http:s.rpcUrls}}});return n({chain:o,transport:r()})}async fetchRoute(t){const{amountIn:n,srcToken:r,dstToken:d,chainId:c,partCount:u,forcePartCount:l}=t,f=l||u||this.getPartCount(r,d,c,this.config.defaultPartCount);if(!K(r,d))throw new m({message:"Invalid tokens provided",code:N.INVALID_TOKENS,details:{srcToken:r,dstToken:d}});if(!Z(n))throw new m({message:"Invalid amount provided",code:N.INVALID_AMOUNT,details:{amountIn:n}});const p=Y(n,r.decimals),{routerAddress:g,bitzyQueryAddress:y,wrappedAddress:b,nativeAddress:h}=this.config.config,w=W(r,h),I=W(d,h);if(w&&$(d,b)||I&&$(r,b)){const e=w?"wrap":"unwrap",t=p;return{routes:[[{routerAddress:g,lpAddress:s,fromToken:r.address,toToken:d.address,from:r.address,to:d.address,part:"100000000",amountAfterFee:"10000",dexInterface:0}]],distributions:[f],amountOutRoutes:[t],amountOutBN:t,amountInParts:[p],isAmountOutError:!1,isWrap:e}}const T=w?{...r,address:b}:r,D=I?{...d,address:b}:d;try{const n=await this.config.apiClient.getPathV3(T,D,p.toFixed(0),t.types||[1,2],t.enabledSources||[1]),{hops:r,validPath:d}=n.data;if(0===r.length)return{routes:[],distributions:[],amountOutRoutes:[],amountOutBN:new e(0),amountInParts:[],isAmountOutError:!0};const u=o([{type:"tuple[][]",components:[{type:"address",name:"src"},{type:"address",name:"dest"},{type:"uint8",name:"typeId"},{type:"uint8",name:"sourceId"},{type:"bytes",name:"path"}]}],[r]);let l=new e(0),m=[],g=[];const h=this.getPublicClient(c);try{const t=a({abi:G,functionName:"splitQuery",args:[p.toFixed(0),u,f]}),n=await h.call({to:y,data:t,gas:50000000000n,gasPrice:void 0});if(n.data){const t=i({abi:G,functionName:"splitQuery",data:n.data})[1];if(t&&t.amountOut){l=new e(t.amountOut.toString());let n=t.distribution.map(t=>new e(t.toString()).toNumber());g=d.reduce((t,r,o)=>(n[o]>0&&t.push(r.map((t,n,r)=>({routerAddress:F[t.source+"_"+t.type]||s,lpAddress:t.pool||s,fromToken:t.src,toToken:t.dest,from:n>0||"V3"===t.type||t.src===b.toLowerCase()?C:A,to:n<r.length-1||n===r.length-1&&t.dest===b.toLowerCase()?C:A,part:"100000000",amountAfterFee:new e(1e4).minus(new e(t.fee||0).dividedBy(100)).toFixed(),dexInterface:E[t.type]||0}))),t),[]),m=n.filter(e=>e>0)}}}catch(t){l=new e(0),m=[],g=[]}const w=m.map(t=>l.times(t).dividedBy(f).dp(0,e.ROUND_DOWN)),I=m.map(t=>p.times(t).dividedBy(f).dp(0,e.ROUND_DOWN));return{routes:g,distributions:m,amountOutRoutes:w,amountOutBN:l,amountInParts:I,isAmountOutError:!1}}catch(e){throw new m({message:"Failed to fetch swap route",code:N.API_ERROR,details:{originalError:e,options:t}})}}getSupportedNetworks(){return Object.keys(x).map(Number)}getNetworkConfig(e){return this.config.config}getPartCount(e,t,n,r){return S(e,t,n,r)}}async function X(e,t={}){const{apiBaseUrl:n=b,defaultPartCount:r=g,timeout:s=3e4,headers:o={},publicClient:a}=t,i=e.chainId,d=B(i);if(!d)throw new Error(`Unsupported network: ${i}`);const c=R.getInstance({baseUrl:n,timeout:s,headers:o});return new J({config:{routerAddress:d.routerAddress,bitzyQueryAddress:d.bitzyQueryAddress,wrappedAddress:d.wrappedAddress,nativeAddress:d.nativeAddress},defaultPartCount:r,apiClient:c,publicClient:a}).fetchRoute(e)}async function ee(e){return(await Promise.allSettled(e.map(async({options:e,config:t})=>{try{return{success:!0,data:await X(e,t)}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error"}}}))).map(e=>"fulfilled"===e.status?e.value:{success:!1,error:e.reason?.message||"Unknown error"})}async function te(e,t,n,r,s={}){const o=await X({amountIn:n,srcToken:e,dstToken:t,chainId:r},s);return{amountOut:o.amountOutBN.toFixed(0),routes:o.routes.length}}async function ne(e,t={}){const{types:n,enabledSources:r}=D(e.chainId);return X({...e,types:n,enabledSources:r},{...t,forcePartCount:t.forcePartCount})}const re=(t,n,r,o,a={})=>{const i=d(()=>({}),[]),f=d(()=>({routerAddress:s,bitzyQueryAddress:s,wrappedAddress:s,nativeAddress:s}),[]),{apiBaseUrl:p,addressConfig:m,defaultPartCount:E,timeout:A,headers:C,refreshInterval:g,publicClient:y,configTypes:h,configEnabledSources:w,forcePartCount:I,useOnlinePartCount:T}=d(()=>{const{apiBaseUrl:e=b,config:t=f,defaultPartCount:n=5,timeout:r=3e4,headers:s=i,refreshInterval:o=1e4,publicClient:d,types:c,enabledSources:u,forcePartCount:l,useOnlinePartCount:p=!1}=a;return{apiBaseUrl:e,addressConfig:t,defaultPartCount:n,timeout:r,headers:s,refreshInterval:o,publicClient:d,configTypes:c,configEnabledSources:u,forcePartCount:l,useOnlinePartCount:p}},[a,i,f]),O=d(()=>D(o),[o]),x=d(()=>h??O.types,[h,O.types]),F=d(()=>w??O.enabledSources,[w,O.enabledSources]);c(()=>{console.log("config",a)},[a]),c(()=>{console.log("srcToken",t)},[t]),c(()=>{console.log("dstToken",n)},[n]),c(()=>{console.log("amountIn",r)},[r]),c(()=>{console.log("chainId",o)},[o]),c(()=>{console.log("apiBaseUrl",p)},[p]),c(()=>{console.log("addressConfig",m)},[m]),c(()=>{console.log("defaultPartCount",E)},[E]),c(()=>{console.log("timeout",A)},[A]),c(()=>{console.log("headers",C)},[C]),c(()=>{console.log("types",x)},[x]),c(()=>{console.log("enabledSources",F)},[F]);const[P,N]=u(new e(0)),[_,k]=u([]),[v,U]=u([]),[L,Q]=u([]),[M,Y]=u([]),[z,W]=u(!1),[$,K]=u(!1),[Z,j]=u(),[q,G]=u(!1),[X,ee]=u(null),[te,ne]=u(null),re=d(()=>(console.log("partCount",0,T),T?null!==te?te:S(t,n,o,E):(console.log("partCount",1,I),void 0!==I?I:(console.log("partCount",2,E),S(t,n,o,E)))),[E,I,T,te,t,n,o]);c(()=>{if(!(T&&t&&n&&r))return void ne(null);(async()=>{try{const e=await V(t,n,r,o,p,E);ne(e)}catch(e){console.warn("Failed to fetch online partCount:",e),ne(null)}})()},[T,t,n,r,o,p,E]);const se=d(()=>{const e=B(o),t=m&&Object.keys(m).length>0?m:{routerAddress:e?.routerAddress||"0x0000000000000000000000000000000000000000",bitzyQueryAddress:e?.bitzyQueryAddress||"0x0000000000000000000000000000000000000000",wrappedAddress:e?.wrappedAddress||"0x0000000000000000000000000000000000000000",nativeAddress:e?.nativeAddress||"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE"},n=R.getInstance({baseUrl:p,timeout:A,headers:C});return new J({config:t,defaultPartCount:E,apiClient:n,publicClient:y})},[m,E,p,A,C,y,o]),oe=l(()=>{ee(null)},[]),ae=l(async()=>{if(!t||!n||!r||"0"===r)return N(new e(0)),k([]),U([]),Q([]),Y([]),K(!1),G(!1),void ee(null);W(!0),ee(null);try{const e={amountIn:r,srcToken:t,dstToken:n,chainId:o,partCount:re,types:x,enabledSources:F},s=await se.fetchRoute(e);N(s.amountOutBN),k(s.routes),U(s.distributions),Q(s.amountOutRoutes),Y(s.amountInParts),K(s.isAmountOutError),j(s.isWrap),G(!0)}catch(t){const n=t instanceof Error?t.message:"Unknown error occurred";ee(n),console.error("Error fetching route:",t),N(new e(0)),k([]),U([]),Q([]),Y([]),K(!0),G(!1)}finally{W(!1)}},[se,t,n,r,o,re,x,F]),ie=d(()=>H(ae,300),[ae]);return c(()=>{if(!r||"0"===r)return N(new e(0)),k([]),U([]),Q([]),Y([]),K(!1),G(!1),void ee(null);ie();const t=setInterval(()=>{ie()},g);return()=>{clearInterval(t),"function"==typeof ie.cancel&&ie.cancel()}},[r,t?.address,n?.address,ie,g]),c(()=>{q&&ae()},[ae,q,se]),{routes:_,distributions:v,amountOutRoutes:L,amountOutBN:P,amountInParts:M,fetchRoute:ae,isLoading:z,isAmountOutError:$,isFirstFetch:q,isWrap:Z,error:X,clearError:oe}};export{R as APIClient,P as API_ENDPOINTS,G as BITZY_QUERY_ABI,w as CONTRACT_ADDRESSES,x as DEFAULT_NETWORKS,g as DEFAULT_PART_COUNT,y as DEFAULT_TIMEOUT,E as DEX_INTERFACE,F as DEX_ROUTER,h as DEX_ROUTERS,N as ERROR_CODES,v as HIGH_VALUE_TOKENS,T as LIQUIDITY_SOURCES,C as ROUTER_TARGET,J as SwapV3Service,A as USER_TARGET,j as calculatePartCount,Q as calculatePriceImpact,k as clearMinimumAmountsCache,H as debounce,f as ensureBigNumber,ee as fetchBatchSwapRoutes,X as fetchSwapRoute,ne as fetchSwapRouteSimple,q as formatError,Y as fromTokenAmount,B as getContractAddresses,O as getDexRouters,D as getLiquiditySources,M as getOptimalPartCount,S as getPartCountOffline,L as getPartCountOnline,V as getPartCountWithFallback,te as getSwapQuote,X as getSwapRoute,p as isBigNumber,U as isHighValueToken,W as isNativeToken,$ as isWrappedToken,z as toTokenAmount,re as useSwapRoutes,re as useSwapV3Routes,Z as validateAmount,K as validateTokens};
4
2
  //# sourceMappingURL=index.esm.js.map