@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.js CHANGED
@@ -31,22 +31,37 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
33
  ALLOWED_HISTORY_DAYS: () => ALLOWED_HISTORY_DAYS,
34
+ API_ENDPOINT: () => API_ENDPOINT,
35
+ DATA_API_BASE_URLS: () => DATA_API_BASE_URLS,
36
+ DATA_API_ENDPOINT: () => DATA_API_ENDPOINT,
34
37
  DEFAULT_TOKEN_ADDRESSES: () => DEFAULT_TOKEN_ADDRESSES,
35
38
  ERC7579_LAUNCHPAD_ADDRESS: () => ERC7579_LAUNCHPAD_ADDRESS,
39
+ EXECUTION_API_BASE_URLS: () => EXECUTION_API_BASE_URLS,
36
40
  INTENT_EXECUTOR: () => INTENT_EXECUTOR,
37
41
  INTENT_SMART_SESSIONS: () => INTENT_SMART_SESSIONS,
42
+ LOCAL_DATA_API_BASE_URL: () => LOCAL_DATA_API_BASE_URL,
43
+ LOCAL_EXECUTION_API_BASE_URL: () => LOCAL_EXECUTION_API_BASE_URL,
44
+ LOCAL_WS_URL: () => LOCAL_WS_URL,
38
45
  OWNABLE_VALIDATOR: () => OWNABLE_VALIDATOR,
39
46
  POOL_MODULE_ADDRESSES: () => POOL_MODULE_ADDRESSES,
40
47
  PROXY_EXECUTOR: () => PROXY_EXECUTOR,
41
48
  SAFE_7579_ADDRESS: () => SAFE_7579_ADDRESS,
42
49
  SMART_SESSIONS_FALLBACK: () => SMART_SESSIONS_FALLBACK,
43
50
  SMART_SESSIONS_VALIDATOR: () => SMART_SESSIONS_VALIDATOR,
51
+ STAGING_DATA_API_BASE_URL: () => STAGING_DATA_API_BASE_URL,
52
+ STAGING_EXECUTION_API_BASE_URL: () => STAGING_EXECUTION_API_BASE_URL,
53
+ STAGING_WS_URL: () => STAGING_WS_URL,
44
54
  VAULT_ADDRESS: () => VAULT_ADDRESS,
55
+ WS_ENDPOINT: () => WS_ENDPOINT,
56
+ WS_URLS: () => WS_URLS,
45
57
  ZyfaiSDK: () => ZyfaiSDK,
46
58
  createBankrProvider: () => createBankrProvider,
47
59
  getChainConfig: () => getChainConfig,
60
+ getDataApiBaseUrl: () => getDataApiBaseUrl,
48
61
  getDefaultTokenAddress: () => getDefaultTokenAddress,
62
+ getExecutionApiBaseUrl: () => getExecutionApiBaseUrl,
49
63
  getSupportedChainIds: () => getSupportedChainIds,
64
+ getWsUrl: () => getWsUrl,
50
65
  isSupportedChain: () => isSupportedChain
51
66
  });
52
67
  module.exports = __toCommonJS(index_exports);
@@ -55,9 +70,40 @@ module.exports = __toCommonJS(index_exports);
55
70
  var import_axios = __toESM(require("axios"));
56
71
 
57
72
  // src/config/endpoints.ts
58
- var API_ENDPOINT = "https://api.zyf.ai";
59
- var DATA_API_ENDPOINT = "https://defiapi.zyf.ai";
60
- var WS_ENDPOINT = "wss://defiapi.zyf.ai/ws/events";
73
+ var EXECUTION_API_BASE_URLS = {
74
+ production: "https://api.zyf.ai",
75
+ staging: "https://staging-api.zyf.ai",
76
+ local: "http://localhost:3000"
77
+ };
78
+ var DATA_API_BASE_URLS = {
79
+ production: "https://defiapi.zyf.ai",
80
+ staging: "https://staging-defiapi.zyf.ai",
81
+ /** Both backends default to port 3000 locally; run one at a time or override PORT. */
82
+ local: "http://localhost:3000"
83
+ };
84
+ var WS_URLS = {
85
+ production: "wss://defiapi.zyf.ai/ws/events",
86
+ staging: "wss://staging-defiapi.zyf.ai/ws/events",
87
+ local: "ws://localhost:3000/ws/events"
88
+ };
89
+ var API_ENDPOINT = EXECUTION_API_BASE_URLS.production;
90
+ var DATA_API_ENDPOINT = DATA_API_BASE_URLS.production;
91
+ var WS_ENDPOINT = WS_URLS.production;
92
+ var STAGING_EXECUTION_API_BASE_URL = EXECUTION_API_BASE_URLS.staging;
93
+ var STAGING_DATA_API_BASE_URL = DATA_API_BASE_URLS.staging;
94
+ var STAGING_WS_URL = WS_URLS.staging;
95
+ var LOCAL_EXECUTION_API_BASE_URL = EXECUTION_API_BASE_URLS.local;
96
+ var LOCAL_DATA_API_BASE_URL = DATA_API_BASE_URLS.local;
97
+ var LOCAL_WS_URL = WS_URLS.local;
98
+ function getExecutionApiBaseUrl(environment = "production") {
99
+ return EXECUTION_API_BASE_URLS[environment];
100
+ }
101
+ function getDataApiBaseUrl(environment = "production") {
102
+ return DATA_API_BASE_URLS[environment];
103
+ }
104
+ function getWsUrl(environment = "production") {
105
+ return WS_URLS[environment];
106
+ }
61
107
  var API_VERSION = "/api/v1";
62
108
  var DATA_API_VERSION = "/api/v2";
63
109
  var ENDPOINTS = {
@@ -103,11 +149,17 @@ var ENDPOINTS = {
103
149
  `networks=${networks}`,
104
150
  `strategy=${params.strategy}`
105
151
  ];
106
- if (params.minSplit !== void 0) query.push(`minSplit=${params.minSplit}`);
107
- if (params.protocols?.length) query.push(`protocols=${params.protocols.join(",")}`);
152
+ if (params.minSplit !== void 0)
153
+ query.push(`minSplit=${params.minSplit}`);
154
+ if (params.protocols?.length)
155
+ query.push(`protocols=${params.protocols.join(",")}`);
108
156
  if (params.pools?.length) query.push(`pools=${params.pools.join(",")}`);
109
- if (params.userPositions?.length) query.push(`userPositions=${encodeURIComponent(JSON.stringify(params.userPositions))}`);
110
- if (params.partOfZyfiTvl !== void 0) query.push(`partOfZyfiTvl=${params.partOfZyfiTvl}`);
157
+ if (params.userPositions?.length)
158
+ query.push(
159
+ `userPositions=${encodeURIComponent(JSON.stringify(params.userPositions))}`
160
+ );
161
+ if (params.partOfZyfiTvl !== void 0)
162
+ query.push(`partOfZyfiTvl=${params.partOfZyfiTvl}`);
111
163
  return `/simulate/best-positions?${query.join("&")}`;
112
164
  },
113
165
  // Customization
@@ -142,12 +194,20 @@ var DATA_ENDPOINTS = {
142
194
  if (status) params.push(`status=${status}`);
143
195
  return params.length > 0 ? `/opportunities/degen-strategies?${params.join("&")}` : "/opportunities/degen-strategies";
144
196
  },
197
+ OPPORTUNITIES_ASYNC: (chainId, asset, status) => {
198
+ const params = [];
199
+ if (chainId !== void 0) params.push(`chainId=${chainId}`);
200
+ if (asset) params.push(`asset=${asset}`);
201
+ if (status) params.push(`status=${status}`);
202
+ return params.length > 0 ? `/opportunities/async?${params.join("&")}` : "/opportunities/async";
203
+ },
145
204
  // APY History
146
205
  DAILY_APY_HISTORY_WEIGHTED: (walletAddress, days) => `/daily-apy-history/weighted-multi-asset/${walletAddress}${days ? `?days=${days}` : ""}`,
147
206
  // Rebalance
148
207
  REBALANCE_INFO: (options) => {
149
208
  const params = [];
150
- if (options?.isCrossChain !== void 0) params.push(`isCrossChain=${options.isCrossChain}`);
209
+ if (options?.isCrossChain !== void 0)
210
+ params.push(`isCrossChain=${options.isCrossChain}`);
151
211
  if (options?.tokenSymbol) params.push(`tokenSymbol=${options.tokenSymbol}`);
152
212
  return params.length > 0 ? `/rebalance/rebalance-info?${params.join("&")}` : "/rebalance/rebalance-info";
153
213
  },
@@ -156,10 +216,12 @@ var DATA_ENDPOINTS = {
156
216
  // APY Per Strategy
157
217
  APY_PER_STRATEGY: (options = {}) => {
158
218
  const params = [];
159
- if (options.isCrossChain !== void 0) params.push(`isCrossChain=${options.isCrossChain}`);
219
+ if (options.isCrossChain !== void 0)
220
+ params.push(`isCrossChain=${options.isCrossChain}`);
160
221
  if (options.days !== void 0) params.push(`days=${options.days}`);
161
222
  if (options.strategy) params.push(`strategy=${options.strategy}`);
162
- if (options.chainId !== void 0) params.push(`chainId=${options.chainId}`);
223
+ if (options.chainId !== void 0)
224
+ params.push(`chainId=${options.chainId}`);
163
225
  if (options.tokenSymbol) params.push(`tokenSymbol=${options.tokenSymbol}`);
164
226
  return params.length > 0 ? `/rebalance/rebalance-info?${params.join("&")}` : "/rebalance/rebalance-info";
165
227
  }
@@ -172,14 +234,16 @@ var HttpClient = class {
172
234
  *
173
235
  * @param apiKey - API key for both Execution API and Data API
174
236
  */
175
- constructor(apiKey) {
237
+ constructor(apiKey, config = {}) {
176
238
  this.authToken = null;
177
239
  this.apiKey = apiKey;
178
- const parsedUrl = new URL(API_ENDPOINT);
240
+ const executionApiUrl = config.executionApiUrl ?? API_ENDPOINT;
241
+ this.dataApiBaseUrl = config.dataApiUrl ?? DATA_API_ENDPOINT;
242
+ const parsedUrl = new URL(executionApiUrl);
179
243
  this.origin = parsedUrl.origin;
180
244
  this.host = parsedUrl.host;
181
245
  this.client = import_axios.default.create({
182
- baseURL: `${API_ENDPOINT}${API_VERSION}`,
246
+ baseURL: `${executionApiUrl}${API_VERSION}`,
183
247
  headers: {
184
248
  "Content-Type": "application/json",
185
249
  "X-API-Key": this.apiKey
@@ -187,7 +251,7 @@ var HttpClient = class {
187
251
  timeout: 3e4
188
252
  });
189
253
  this.dataClient = import_axios.default.create({
190
- baseURL: `${DATA_API_ENDPOINT}${DATA_API_VERSION}`,
254
+ baseURL: `${this.dataApiBaseUrl}${DATA_API_VERSION}`,
191
255
  headers: {
192
256
  "Content-Type": "application/json",
193
257
  "X-API-Key": this.apiKey
@@ -230,7 +294,9 @@ var HttpClient = class {
230
294
  const data = error.response.data;
231
295
  switch (status) {
232
296
  case 401:
233
- throw new Error("Unauthorized: Invalid API key");
297
+ throw new Error(
298
+ 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."
299
+ );
234
300
  case 403:
235
301
  throw new Error("Forbidden: Access denied");
236
302
  case 404:
@@ -240,7 +306,9 @@ var HttpClient = class {
240
306
  case 429:
241
307
  throw new Error("Rate limit exceeded. Please try again later.");
242
308
  case 500:
243
- throw new Error(data?.message || data?.error || "Internal server error. Please try again later.");
309
+ throw new Error(
310
+ data?.message || data?.error || "Internal server error. Please try again later."
311
+ );
244
312
  default:
245
313
  throw new Error(data.message || "An error occurred");
246
314
  }
@@ -286,7 +354,7 @@ var HttpClient = class {
286
354
  * @param config - Additional axios config
287
355
  */
288
356
  async dataPostCustom(path, data, config) {
289
- const fullUrl = `${DATA_API_ENDPOINT}${path}`;
357
+ const fullUrl = `${this.dataApiBaseUrl}${path}`;
290
358
  const headers = {
291
359
  "Content-Type": "application/json",
292
360
  "X-API-Key": this.apiKey,
@@ -321,7 +389,9 @@ var HttpClient = class {
321
389
  const data = error.response.data;
322
390
  switch (status) {
323
391
  case 401:
324
- throw new Error("Unauthorized: Invalid API key");
392
+ throw new Error(
393
+ 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."
394
+ );
325
395
  case 403:
326
396
  throw new Error("Forbidden: Access denied to data API");
327
397
  case 404:
@@ -943,15 +1013,18 @@ var signSessionKey = async (config, sessions, allPublicClients, signingParams) =
943
1013
  };
944
1014
 
945
1015
  // src/utils/strategy.ts
1016
+ var PUBLIC_STRATEGIES = `"conservative", "aggressive" or "yieldmaxxing"`;
946
1017
  function toInternalStrategy(publicStrategy) {
947
1018
  switch (publicStrategy) {
948
1019
  case "conservative":
949
1020
  return "safe_strategy";
950
1021
  case "aggressive":
951
1022
  return "degen_strategy";
1023
+ case "yieldmaxxing":
1024
+ return "async_strategy";
952
1025
  default:
953
1026
  throw new Error(
954
- `Invalid public strategy: ${publicStrategy}. Must be "conservative" or "aggressive".`
1027
+ `Invalid public strategy: ${publicStrategy}. Must be ${PUBLIC_STRATEGIES}.`
955
1028
  );
956
1029
  }
957
1030
  }
@@ -962,12 +1035,25 @@ function toPublicStrategy(internalStrategy) {
962
1035
  if (internalStrategy === "degen_strategy" || internalStrategy === "degen") {
963
1036
  return "aggressive";
964
1037
  }
1038
+ if (internalStrategy === "async_strategy" || internalStrategy === "async") {
1039
+ return "yieldmaxxing";
1040
+ }
965
1041
  throw new Error(
966
- `Invalid internal strategy: ${internalStrategy}. Must be "safe_strategy" or "degen_strategy".`
1042
+ `Invalid internal strategy: ${internalStrategy}. Must be "safe_strategy", "degen_strategy" or "async_strategy".`
967
1043
  );
968
1044
  }
1045
+ function toPublicStrategyOrUndefined(internalStrategy) {
1046
+ if (!internalStrategy) {
1047
+ return void 0;
1048
+ }
1049
+ try {
1050
+ return toPublicStrategy(internalStrategy);
1051
+ } catch {
1052
+ return void 0;
1053
+ }
1054
+ }
969
1055
  function isValidPublicStrategy(strategy) {
970
- return strategy === "conservative" || strategy === "aggressive";
1056
+ return strategy === "conservative" || strategy === "aggressive" || strategy === "yieldmaxxing";
971
1057
  }
972
1058
  function convertStrategyToPublic(obj) {
973
1059
  if (!obj.strategy) {
@@ -1062,16 +1148,19 @@ var hasAssetOnSelectedChains = (protocol, chains, asset) => {
1062
1148
  (a) => chains.includes(a.chainId) && validSymbols.includes(a.symbol)
1063
1149
  );
1064
1150
  };
1151
+ var ELIGIBLE_PROTOCOL_STRATEGIES = {
1152
+ safe_strategy: ["safe_strategy"],
1153
+ degen_strategy: ["safe_strategy", "degen_strategy"],
1154
+ async_strategy: ["safe_strategy", "degen_strategy", "async_strategy"]
1155
+ };
1065
1156
  var getMatchingProtocolIds = (protocols, internalStrategy, chains, asset) => {
1066
1157
  if (chains.length === 0) return [];
1158
+ const eligible = ELIGIBLE_PROTOCOL_STRATEGIES[internalStrategy] ?? ELIGIBLE_PROTOCOL_STRATEGIES.safe_strategy;
1067
1159
  return protocols.filter((protocol) => {
1068
1160
  if (!protocol || !protocol.strategies) return false;
1069
1161
  if (!protocol.chains?.some((c) => chains.includes(c))) return false;
1070
1162
  if (!hasAssetOnSelectedChains(protocol, chains, asset)) return false;
1071
- if (internalStrategy === "degen_strategy") {
1072
- return protocol.strategies.includes("degen_strategy") || protocol.strategies.includes("safe_strategy");
1073
- }
1074
- return protocol.strategies.includes("safe_strategy");
1163
+ return protocol.strategies.some((s) => eligible.includes(s));
1075
1164
  }).map((protocol) => protocol.id);
1076
1165
  };
1077
1166
  var hasMatchingPool = (data, chains, asset) => {
@@ -1450,11 +1539,21 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1450
1539
  this.currentProvider = null;
1451
1540
  this.currentChainId = null;
1452
1541
  const sdkConfig = typeof config === "string" ? { apiKey: config } : config;
1453
- const { apiKey, rpcUrls, referralSource } = sdkConfig;
1542
+ const {
1543
+ apiKey,
1544
+ rpcUrls,
1545
+ referralSource,
1546
+ executionApiUrl,
1547
+ dataApiUrl
1548
+ } = sdkConfig;
1454
1549
  if (!apiKey) {
1455
1550
  throw new Error("API key is required");
1456
1551
  }
1457
- this.httpClient = new HttpClient(apiKey);
1552
+ this.executionApiUrl = executionApiUrl ?? API_ENDPOINT;
1553
+ this.httpClient = new HttpClient(apiKey, {
1554
+ executionApiUrl: this.executionApiUrl,
1555
+ dataApiUrl
1556
+ });
1458
1557
  this.rpcUrls = rpcUrls;
1459
1558
  this.referralSource = referralSource;
1460
1559
  }
@@ -1491,8 +1590,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1491
1590
  uri = globalWindow.location.origin;
1492
1591
  domain = globalWindow.location.host;
1493
1592
  } else {
1494
- uri = API_ENDPOINT;
1495
- domain = API_ENDPOINT.split("//")[1];
1593
+ uri = this.executionApiUrl;
1594
+ domain = new URL(this.executionApiUrl).host;
1496
1595
  }
1497
1596
  const messageObj = new import_siwe.SiweMessage({
1498
1597
  address: userAddress,
@@ -1562,12 +1661,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1562
1661
  if (request.strategy) {
1563
1662
  if (!isValidPublicStrategy(request.strategy)) {
1564
1663
  throw new Error(
1565
- `Invalid strategy: ${request.strategy}. Must be "conservative" or "aggressive".`
1664
+ `Invalid strategy: ${request.strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
1566
1665
  );
1567
1666
  }
1568
- rebalanceStrategy = toInternalStrategy(
1569
- request.strategy
1570
- );
1667
+ rebalanceStrategy = toInternalStrategy(request.strategy);
1571
1668
  }
1572
1669
  const assetSettings = {};
1573
1670
  if (rebalanceStrategy !== void 0) assetSettings.rebalanceStrategy = rebalanceStrategy;
@@ -1661,9 +1758,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1661
1758
  const allProtocols = await this.httpClient.get(
1662
1759
  ENDPOINTS.PROTOCOLS()
1663
1760
  );
1664
- const usdcStrategy = userDetailsUSDC.strategy || "safe_strategy";
1665
- const ethStrategy = userDetailsETH.strategy || "safe_strategy";
1666
- const eurcStrategy = userDetailsEURC.strategy || "safe_strategy";
1761
+ const internalStrategyOf = (strategy) => isValidPublicStrategy(strategy ?? "") ? toInternalStrategy(strategy) : "safe_strategy";
1762
+ const usdcStrategy = internalStrategyOf(userDetailsUSDC.strategy);
1763
+ const ethStrategy = internalStrategyOf(userDetailsETH.strategy);
1764
+ const eurcStrategy = internalStrategyOf(userDetailsEURC.strategy);
1667
1765
  const filterProtocolsByStrategy = (strategy, selectedChains) => {
1668
1766
  return allProtocols.filter((protocol) => {
1669
1767
  const hasMatchingChain = protocol.chains.some(
@@ -1672,6 +1770,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1672
1770
  if (!hasMatchingChain) {
1673
1771
  return false;
1674
1772
  }
1773
+ if (strategy === "async_strategy") {
1774
+ return protocol.strategies?.includes("safe_strategy") || protocol.strategies?.includes("degen_strategy") || protocol.strategies?.includes("async_strategy");
1775
+ }
1675
1776
  if (strategy === "degen_strategy") {
1676
1777
  return protocol.strategies?.includes("safe_strategy") || protocol.strategies?.includes("degen_strategy");
1677
1778
  }
@@ -2091,7 +2192,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2091
2192
  *
2092
2193
  * @param userAddress - User's EOA address (the connected EOA, not the smart wallet address)
2093
2194
  * @param chainId - Target chain ID
2094
- * @param strategy - Optional strategy selection: "conservative" (default) or "aggressive"
2195
+ * @param strategy - Optional strategy selection: "conservative" (default), "aggressive" or "yieldmaxxing"
2095
2196
  * @param createSessionKey - If true, automatically creates a session key after deployment (default: false)
2096
2197
  * @returns Deployment response with Safe address and transaction hash
2097
2198
  *
@@ -2437,27 +2538,30 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2437
2538
  const withPools = await this.filterProtocolIdsWithPools(
2438
2539
  matching,
2439
2540
  effectiveChains,
2440
- asset
2541
+ asset,
2542
+ internalStrategy
2441
2543
  );
2442
2544
  await this.updateUserProfile({
2443
2545
  asset,
2444
2546
  protocols: withPools,
2445
- chains: effectiveChains
2547
+ chains: effectiveChains,
2548
+ ...strategy !== void 0 && { strategy }
2446
2549
  });
2447
2550
  }
2448
2551
  /**
2449
2552
  * Drop protocols that have no pools on any of the selected chains for the
2450
- * requested asset. Uses the /customization/pools endpoint with
2451
- * `degen_strategy` as the master strategy so the response includes both
2452
- * safe and degen pools — mirrors the front-end behavior.
2553
+ * requested asset. The /customization/pools endpoint filters server-side on
2554
+ * the strategy, and each tier is a superset of the previous one, so the
2555
+ * caller's strategy must be passed through — asking for `degen_strategy`
2556
+ * returns an empty pool set for async-only assets.
2453
2557
  * @internal
2454
2558
  */
2455
- async filterProtocolIdsWithPools(protocolIds, chains, asset) {
2559
+ async filterProtocolIdsWithPools(protocolIds, chains, asset, internalStrategy = "degen_strategy") {
2456
2560
  if (protocolIds.length === 0) return [];
2457
2561
  const results = await Promise.allSettled(
2458
2562
  protocolIds.map(async (id) => {
2459
2563
  const poolsData = await this.httpClient.get(
2460
- ENDPOINTS.CUSTOMIZATION_POOLS(id, "degen_strategy")
2564
+ ENDPOINTS.CUSTOMIZATION_POOLS(id, internalStrategy)
2461
2565
  );
2462
2566
  return { id, hasPool: hasMatchingPool(poolsData, chains, asset) };
2463
2567
  })
@@ -2510,7 +2614,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2510
2614
  * protocol selection for USDC, WETH, and EURC across all supported chains
2511
2615
  * (EURC on Mainnet/Base only) before the transfer and log_deposit.
2512
2616
  * Pass `strategy` to select protocols for that first-deposit setup
2513
- * (same role as the former `deploySafe` strategy argument).
2617
+ * (same role as the former `deploySafe` strategy argument). On every later
2618
+ * deposit the argument is ignored without error, since re-running the patch
2619
+ * would overwrite a protocol selection the user may have customised. To
2620
+ * change the strategy of an existing account, call
2621
+ * `updateUserProfile({ asset, strategy })`.
2514
2622
  *
2515
2623
  * Minimum portfolio balance enforced (Safe balance + deposit amount):
2516
2624
  * - Stablecoins: `MIN_PORTFOLIO_BALANCE` (Mainnet 10,000 USDC/EURC; Base/Arbitrum 100)
@@ -2522,7 +2630,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2522
2630
  * @param asset - Asset symbol: "USDC", "WETH", or "EURC".
2523
2631
  * EURC is supported on Ethereum Mainnet and Base only.
2524
2632
  * @param strategy - Optional strategy for first-deposit protocol patching:
2525
- * "conservative" (default) or "aggressive"
2633
+ * "conservative" (default), "aggressive" or "yieldmaxxing". Ignored on
2634
+ * later deposits — use `updateUserProfile` to change an existing account.
2526
2635
  * @returns Deposit response with transaction hash
2527
2636
  *
2528
2637
  * @example
@@ -2537,6 +2646,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2537
2646
  *
2538
2647
  * // First deposit with aggressive strategy
2539
2648
  * await sdk.depositFunds(userAddress, 8453, "10000000000", "USDC", "aggressive");
2649
+ *
2650
+ * // Changing the strategy of an account that has already deposited
2651
+ * await sdk.updateUserProfile({ asset: "USDC", strategy: "yieldmaxxing" });
2540
2652
  * ```
2541
2653
  */
2542
2654
  /**
@@ -2581,7 +2693,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2581
2693
  }
2582
2694
  if (strategy !== void 0 && !isValidPublicStrategy(strategy)) {
2583
2695
  throw new Error(
2584
- `Invalid strategy: ${strategy}. Must be "conservative" or "aggressive".`
2696
+ `Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
2585
2697
  );
2586
2698
  }
2587
2699
  const assetSymbol = asset.toUpperCase();
@@ -2603,6 +2715,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2603
2715
  }
2604
2716
  const token = getDefaultTokenAddress(chainId, assetSymbol);
2605
2717
  const walletClient = this.getWalletClient();
2718
+ await this.authenticateUser();
2606
2719
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
2607
2720
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
2608
2721
  if (!safeAddress) {
@@ -2661,19 +2774,16 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2661
2774
  const receipt = await chainConfig.publicClient.waitForTransactionReceipt({
2662
2775
  hash: txHash
2663
2776
  });
2664
- try {
2665
- await this.httpClient.post(ENDPOINTS.LOG_DEPOSIT, {
2666
- chainId,
2667
- transaction: txHash,
2668
- token,
2669
- amount
2670
- });
2671
- } catch (logError) {
2672
- console.warn("Failed to log deposit:", logError.message);
2673
- }
2674
2777
  if (receipt.status !== "success") {
2675
2778
  throw new Error("Deposit transaction failed");
2676
2779
  }
2780
+ try {
2781
+ await this.logDeposit(chainId, txHash, amount, token);
2782
+ } catch (logError) {
2783
+ throw new Error(
2784
+ `On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}") to retry.`
2785
+ );
2786
+ }
2677
2787
  return {
2678
2788
  success: true,
2679
2789
  txHash,
@@ -2693,6 +2803,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2693
2803
  * wallet stays reserved (no ownership rotation), and yield/agent tracking does
2694
2804
  * not start.
2695
2805
  *
2806
+ * Requires `connectAccount()` on the same SDK instance first (SIWE user JWT).
2807
+ * The SDK API key alone is not enough — `log_deposit` returns 401 without a
2808
+ * Bearer token.
2809
+ *
2696
2810
  * Use this method when you execute the deposit transaction yourself and need to
2697
2811
  * register it with the Zyfai backend.
2698
2812
  *
@@ -2739,6 +2853,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2739
2853
  throw new Error("Valid amount is required");
2740
2854
  }
2741
2855
  const token = tokenAddress || getDefaultTokenAddress(chainId);
2856
+ await this.authenticateUser();
2742
2857
  await this.httpClient.post(ENDPOINTS.LOG_DEPOSIT, {
2743
2858
  chainId,
2744
2859
  transaction: txHash,
@@ -2759,6 +2874,25 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2759
2874
  * Note: The withdrawal is processed asynchronously, so txHash may not be immediately available
2760
2875
  * Funds are always withdrawn to the Safe owner's address (userAddress)
2761
2876
  *
2877
+ * **Delayed withdrawals.** Positions held under the `"yieldmaxxing"`
2878
+ * strategy sit in protocols that cannot be exited on demand. For those the
2879
+ * backend transfers the immediately available portion, then queues a
2880
+ * redemption for the rest and forwards the funds to the EOA once the
2881
+ * protocol releases them — about a day on Ipor, three on Superform. No
2882
+ * further call is needed, but the returned `txHash` only covers the
2883
+ * immediate portion. Track the remainder through
2884
+ * `getPortfolio().portfolio.pendingAsyncWithdrawals`, whose entries carry a
2885
+ * `status` and an `estimatedClaimAt`.
2886
+ *
2887
+ * When every source is an async pool nothing settles on-chain at that point,
2888
+ * so `txHash` is `undefined` on a successful call.
2889
+ *
2890
+ * Once requested, that amount can no longer be withdrawn: it is gone from
2891
+ * both the position snapshot and the Safe balance, so a second call silently
2892
+ * returns only what is left. Validate user-entered amounts against
2893
+ * `portfolioByAssetType`, not against the total that includes in-flight
2894
+ * funds — see `getPortfolio`.
2895
+ *
2762
2896
  * @param userAddress - User's address (owner of the Safe)
2763
2897
  * @param chainId - Target chain ID
2764
2898
  * @param amount - Optional: Amount in least decimal units to withdraw (partial withdrawal). If not specified, withdraws all funds
@@ -2923,6 +3057,29 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2923
3057
  * Note: portfolio balances are live; earnings used for the fee may be from
2924
3058
  * a snapshot, so net values can differ slightly from a fully live calc.
2925
3059
  *
3060
+ * **Total balance.** `portfolioByAssetType` sums deployed positions and idle
3061
+ * Safe balances, and nothing else. Under the `"yieldmaxxing"` strategy a
3062
+ * redemption in flight has already left its position and has not landed in
3063
+ * the Safe yet, so its funds appear in no balance field at all. That makes
3064
+ * two distinct numbers:
3065
+ *
3066
+ * ```
3067
+ * total = portfolioByAssetType[assetType].balance
3068
+ * + sum(pendingAsyncWithdrawals where REQUESTED or CLAIMABLE)
3069
+ *
3070
+ * requestable = portfolioByAssetType[assetType].balance
3071
+ * ```
3072
+ *
3073
+ * An in-flight amount is no longer withdrawable: `withdrawFunds` only reaches
3074
+ * the current positions and idle balances, so calling it again neither speeds
3075
+ * those funds up nor errors. They reach the EOA on their own. Cap any
3076
+ * user-entered withdrawal amount at `requestable`, never at `total`.
3077
+ *
3078
+ * Do not add `staleBalances` on top — those are the same idle balances
3079
+ * `portfolioByAssetType` already counts, exposed as a per-chain view.
3080
+ * Do not add `CLAIMED` withdrawals either (the array keeps them for 24
3081
+ * hours); their funds are back in the Safe and already counted.
3082
+ *
2926
3083
  * @param userAddress - User's EOA address
2927
3084
  * @returns Portfolio with optional fee-adjusted balance fields
2928
3085
  *
@@ -2930,6 +3087,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2930
3087
  * ```typescript
2931
3088
  * const { portfolio } = await sdk.getPortfolio(userAddress);
2932
3089
  * console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
3090
+ *
3091
+ * // Funds still locked in an async redemption
3092
+ * const inFlight = (portfolio.pendingAsyncWithdrawals ?? []).filter(
3093
+ * (w) => w.status === "REQUESTED" || w.status === "CLAIMABLE"
3094
+ * );
2933
3095
  * ```
2934
3096
  */
2935
3097
  async getPortfolio(userAddress) {
@@ -3003,7 +3165,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3003
3165
  omniAccount: convertedResponse.omniAccount,
3004
3166
  asset,
3005
3167
  autoSelectProtocols: convertedResponse.assetTypeSettings?.[internalAsset]?.autoSelectProtocols,
3006
- strategy: convertedResponse.assetTypeSettings?.[internalAsset]?.rebalanceStrategy,
3168
+ // `convertStrategyToPublic` only touches the root `strategy` field;
3169
+ // the per-asset one is nested and has to be converted here.
3170
+ strategy: toPublicStrategyOrUndefined(
3171
+ convertedResponse.assetTypeSettings?.[internalAsset]?.rebalanceStrategy
3172
+ ),
3007
3173
  autocompounding: convertedResponse.assetTypeSettings?.[internalAsset]?.autocompounding,
3008
3174
  crosschainStrategy: convertedResponse.assetTypeSettings?.[internalAsset]?.crosschainStrategy,
3009
3175
  splitting: convertedResponse.assetTypeSettings?.[internalAsset]?.splitting,
@@ -3050,7 +3216,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3050
3216
  *
3051
3217
  * @param crossChain - Whether to get cross-chain APY (true = omni account, false = simple account)
3052
3218
  * @param days - Time period: 7, 14, or 30
3053
- * @param strategy - Strategy type: "conservative" (default) or "aggressive"
3219
+ * @param strategy - Strategy type: "conservative" (default), "aggressive" or "yieldmaxxing"
3054
3220
  * @param chainId - Optional chain ID filter
3055
3221
  * @param tokenSymbol - Optional token symbol filter (e.g. "USDC", "WETH", "WBTC")
3056
3222
  * @returns APY per strategy for a specific chain
@@ -3517,6 +3683,53 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3517
3683
  );
3518
3684
  }
3519
3685
  }
3686
+ /**
3687
+ * Get yieldmaxxing opportunities — pools reachable only with the
3688
+ * `"yieldmaxxing"` strategy, including protocols whose withdrawals are
3689
+ * asynchronous (Ipor, Superform). Exiting these pools takes about a day
3690
+ * on Ipor and three on Superform; track the redemption through
3691
+ * `getPortfolio().portfolio.pendingAsyncWithdrawals`.
3692
+ *
3693
+ * @param chainId - Optional chain ID filter
3694
+ * @param asset - Optional asset filter (e.g. "USDC", "WETH")
3695
+ * @returns List of yieldmaxxing opportunities
3696
+ *
3697
+ * @example
3698
+ * ```typescript
3699
+ * const opportunities = await sdk.getAsyncOpportunities(8453);
3700
+ * opportunities.data.forEach(o => console.log(o.protocolName, o.apy));
3701
+ * ```
3702
+ */
3703
+ async getAsyncOpportunities(chainId, asset, status) {
3704
+ try {
3705
+ const response = await this.httpClient.dataGet(
3706
+ DATA_ENDPOINTS.OPPORTUNITIES_ASYNC(chainId, asset, status)
3707
+ );
3708
+ const data = response.data || response || [];
3709
+ return {
3710
+ success: true,
3711
+ chainId,
3712
+ strategyType: "yieldmaxxing",
3713
+ data: Array.isArray(data) ? data.map((o) => ({
3714
+ id: o.id,
3715
+ protocolId: o.protocol_id || o.protocolId,
3716
+ protocolName: o.protocol_name || o.protocolName,
3717
+ poolName: o.pool_name || o.poolName,
3718
+ chainId: o.chain_id || o.chainId,
3719
+ apy: o.combined_apy || 0,
3720
+ tvl: o.tvl || o.zyfiTvl,
3721
+ asset: o.asset || o.underlying_token,
3722
+ risk: o.risk,
3723
+ strategyType: "yieldmaxxing",
3724
+ status: o.status
3725
+ })) : []
3726
+ };
3727
+ } catch (error) {
3728
+ throw new Error(
3729
+ `Failed to get yieldmaxxing opportunities: ${error.message}`
3730
+ );
3731
+ }
3732
+ }
3520
3733
  /**
3521
3734
  * Get active conservative opportunities (status = "live") with risk and utilization data
3522
3735
  * Returns pool info, liquidity depth (true if > 1M), utilization rate, stability metrics, avg APY, and collateral
@@ -3893,7 +4106,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3893
4106
  * Returns the list of pools available for a given protocol, optionally filtered by strategy.
3894
4107
  *
3895
4108
  * @param protocolId - The protocol UUID
3896
- * @param strategy - Optional strategy filter ("conservative" or "aggressive")
4109
+ * @param strategy - Optional strategy filter ("conservative", "aggressive" or "yieldmaxxing")
3897
4110
  * @returns List of available pool names
3898
4111
  *
3899
4112
  * @example
@@ -3915,7 +4128,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3915
4128
  if (strategy) {
3916
4129
  if (!isValidPublicStrategy(strategy)) {
3917
4130
  throw new Error(
3918
- `Invalid strategy: ${strategy}. Must be "conservative" or "aggressive".`
4131
+ `Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
3919
4132
  );
3920
4133
  }
3921
4134
  internalStrategy = toInternalStrategy(strategy);
@@ -3961,7 +4174,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3961
4174
  try {
3962
4175
  if (!isValidPublicStrategy(params.strategy)) {
3963
4176
  throw new Error(
3964
- `Invalid strategy: ${params.strategy}. Must be "conservative" or "aggressive".`
4177
+ `Invalid strategy: ${params.strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
3965
4178
  );
3966
4179
  }
3967
4180
  const internalStrategy = toInternalStrategy(params.strategy);
@@ -4670,21 +4883,36 @@ function createBankrProvider(config) {
4670
4883
  // Annotate the CommonJS export names for ESM import in node:
4671
4884
  0 && (module.exports = {
4672
4885
  ALLOWED_HISTORY_DAYS,
4886
+ API_ENDPOINT,
4887
+ DATA_API_BASE_URLS,
4888
+ DATA_API_ENDPOINT,
4673
4889
  DEFAULT_TOKEN_ADDRESSES,
4674
4890
  ERC7579_LAUNCHPAD_ADDRESS,
4891
+ EXECUTION_API_BASE_URLS,
4675
4892
  INTENT_EXECUTOR,
4676
4893
  INTENT_SMART_SESSIONS,
4894
+ LOCAL_DATA_API_BASE_URL,
4895
+ LOCAL_EXECUTION_API_BASE_URL,
4896
+ LOCAL_WS_URL,
4677
4897
  OWNABLE_VALIDATOR,
4678
4898
  POOL_MODULE_ADDRESSES,
4679
4899
  PROXY_EXECUTOR,
4680
4900
  SAFE_7579_ADDRESS,
4681
4901
  SMART_SESSIONS_FALLBACK,
4682
4902
  SMART_SESSIONS_VALIDATOR,
4903
+ STAGING_DATA_API_BASE_URL,
4904
+ STAGING_EXECUTION_API_BASE_URL,
4905
+ STAGING_WS_URL,
4683
4906
  VAULT_ADDRESS,
4907
+ WS_ENDPOINT,
4908
+ WS_URLS,
4684
4909
  ZyfaiSDK,
4685
4910
  createBankrProvider,
4686
4911
  getChainConfig,
4912
+ getDataApiBaseUrl,
4687
4913
  getDefaultTokenAddress,
4914
+ getExecutionApiBaseUrl,
4688
4915
  getSupportedChainIds,
4916
+ getWsUrl,
4689
4917
  isSupportedChain
4690
4918
  });