@zyfai/sdk 0.2.55 → 0.2.57

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/dist/index.mjs CHANGED
@@ -2,9 +2,40 @@
2
2
  import axios from "axios";
3
3
 
4
4
  // src/config/endpoints.ts
5
- var API_ENDPOINT = "https://api.zyf.ai";
6
- var DATA_API_ENDPOINT = "https://defiapi.zyf.ai";
7
- var WS_ENDPOINT = "wss://defiapi.zyf.ai/ws/events";
5
+ var EXECUTION_API_BASE_URLS = {
6
+ production: "https://api.zyf.ai",
7
+ staging: "https://staging-api.zyf.ai",
8
+ local: "http://localhost:3000"
9
+ };
10
+ var DATA_API_BASE_URLS = {
11
+ production: "https://defiapi.zyf.ai",
12
+ staging: "https://staging-defiapi.zyf.ai",
13
+ /** Both backends default to port 3000 locally; run one at a time or override PORT. */
14
+ local: "http://localhost:3000"
15
+ };
16
+ var WS_URLS = {
17
+ production: "wss://defiapi.zyf.ai/ws/events",
18
+ staging: "wss://staging-defiapi.zyf.ai/ws/events",
19
+ local: "ws://localhost:3000/ws/events"
20
+ };
21
+ var API_ENDPOINT = EXECUTION_API_BASE_URLS.production;
22
+ var DATA_API_ENDPOINT = DATA_API_BASE_URLS.production;
23
+ var WS_ENDPOINT = WS_URLS.production;
24
+ var STAGING_EXECUTION_API_BASE_URL = EXECUTION_API_BASE_URLS.staging;
25
+ var STAGING_DATA_API_BASE_URL = DATA_API_BASE_URLS.staging;
26
+ var STAGING_WS_URL = WS_URLS.staging;
27
+ var LOCAL_EXECUTION_API_BASE_URL = EXECUTION_API_BASE_URLS.local;
28
+ var LOCAL_DATA_API_BASE_URL = DATA_API_BASE_URLS.local;
29
+ var LOCAL_WS_URL = WS_URLS.local;
30
+ function getExecutionApiBaseUrl(environment = "production") {
31
+ return EXECUTION_API_BASE_URLS[environment];
32
+ }
33
+ function getDataApiBaseUrl(environment = "production") {
34
+ return DATA_API_BASE_URLS[environment];
35
+ }
36
+ function getWsUrl(environment = "production") {
37
+ return WS_URLS[environment];
38
+ }
8
39
  var API_VERSION = "/api/v1";
9
40
  var DATA_API_VERSION = "/api/v2";
10
41
  var ENDPOINTS = {
@@ -50,11 +81,17 @@ var ENDPOINTS = {
50
81
  `networks=${networks}`,
51
82
  `strategy=${params.strategy}`
52
83
  ];
53
- if (params.minSplit !== void 0) query.push(`minSplit=${params.minSplit}`);
54
- if (params.protocols?.length) query.push(`protocols=${params.protocols.join(",")}`);
84
+ if (params.minSplit !== void 0)
85
+ query.push(`minSplit=${params.minSplit}`);
86
+ if (params.protocols?.length)
87
+ query.push(`protocols=${params.protocols.join(",")}`);
55
88
  if (params.pools?.length) query.push(`pools=${params.pools.join(",")}`);
56
- if (params.userPositions?.length) query.push(`userPositions=${encodeURIComponent(JSON.stringify(params.userPositions))}`);
57
- if (params.partOfZyfiTvl !== void 0) query.push(`partOfZyfiTvl=${params.partOfZyfiTvl}`);
89
+ if (params.userPositions?.length)
90
+ query.push(
91
+ `userPositions=${encodeURIComponent(JSON.stringify(params.userPositions))}`
92
+ );
93
+ if (params.partOfZyfiTvl !== void 0)
94
+ query.push(`partOfZyfiTvl=${params.partOfZyfiTvl}`);
58
95
  return `/simulate/best-positions?${query.join("&")}`;
59
96
  },
60
97
  // Customization
@@ -89,12 +126,20 @@ var DATA_ENDPOINTS = {
89
126
  if (status) params.push(`status=${status}`);
90
127
  return params.length > 0 ? `/opportunities/degen-strategies?${params.join("&")}` : "/opportunities/degen-strategies";
91
128
  },
129
+ OPPORTUNITIES_ASYNC: (chainId, asset, status) => {
130
+ const params = [];
131
+ if (chainId !== void 0) params.push(`chainId=${chainId}`);
132
+ if (asset) params.push(`asset=${asset}`);
133
+ if (status) params.push(`status=${status}`);
134
+ return params.length > 0 ? `/opportunities/async?${params.join("&")}` : "/opportunities/async";
135
+ },
92
136
  // APY History
93
137
  DAILY_APY_HISTORY_WEIGHTED: (walletAddress, days) => `/daily-apy-history/weighted-multi-asset/${walletAddress}${days ? `?days=${days}` : ""}`,
94
138
  // Rebalance
95
139
  REBALANCE_INFO: (options) => {
96
140
  const params = [];
97
- if (options?.isCrossChain !== void 0) params.push(`isCrossChain=${options.isCrossChain}`);
141
+ if (options?.isCrossChain !== void 0)
142
+ params.push(`isCrossChain=${options.isCrossChain}`);
98
143
  if (options?.tokenSymbol) params.push(`tokenSymbol=${options.tokenSymbol}`);
99
144
  return params.length > 0 ? `/rebalance/rebalance-info?${params.join("&")}` : "/rebalance/rebalance-info";
100
145
  },
@@ -103,10 +148,12 @@ var DATA_ENDPOINTS = {
103
148
  // APY Per Strategy
104
149
  APY_PER_STRATEGY: (options = {}) => {
105
150
  const params = [];
106
- if (options.isCrossChain !== void 0) params.push(`isCrossChain=${options.isCrossChain}`);
151
+ if (options.isCrossChain !== void 0)
152
+ params.push(`isCrossChain=${options.isCrossChain}`);
107
153
  if (options.days !== void 0) params.push(`days=${options.days}`);
108
154
  if (options.strategy) params.push(`strategy=${options.strategy}`);
109
- if (options.chainId !== void 0) params.push(`chainId=${options.chainId}`);
155
+ if (options.chainId !== void 0)
156
+ params.push(`chainId=${options.chainId}`);
110
157
  if (options.tokenSymbol) params.push(`tokenSymbol=${options.tokenSymbol}`);
111
158
  return params.length > 0 ? `/rebalance/rebalance-info?${params.join("&")}` : "/rebalance/rebalance-info";
112
159
  }
@@ -119,14 +166,16 @@ var HttpClient = class {
119
166
  *
120
167
  * @param apiKey - API key for both Execution API and Data API
121
168
  */
122
- constructor(apiKey) {
169
+ constructor(apiKey, config = {}) {
123
170
  this.authToken = null;
124
171
  this.apiKey = apiKey;
125
- const parsedUrl = new URL(API_ENDPOINT);
172
+ const executionApiUrl = config.executionApiUrl ?? API_ENDPOINT;
173
+ this.dataApiBaseUrl = config.dataApiUrl ?? DATA_API_ENDPOINT;
174
+ const parsedUrl = new URL(executionApiUrl);
126
175
  this.origin = parsedUrl.origin;
127
176
  this.host = parsedUrl.host;
128
177
  this.client = axios.create({
129
- baseURL: `${API_ENDPOINT}${API_VERSION}`,
178
+ baseURL: `${executionApiUrl}${API_VERSION}`,
130
179
  headers: {
131
180
  "Content-Type": "application/json",
132
181
  "X-API-Key": this.apiKey
@@ -134,7 +183,7 @@ var HttpClient = class {
134
183
  timeout: 3e4
135
184
  });
136
185
  this.dataClient = axios.create({
137
- baseURL: `${DATA_API_ENDPOINT}${DATA_API_VERSION}`,
186
+ baseURL: `${this.dataApiBaseUrl}${DATA_API_VERSION}`,
138
187
  headers: {
139
188
  "Content-Type": "application/json",
140
189
  "X-API-Key": this.apiKey
@@ -177,7 +226,9 @@ var HttpClient = class {
177
226
  const data = error.response.data;
178
227
  switch (status) {
179
228
  case 401:
180
- throw new Error("Unauthorized: Invalid API key");
229
+ throw new Error(
230
+ this.authToken ? "Unauthorized: Invalid or expired user session. Call connectAccount() to sign in again." : "Unauthorized: Missing user session. Call connectAccount() before this endpoint \u2014 the SDK API key alone is not sufficient."
231
+ );
181
232
  case 403:
182
233
  throw new Error("Forbidden: Access denied");
183
234
  case 404:
@@ -187,7 +238,9 @@ var HttpClient = class {
187
238
  case 429:
188
239
  throw new Error("Rate limit exceeded. Please try again later.");
189
240
  case 500:
190
- throw new Error(data?.message || data?.error || "Internal server error. Please try again later.");
241
+ throw new Error(
242
+ data?.message || data?.error || "Internal server error. Please try again later."
243
+ );
191
244
  default:
192
245
  throw new Error(data.message || "An error occurred");
193
246
  }
@@ -233,7 +286,7 @@ var HttpClient = class {
233
286
  * @param config - Additional axios config
234
287
  */
235
288
  async dataPostCustom(path, data, config) {
236
- const fullUrl = `${DATA_API_ENDPOINT}${path}`;
289
+ const fullUrl = `${this.dataApiBaseUrl}${path}`;
237
290
  const headers = {
238
291
  "Content-Type": "application/json",
239
292
  "X-API-Key": this.apiKey,
@@ -268,7 +321,9 @@ var HttpClient = class {
268
321
  const data = error.response.data;
269
322
  switch (status) {
270
323
  case 401:
271
- throw new Error("Unauthorized: Invalid API key");
324
+ throw new Error(
325
+ this.authToken ? "Unauthorized: Invalid or expired user session. Call connectAccount() to sign in again." : "Unauthorized: Missing user session. Call connectAccount() before this endpoint \u2014 the SDK API key alone is not sufficient."
326
+ );
272
327
  case 403:
273
328
  throw new Error("Forbidden: Access denied to data API");
274
329
  case 404:
@@ -910,15 +965,18 @@ var signSessionKey = async (config, sessions, allPublicClients, signingParams) =
910
965
  };
911
966
 
912
967
  // src/utils/strategy.ts
968
+ var PUBLIC_STRATEGIES = `"conservative", "aggressive" or "yieldmaxxing"`;
913
969
  function toInternalStrategy(publicStrategy) {
914
970
  switch (publicStrategy) {
915
971
  case "conservative":
916
972
  return "safe_strategy";
917
973
  case "aggressive":
918
974
  return "degen_strategy";
975
+ case "yieldmaxxing":
976
+ return "async_strategy";
919
977
  default:
920
978
  throw new Error(
921
- `Invalid public strategy: ${publicStrategy}. Must be "conservative" or "aggressive".`
979
+ `Invalid public strategy: ${publicStrategy}. Must be ${PUBLIC_STRATEGIES}.`
922
980
  );
923
981
  }
924
982
  }
@@ -929,12 +987,25 @@ function toPublicStrategy(internalStrategy) {
929
987
  if (internalStrategy === "degen_strategy" || internalStrategy === "degen") {
930
988
  return "aggressive";
931
989
  }
990
+ if (internalStrategy === "async_strategy" || internalStrategy === "async") {
991
+ return "yieldmaxxing";
992
+ }
932
993
  throw new Error(
933
- `Invalid internal strategy: ${internalStrategy}. Must be "safe_strategy" or "degen_strategy".`
994
+ `Invalid internal strategy: ${internalStrategy}. Must be "safe_strategy", "degen_strategy" or "async_strategy".`
934
995
  );
935
996
  }
997
+ function toPublicStrategyOrUndefined(internalStrategy) {
998
+ if (!internalStrategy) {
999
+ return void 0;
1000
+ }
1001
+ try {
1002
+ return toPublicStrategy(internalStrategy);
1003
+ } catch {
1004
+ return void 0;
1005
+ }
1006
+ }
936
1007
  function isValidPublicStrategy(strategy) {
937
- return strategy === "conservative" || strategy === "aggressive";
1008
+ return strategy === "conservative" || strategy === "aggressive" || strategy === "yieldmaxxing";
938
1009
  }
939
1010
  function convertStrategyToPublic(obj) {
940
1011
  if (!obj.strategy) {
@@ -1029,16 +1100,19 @@ var hasAssetOnSelectedChains = (protocol, chains, asset) => {
1029
1100
  (a) => chains.includes(a.chainId) && validSymbols.includes(a.symbol)
1030
1101
  );
1031
1102
  };
1103
+ var ELIGIBLE_PROTOCOL_STRATEGIES = {
1104
+ safe_strategy: ["safe_strategy"],
1105
+ degen_strategy: ["safe_strategy", "degen_strategy"],
1106
+ async_strategy: ["safe_strategy", "degen_strategy", "async_strategy"]
1107
+ };
1032
1108
  var getMatchingProtocolIds = (protocols, internalStrategy, chains, asset) => {
1033
1109
  if (chains.length === 0) return [];
1110
+ const eligible = ELIGIBLE_PROTOCOL_STRATEGIES[internalStrategy] ?? ELIGIBLE_PROTOCOL_STRATEGIES.safe_strategy;
1034
1111
  return protocols.filter((protocol) => {
1035
1112
  if (!protocol || !protocol.strategies) return false;
1036
1113
  if (!protocol.chains?.some((c) => chains.includes(c))) return false;
1037
1114
  if (!hasAssetOnSelectedChains(protocol, chains, asset)) return false;
1038
- if (internalStrategy === "degen_strategy") {
1039
- return protocol.strategies.includes("degen_strategy") || protocol.strategies.includes("safe_strategy");
1040
- }
1041
- return protocol.strategies.includes("safe_strategy");
1115
+ return protocol.strategies.some((s) => eligible.includes(s));
1042
1116
  }).map((protocol) => protocol.id);
1043
1117
  };
1044
1118
  var hasMatchingPool = (data, chains, asset) => {
@@ -1417,11 +1491,21 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1417
1491
  this.currentProvider = null;
1418
1492
  this.currentChainId = null;
1419
1493
  const sdkConfig = typeof config === "string" ? { apiKey: config } : config;
1420
- const { apiKey, rpcUrls, referralSource } = sdkConfig;
1494
+ const {
1495
+ apiKey,
1496
+ rpcUrls,
1497
+ referralSource,
1498
+ executionApiUrl,
1499
+ dataApiUrl
1500
+ } = sdkConfig;
1421
1501
  if (!apiKey) {
1422
1502
  throw new Error("API key is required");
1423
1503
  }
1424
- this.httpClient = new HttpClient(apiKey);
1504
+ this.executionApiUrl = executionApiUrl ?? API_ENDPOINT;
1505
+ this.httpClient = new HttpClient(apiKey, {
1506
+ executionApiUrl: this.executionApiUrl,
1507
+ dataApiUrl
1508
+ });
1425
1509
  this.rpcUrls = rpcUrls;
1426
1510
  this.referralSource = referralSource;
1427
1511
  }
@@ -1458,8 +1542,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1458
1542
  uri = globalWindow.location.origin;
1459
1543
  domain = globalWindow.location.host;
1460
1544
  } else {
1461
- uri = API_ENDPOINT;
1462
- domain = API_ENDPOINT.split("//")[1];
1545
+ uri = this.executionApiUrl;
1546
+ domain = new URL(this.executionApiUrl).host;
1463
1547
  }
1464
1548
  const messageObj = new SiweMessage({
1465
1549
  address: userAddress,
@@ -1529,12 +1613,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1529
1613
  if (request.strategy) {
1530
1614
  if (!isValidPublicStrategy(request.strategy)) {
1531
1615
  throw new Error(
1532
- `Invalid strategy: ${request.strategy}. Must be "conservative" or "aggressive".`
1616
+ `Invalid strategy: ${request.strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
1533
1617
  );
1534
1618
  }
1535
- rebalanceStrategy = toInternalStrategy(
1536
- request.strategy
1537
- );
1619
+ rebalanceStrategy = toInternalStrategy(request.strategy);
1538
1620
  }
1539
1621
  const assetSettings = {};
1540
1622
  if (rebalanceStrategy !== void 0) assetSettings.rebalanceStrategy = rebalanceStrategy;
@@ -1628,9 +1710,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1628
1710
  const allProtocols = await this.httpClient.get(
1629
1711
  ENDPOINTS.PROTOCOLS()
1630
1712
  );
1631
- const usdcStrategy = userDetailsUSDC.strategy || "safe_strategy";
1632
- const ethStrategy = userDetailsETH.strategy || "safe_strategy";
1633
- const eurcStrategy = userDetailsEURC.strategy || "safe_strategy";
1713
+ const internalStrategyOf = (strategy) => isValidPublicStrategy(strategy ?? "") ? toInternalStrategy(strategy) : "safe_strategy";
1714
+ const usdcStrategy = internalStrategyOf(userDetailsUSDC.strategy);
1715
+ const ethStrategy = internalStrategyOf(userDetailsETH.strategy);
1716
+ const eurcStrategy = internalStrategyOf(userDetailsEURC.strategy);
1634
1717
  const filterProtocolsByStrategy = (strategy, selectedChains) => {
1635
1718
  return allProtocols.filter((protocol) => {
1636
1719
  const hasMatchingChain = protocol.chains.some(
@@ -1639,6 +1722,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1639
1722
  if (!hasMatchingChain) {
1640
1723
  return false;
1641
1724
  }
1725
+ if (strategy === "async_strategy") {
1726
+ return protocol.strategies?.includes("safe_strategy") || protocol.strategies?.includes("degen_strategy") || protocol.strategies?.includes("async_strategy");
1727
+ }
1642
1728
  if (strategy === "degen_strategy") {
1643
1729
  return protocol.strategies?.includes("safe_strategy") || protocol.strategies?.includes("degen_strategy");
1644
1730
  }
@@ -2058,7 +2144,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2058
2144
  *
2059
2145
  * @param userAddress - User's EOA address (the connected EOA, not the smart wallet address)
2060
2146
  * @param chainId - Target chain ID
2061
- * @param strategy - Optional strategy selection: "conservative" (default) or "aggressive"
2147
+ * @param strategy - Optional strategy selection: "conservative" (default), "aggressive" or "yieldmaxxing"
2062
2148
  * @param createSessionKey - If true, automatically creates a session key after deployment (default: false)
2063
2149
  * @returns Deployment response with Safe address and transaction hash
2064
2150
  *
@@ -2404,27 +2490,30 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2404
2490
  const withPools = await this.filterProtocolIdsWithPools(
2405
2491
  matching,
2406
2492
  effectiveChains,
2407
- asset
2493
+ asset,
2494
+ internalStrategy
2408
2495
  );
2409
2496
  await this.updateUserProfile({
2410
2497
  asset,
2411
2498
  protocols: withPools,
2412
- chains: effectiveChains
2499
+ chains: effectiveChains,
2500
+ ...strategy !== void 0 && { strategy }
2413
2501
  });
2414
2502
  }
2415
2503
  /**
2416
2504
  * Drop protocols that have no pools on any of the selected chains for the
2417
- * requested asset. Uses the /customization/pools endpoint with
2418
- * `degen_strategy` as the master strategy so the response includes both
2419
- * safe and degen pools — mirrors the front-end behavior.
2505
+ * requested asset. The /customization/pools endpoint filters server-side on
2506
+ * the strategy, and each tier is a superset of the previous one, so the
2507
+ * caller's strategy must be passed through — asking for `degen_strategy`
2508
+ * returns an empty pool set for async-only assets.
2420
2509
  * @internal
2421
2510
  */
2422
- async filterProtocolIdsWithPools(protocolIds, chains, asset) {
2511
+ async filterProtocolIdsWithPools(protocolIds, chains, asset, internalStrategy = "degen_strategy") {
2423
2512
  if (protocolIds.length === 0) return [];
2424
2513
  const results = await Promise.allSettled(
2425
2514
  protocolIds.map(async (id) => {
2426
2515
  const poolsData = await this.httpClient.get(
2427
- ENDPOINTS.CUSTOMIZATION_POOLS(id, "degen_strategy")
2516
+ ENDPOINTS.CUSTOMIZATION_POOLS(id, internalStrategy)
2428
2517
  );
2429
2518
  return { id, hasPool: hasMatchingPool(poolsData, chains, asset) };
2430
2519
  })
@@ -2477,7 +2566,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2477
2566
  * protocol selection for USDC, WETH, and EURC across all supported chains
2478
2567
  * (EURC on Mainnet/Base only) before the transfer and log_deposit.
2479
2568
  * Pass `strategy` to select protocols for that first-deposit setup
2480
- * (same role as the former `deploySafe` strategy argument).
2569
+ * (same role as the former `deploySafe` strategy argument). On every later
2570
+ * deposit the argument is ignored without error, since re-running the patch
2571
+ * would overwrite a protocol selection the user may have customised. To
2572
+ * change the strategy of an existing account, call
2573
+ * `updateUserProfile({ asset, strategy })`.
2481
2574
  *
2482
2575
  * Minimum portfolio balance enforced (Safe balance + deposit amount):
2483
2576
  * - Stablecoins: `MIN_PORTFOLIO_BALANCE` (Mainnet 10,000 USDC/EURC; Base/Arbitrum 100)
@@ -2489,7 +2582,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2489
2582
  * @param asset - Asset symbol: "USDC", "WETH", or "EURC".
2490
2583
  * EURC is supported on Ethereum Mainnet and Base only.
2491
2584
  * @param strategy - Optional strategy for first-deposit protocol patching:
2492
- * "conservative" (default) or "aggressive"
2585
+ * "conservative" (default), "aggressive" or "yieldmaxxing". Ignored on
2586
+ * later deposits — use `updateUserProfile` to change an existing account.
2493
2587
  * @returns Deposit response with transaction hash
2494
2588
  *
2495
2589
  * @example
@@ -2504,6 +2598,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2504
2598
  *
2505
2599
  * // First deposit with aggressive strategy
2506
2600
  * await sdk.depositFunds(userAddress, 8453, "10000000000", "USDC", "aggressive");
2601
+ *
2602
+ * // Changing the strategy of an account that has already deposited
2603
+ * await sdk.updateUserProfile({ asset: "USDC", strategy: "yieldmaxxing" });
2507
2604
  * ```
2508
2605
  */
2509
2606
  /**
@@ -2548,7 +2645,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2548
2645
  }
2549
2646
  if (strategy !== void 0 && !isValidPublicStrategy(strategy)) {
2550
2647
  throw new Error(
2551
- `Invalid strategy: ${strategy}. Must be "conservative" or "aggressive".`
2648
+ `Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
2552
2649
  );
2553
2650
  }
2554
2651
  const assetSymbol = asset.toUpperCase();
@@ -2570,6 +2667,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2570
2667
  }
2571
2668
  const token = getDefaultTokenAddress(chainId, assetSymbol);
2572
2669
  const walletClient = this.getWalletClient();
2670
+ await this.authenticateUser();
2573
2671
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
2574
2672
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
2575
2673
  if (!safeAddress) {
@@ -2628,19 +2726,16 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2628
2726
  const receipt = await chainConfig.publicClient.waitForTransactionReceipt({
2629
2727
  hash: txHash
2630
2728
  });
2631
- try {
2632
- await this.httpClient.post(ENDPOINTS.LOG_DEPOSIT, {
2633
- chainId,
2634
- transaction: txHash,
2635
- token,
2636
- amount
2637
- });
2638
- } catch (logError) {
2639
- console.warn("Failed to log deposit:", logError.message);
2640
- }
2641
2729
  if (receipt.status !== "success") {
2642
2730
  throw new Error("Deposit transaction failed");
2643
2731
  }
2732
+ try {
2733
+ await this.logDeposit(chainId, txHash, amount, token);
2734
+ } catch (logError) {
2735
+ throw new Error(
2736
+ `On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}") to retry.`
2737
+ );
2738
+ }
2644
2739
  return {
2645
2740
  success: true,
2646
2741
  txHash,
@@ -2660,6 +2755,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2660
2755
  * wallet stays reserved (no ownership rotation), and yield/agent tracking does
2661
2756
  * not start.
2662
2757
  *
2758
+ * Requires `connectAccount()` on the same SDK instance first (SIWE user JWT).
2759
+ * The SDK API key alone is not enough — `log_deposit` returns 401 without a
2760
+ * Bearer token.
2761
+ *
2663
2762
  * Use this method when you execute the deposit transaction yourself and need to
2664
2763
  * register it with the Zyfai backend.
2665
2764
  *
@@ -2706,6 +2805,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2706
2805
  throw new Error("Valid amount is required");
2707
2806
  }
2708
2807
  const token = tokenAddress || getDefaultTokenAddress(chainId);
2808
+ await this.authenticateUser();
2709
2809
  await this.httpClient.post(ENDPOINTS.LOG_DEPOSIT, {
2710
2810
  chainId,
2711
2811
  transaction: txHash,
@@ -2726,6 +2826,25 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2726
2826
  * Note: The withdrawal is processed asynchronously, so txHash may not be immediately available
2727
2827
  * Funds are always withdrawn to the Safe owner's address (userAddress)
2728
2828
  *
2829
+ * **Delayed withdrawals.** Positions held under the `"yieldmaxxing"`
2830
+ * strategy sit in protocols that cannot be exited on demand. For those the
2831
+ * backend transfers the immediately available portion, then queues a
2832
+ * redemption for the rest and forwards the funds to the EOA once the
2833
+ * protocol releases them — about a day on Ipor, three on Superform. No
2834
+ * further call is needed, but the returned `txHash` only covers the
2835
+ * immediate portion. Track the remainder through
2836
+ * `getPortfolio().portfolio.pendingAsyncWithdrawals`, whose entries carry a
2837
+ * `status` and an `estimatedClaimAt`.
2838
+ *
2839
+ * When every source is an async pool nothing settles on-chain at that point,
2840
+ * so `txHash` is `undefined` on a successful call.
2841
+ *
2842
+ * Once requested, that amount can no longer be withdrawn: it is gone from
2843
+ * both the position snapshot and the Safe balance, so a second call silently
2844
+ * returns only what is left. Validate user-entered amounts against
2845
+ * `portfolioByAssetType`, not against the total that includes in-flight
2846
+ * funds — see `getPortfolio`.
2847
+ *
2729
2848
  * @param userAddress - User's address (owner of the Safe)
2730
2849
  * @param chainId - Target chain ID
2731
2850
  * @param amount - Optional: Amount in least decimal units to withdraw (partial withdrawal). If not specified, withdraws all funds
@@ -2890,6 +3009,29 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2890
3009
  * Note: portfolio balances are live; earnings used for the fee may be from
2891
3010
  * a snapshot, so net values can differ slightly from a fully live calc.
2892
3011
  *
3012
+ * **Total balance.** `portfolioByAssetType` sums deployed positions and idle
3013
+ * Safe balances, and nothing else. Under the `"yieldmaxxing"` strategy a
3014
+ * redemption in flight has already left its position and has not landed in
3015
+ * the Safe yet, so its funds appear in no balance field at all. That makes
3016
+ * two distinct numbers:
3017
+ *
3018
+ * ```
3019
+ * total = portfolioByAssetType[assetType].balance
3020
+ * + sum(pendingAsyncWithdrawals where REQUESTED or CLAIMABLE)
3021
+ *
3022
+ * requestable = portfolioByAssetType[assetType].balance
3023
+ * ```
3024
+ *
3025
+ * An in-flight amount is no longer withdrawable: `withdrawFunds` only reaches
3026
+ * the current positions and idle balances, so calling it again neither speeds
3027
+ * those funds up nor errors. They reach the EOA on their own. Cap any
3028
+ * user-entered withdrawal amount at `requestable`, never at `total`.
3029
+ *
3030
+ * Do not add `staleBalances` on top — those are the same idle balances
3031
+ * `portfolioByAssetType` already counts, exposed as a per-chain view.
3032
+ * Do not add `CLAIMED` withdrawals either (the array keeps them for 24
3033
+ * hours); their funds are back in the Safe and already counted.
3034
+ *
2893
3035
  * @param userAddress - User's EOA address
2894
3036
  * @returns Portfolio with optional fee-adjusted balance fields
2895
3037
  *
@@ -2897,6 +3039,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2897
3039
  * ```typescript
2898
3040
  * const { portfolio } = await sdk.getPortfolio(userAddress);
2899
3041
  * console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
3042
+ *
3043
+ * // Funds still locked in an async redemption
3044
+ * const inFlight = (portfolio.pendingAsyncWithdrawals ?? []).filter(
3045
+ * (w) => w.status === "REQUESTED" || w.status === "CLAIMABLE"
3046
+ * );
2900
3047
  * ```
2901
3048
  */
2902
3049
  async getPortfolio(userAddress) {
@@ -2970,7 +3117,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2970
3117
  omniAccount: convertedResponse.omniAccount,
2971
3118
  asset,
2972
3119
  autoSelectProtocols: convertedResponse.assetTypeSettings?.[internalAsset]?.autoSelectProtocols,
2973
- strategy: convertedResponse.assetTypeSettings?.[internalAsset]?.rebalanceStrategy,
3120
+ // `convertStrategyToPublic` only touches the root `strategy` field;
3121
+ // the per-asset one is nested and has to be converted here.
3122
+ strategy: toPublicStrategyOrUndefined(
3123
+ convertedResponse.assetTypeSettings?.[internalAsset]?.rebalanceStrategy
3124
+ ),
2974
3125
  autocompounding: convertedResponse.assetTypeSettings?.[internalAsset]?.autocompounding,
2975
3126
  crosschainStrategy: convertedResponse.assetTypeSettings?.[internalAsset]?.crosschainStrategy,
2976
3127
  splitting: convertedResponse.assetTypeSettings?.[internalAsset]?.splitting,
@@ -3017,7 +3168,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3017
3168
  *
3018
3169
  * @param crossChain - Whether to get cross-chain APY (true = omni account, false = simple account)
3019
3170
  * @param days - Time period: 7, 14, or 30
3020
- * @param strategy - Strategy type: "conservative" (default) or "aggressive"
3171
+ * @param strategy - Strategy type: "conservative" (default), "aggressive" or "yieldmaxxing"
3021
3172
  * @param chainId - Optional chain ID filter
3022
3173
  * @param tokenSymbol - Optional token symbol filter (e.g. "USDC", "WETH", "WBTC")
3023
3174
  * @returns APY per strategy for a specific chain
@@ -3484,6 +3635,53 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3484
3635
  );
3485
3636
  }
3486
3637
  }
3638
+ /**
3639
+ * Get yieldmaxxing opportunities — pools reachable only with the
3640
+ * `"yieldmaxxing"` strategy, including protocols whose withdrawals are
3641
+ * asynchronous (Ipor, Superform). Exiting these pools takes about a day
3642
+ * on Ipor and three on Superform; track the redemption through
3643
+ * `getPortfolio().portfolio.pendingAsyncWithdrawals`.
3644
+ *
3645
+ * @param chainId - Optional chain ID filter
3646
+ * @param asset - Optional asset filter (e.g. "USDC", "WETH")
3647
+ * @returns List of yieldmaxxing opportunities
3648
+ *
3649
+ * @example
3650
+ * ```typescript
3651
+ * const opportunities = await sdk.getAsyncOpportunities(8453);
3652
+ * opportunities.data.forEach(o => console.log(o.protocolName, o.apy));
3653
+ * ```
3654
+ */
3655
+ async getAsyncOpportunities(chainId, asset, status) {
3656
+ try {
3657
+ const response = await this.httpClient.dataGet(
3658
+ DATA_ENDPOINTS.OPPORTUNITIES_ASYNC(chainId, asset, status)
3659
+ );
3660
+ const data = response.data || response || [];
3661
+ return {
3662
+ success: true,
3663
+ chainId,
3664
+ strategyType: "yieldmaxxing",
3665
+ data: Array.isArray(data) ? data.map((o) => ({
3666
+ id: o.id,
3667
+ protocolId: o.protocol_id || o.protocolId,
3668
+ protocolName: o.protocol_name || o.protocolName,
3669
+ poolName: o.pool_name || o.poolName,
3670
+ chainId: o.chain_id || o.chainId,
3671
+ apy: o.combined_apy || 0,
3672
+ tvl: o.tvl || o.zyfiTvl,
3673
+ asset: o.asset || o.underlying_token,
3674
+ risk: o.risk,
3675
+ strategyType: "yieldmaxxing",
3676
+ status: o.status
3677
+ })) : []
3678
+ };
3679
+ } catch (error) {
3680
+ throw new Error(
3681
+ `Failed to get yieldmaxxing opportunities: ${error.message}`
3682
+ );
3683
+ }
3684
+ }
3487
3685
  /**
3488
3686
  * Get active conservative opportunities (status = "live") with risk and utilization data
3489
3687
  * Returns pool info, liquidity depth (true if > 1M), utilization rate, stability metrics, avg APY, and collateral
@@ -3860,7 +4058,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3860
4058
  * Returns the list of pools available for a given protocol, optionally filtered by strategy.
3861
4059
  *
3862
4060
  * @param protocolId - The protocol UUID
3863
- * @param strategy - Optional strategy filter ("conservative" or "aggressive")
4061
+ * @param strategy - Optional strategy filter ("conservative", "aggressive" or "yieldmaxxing")
3864
4062
  * @returns List of available pool names
3865
4063
  *
3866
4064
  * @example
@@ -3882,7 +4080,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3882
4080
  if (strategy) {
3883
4081
  if (!isValidPublicStrategy(strategy)) {
3884
4082
  throw new Error(
3885
- `Invalid strategy: ${strategy}. Must be "conservative" or "aggressive".`
4083
+ `Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
3886
4084
  );
3887
4085
  }
3888
4086
  internalStrategy = toInternalStrategy(strategy);
@@ -3928,7 +4126,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3928
4126
  try {
3929
4127
  if (!isValidPublicStrategy(params.strategy)) {
3930
4128
  throw new Error(
3931
- `Invalid strategy: ${params.strategy}. Must be "conservative" or "aggressive".`
4129
+ `Invalid strategy: ${params.strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
3932
4130
  );
3933
4131
  }
3934
4132
  const internalStrategy = toInternalStrategy(params.strategy);
@@ -4636,21 +4834,36 @@ function createBankrProvider(config) {
4636
4834
  }
4637
4835
  export {
4638
4836
  ALLOWED_HISTORY_DAYS,
4837
+ API_ENDPOINT,
4838
+ DATA_API_BASE_URLS,
4839
+ DATA_API_ENDPOINT,
4639
4840
  DEFAULT_TOKEN_ADDRESSES,
4640
4841
  ERC7579_LAUNCHPAD_ADDRESS,
4842
+ EXECUTION_API_BASE_URLS,
4641
4843
  INTENT_EXECUTOR,
4642
4844
  INTENT_SMART_SESSIONS,
4845
+ LOCAL_DATA_API_BASE_URL,
4846
+ LOCAL_EXECUTION_API_BASE_URL,
4847
+ LOCAL_WS_URL,
4643
4848
  OWNABLE_VALIDATOR,
4644
4849
  POOL_MODULE_ADDRESSES,
4645
4850
  PROXY_EXECUTOR,
4646
4851
  SAFE_7579_ADDRESS,
4647
4852
  SMART_SESSIONS_FALLBACK,
4648
4853
  SMART_SESSIONS_VALIDATOR,
4854
+ STAGING_DATA_API_BASE_URL,
4855
+ STAGING_EXECUTION_API_BASE_URL,
4856
+ STAGING_WS_URL,
4649
4857
  VAULT_ADDRESS,
4858
+ WS_ENDPOINT,
4859
+ WS_URLS,
4650
4860
  ZyfaiSDK,
4651
4861
  createBankrProvider,
4652
4862
  getChainConfig,
4863
+ getDataApiBaseUrl,
4653
4864
  getDefaultTokenAddress,
4865
+ getExecutionApiBaseUrl,
4654
4866
  getSupportedChainIds,
4867
+ getWsUrl,
4655
4868
  isSupportedChain
4656
4869
  };