@zyfai/sdk 0.2.57 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -112,9 +112,13 @@ var ENDPOINTS = {
112
112
  AUTH_CHALLENGE: "/auth/challenge",
113
113
  // User
114
114
  USER_ME: "/users/me",
115
+ USER_AGENT_MANDATE: "/users/me/agent-mandate",
116
+ USER_AGENT_ENTER_INTENTS: "/users/me/agent-enter-intents",
117
+ USER_AGENT_ENTER_INTENT_CONSUME: (actionId) => `/users/me/agent-enter-intents/${encodeURIComponent(actionId)}/consume`,
115
118
  USER_WITHDRAW: "/users/withdraw",
116
119
  PARTIAL_WITHDRAW: "/users/partial-withdraw",
117
- LOG_DEPOSIT: "/users/log_deposit",
120
+ LOG_DEPOSIT: "/users/log_deposit/v2",
121
+ DEPOSIT_STATUS: (depositId) => `/users/deposits/${depositId}`,
118
122
  // Safe Deployment (single endpoint)
119
123
  SAFE_DEPLOY: "/users/safe-deploy",
120
124
  // Multichain deploy for predeployed (pool) wallets — deploys + rotates the
@@ -236,6 +240,8 @@ var HttpClient = class {
236
240
  */
237
241
  constructor(apiKey, config = {}) {
238
242
  this.authToken = null;
243
+ /** @internal Extra headers on execution API requests (e.g. MCP server channel key). */
244
+ this.extraExecutionHeaders = {};
239
245
  this.apiKey = apiKey;
240
246
  const executionApiUrl = config.executionApiUrl ?? API_ENDPOINT;
241
247
  this.dataApiBaseUrl = config.dataApiUrl ?? DATA_API_ENDPOINT;
@@ -264,9 +270,17 @@ var HttpClient = class {
264
270
  setAuthToken(token) {
265
271
  this.authToken = token;
266
272
  }
273
+ /** @internal */
274
+ setExtraExecutionHeaders(headers) {
275
+ this.extraExecutionHeaders = headers;
276
+ }
267
277
  clearAuthToken() {
268
278
  this.authToken = null;
269
279
  }
280
+ /** Whether a user Bearer token is set on this client instance. */
281
+ hasAuthToken() {
282
+ return this.authToken !== null;
283
+ }
270
284
  getOrigin() {
271
285
  return this.origin;
272
286
  }
@@ -280,6 +294,9 @@ var HttpClient = class {
280
294
  if (this.authToken) {
281
295
  config.headers["Authorization"] = `Bearer ${this.authToken}`;
282
296
  }
297
+ for (const [key, value] of Object.entries(this.extraExecutionHeaders)) {
298
+ config.headers[key] = value;
299
+ }
283
300
  return config;
284
301
  },
285
302
  (error) => {
@@ -332,6 +349,10 @@ var HttpClient = class {
332
349
  const response = await this.client.patch(url, data, config);
333
350
  return response.data;
334
351
  }
352
+ async put(url, data, config) {
353
+ const response = await this.client.put(url, data, config);
354
+ return response.data;
355
+ }
335
356
  async delete(url, config) {
336
357
  const response = await this.client.delete(url, config);
337
358
  return response.data;
@@ -419,26 +440,30 @@ var HttpClient = class {
419
440
  }
420
441
  };
421
442
 
422
- // src/utils/eth-price.ts
443
+ // src/utils/poll.ts
444
+ function sleep(ms) {
445
+ return new Promise((resolve) => setTimeout(resolve, ms));
446
+ }
447
+
448
+ // src/utils/token-price.ts
423
449
  var PRICE_SCALE = 8;
424
- var parseEthUsdPrice = (response) => {
450
+ var parseTokenUsdPrice = (response) => {
425
451
  const priceUsd = response?.data?.price_usd;
426
452
  if (typeof priceUsd !== "number" || !Number.isFinite(priceUsd) || priceUsd <= 0) {
427
- throw new Error("ETH/USD price must be a positive number");
453
+ throw new Error("Token USD price must be a positive number");
428
454
  }
429
455
  return priceUsd;
430
456
  };
431
- var usdToWethWei = (usdAmount, ethUsd) => {
432
- if (!Number.isFinite(ethUsd) || ethUsd <= 0) {
433
- throw new Error("ETH/USD price must be positive");
457
+ var usdToTokenUnits = (usdAmount, priceUsd, decimals) => {
458
+ if (!Number.isFinite(priceUsd) || priceUsd <= 0) {
459
+ throw new Error("Token USD price must be positive");
434
460
  }
435
- const scaledPrice = BigInt(Math.round(ethUsd * 10 ** PRICE_SCALE));
461
+ const scaledPrice = BigInt(Math.round(priceUsd * 10 ** PRICE_SCALE));
436
462
  if (scaledPrice <= 0n) {
437
- throw new Error("ETH/USD price must be positive");
463
+ throw new Error("Token USD price must be positive");
438
464
  }
439
- return usdAmount * 10n ** 18n * 10n ** BigInt(PRICE_SCALE) / scaledPrice;
465
+ return usdAmount * 10n ** BigInt(decimals) * 10n ** BigInt(PRICE_SCALE) / scaledPrice;
440
466
  };
441
- var minWethWeiForUsd = (ethUsd, usdAmount) => usdToWethWei(usdAmount, ethUsd);
442
467
 
443
468
  // src/config/abis.ts
444
469
  var import_viem = require("viem");
@@ -631,11 +656,26 @@ var MIN_PORTFOLIO_BALANCE = {
631
656
  // 100 EURC (6 decimals)
632
657
  }
633
658
  };
634
- var MIN_WETH_USD = {
635
- 1: 10000n,
636
- 8453: 100n,
637
- 42161: 100n
659
+ var MIN_PORTFOLIO_USD = {
660
+ 1: { WETH: 10000n },
661
+ 8453: { WETH: 100n, NVDAc: 100n },
662
+ 42161: { WETH: 100n }
663
+ };
664
+ var DEPOSIT_CREDIT_INTERVAL_MS = {
665
+ 1: 2e3,
666
+ 8453: 500,
667
+ 42161: 250
638
668
  };
669
+ var DEPOSIT_CREDIT_TIMEOUT_MS = {
670
+ 1: 6e4,
671
+ // 1 minute
672
+ 8453: 2e4,
673
+ // ~10 Base blocks
674
+ 42161: 2e4
675
+ // ~10 Arbitrum blocks
676
+ };
677
+ var getDepositCreditIntervalMs = (chainId) => DEPOSIT_CREDIT_INTERVAL_MS[chainId];
678
+ var getDepositCreditTimeoutMs = (chainId) => DEPOSIT_CREDIT_TIMEOUT_MS[chainId];
639
679
  var formatMinPortfolioLabel = (raw, decimals, symbol) => {
640
680
  const base2 = 10n ** BigInt(decimals);
641
681
  const whole = raw / base2;
@@ -647,6 +687,36 @@ var formatMinPortfolioLabel = (raw, decimals, symbol) => {
647
687
  return `${whole.toString()}.${fractionStr} ${symbol}`;
648
688
  };
649
689
 
690
+ // src/config/local-dev.ts
691
+ function isLocalExecutionApiUrl(executionApiUrl) {
692
+ if (executionApiUrl === EXECUTION_API_BASE_URLS.local) {
693
+ return true;
694
+ }
695
+ try {
696
+ const { hostname } = new URL(executionApiUrl);
697
+ return hostname === "localhost" || hostname === "127.0.0.1";
698
+ } catch {
699
+ return false;
700
+ }
701
+ }
702
+ function isStagingExecutionApiUrl(executionApiUrl) {
703
+ if (executionApiUrl === EXECUTION_API_BASE_URLS.staging) {
704
+ return true;
705
+ }
706
+ try {
707
+ const { hostname } = new URL(executionApiUrl);
708
+ return hostname === "staging-api.zyf.ai";
709
+ } catch {
710
+ return false;
711
+ }
712
+ }
713
+ function shouldBypassMinPortfolioCheck(executionApiUrl) {
714
+ if (process.env.NODE_ENV === "production") {
715
+ return false;
716
+ }
717
+ return isLocalExecutionApiUrl(executionApiUrl) || isStagingExecutionApiUrl(executionApiUrl);
718
+ }
719
+
650
720
  // src/core/ZyfaiSDK.ts
651
721
  var import_accounts2 = require("viem/accounts");
652
722
  var import_viem4 = require("viem");
@@ -697,6 +767,8 @@ var ASSET_CONFIGS = {
697
767
  displayName: "WETH",
698
768
  icon: "/ai-dashboard/eth-token.png",
699
769
  decimals: 18,
770
+ // Data API `/price?token=` identifier, used for USD-denominated minimums.
771
+ priceTokenSymbol: "eth",
700
772
  tokenSymbols: ["WETH", "ETH"],
701
773
  tokenSymbolsByChainId: {
702
774
  1: "WETH",
@@ -737,8 +809,39 @@ var ASSET_CONFIGS = {
737
809
  // Base
738
810
  },
739
811
  enabled: true
812
+ },
813
+ // Coinbase B20 tokenized NVIDIA equity. Base only, and only reachable through
814
+ // protocols with delayed withdrawals — see the `yieldmaxxing` strategy.
815
+ NVDAc: {
816
+ symbol: "NVDAc",
817
+ assetType: "nvdac",
818
+ displayName: "NVIDIA",
819
+ icon: "https://metadata.coinbase.com/equity_icons/1fee9b7a44e800d438dd9d96c3283e05784c925c2c871a48ff735950740b551a.png",
820
+ decimals: 8,
821
+ priceTokenSymbol: "nvdac",
822
+ tokenSymbols: ["NVDAc"],
823
+ tokenSymbolsByChainId: {
824
+ 8453: "NVDAc"
825
+ },
826
+ addresses: {
827
+ 8453: "0xb20000000000000000000078ee7ce2fE4908108C"
828
+ // Base
829
+ },
830
+ enabled: true
831
+ }
832
+ };
833
+ var resolveAssetSymbol = (asset) => {
834
+ const match = Object.keys(ASSET_CONFIGS).find(
835
+ (key) => key.toLowerCase() === asset.toLowerCase()
836
+ );
837
+ if (!match) {
838
+ throw new Error(
839
+ `Unsupported asset: ${asset}. Supported: ${Object.keys(ASSET_CONFIGS).join(", ")}.`
840
+ );
740
841
  }
842
+ return match;
741
843
  };
844
+ var getAssetChainIds = (asset) => Object.keys(ASSET_CONFIGS[asset]?.addresses ?? {}).map(Number).filter((chainId) => chainId in CHAINS);
742
845
  var getDefaultTokenAddress = (chainId, asset) => {
743
846
  const address = ASSET_CONFIGS[asset || "USDC"]?.addresses[chainId];
744
847
  if (!address || address === "0x0000000000000000000000000000000000000000") {
@@ -1014,6 +1117,7 @@ var signSessionKey = async (config, sessions, allPublicClients, signingParams) =
1014
1117
 
1015
1118
  // src/utils/strategy.ts
1016
1119
  var PUBLIC_STRATEGIES = `"conservative", "aggressive" or "yieldmaxxing"`;
1120
+ var SUPPORTED_ASSETS = `"USDC", "WETH", "EURC" or "NVDAc"`;
1017
1121
  function toInternalStrategy(publicStrategy) {
1018
1122
  switch (publicStrategy) {
1019
1123
  case "conservative":
@@ -1102,8 +1206,11 @@ function convertAssetInternally(asset) {
1102
1206
  if (asset === "EURC") {
1103
1207
  return "eurc";
1104
1208
  }
1209
+ if (asset === "NVDAc") {
1210
+ return "nvdac";
1211
+ }
1105
1212
  throw new Error(
1106
- `Invalid asset: ${asset}. Must be "USDC", "WETH", or "EURC".`
1213
+ `Invalid asset: ${asset}. Must be ${SUPPORTED_ASSETS}.`
1107
1214
  );
1108
1215
  }
1109
1216
  function convertStrategiesToPublic(array) {
@@ -1491,7 +1598,7 @@ function enrichOnchainEarningsTotals(apiData) {
1491
1598
  const unrealized = unrealizedByToken[symbol] ?? 0;
1492
1599
  const current = currentByToken[symbol] ?? 0;
1493
1600
  totalEarningsByTokenWithFee[symbol] = formatHumanAmount(
1494
- lifetime + unrealized + current * keepRate
1601
+ (lifetime + unrealized + current) * keepRate
1495
1602
  );
1496
1603
  });
1497
1604
  const chainKeys = /* @__PURE__ */ new Set([
@@ -1515,7 +1622,7 @@ function enrichOnchainEarningsTotals(apiData) {
1515
1622
  const unrealized = parseHumanAmount(unrealizedTokens[symbol]);
1516
1623
  const current = parseHumanAmount(currentTokens[symbol]);
1517
1624
  chainMap[symbol] = formatHumanAmount(
1518
- lifetime + unrealized + current * keepRate
1625
+ (lifetime + unrealized + current) * keepRate
1519
1626
  );
1520
1627
  });
1521
1628
  totalEarningsByChainWithFee[chainId] = chainMap;
@@ -1526,9 +1633,51 @@ function enrichOnchainEarningsTotals(apiData) {
1526
1633
  };
1527
1634
  }
1528
1635
 
1636
+ // src/utils/async-withdrawals.ts
1637
+ var findBlockingAsyncRedemption = (portfolio, chainId, tokenSymbol) => {
1638
+ const matchesToken = (symbol) => !tokenSymbol || symbol?.toLowerCase() === tokenSymbol.toLowerCase();
1639
+ const blocked = (portfolio.pendingAsyncWithdrawals ?? []).filter(
1640
+ (w) => w.chainId === chainId && (w.status === "REQUESTED" || w.status === "CLAIMABLE") && matchesToken(w.token?.symbol)
1641
+ );
1642
+ if (blocked.length === 0) return void 0;
1643
+ const blockedPools = new Set(
1644
+ blocked.map((w) => w.pool?.toLowerCase()).filter(Boolean)
1645
+ );
1646
+ const hasFreePosition = (portfolio.positions ?? []).some(
1647
+ (p) => matchesToken(p.token_symbol) && Number(chainNameToId(p.chain ?? "")) === chainId && !blockedPools.has(p.pool?.toLowerCase() ?? "")
1648
+ );
1649
+ const hasIdleBalance = (portfolio.staleBalances ?? []).some(
1650
+ (b) => b.chainId === chainId && matchesToken(b.tokenSymbol) && BigInt(b.balance ?? "0") > 0n
1651
+ );
1652
+ return hasFreePosition || hasIdleBalance ? void 0 : blocked[0];
1653
+ };
1654
+
1529
1655
  // src/core/ZyfaiSDK.ts
1530
1656
  var import_siwe = require("siwe");
1657
+ var DepositCreditTimeoutError = class extends Error {
1658
+ constructor(depositId) {
1659
+ super(`Timed out waiting for deposit ${depositId} to be credited`);
1660
+ this.name = "DepositCreditTimeoutError";
1661
+ }
1662
+ };
1663
+ var MANAGED_ASSETS = ["USDC", "WETH", "EURC", "NVDAc"];
1531
1664
  var _ZyfaiSDK = class _ZyfaiSDK {
1665
+ /**
1666
+ * Create an SDK instance bound to a partner API key.
1667
+ *
1668
+ * @param config - API key string or {@link SDKConfig} with optional `rpcUrls` and `referralSource`
1669
+ *
1670
+ * @remarks
1671
+ * `@internal` fields on {@link SDKConfig} (`executionApiUrl`, `dataApiUrl`,
1672
+ * `bypassMinPortfolio`) are for local integration tests only.
1673
+ *
1674
+ * @throws If `apiKey` is missing
1675
+ *
1676
+ * @example
1677
+ * ```typescript
1678
+ * const sdk = new ZyfaiSDK({ apiKey: process.env.ZYFAI_API_KEY! });
1679
+ * ```
1680
+ */
1532
1681
  constructor(config) {
1533
1682
  this.signer = null;
1534
1683
  this.walletClient = null;
@@ -1538,18 +1687,22 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1538
1687
  this.connectedSmartWallet = null;
1539
1688
  this.currentProvider = null;
1540
1689
  this.currentChainId = null;
1690
+ /** EOA of the active user session (bearer or SIWE). Cleared on disconnect. */
1691
+ this.sessionEoa = null;
1541
1692
  const sdkConfig = typeof config === "string" ? { apiKey: config } : config;
1542
1693
  const {
1543
1694
  apiKey,
1544
1695
  rpcUrls,
1545
1696
  referralSource,
1546
1697
  executionApiUrl,
1547
- dataApiUrl
1698
+ dataApiUrl,
1699
+ bypassMinPortfolio
1548
1700
  } = sdkConfig;
1549
1701
  if (!apiKey) {
1550
1702
  throw new Error("API key is required");
1551
1703
  }
1552
1704
  this.executionApiUrl = executionApiUrl ?? API_ENDPOINT;
1705
+ this.bypassMinPortfolio = bypassMinPortfolio ?? shouldBypassMinPortfolioCheck(this.executionApiUrl);
1553
1706
  this.httpClient = new HttpClient(apiKey, {
1554
1707
  executionApiUrl: this.executionApiUrl,
1555
1708
  dataApiUrl
@@ -1558,12 +1711,84 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1558
1711
  this.referralSource = referralSource;
1559
1712
  }
1560
1713
  /**
1561
- * Warn that a legacy method is deprecated in favor of depositFunds.
1714
+ * Create an SDK instance with an existing Zyfai user JWT (no wallet connected).
1715
+ *
1716
+ * @group Authentication and wallet
1717
+ */
1718
+ static forUser(config, session) {
1719
+ const sdk = new _ZyfaiSDK(config);
1720
+ sdk.applyUserSession(session);
1721
+ return sdk;
1722
+ }
1723
+ /** Alias for MCP delegated grants (scoped agent JWT). */
1724
+ static forDelegatedGrant(config, session) {
1725
+ return _ZyfaiSDK.forUser(config, session);
1726
+ }
1727
+ /**
1728
+ * Attach a Zyfai user JWT for API calls without `connectAccount`.
1729
+ *
1730
+ * @group Authentication and wallet
1731
+ */
1732
+ applyUserSession(session) {
1733
+ if (!session.accessToken) {
1734
+ throw new Error("accessToken is required");
1735
+ }
1736
+ this.httpClient.setAuthToken(session.accessToken);
1737
+ this.authenticatedUserId = session.userId ?? "bearer-session";
1738
+ this.sessionEoa = session.eoa ? (0, import_viem4.getAddress)(session.eoa) : null;
1739
+ }
1740
+ /**
1741
+ * @internal Attach headers to execution API requests (MCP server agent channel).
1742
+ */
1743
+ setExecutionRequestHeaders(headers) {
1744
+ this.httpClient.setExtraExecutionHeaders(headers);
1745
+ }
1746
+ /** EOA of the active user session, if one is bound. */
1747
+ getSessionEoa() {
1748
+ return this.sessionEoa;
1749
+ }
1750
+ /**
1751
+ * Complete SIWE login with a prepared message and signature (OAuth consent, MCP).
1752
+ *
1753
+ * @group Authentication and wallet
1754
+ *
1755
+ * @param params.message - SIWE message fields (same shape as login API body)
1756
+ * @param params.signature - Wallet signature over the prepared SIWE string
1757
+ * @param params.origin - Origin header value; must match `message.uri`
1758
+ */
1759
+ async authenticateWithSignature(params) {
1760
+ const origin = params.origin ?? params.message.uri;
1761
+ const loginResponse = await this.httpClient.post(
1762
+ ENDPOINTS.AUTH_LOGIN,
1763
+ {
1764
+ message: params.message,
1765
+ signature: params.signature,
1766
+ referralSource: this.referralSource
1767
+ },
1768
+ {
1769
+ headers: {
1770
+ Origin: origin
1771
+ }
1772
+ }
1773
+ );
1774
+ if (!loginResponse.accessToken) {
1775
+ throw new Error("Authentication response missing access token");
1776
+ }
1777
+ this.httpClient.setAuthToken(loginResponse.accessToken);
1778
+ this.authenticatedUserId = loginResponse.userId || null;
1779
+ this.hasActiveSessionKey = loginResponse.hasActiveSessionKey || false;
1780
+ this.isPredeployed = loginResponse.predeployed || false;
1781
+ this.connectedSmartWallet = loginResponse.smartWallet || null;
1782
+ this.sessionEoa = (0, import_viem4.getAddress)(params.message.address);
1783
+ return loginResponse;
1784
+ }
1785
+ /**
1786
+ * Warn that a legacy method is deprecated in favor of sendDeposit.
1562
1787
  * Predeployed wallets no longer require deploySafe / createSessionKey.
1563
1788
  */
1564
1789
  warnDeprecatedOnboardingMethod(methodName) {
1565
1790
  console.warn(
1566
- `[ZyfaiSDK] ${methodName}() is deprecated for partner integrations. Prefer depositFunds() \u2014 predeployed Safes and session keys are handled automatically on first deposit.`
1791
+ `[ZyfaiSDK] ${methodName}() is deprecated for partner integrations. Prefer sendDeposit() \u2014 predeployed Safes and session keys are handled automatically on first deposit.`
1567
1792
  );
1568
1793
  }
1569
1794
  /**
@@ -1578,6 +1803,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1578
1803
  if (this.authenticatedUserId !== null) {
1579
1804
  return;
1580
1805
  }
1806
+ if (this.httpClient.hasAuthToken()) {
1807
+ return;
1808
+ }
1581
1809
  const walletClient = this.getWalletClient();
1582
1810
  const userAddress = (0, import_viem4.getAddress)(walletClient.account.address);
1583
1811
  const chainId = this.currentChainId || walletClient.chain?.id || 8453;
@@ -1631,6 +1859,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1631
1859
  this.hasActiveSessionKey = loginResponse.hasActiveSessionKey || false;
1632
1860
  this.isPredeployed = loginResponse.predeployed || false;
1633
1861
  this.connectedSmartWallet = loginResponse.smartWallet || null;
1862
+ this.sessionEoa = userAddress;
1634
1863
  } catch (error) {
1635
1864
  throw new Error(
1636
1865
  `Failed to authenticate user: ${error.message}`
@@ -1641,8 +1870,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1641
1870
  * Update user profile with Smart Wallet address and chain configuration
1642
1871
  * This method requires SIWE authentication and is automatically called after deploySafe
1643
1872
  *
1644
- * @param request - User profile update data
1645
- * @returns Updated user profile information
1873
+ * @group Portfolio and execution
1874
+ *
1875
+ * @param request - Profile fields to update (per-asset settings supported)
1876
+ * @returns Updated user profile from the execution API
1877
+ *
1878
+ * @throws If strategy is invalid or authentication fails
1646
1879
  *
1647
1880
  * @example
1648
1881
  * ```typescript
@@ -1667,25 +1900,31 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1667
1900
  rebalanceStrategy = toInternalStrategy(request.strategy);
1668
1901
  }
1669
1902
  const assetSettings = {};
1670
- if (rebalanceStrategy !== void 0) assetSettings.rebalanceStrategy = rebalanceStrategy;
1671
- if (request.autocompounding !== void 0) assetSettings.autocompounding = request.autocompounding;
1672
- if (request.crosschainStrategy !== void 0) assetSettings.crosschainStrategy = request.crosschainStrategy;
1673
- if (request.splitting !== void 0) assetSettings.splitting = request.splitting;
1674
- if (request.minSplits !== void 0) assetSettings.minSplits = request.minSplits;
1903
+ if (rebalanceStrategy !== void 0)
1904
+ assetSettings.rebalanceStrategy = rebalanceStrategy;
1905
+ if (request.autocompounding !== void 0)
1906
+ assetSettings.autocompounding = request.autocompounding;
1907
+ if (request.crosschainStrategy !== void 0)
1908
+ assetSettings.crosschainStrategy = request.crosschainStrategy;
1909
+ if (request.splitting !== void 0)
1910
+ assetSettings.splitting = request.splitting;
1911
+ if (request.minSplits !== void 0)
1912
+ assetSettings.minSplits = request.minSplits;
1675
1913
  if (request.chains !== void 0) assetSettings.chains = request.chains;
1676
- if (request.autoSelectProtocols !== void 0) assetSettings.autoSelectProtocols = request.autoSelectProtocols;
1677
- if (request.protocols !== void 0) assetSettings.protocols = request.protocols;
1914
+ if (request.autoSelectProtocols !== void 0)
1915
+ assetSettings.autoSelectProtocols = request.autoSelectProtocols;
1916
+ if (request.protocols !== void 0)
1917
+ assetSettings.protocols = request.protocols;
1678
1918
  const payload = {
1679
1919
  assetTypeSettings: {
1680
1920
  [internalAsset]: assetSettings
1681
1921
  }
1682
1922
  };
1683
- if (request.omniAccount !== void 0) payload.omniAccount = request.omniAccount;
1684
- if (request.agentName !== void 0) payload.agentName = request.agentName;
1685
- await this.httpClient.patch(
1686
- ENDPOINTS.USER_ME,
1687
- payload
1688
- );
1923
+ if (request.omniAccount !== void 0)
1924
+ payload.omniAccount = request.omniAccount;
1925
+ if (request.agentName !== void 0)
1926
+ payload.agentName = request.agentName;
1927
+ await this.httpClient.patch(ENDPOINTS.USER_ME, payload);
1689
1928
  return await this.getUserDetails(asset);
1690
1929
  } catch (error) {
1691
1930
  throw new Error(
@@ -1697,8 +1936,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1697
1936
  * Pause the agent by clearing all protocols
1698
1937
  * Sets the user's protocols to an empty array, effectively pausing automated operations
1699
1938
  *
1939
+ * @group Portfolio and execution
1940
+ *
1700
1941
  * @returns Response indicating success and updated user details
1701
1942
  *
1943
+ * @remarks Requires {@link ZyfaiSDK.connectAccount} (SIWE).
1944
+ *
1702
1945
  * @example
1703
1946
  * ```typescript
1704
1947
  * const sdk = new ZyfaiSDK({ apiKey: 'your-api-key' });
@@ -1713,19 +1956,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1713
1956
  */
1714
1957
  async pauseAgent() {
1715
1958
  try {
1716
- await this.updateUserProfile({
1717
- asset: "USDC",
1718
- protocols: []
1719
- });
1720
- await this.updateUserProfile({
1721
- asset: "WETH",
1722
- protocols: []
1723
- });
1724
- const response = await this.updateUserProfile({
1725
- asset: "EURC",
1726
- protocols: []
1727
- });
1728
- return response;
1959
+ let latest;
1960
+ for (const asset of MANAGED_ASSETS) {
1961
+ latest = await this.updateUserProfile({ asset, protocols: [] });
1962
+ }
1963
+ if (!latest) {
1964
+ throw new Error("No supported assets to pause");
1965
+ }
1966
+ return latest;
1729
1967
  } catch (error) {
1730
1968
  throw new Error(`Failed to pause agent: ${error.message}`);
1731
1969
  }
@@ -1734,8 +1972,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1734
1972
  * Resume the agent by restoring protocols based on user's strategy for each asset
1735
1973
  * Fetches available protocols and assigns them based on each asset's strategy
1736
1974
  *
1975
+ * @group Portfolio and execution
1976
+ *
1737
1977
  * @returns Response indicating success and updated user details
1738
1978
  *
1979
+ * @remarks Requires {@link ZyfaiSDK.connectAccount} (SIWE).
1980
+ *
1739
1981
  * @example
1740
1982
  * ```typescript
1741
1983
  * const sdk = new ZyfaiSDK({ apiKey: 'your-api-key' });
@@ -1750,50 +1992,22 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1750
1992
  */
1751
1993
  async resumeAgent() {
1752
1994
  try {
1753
- const userDetailsUSDC = await this.getUserDetails("USDC");
1754
- const userDetailsETH = await this.getUserDetails("WETH");
1755
- const userDetailsEURC = await this.getUserDetails("EURC");
1756
- const chains = userDetailsUSDC.chains && userDetailsUSDC.chains.length > 0 ? userDetailsUSDC.chains : [8453, 42161];
1757
- const eurcChains = userDetailsEURC.chains && userDetailsEURC.chains.length > 0 ? userDetailsEURC.chains.filter((c) => c === 1 || c === 8453) : [1, 8453];
1758
1995
  const allProtocols = await this.httpClient.get(
1759
1996
  ENDPOINTS.PROTOCOLS()
1760
1997
  );
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);
1765
- const filterProtocolsByStrategy = (strategy, selectedChains) => {
1766
- return allProtocols.filter((protocol) => {
1767
- const hasMatchingChain = protocol.chains.some(
1768
- (chain) => selectedChains.includes(chain)
1769
- );
1770
- if (!hasMatchingChain) {
1771
- return false;
1772
- }
1773
- if (strategy === "async_strategy") {
1774
- return protocol.strategies?.includes("safe_strategy") || protocol.strategies?.includes("degen_strategy") || protocol.strategies?.includes("async_strategy");
1775
- }
1776
- if (strategy === "degen_strategy") {
1777
- return protocol.strategies?.includes("safe_strategy") || protocol.strategies?.includes("degen_strategy");
1778
- }
1779
- return protocol.strategies?.includes("safe_strategy");
1780
- }).map((protocol) => protocol.id);
1781
- };
1782
- const usdcProtocols = filterProtocolsByStrategy(usdcStrategy, chains);
1783
- const ethProtocols = filterProtocolsByStrategy(ethStrategy, chains);
1784
- const eurcProtocols = filterProtocolsByStrategy(eurcStrategy, eurcChains);
1785
- await this.updateUserProfile({
1786
- asset: "USDC",
1787
- protocols: usdcProtocols
1788
- });
1789
- await this.updateUserProfile({
1790
- asset: "WETH",
1791
- protocols: ethProtocols
1792
- });
1793
- return await this.updateUserProfile({
1794
- asset: "EURC",
1795
- protocols: eurcProtocols
1796
- });
1998
+ let latest;
1999
+ for (const asset of MANAGED_ASSETS) {
2000
+ latest = await this.updateUserProtocolsForAsset(
2001
+ asset,
2002
+ getAssetChainIds(asset),
2003
+ void 0,
2004
+ allProtocols
2005
+ );
2006
+ }
2007
+ if (!latest) {
2008
+ throw new Error("No supported assets to resume");
2009
+ }
2010
+ return latest;
1797
2011
  } catch (error) {
1798
2012
  throw new Error(`Failed to resume agent: ${error.message}`);
1799
2013
  }
@@ -1802,9 +2016,16 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1802
2016
  * Enable splitting for the user's account
1803
2017
  * When enabled, deposits are split across multiple protocols based on minSplits setting
1804
2018
  *
1805
- * @param minSplits - Optional minimum number of protocols to split across (default: 3)
2019
+ * @group Portfolio and execution
2020
+ *
2021
+ * @param minSplits - Minimum protocols to split across (max 4)
2022
+ * @defaultValue 1
1806
2023
  * @returns Response indicating success and updated user details
1807
2024
  *
2025
+ * @remarks Requires {@link ZyfaiSDK.connectAccount} (SIWE).
2026
+ *
2027
+ * @throws If `minSplits` exceeds 4
2028
+ *
1808
2029
  * @example
1809
2030
  * ```typescript
1810
2031
  * const sdk = new ZyfaiSDK({ apiKey: 'your-api-key' });
@@ -1828,15 +2049,21 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1828
2049
  });
1829
2050
  return response;
1830
2051
  } catch (error) {
1831
- throw new Error(`Failed to enable splitting: ${error.message}`);
2052
+ throw new Error(
2053
+ `Failed to enable splitting: ${error.message}`
2054
+ );
1832
2055
  }
1833
2056
  }
1834
2057
  /**
1835
2058
  * Disable splitting for the user's account
1836
2059
  * When disabled, deposits will not be split across multiple protocols
1837
2060
  *
2061
+ * @group Portfolio and execution
2062
+ *
1838
2063
  * @returns Response indicating success and updated user details
1839
2064
  *
2065
+ * @remarks Requires {@link ZyfaiSDK.connectAccount} (SIWE).
2066
+ *
1840
2067
  * @example
1841
2068
  * ```typescript
1842
2069
  * const sdk = new ZyfaiSDK({ apiKey: 'your-api-key' });
@@ -1856,16 +2083,22 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1856
2083
  });
1857
2084
  return response;
1858
2085
  } catch (error) {
1859
- throw new Error(`Failed to disable splitting: ${error.message}`);
2086
+ throw new Error(
2087
+ `Failed to disable splitting: ${error.message}`
2088
+ );
1860
2089
  }
1861
2090
  }
1862
2091
  /**
1863
2092
  * Update the minimum number of splits for the user's account
1864
2093
  * This controls across how many protocols deposits should be distributed
1865
2094
  *
1866
- * @param minSplits - Minimum number of protocols to split across
2095
+ * @group Portfolio and execution
2096
+ *
2097
+ * @param minSplits - Minimum number of protocols to split across (at least 1)
1867
2098
  * @returns Response indicating success and updated user details
1868
2099
  *
2100
+ * @throws If `minSplits` is less than 1
2101
+ *
1869
2102
  * @example
1870
2103
  * ```typescript
1871
2104
  * const sdk = new ZyfaiSDK({ apiKey: 'your-api-key' });
@@ -1888,7 +2121,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1888
2121
  });
1889
2122
  return response;
1890
2123
  } catch (error) {
1891
- throw new Error(`Failed to update min splits: ${error.message}`);
2124
+ throw new Error(
2125
+ `Failed to update min splits: ${error.message}`
2126
+ );
1892
2127
  }
1893
2128
  }
1894
2129
  /**
@@ -1942,6 +2177,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1942
2177
  }
1943
2178
  this.authenticatedUserId = null;
1944
2179
  this.hasActiveSessionKey = false;
2180
+ this.sessionEoa = null;
1945
2181
  this.httpClient.clearAuthToken();
1946
2182
  if (this.walletClient && this.currentProvider) {
1947
2183
  const chainConfig = getChainConfig(
@@ -1965,12 +2201,20 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1965
2201
  }
1966
2202
  }
1967
2203
  /**
1968
- * Connect account for signing transactions
1969
- * Accepts either a private key string or a modern wallet provider
2204
+ * Connect an account for signing (SIWE and on-chain transfers).
2205
+ *
2206
+ * @remarks
2207
+ * Required before user-scoped execution calls (deposits, withdrawals, profile).
2208
+ * Data API reads typically need only the API key.
1970
2209
  *
1971
- * @param account - Private key string or wallet provider object
1972
- * @param chainId - Target chain ID (default: 8453 - Base)
1973
- * @returns The connected EOA address
2210
+ * @group Authentication and wallet
2211
+ *
2212
+ * @param account - Private key hex string or EIP-1193 wallet provider
2213
+ * @param chainId - Initial chain for RPC and SIWE
2214
+ * @defaultValue 8453
2215
+ * @returns The connected EOA address (checksum)
2216
+ *
2217
+ * @throws If the chain is unsupported or the provider returns no accounts
1974
2218
  *
1975
2219
  * @example
1976
2220
  * // With private key
@@ -1989,6 +2233,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1989
2233
  this.isPredeployed = false;
1990
2234
  this.connectedSmartWallet = null;
1991
2235
  this.currentChainId = null;
2236
+ this.sessionEoa = null;
1992
2237
  this.httpClient.clearAuthToken();
1993
2238
  if (this.currentProvider?.removeAllListeners) {
1994
2239
  try {
@@ -2056,8 +2301,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2056
2301
  return connectedAddress;
2057
2302
  }
2058
2303
  /**
2059
- * Disconnect account and clear authentication state
2060
- * Resets wallet connection, JWT token, and all authentication-related state
2304
+ * Clear the connected wallet, SIWE session, and cached smart-wallet state.
2305
+ *
2306
+ * @group Authentication and wallet
2307
+ *
2308
+ * @returns Resolves when local SDK state is cleared
2061
2309
  *
2062
2310
  * @example
2063
2311
  * ```typescript
@@ -2080,6 +2328,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2080
2328
  this.hasActiveSessionKey = false;
2081
2329
  this.isPredeployed = false;
2082
2330
  this.connectedSmartWallet = null;
2331
+ this.sessionEoa = null;
2083
2332
  this.httpClient.clearAuthToken();
2084
2333
  }
2085
2334
  /**
@@ -2146,15 +2395,19 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2146
2395
  });
2147
2396
  }
2148
2397
  /**
2149
- * Get smart wallet address for a user
2150
- * Returns the Safe address for an EOA (deterministic for legacy wallets,
2151
- * backend-assigned for predeployed pool wallets).
2398
+ * Resolve the Safe smart wallet for an EOA on a chain.
2399
+ *
2400
+ * @remarks
2401
+ * Predeployed pool wallets use a backend-assigned address; legacy wallets use
2402
+ * a deterministic CREATE2 address.
2403
+ *
2404
+ * @group Authentication and wallet
2152
2405
  *
2153
2406
  * @param userAddress - User's EOA address
2154
2407
  * @param chainId - Target chain ID
2155
- * @returns Smart wallet address, deployment status, and whether userAddress
2156
- * is an on-chain OwnableValidator owner (false for reserved predeployed
2157
- * wallets until the first deposit rotates ownership)
2408
+ * @returns Smart wallet address, deployment status, and on-chain ownership flag
2409
+ *
2410
+ * @throws If `userAddress` is missing or `chainId` is unsupported
2158
2411
  */
2159
2412
  async getSmartWalletAddress(userAddress, chainId) {
2160
2413
  if (!userAddress) {
@@ -2186,10 +2439,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2186
2439
  /**
2187
2440
  * Deploy Safe Smart Wallet for a user
2188
2441
  *
2189
- * @deprecated Prefer `depositFunds()`. Predeployed Safes and session keys are
2442
+ * @deprecated Prefer {@link ZyfaiSDK.sendDeposit}. Predeployed Safes and session keys are
2190
2443
  * managed automatically on first deposit. This method remains available for
2191
2444
  * legacy flows.
2192
2445
  *
2446
+ * @see {@link ZyfaiSDK.sendDeposit}
2447
+ *
2448
+ * @group Deposits and withdrawals
2449
+ *
2193
2450
  * @param userAddress - User's EOA address (the connected EOA, not the smart wallet address)
2194
2451
  * @param chainId - Target chain ID
2195
2452
  * @param strategy - Optional strategy selection: "conservative" (default), "aggressive" or "yieldmaxxing"
@@ -2198,8 +2455,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2198
2455
  *
2199
2456
  * @example
2200
2457
  * ```typescript
2201
- * // Preferred: depositFunds handles predeployed wallet onboarding
2202
- * await sdk.depositFunds(userAddress, 8453, amount, "USDC");
2458
+ * // Preferred: sendDeposit handles predeployed wallet onboarding
2459
+ * const sent = await sdk.sendDeposit(userAddress, 8453, amount, "USDC");
2460
+ * await sdk.waitForDepositCredit(sent.registration.id, 8453);
2203
2461
  *
2204
2462
  * // Legacy: deploy with default conservative strategy
2205
2463
  * await sdk.deploySafe(userAddress, 8453);
@@ -2317,7 +2575,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2317
2575
  } catch (error) {
2318
2576
  console.error("Safe deployment failed:", error);
2319
2577
  throw new Error(
2320
- `Safe deployment failed: ${error.message}. deploySafe() is deprecated \u2014 prefer depositFunds() for predeployed wallet onboarding.`
2578
+ `Safe deployment failed: ${error.message}. deploySafe() is deprecated \u2014 prefer sendDeposit() for predeployed wallet onboarding.`
2321
2579
  );
2322
2580
  }
2323
2581
  }
@@ -2325,18 +2583,23 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2325
2583
  * Create session key with auto-fetched configuration from Zyfai API
2326
2584
  * This is the simplified method that automatically fetches session configuration
2327
2585
  *
2328
- * @deprecated Prefer `depositFunds()`. Predeployed wallets already have the
2586
+ * @deprecated Prefer {@link ZyfaiSDK.sendDeposit}. Predeployed wallets already have the
2329
2587
  * agent session enabled; session activation is handled after first deposit.
2330
2588
  * This method remains available for legacy flows.
2331
2589
  *
2590
+ * @see {@link ZyfaiSDK.sendDeposit}
2591
+ *
2592
+ * @group Deposits and withdrawals
2593
+ *
2332
2594
  * @param userAddress - User's EOA or Safe address
2333
2595
  * @param chainId - Target chain ID
2334
2596
  * @returns Session key response with signature and nonces
2335
2597
  *
2336
2598
  * @example
2337
2599
  * ```typescript
2338
- * // Preferred: depositFunds handles session onboarding for predeployed wallets
2339
- * await sdk.depositFunds(userAddress, 8453, amount, "USDC");
2600
+ * // Preferred: sendDeposit handles session onboarding for predeployed wallets
2601
+ * const sent = await sdk.sendDeposit(userAddress, 8453, amount, "USDC");
2602
+ * await sdk.waitForDepositCredit(sent.registration.id, 8453);
2340
2603
  *
2341
2604
  * // Legacy:
2342
2605
  * const result = await sdk.createSessionKey(userAddress, 8453);
@@ -2417,7 +2680,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2417
2680
  };
2418
2681
  } catch (error) {
2419
2682
  throw new Error(
2420
- `Failed to create session key: ${error.message}. createSessionKey() is deprecated \u2014 prefer depositFunds() for predeployed wallet onboarding.`
2683
+ `Failed to create session key: ${error.message}. createSessionKey() is deprecated \u2014 prefer sendDeposit() for predeployed wallet onboarding.`
2421
2684
  );
2422
2685
  }
2423
2686
  }
@@ -2484,34 +2747,46 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2484
2747
  * asset/chain/strategy combo.
2485
2748
  * 4. Persist via `updateUserProfile` (writes `assetTypeSettings`).
2486
2749
  *
2487
- * Called from `deploySafe` after every path, and from `depositFunds` on
2750
+ * Called from `deploySafe` after every path, and from `sendDeposit` on
2488
2751
  * the account's first deposit (when USDC chains are still empty).
2489
2752
  *
2490
2753
  * @internal
2491
2754
  */
2492
- async updateUserProtocols(strategy) {
2755
+ async updateUserProtocols(strategy, options) {
2756
+ const strict = options?.strict ?? false;
2757
+ const assetErrors = [];
2493
2758
  try {
2494
2759
  const allProtocols = await this.httpClient.get(
2495
2760
  ENDPOINTS.PROTOCOLS()
2496
2761
  );
2497
- const allChains = [1, 8453, 42161];
2498
- const assets = ["USDC", "WETH", "EURC"];
2499
- for (const asset of assets) {
2762
+ for (const asset of MANAGED_ASSETS) {
2500
2763
  try {
2501
- const chainsForAsset = asset === "EURC" ? [1, 8453] : allChains;
2502
2764
  await this.updateUserProtocolsForAsset(
2503
2765
  asset,
2504
- chainsForAsset,
2766
+ getAssetChainIds(asset),
2505
2767
  strategy,
2506
2768
  allProtocols
2507
2769
  );
2508
2770
  } catch (assetError) {
2509
- console.warn(
2510
- `Failed to update ${asset} protocols: ${assetError.message}`
2511
- );
2771
+ const message = assetError.message;
2772
+ if (strict) {
2773
+ assetErrors.push(`${asset}: ${message}`);
2774
+ } else {
2775
+ console.warn(`Failed to update ${asset} protocols: ${message}`);
2776
+ }
2512
2777
  }
2513
2778
  }
2779
+ if (strict && assetErrors.length > 0) {
2780
+ throw new Error(
2781
+ `Failed to configure user protocols for first deposit: ${assetErrors.join(
2782
+ "; "
2783
+ )}`
2784
+ );
2785
+ }
2514
2786
  } catch (error) {
2787
+ if (strict) {
2788
+ throw error;
2789
+ }
2515
2790
  console.warn(
2516
2791
  `Failed to update user protocols: ${error.message}`
2517
2792
  );
@@ -2541,13 +2816,85 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2541
2816
  asset,
2542
2817
  internalStrategy
2543
2818
  );
2544
- await this.updateUserProfile({
2819
+ return await this.updateUserProfile({
2545
2820
  asset,
2546
2821
  protocols: withPools,
2547
2822
  chains: effectiveChains,
2548
2823
  ...strategy !== void 0 && { strategy }
2549
2824
  });
2550
2825
  }
2826
+ /**
2827
+ * Switch one asset to a strategy and select the protocols that go with it.
2828
+ *
2829
+ * `updateUserProfile` stores a strategy but does not compute a protocol
2830
+ * list, so on its own it leaves the asset with nothing to deploy into. This
2831
+ * method does both in one call: it resolves the protocols that support the
2832
+ * asset on the requested chains under the requested strategy, drops those
2833
+ * with no pool available, and persists strategy, chains and protocols
2834
+ * together.
2835
+ *
2836
+ * Mostly needed for assets that are not set up by the account's first
2837
+ * deposit, or to change an existing account's strategy — `sendDeposit`
2838
+ * ignores its `strategy` argument after the first deposit.
2839
+ *
2840
+ * @param params.asset - Asset to configure
2841
+ * @param params.strategy - Strategy to apply; defaults to the one already
2842
+ * stored for this asset (`"conservative"` on a fresh account), which lets
2843
+ * you recompute a protocol list without changing the strategy
2844
+ * @param params.chains - Chains to enable. Defaults to every chain the asset
2845
+ * exists on. **Additive**: chains already enabled are kept, so this cannot
2846
+ * be used to disable one.
2847
+ * @group Portfolio and execution
2848
+ *
2849
+ * @returns The updated profile for that asset
2850
+ *
2851
+ * @example
2852
+ * ```typescript
2853
+ * // NVDAc only lives in async protocols, so it needs "yieldmaxxing".
2854
+ * // Chains default to Base, the only chain it exists on.
2855
+ * const profile = await sdk.setAssetStrategy({
2856
+ * asset: "NVDAc",
2857
+ * strategy: "yieldmaxxing",
2858
+ * });
2859
+ * console.log(profile.protocols); // Ipor + Superform
2860
+ * ```
2861
+ */
2862
+ async setAssetStrategy(params) {
2863
+ const { asset, strategy, chains } = params;
2864
+ try {
2865
+ if (strategy !== void 0 && !isValidPublicStrategy(strategy)) {
2866
+ throw new Error(
2867
+ `Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
2868
+ );
2869
+ }
2870
+ const supported = getAssetChainIds(asset);
2871
+ if (supported.length === 0) {
2872
+ throw new Error(`Unsupported asset: ${asset}.`);
2873
+ }
2874
+ const targetChains = chains ?? supported;
2875
+ const unsupported = targetChains.filter((c) => !supported.includes(c));
2876
+ if (unsupported.length > 0) {
2877
+ throw new Error(
2878
+ `${asset} is not available on chain ${unsupported.join(
2879
+ ", "
2880
+ )}. Supported chains: ${supported.join(", ")}.`
2881
+ );
2882
+ }
2883
+ const allProtocols = await this.httpClient.get(
2884
+ ENDPOINTS.PROTOCOLS()
2885
+ );
2886
+ return await this.updateUserProtocolsForAsset(
2887
+ asset,
2888
+ targetChains,
2889
+ strategy,
2890
+ allProtocols
2891
+ );
2892
+ } catch (error) {
2893
+ throw new Error(
2894
+ `Failed to set ${asset} strategy: ${error.message}`
2895
+ );
2896
+ }
2897
+ }
2551
2898
  /**
2552
2899
  * Drop protocols that have no pools on any of the selected chains for the
2553
2900
  * requested asset. The /customization/pools endpoint filters server-side on
@@ -2602,55 +2949,6 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2602
2949
  return value;
2603
2950
  });
2604
2951
  }
2605
- /**
2606
- * Deposit funds from EOA to Safe smart wallet
2607
- * Transfers tokens from the connected wallet to the user's Safe and logs the deposit
2608
- *
2609
- * Token address is selected from `asset` for the given chain:
2610
- * - Ethereum Mainnet (1), Base (8453), Arbitrum (42161): USDC or WETH
2611
- * - Ethereum Mainnet (1), Base (8453): EURC
2612
- *
2613
- * On the account's first deposit (USDC profile has no chains yet), patches
2614
- * protocol selection for USDC, WETH, and EURC across all supported chains
2615
- * (EURC on Mainnet/Base only) before the transfer and log_deposit.
2616
- * Pass `strategy` to select protocols for that first-deposit setup
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 })`.
2622
- *
2623
- * Minimum portfolio balance enforced (Safe balance + deposit amount):
2624
- * - Stablecoins: `MIN_PORTFOLIO_BALANCE` (Mainnet 10,000 USDC/EURC; Base/Arbitrum 100)
2625
- * - WETH: about $10,000 on Mainnet, $100 on Base/Arbitrum, from Data API `/price?token=eth`
2626
- *
2627
- * @param userAddress - User's address (owner of the Safe)
2628
- * @param chainId - Target chain ID
2629
- * @param amount - Amount in least decimal units (e.g., "100000000" for 100 USDC with 6 decimals)
2630
- * @param asset - Asset symbol: "USDC", "WETH", or "EURC".
2631
- * EURC is supported on Ethereum Mainnet and Base only.
2632
- * @param strategy - Optional strategy for first-deposit protocol patching:
2633
- * "conservative" (default), "aggressive" or "yieldmaxxing". Ignored on
2634
- * later deposits — use `updateUserProfile` to change an existing account.
2635
- * @returns Deposit response with transaction hash
2636
- *
2637
- * @example
2638
- * ```typescript
2639
- * // Deposit 10,000 USDC (6 decimals) to Safe on Base
2640
- * const result = await sdk.depositFunds(
2641
- * "0xUser...",
2642
- * 8453,
2643
- * "10000000000",
2644
- * "USDC"
2645
- * );
2646
- *
2647
- * // First deposit with aggressive strategy
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" });
2652
- * ```
2653
- */
2654
2952
  /**
2655
2953
  * Deploy the connected predeployed (pool) wallet on one or more chains.
2656
2954
  *
@@ -2661,11 +2959,20 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2661
2959
  * resolves once all requested chains have landed on-chain. Idempotent — chains
2662
2960
  * already deployed are a no-op.
2663
2961
  *
2664
- * Optional for deposits: `depositFunds` no longer pre-deploys the target chain — the ERC20
2962
+ * Optional for deposits: `sendDeposit` no longer pre-deploys the target chain — the ERC20
2665
2963
  * transfer lands on the counterfactual address and the backend deploys + hands over on first
2666
2964
  * deposit (report-deposit). Use this only to pre-provision chains ahead of time.
2667
2965
  *
2668
- * @param chainIds - Chain IDs to deploy the wallet on (e.g. [1, 42161])
2966
+ * @group Deposits and withdrawals
2967
+ *
2968
+ * @param chainIds - Chain IDs to deploy the wallet on (e.g. `[1, 42161]`)
2969
+ * @returns Deployment summary from the execution API
2970
+ *
2971
+ * @throws If `chainIds` is empty or contains an unsupported chain
2972
+ *
2973
+ * @remarks
2974
+ * Requires {@link ZyfaiSDK.connectAccount} (SIWE). Optional ahead of deposits;
2975
+ * {@link ZyfaiSDK.sendDeposit} can deploy on first deposit for predeployed wallets.
2669
2976
  */
2670
2977
  async deployOnChains(chainIds) {
2671
2978
  if (!chainIds?.length) {
@@ -2677,7 +2984,36 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2677
2984
  await this.authenticateUser();
2678
2985
  return this.httpClient.post(ENDPOINTS.DEPLOY_CHAINS, { chainIds });
2679
2986
  }
2680
- async depositFunds(userAddress, chainId, amount, asset, strategy) {
2987
+ /**
2988
+ * Transfer funds from the connected EOA to the user's Safe and register the deposit.
2989
+ *
2990
+ * @remarks
2991
+ * Execution API + on-chain ERC-20 `transfer`. Confirms the transaction, then calls
2992
+ * {@link ZyfaiSDK.logDeposit}. Pair with {@link ZyfaiSDK.waitForDepositCredit} for
2993
+ * investable balance. Custom-wallet flows: {@link ZyfaiSDK.buildDepositTransfer},
2994
+ * {@link ZyfaiSDK.logDeposit}, {@link ZyfaiSDK.getDepositStatus}.
2995
+ *
2996
+ * Requires {@link ZyfaiSDK.connectAccount}. Pass the **EOA** as `userAddress`.
2997
+ *
2998
+ * @group Deposits and withdrawals
2999
+ *
3000
+ * @param userAddress - Owner EOA (not the Safe)
3001
+ * @param chainId - Chain for the transfer
3002
+ * @param amount - Amount in least units (string integer)
3003
+ * @param asset - Asset symbol (`USDC`, `WETH`, `EURC`, `NVDAc`)
3004
+ * @param strategy - Optional first-deposit {@link Strategy}
3005
+ * @returns Transfer receipt and deposit registration (not yet credited until polled)
3006
+ *
3007
+ * @throws If validation fails, minimum portfolio is not met, Safe is unavailable, or transfer/register fails
3008
+ *
3009
+ * @example
3010
+ * ```typescript
3011
+ * await sdk.connectAccount(provider);
3012
+ * const sent = await sdk.sendDeposit(eoa, 8453, "10000000", "USDC", "conservative");
3013
+ * await sdk.waitForDepositCredit(sent.registration.id, 8453);
3014
+ * ```
3015
+ */
3016
+ async sendDeposit(userAddress, chainId, amount, asset, strategy) {
2681
3017
  try {
2682
3018
  if (!userAddress) {
2683
3019
  throw new Error("User address is required");
@@ -2696,35 +3032,51 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2696
3032
  `Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
2697
3033
  );
2698
3034
  }
2699
- const assetSymbol = asset.toUpperCase();
3035
+ const assetSymbol = resolveAssetSymbol(asset);
2700
3036
  const assetConfig = ASSET_CONFIGS[assetSymbol];
2701
- if (!assetConfig) {
3037
+ const assetChains = getAssetChainIds(assetSymbol);
3038
+ if (!assetChains.includes(chainId)) {
2702
3039
  throw new Error(
2703
- `Unsupported asset: ${assetSymbol}. Supported: USDC, WETH, EURC.`
2704
- );
2705
- }
2706
- let minRequired = MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
2707
- if (assetSymbol === "WETH") {
2708
- const priceResponse = await this.httpClient.dataGet(
2709
- DATA_ENDPOINTS.TOKEN_PRICE("eth")
2710
- );
2711
- minRequired = minWethWeiForUsd(
2712
- parseEthUsdPrice(priceResponse),
2713
- MIN_WETH_USD[chainId]
3040
+ `${assetSymbol} is not available on chain ${chainId}. Supported chains: ${assetChains.join(
3041
+ ", "
3042
+ )}.`
2714
3043
  );
2715
3044
  }
3045
+ let minRequired = this.bypassMinPortfolio ? void 0 : MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
3046
+ const minUsd = this.bypassMinPortfolio ? void 0 : MIN_PORTFOLIO_USD[chainId]?.[assetSymbol];
2716
3047
  const token = getDefaultTokenAddress(chainId, assetSymbol);
2717
3048
  const walletClient = this.getWalletClient();
2718
- await this.authenticateUser();
2719
3049
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
3050
+ if (minUsd !== void 0) {
3051
+ const [, priceResponse] = await Promise.all([
3052
+ this.authenticateUser(),
3053
+ this.httpClient.dataGet(
3054
+ DATA_ENDPOINTS.TOKEN_PRICE(assetConfig.priceTokenSymbol)
3055
+ )
3056
+ ]);
3057
+ minRequired = usdToTokenUnits(
3058
+ minUsd,
3059
+ parseTokenUsdPrice(priceResponse),
3060
+ assetConfig.decimals
3061
+ );
3062
+ } else {
3063
+ await this.authenticateUser();
3064
+ }
2720
3065
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
2721
3066
  if (!safeAddress) {
2722
3067
  throw new Error("Smart wallet address is not available");
2723
3068
  }
2724
- const isDeployed = await isSafeDeployed(
2725
- safeAddress,
2726
- chainConfig.publicClient
2727
- );
3069
+ const amountBigInt = BigInt(amount);
3070
+ const [isDeployed, currentSafeBalance] = await Promise.all([
3071
+ isSafeDeployed(safeAddress, chainConfig.publicClient),
3072
+ minRequired !== void 0 ? chainConfig.publicClient.readContract({
3073
+ address: token,
3074
+ abi: ERC20_ABI,
3075
+ functionName: "balanceOf",
3076
+ args: [safeAddress]
3077
+ }) : Promise.resolve(void 0),
3078
+ this.prepareFirstDeposit(strategy)
3079
+ ]).then(([deployed, balance]) => [deployed, balance]);
2728
3080
  if (!isDeployed) {
2729
3081
  if (!(this.isPredeployed && this.isConnectedUser(userAddress))) {
2730
3082
  throw new Error(
@@ -2732,26 +3084,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2732
3084
  );
2733
3085
  }
2734
3086
  }
2735
- try {
2736
- const usdcDetails = await this.getUserDetails("USDC");
2737
- if ((usdcDetails.chains?.length ?? 0) === 0) {
2738
- await this.updateUserProtocols(strategy);
2739
- }
2740
- } catch (protocolError) {
2741
- console.warn(
2742
- "Failed to update user protocols before deposit:",
2743
- protocolError.message
2744
- );
2745
- }
2746
- const amountBigInt = BigInt(amount);
2747
3087
  if (minRequired !== void 0) {
2748
- const currentSafeBalance = await chainConfig.publicClient.readContract({
2749
- address: token,
2750
- abi: ERC20_ABI,
2751
- functionName: "balanceOf",
2752
- args: [safeAddress]
2753
- });
2754
- const totalAfterDeposit = currentSafeBalance + amountBigInt;
3088
+ const safeBalance = currentSafeBalance;
3089
+ const totalAfterDeposit = safeBalance + amountBigInt;
2755
3090
  if (totalAfterDeposit < minRequired) {
2756
3091
  const minLabel = formatMinPortfolioLabel(
2757
3092
  minRequired,
@@ -2759,7 +3094,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2759
3094
  assetSymbol
2760
3095
  );
2761
3096
  throw new Error(
2762
- `Minimum portfolio balance not met on chain ${chainId}. Total portfolio must be at least ${minLabel}. Current Safe balance: ${currentSafeBalance.toString()}, deposit amount: ${amountBigInt.toString()}, total after deposit: ${totalAfterDeposit.toString()} (raw units, ${assetConfig.decimals} decimals).`
3097
+ `Minimum portfolio balance not met on chain ${chainId}. Total portfolio must be at least ${minLabel}. Current Safe balance: ${safeBalance.toString()}, deposit amount: ${amountBigInt.toString()}, total after deposit: ${totalAfterDeposit.toString()} (raw units, ${assetConfig.decimals} decimals).`
2763
3098
  );
2764
3099
  }
2765
3100
  }
@@ -2777,27 +3112,254 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2777
3112
  if (receipt.status !== "success") {
2778
3113
  throw new Error("Deposit transaction failed");
2779
3114
  }
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
- }
3115
+ const registration = await this.registerDeposit(
3116
+ chainId,
3117
+ txHash,
3118
+ amount,
3119
+ token
3120
+ );
2787
3121
  return {
2788
3122
  success: true,
2789
3123
  txHash,
2790
3124
  smartWallet: safeAddress,
2791
- amount: amountBigInt.toString()
3125
+ amount: amountBigInt.toString(),
3126
+ registration
2792
3127
  };
2793
3128
  } catch (error) {
2794
3129
  throw new Error(`Deposit failed: ${error.message}`);
2795
3130
  }
2796
3131
  }
3132
+ /**
3133
+ * @deprecated Compatibility convenience method. Prefer {@link ZyfaiSDK.sendDeposit} followed by
3134
+ * {@link ZyfaiSDK.waitForDepositCredit} when the caller owns the completion UX.
3135
+ *
3136
+ * @see {@link ZyfaiSDK.sendDeposit}
3137
+ *
3138
+ * @group Deposits and withdrawals
3139
+ */
3140
+ async depositFunds(userAddress, chainId, amount, asset, strategy) {
3141
+ this.warnDeprecatedOnboardingMethod("depositFunds");
3142
+ const sent = await this.sendDeposit(
3143
+ userAddress,
3144
+ chainId,
3145
+ amount,
3146
+ asset,
3147
+ strategy
3148
+ );
3149
+ return {
3150
+ ...sent,
3151
+ registration: await this.waitForDepositCredit(
3152
+ sent.registration.id,
3153
+ chainId
3154
+ )
3155
+ };
3156
+ }
3157
+ /**
3158
+ * Build ERC-20 transfer calldata for a custom signer or sponsored tx flow.
3159
+ *
3160
+ * @remarks
3161
+ * Compose with {@link ZyfaiSDK.ensureFirstDepositSetup}, submit the transfer, then
3162
+ * {@link ZyfaiSDK.logDeposit} and {@link ZyfaiSDK.waitForDepositCredit}.
3163
+ *
3164
+ * @group Deposits and withdrawals
3165
+ *
3166
+ * @param params.userAddress - Owner EOA
3167
+ * @param params.chainId - Target chain
3168
+ * @param params.amount - Least units (string integer)
3169
+ * @param params.asset - {@link SupportedAsset}
3170
+ * @returns Safe address, token, and encoded `transfer` calldata
3171
+ *
3172
+ * @throws If inputs are invalid or the Safe address cannot be resolved
3173
+ */
3174
+ async buildDepositTransfer(params) {
3175
+ const { userAddress, chainId, amount, asset } = params;
3176
+ if (!userAddress || !amount || BigInt(amount) <= 0n) {
3177
+ throw new Error("A user address and positive amount are required");
3178
+ }
3179
+ if (!isSupportedChain(chainId)) {
3180
+ throw new Error(`Unsupported chain ID: ${chainId}`);
3181
+ }
3182
+ const assetSymbol = resolveAssetSymbol(asset);
3183
+ const assetChains = getAssetChainIds(assetSymbol);
3184
+ if (!assetChains.includes(chainId)) {
3185
+ throw new Error(
3186
+ `${assetSymbol} is not available on chain ${chainId}. Supported chains: ${assetChains.join(
3187
+ ", "
3188
+ )}.`
3189
+ );
3190
+ }
3191
+ const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
3192
+ if (!safeAddress) {
3193
+ throw new Error("Smart wallet address is not available");
3194
+ }
3195
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3196
+ const isDeployed = await isSafeDeployed(
3197
+ safeAddress,
3198
+ chainConfig.publicClient
3199
+ );
3200
+ if (!(isDeployed || this.isPredeployed && this.isConnectedUser(userAddress))) {
3201
+ throw new Error(
3202
+ `Safe not available for ${userAddress} on chain ${chainId}.`
3203
+ );
3204
+ }
3205
+ const amountBigInt = BigInt(amount);
3206
+ await this.enforceMinimumPortfolioBalance(
3207
+ chainId,
3208
+ asset,
3209
+ amountBigInt,
3210
+ safeAddress
3211
+ );
3212
+ const tokenAddress = getDefaultTokenAddress(
3213
+ chainId,
3214
+ assetSymbol
3215
+ );
3216
+ return {
3217
+ safeAddress,
3218
+ tokenAddress,
3219
+ to: tokenAddress,
3220
+ data: (0, import_viem4.encodeFunctionData)({
3221
+ abi: ERC20_ABI,
3222
+ functionName: "transfer",
3223
+ args: [safeAddress, amountBigInt]
3224
+ }),
3225
+ value: "0"
3226
+ };
3227
+ }
3228
+ /** Apply the same per-asset minimum portfolio rule as sendDeposit. */
3229
+ async enforceMinimumPortfolioBalance(chainId, asset, amount, safeAddress) {
3230
+ if (this.bypassMinPortfolio) {
3231
+ return;
3232
+ }
3233
+ const assetSymbol = resolveAssetSymbol(asset);
3234
+ const assetConfig = ASSET_CONFIGS[assetSymbol];
3235
+ let minRequired = MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
3236
+ const minUsd = MIN_PORTFOLIO_USD[chainId]?.[assetSymbol];
3237
+ if (minUsd !== void 0) {
3238
+ const [, priceResponse] = await Promise.all([
3239
+ this.authenticateUser(),
3240
+ this.httpClient.dataGet(
3241
+ DATA_ENDPOINTS.TOKEN_PRICE(assetConfig.priceTokenSymbol)
3242
+ )
3243
+ ]);
3244
+ minRequired = usdToTokenUnits(
3245
+ minUsd,
3246
+ parseTokenUsdPrice(priceResponse),
3247
+ assetConfig.decimals
3248
+ );
3249
+ }
3250
+ if (minRequired === void 0) return;
3251
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3252
+ const token = getDefaultTokenAddress(chainId, assetSymbol);
3253
+ const currentSafeBalance = await chainConfig.publicClient.readContract({
3254
+ address: token,
3255
+ abi: ERC20_ABI,
3256
+ functionName: "balanceOf",
3257
+ args: [safeAddress]
3258
+ });
3259
+ const totalAfterDeposit = currentSafeBalance + amount;
3260
+ if (totalAfterDeposit < minRequired) {
3261
+ const minLabel = formatMinPortfolioLabel(
3262
+ minRequired,
3263
+ assetConfig.decimals,
3264
+ assetSymbol
3265
+ );
3266
+ throw new Error(
3267
+ `Minimum portfolio balance not met on chain ${chainId}. Total portfolio must be at least ${minLabel}. Current Safe balance: ${currentSafeBalance.toString()}, deposit amount: ${amount.toString()}, total after deposit: ${totalAfterDeposit.toString()} (raw units, ${assetConfig.decimals} decimals).`
3268
+ );
3269
+ }
3270
+ }
3271
+ /**
3272
+ * Idempotently apply the first-deposit profile configuration for builders
3273
+ * composing an advanced custom transfer flow. Most custom-wallet
3274
+ * integrations can use this with `buildDepositTransfer()` and `logDeposit()`.
3275
+ *
3276
+ * When setup runs (`applied: true`), protocol configuration is persisted
3277
+ * before returning. Failures throw so callers can abort before submitting a
3278
+ * transfer. High-level deposit methods still treat setup as best-effort.
3279
+ *
3280
+ * @group Deposits and withdrawals
3281
+ *
3282
+ * @param strategy - Optional first-deposit {@link Strategy}
3283
+ * @returns `{ applied: true }` when chain/protocol config was written; `false` if already configured
3284
+ *
3285
+ * @throws If strategy is invalid or setup did not persist
3286
+ */
3287
+ async ensureFirstDepositSetup(strategy) {
3288
+ if (strategy !== void 0 && !isValidPublicStrategy(strategy)) {
3289
+ throw new Error(
3290
+ `Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
3291
+ );
3292
+ }
3293
+ await this.authenticateUser();
3294
+ const usdcDetails = await this.getUserDetails("USDC");
3295
+ if ((usdcDetails.chains?.length ?? 0) > 0) {
3296
+ return { applied: false };
3297
+ }
3298
+ await this.updateUserProtocols(strategy, { strict: true });
3299
+ const usdcAfterSetup = await this.getUserDetails("USDC");
3300
+ if ((usdcAfterSetup.chains?.length ?? 0) === 0) {
3301
+ throw new Error(
3302
+ "First-deposit setup did not persist USDC chain configuration."
3303
+ );
3304
+ }
3305
+ return { applied: true };
3306
+ }
3307
+ /**
3308
+ * Prepare entering a position: persist first-deposit profile when needed and
3309
+ * return ERC-20 transfer calldata for the user to sign (does not broadcast).
3310
+ *
3311
+ * @group Deposits and withdrawals
3312
+ */
3313
+ async prepareEnterPosition(params) {
3314
+ const { userAddress, chainId, amount, asset, strategy } = params;
3315
+ if (this.sessionEoa && (0, import_viem4.getAddress)(userAddress) !== this.sessionEoa) {
3316
+ throw new Error("userAddress does not match authenticated session EOA");
3317
+ }
3318
+ const setup = await this.ensureFirstDepositSetup(strategy);
3319
+ const transfer = await this.buildDepositTransfer({
3320
+ userAddress,
3321
+ chainId,
3322
+ amount,
3323
+ asset
3324
+ });
3325
+ return {
3326
+ phase: "prepare_transfer",
3327
+ setup,
3328
+ transfer
3329
+ };
3330
+ }
3331
+ /** Best-effort first-deposit setup shared by both high-level deposit flows. */
3332
+ async prepareFirstDeposit(strategy) {
3333
+ try {
3334
+ await this.ensureFirstDepositSetup(strategy);
3335
+ } catch (protocolError) {
3336
+ console.warn(
3337
+ "Failed to update user protocols before deposit:",
3338
+ protocolError.message
3339
+ );
3340
+ }
3341
+ }
3342
+ /** Shared post-transfer registration path for every deposit flow. */
3343
+ async registerDeposit(chainId, txHash, amount, tokenAddress) {
3344
+ let registration;
3345
+ try {
3346
+ registration = await this.logDeposit(
3347
+ chainId,
3348
+ txHash,
3349
+ amount,
3350
+ tokenAddress
3351
+ );
3352
+ } catch (logError) {
3353
+ throw new Error(
3354
+ `On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}") to retry.`
3355
+ );
3356
+ }
3357
+ return registration.deposit;
3358
+ }
2797
3359
  /**
2798
3360
  * Log a deposit that was executed client-side.
2799
3361
  *
2800
- * `depositFunds()` already calls this after the ERC20 transfer. If you send the
3362
+ * `sendDeposit()` already calls this after the ERC20 transfer. If you send the
2801
3363
  * transfer yourself (front, Privy, Biconomy, custom wallet) you **must** call
2802
3364
  * `logDeposit` — otherwise the backend never sees the deposit: a reserved pool
2803
3365
  * wallet stays reserved (no ownership rotation), and yield/agent tracking does
@@ -2821,8 +3383,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2821
3383
  * @param chainId - Chain ID where the deposit was made
2822
3384
  * @param txHash - Transaction hash of the deposit
2823
3385
  * @param amount - Amount in least decimal units (e.g., "100000000" for 100 USDC with 6 decimals)
2824
- * @param tokenAddress - Optional: Token address (auto-selected based on chain if not provided)
2825
- * @returns Log deposit response with success status
3386
+ * @param tokenAddress - Optional token contract (defaults per chain)
3387
+ * @returns Log deposit response with lifecycle record
3388
+ *
3389
+ * @group Deposits and withdrawals
3390
+ *
3391
+ * @throws If inputs are invalid or the execution API rejects registration
2826
3392
  *
2827
3393
  * @example
2828
3394
  * ```typescript
@@ -2854,20 +3420,97 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2854
3420
  }
2855
3421
  const token = tokenAddress || getDefaultTokenAddress(chainId);
2856
3422
  await this.authenticateUser();
2857
- await this.httpClient.post(ENDPOINTS.LOG_DEPOSIT, {
2858
- chainId,
2859
- transaction: txHash,
2860
- token,
2861
- amount
2862
- });
3423
+ const deposit = await this.httpClient.post(
3424
+ ENDPOINTS.LOG_DEPOSIT,
3425
+ {
3426
+ chainId,
3427
+ transaction: txHash,
3428
+ token,
3429
+ amount
3430
+ }
3431
+ );
2863
3432
  return {
2864
3433
  success: true,
2865
- message: "Deposit logged successfully"
3434
+ message: deposit.status === "credited" ? "Deposit credited successfully" : "Deposit accepted; custody handover is pending",
3435
+ deposit
2866
3436
  };
2867
3437
  } catch (error) {
2868
3438
  throw new Error(`Log deposit failed: ${error.message}`);
2869
3439
  }
2870
3440
  }
3441
+ /**
3442
+ * Fetch custody handover and balance-credit status for a registered deposit.
3443
+ *
3444
+ * @remarks
3445
+ * `status === "credited"` with `balanceCredited === true` means funds are investable.
3446
+ * Requires {@link ZyfaiSDK.connectAccount} (SIWE).
3447
+ *
3448
+ * @group Deposits and withdrawals
3449
+ *
3450
+ * @param depositId - Id from {@link LogDepositResponse} / {@link DepositResponse.registration}
3451
+ * @returns {@link DepositLifecycleResponse}
3452
+ *
3453
+ * @throws If `depositId` is missing
3454
+ */
3455
+ async getDepositStatus(depositId) {
3456
+ if (!depositId) {
3457
+ throw new Error("Deposit ID is required");
3458
+ }
3459
+ await this.authenticateUser();
3460
+ return this.httpClient.get(
3461
+ ENDPOINTS.DEPOSIT_STATUS(depositId)
3462
+ );
3463
+ }
3464
+ /**
3465
+ * Await deposit credit after `logDeposit` returns `handover_pending`.
3466
+ *
3467
+ * Polls `getDepositStatus` until `status === "credited"` and
3468
+ * `balanceCredited === true`. Rejects on recovery, timeout, or poll errors.
3469
+ *
3470
+ * Poll interval and timeout are chain-specific. Mainnet defaults to a 2s
3471
+ * interval and 1 minute ceiling; Base/Arbitrum use tighter polling (~500ms /
3472
+ * ~250ms) with a ~20 second completion window. Override `timeoutMs` when a
3473
+ * caller intentionally wants to wait longer than the normal UX window.
3474
+ *
3475
+ * Requires {@link ZyfaiSDK.connectAccount} on the same SDK instance.
3476
+ *
3477
+ * @group Deposits and withdrawals
3478
+ *
3479
+ * @param depositId - Deposit lifecycle id
3480
+ * @param chainId - Chain (controls poll interval and default timeout)
3481
+ * @param options - Optional `intervalMs` and `timeoutMs` overrides
3482
+ * @returns Final lifecycle record when credited
3483
+ *
3484
+ * @throws `DepositCreditTimeoutError` when the poll window elapses without credit
3485
+ * @throws If deposit recovers to EOA or polling fails
3486
+ */
3487
+ async waitForDepositCredit(depositId, chainId, options) {
3488
+ if (!depositId) {
3489
+ throw new Error("Deposit ID is required");
3490
+ }
3491
+ if (!isSupportedChain(chainId)) {
3492
+ throw new Error(`Unsupported chain ID: ${chainId}`);
3493
+ }
3494
+ const intervalMs = options?.intervalMs ?? getDepositCreditIntervalMs(chainId);
3495
+ const timeoutMs = options?.timeoutMs ?? getDepositCreditTimeoutMs(chainId);
3496
+ const started = Date.now();
3497
+ while (Date.now() - started < timeoutMs) {
3498
+ const status = await this.getDepositStatus(depositId);
3499
+ if (status.status === "credited" && status.balanceCredited) {
3500
+ return status;
3501
+ }
3502
+ if (status.status === "recovered_to_eoa") {
3503
+ throw new Error(
3504
+ `Deposit ${depositId} recovered to EOA (status=${status.status}); balance was not credited`
3505
+ );
3506
+ }
3507
+ if (Date.now() - started >= timeoutMs) {
3508
+ break;
3509
+ }
3510
+ await sleep(intervalMs);
3511
+ }
3512
+ throw new DepositCreditTimeoutError(depositId);
3513
+ }
2871
3514
  /**
2872
3515
  * Withdraw funds from Safe smart wallet
2873
3516
  * Initiates a withdrawal request to the Zyfai API
@@ -2887,6 +3530,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2887
3530
  * When every source is an async pool nothing settles on-chain at that point,
2888
3531
  * so `txHash` is `undefined` on a successful call.
2889
3532
  *
3533
+ * **One redemption per pool at a time.** While an entry for a pool is
3534
+ * `REQUESTED` or `CLAIMABLE`, the backend drops a further withdrawal aimed at
3535
+ * that same pool — the protocols behind it (ERC-7540) hold a single request
3536
+ * slot per user. This method throws rather than reporting that no-op as a
3537
+ * success. It only throws when nothing the call could reach is withdrawable:
3538
+ * another pool, another asset or an idle Safe balance still goes through.
3539
+ *
2890
3540
  * Once requested, that amount can no longer be withdrawn: it is gone from
2891
3541
  * both the position snapshot and the Safe balance, so a second call silently
2892
3542
  * returns only what is left. Validate user-entered amounts against
@@ -2895,8 +3545,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2895
3545
  *
2896
3546
  * @param userAddress - User's address (owner of the Safe)
2897
3547
  * @param chainId - Target chain ID
2898
- * @param amount - Optional: Amount in least decimal units to withdraw (partial withdrawal). If not specified, withdraws all funds
2899
- * @returns Withdraw response with message and optional transaction hash (available once processed)
3548
+ * @param amount - Optional amount in least units (partial withdrawal); omit for full withdraw
3549
+ * @param tokenSymbol - Optional asset symbol when withdrawing a specific token
3550
+ * @returns Withdraw response with message and optional transaction hash
3551
+ *
3552
+ * @group Deposits and withdrawals
3553
+ *
3554
+ * @throws If `userAddress` or `chainId` is invalid, or the execution API rejects the request
2900
3555
  *
2901
3556
  * @example
2902
3557
  * ```typescript
@@ -2935,6 +3590,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2935
3590
  );
2936
3591
  }
2937
3592
  await this.authenticateUser();
3593
+ await this.assertAsyncRedemptionSlotFree(
3594
+ userAddress,
3595
+ chainId,
3596
+ tokenSymbol
3597
+ );
2938
3598
  let response = {};
2939
3599
  if (amount) {
2940
3600
  response = await this.httpClient.post(ENDPOINTS.PARTIAL_WITHDRAW, {
@@ -2963,11 +3623,42 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2963
3623
  }
2964
3624
  }
2965
3625
  /**
2966
- * Get available DeFi protocols and pools for a specific chain
3626
+ * Turn a withdrawal the backend would silently drop — one aimed only at
3627
+ * async pools that already hold an in-flight redemption — into an error, so
3628
+ * the caller gets an answer rather than a `success: true` no-op.
3629
+ *
3630
+ * @internal
3631
+ */
3632
+ async assertAsyncRedemptionSlotFree(userAddress, chainId, tokenSymbol) {
3633
+ let portfolio;
3634
+ try {
3635
+ ({ portfolio } = await this.getPortfolio(userAddress));
3636
+ } catch {
3637
+ return;
3638
+ }
3639
+ const blocking = findBlockingAsyncRedemption(
3640
+ portfolio,
3641
+ chainId,
3642
+ tokenSymbol
3643
+ );
3644
+ if (!blocking) return;
3645
+ const eta = blocking.estimatedClaimAt ? ` Estimated settlement: ${blocking.estimatedClaimAt}.` : "";
3646
+ throw new Error(
3647
+ `A redemption is already in flight for ${blocking.token?.symbol ?? "this asset"} on ${blocking.pool ?? "the pool"} (status ${blocking.status}), and async pools allow only one at a time. Wait for it to reach CLAIMED before withdrawing the rest.${eta}`
3648
+ );
3649
+ }
3650
+ /**
3651
+ * Get available DeFi protocols and pools for a specific chain.
3652
+ *
3653
+ * @group Portfolio and execution
3654
+ *
3655
+ * @remarks Execution API. Partner API key only.
2967
3656
  *
2968
3657
  * @param chainId - Target chain ID
2969
3658
  * @returns List of available protocols with their pools and APY data
2970
3659
  *
3660
+ * @throws If `chainId` is unsupported
3661
+ *
2971
3662
  * @example
2972
3663
  * ```typescript
2973
3664
  * const protocols = await sdk.getAvailableProtocols(8453);
@@ -2996,11 +3687,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2996
3687
  }
2997
3688
  }
2998
3689
  /**
2999
- * Get all active DeFi positions for a user
3690
+ * Get active DeFi positions for a user.
3691
+ *
3692
+ * @group Portfolio and execution
3693
+ *
3694
+ * @remarks Execution API (`/data/position`). Pass the **EOA**; the SDK resolves the Safe.
3000
3695
  *
3001
3696
  * @param userAddress - User's EOA address
3002
- * @param chainId - Optional chain used to resolve the Safe address (defaults to Base 8453)
3003
- * @returns User's positions across all protocols
3697
+ * @param chainId - Chain used to resolve the Safe (defaults to Base `8453`)
3698
+ * @returns User's positions across protocols
3004
3699
  *
3005
3700
  * @example
3006
3701
  * ```typescript
@@ -3080,9 +3775,16 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3080
3775
  * Do not add `CLAIMED` withdrawals either (the array keeps them for 24
3081
3776
  * hours); their funds are back in the Safe and already counted.
3082
3777
  *
3778
+ * @group Portfolio and execution
3779
+ *
3780
+ * @remarks Data API portfolio endpoint. See {@link PortfolioDetailed.pendingAsyncWithdrawals}
3781
+ * when using {@link Strategy | yieldmaxxing}.
3782
+ *
3083
3783
  * @param userAddress - User's EOA address
3084
3784
  * @returns Portfolio with optional fee-adjusted balance fields
3085
3785
  *
3786
+ * @throws If `userAddress` is missing
3787
+ *
3086
3788
  * @example
3087
3789
  * ```typescript
3088
3790
  * const { portfolio } = await sdk.getPortfolio(userAddress);
@@ -3137,10 +3839,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3137
3839
  // User Details Methods
3138
3840
  // ============================================================================
3139
3841
  /**
3140
- * Get current authenticated user details
3141
- * Requires SIWE authentication
3842
+ * Get the authenticated user's profile for an asset.
3843
+ *
3844
+ * @group Portfolio and execution
3845
+ *
3846
+ * @remarks Execution API. Requires {@link ZyfaiSDK.connectAccount} (SIWE).
3142
3847
  *
3143
- * @returns User details including smart wallet, chains, protocols, etc.
3848
+ * @param asset - Asset slice of the profile to return
3849
+ * @defaultValue `"USDC"`
3850
+ * @returns User details including smart wallet, chains, and protocols
3144
3851
  *
3145
3852
  * @example
3146
3853
  * ```typescript
@@ -3187,9 +3894,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3187
3894
  // TVL & Volume Methods
3188
3895
  // ============================================================================
3189
3896
  /**
3190
- * Get total value locked (TVL) across all Zyfai accounts
3897
+ * Get total value locked (TVL) across all Zyfai accounts.
3191
3898
  *
3192
- * @returns Total TVL in USD and breakdown by chain
3899
+ * @group Analytics and opportunities
3900
+ *
3901
+ * @remarks Data API. Partner API key only; SIWE not required.
3902
+ *
3903
+ * @returns Total TVL in USD
3193
3904
  *
3194
3905
  * @example
3195
3906
  * ```typescript
@@ -3212,7 +3923,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3212
3923
  // APY Per Strategy Methods
3213
3924
  // ============================================================================
3214
3925
  /**
3215
- * Get APY per strategy for a specific chain
3926
+ * Get APY per strategy for a specific chain.
3927
+ *
3928
+ * @group Analytics and opportunities
3929
+ *
3930
+ * @remarks Data API. Partner API key only.
3216
3931
  *
3217
3932
  * @param crossChain - Whether to get cross-chain APY (true = omni account, false = simple account)
3218
3933
  * @param days - Time period: 7, 14, or 30
@@ -3255,7 +3970,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3255
3970
  }
3256
3971
  }
3257
3972
  /**
3258
- * Get total volume across all Zyfai accounts
3973
+ * Get total volume across all Zyfai accounts.
3974
+ *
3975
+ * @group Analytics and opportunities
3976
+ *
3977
+ * @remarks Data API. Partner API key only.
3259
3978
  *
3260
3979
  * @returns Total volume in USD
3261
3980
  *
@@ -3267,7 +3986,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3267
3986
  */
3268
3987
  async getVolume(assetType = "usdc") {
3269
3988
  try {
3270
- const response = await this.httpClient.get(ENDPOINTS.DATA_VOLUME(assetType));
3989
+ const response = await this.httpClient.get(
3990
+ ENDPOINTS.DATA_VOLUME(assetType)
3991
+ );
3271
3992
  return {
3272
3993
  success: true,
3273
3994
  volumeInUSD: response.volumeInUSD || "0"
@@ -3280,7 +4001,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3280
4001
  // Active Wallets Methods
3281
4002
  // ============================================================================
3282
4003
  /**
3283
- * Get active wallets for a specific chain
4004
+ * Get active wallets for a specific chain.
4005
+ *
4006
+ * @group Analytics and opportunities
4007
+ *
4008
+ * @remarks Data API. Partner API key only.
3284
4009
  *
3285
4010
  * @param chainId - Chain ID to filter wallets
3286
4011
  * @returns List of active wallets on the specified chain
@@ -3317,7 +4042,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3317
4042
  }
3318
4043
  }
3319
4044
  /**
3320
- * Get smart wallets associated with an EOA address
4045
+ * Get smart wallets associated with an EOA address.
4046
+ *
4047
+ * @group Analytics and opportunities
4048
+ *
4049
+ * @remarks Data API. Partner API key only.
3321
4050
  *
3322
4051
  * @param eoaAddress - EOA (externally owned account) address
3323
4052
  * @returns List of smart wallets owned by the EOA
@@ -3354,7 +4083,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3354
4083
  // First Topup & History Methods
3355
4084
  // ============================================================================
3356
4085
  /**
3357
- * Get the first topup (deposit) information for a wallet
4086
+ * Get the first topup (deposit) information for a wallet.
4087
+ *
4088
+ * @group Analytics and opportunities
4089
+ *
4090
+ * @remarks Data API. Partner API key only.
3358
4091
  *
3359
4092
  * @param walletAddress - Smart wallet address
3360
4093
  * @param chainId - Chain ID
@@ -3389,7 +4122,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3389
4122
  }
3390
4123
  }
3391
4124
  /**
3392
- * Get transaction history for a wallet
4125
+ * Get transaction history for a wallet.
4126
+ *
4127
+ * @group Analytics and opportunities
4128
+ *
4129
+ * @remarks Data API. Partner API key only.
3393
4130
  *
3394
4131
  * @param walletAddress - Smart wallet address
3395
4132
  * @param chainId - Chain ID
@@ -3445,11 +4182,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3445
4182
  // Onchain Earnings Methods (Data API v2)
3446
4183
  // ============================================================================
3447
4184
  /**
3448
- * Get onchain earnings for a wallet
4185
+ * Get onchain earnings for a wallet.
4186
+ *
4187
+ * @group Analytics and opportunities
4188
+ *
4189
+ * @remarks Data API. Partner API key only.
3449
4190
  *
3450
4191
  * Includes gross totals plus net-of-fee totals:
3451
- * `totalEarningsByTokenWithFee = lifetime + unrealized + current × (1 - feeRate)`.
3452
- * Lifetime and unrealized are never multiplied by the keep-rate.
4192
+ * `totalEarningsByTokenWithFee = (lifetime + unrealized + current) × (1 - feeRate)`.
4193
+ * Ledger buckets are gross, so the keep-rate applies to all three.
3453
4194
  *
3454
4195
  * @param walletAddress - Smart wallet address
3455
4196
  * @returns Onchain earnings data with per-token breakdowns
@@ -3598,7 +4339,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3598
4339
  // Opportunities Methods (Data API v2)
3599
4340
  // ============================================================================
3600
4341
  /**
3601
- * Get conservative (low-risk) yield opportunities
4342
+ * Get conservative (low-risk) yield opportunities.
4343
+ *
4344
+ * @group Analytics and opportunities
4345
+ *
4346
+ * @remarks Data API. Partner API key only.
3602
4347
  *
3603
4348
  * @param chainId - Optional chain ID filter
3604
4349
  * @param asset - Optional asset filter (e.g. "USDC", "WETH", "WBTC")
@@ -4044,9 +4789,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4044
4789
  }
4045
4790
  };
4046
4791
  } catch (error) {
4047
- throw new Error(
4048
- `Failed to get SDK key TVL: ${error.message}`
4049
- );
4792
+ throw new Error(`Failed to get SDK key TVL: ${error.message}`);
4050
4793
  }
4051
4794
  }
4052
4795
  // ============================================================================
@@ -4058,6 +4801,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4058
4801
  * Allows granular control over which pools to use for each protocol on each chain.
4059
4802
  * This is useful for advanced users who want to target specific pools with desired APY/risk profiles.
4060
4803
  *
4804
+ * @group Customization and simulation
4805
+ *
4806
+ * @remarks Execution API. Requires {@link ZyfaiSDK.connectAccount} (SIWE).
4807
+ *
4061
4808
  * @param customizations - Array of customization configurations
4062
4809
  * @returns Response indicating success
4063
4810
  *
@@ -4086,6 +4833,65 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4086
4833
  * ]);
4087
4834
  * ```
4088
4835
  */
4836
+ /**
4837
+ * Get the user's agent management mandate (autonomy limits).
4838
+ *
4839
+ * @group Agent management
4840
+ */
4841
+ async getAgentMandate(oauthClientId) {
4842
+ await this.authenticateUser();
4843
+ const query = oauthClientId ? `?oauthClientId=${encodeURIComponent(oauthClientId)}` : "";
4844
+ return this.httpClient.get(
4845
+ `${ENDPOINTS.USER_AGENT_MANDATE}${query}`
4846
+ );
4847
+ }
4848
+ /**
4849
+ * Create or update the user's agent management mandate.
4850
+ *
4851
+ * @group Agent management
4852
+ */
4853
+ async setAgentMandate(request) {
4854
+ await this.authenticateUser();
4855
+ return this.httpClient.put(
4856
+ ENDPOINTS.USER_AGENT_MANDATE,
4857
+ request
4858
+ );
4859
+ }
4860
+ /**
4861
+ * Revoke the user's agent management mandate.
4862
+ *
4863
+ * @group Agent management
4864
+ */
4865
+ async revokeAgentMandate(oauthClientId) {
4866
+ await this.authenticateUser();
4867
+ return this.httpClient.delete(
4868
+ `${ENDPOINTS.USER_AGENT_MANDATE}?oauthClientId=${encodeURIComponent(oauthClientId)}`
4869
+ );
4870
+ }
4871
+ /**
4872
+ * Reserve a one-time action id before the user signs an ERC-20 transfer.
4873
+ *
4874
+ * @group Agent management
4875
+ */
4876
+ async createAgentEnterIntent(request) {
4877
+ await this.authenticateUser();
4878
+ return this.httpClient.post(
4879
+ ENDPOINTS.USER_AGENT_ENTER_INTENTS,
4880
+ request
4881
+ );
4882
+ }
4883
+ /**
4884
+ * Consume a one-time action id when registering the signed deposit.
4885
+ *
4886
+ * @group Agent management
4887
+ */
4888
+ async consumeAgentEnterIntent(actionId, request) {
4889
+ await this.authenticateUser();
4890
+ await this.httpClient.post(
4891
+ ENDPOINTS.USER_AGENT_ENTER_INTENT_CONSUME(actionId),
4892
+ request
4893
+ );
4894
+ }
4089
4895
  async customizeBatch(customizations) {
4090
4896
  try {
4091
4897
  await this.authenticateUser();
@@ -4105,8 +4911,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4105
4911
  *
4106
4912
  * Returns the list of pools available for a given protocol, optionally filtered by strategy.
4107
4913
  *
4914
+ * @group Customization and simulation
4915
+ *
4916
+ * @remarks Execution API. Partner API key only.
4917
+ *
4108
4918
  * @param protocolId - The protocol UUID
4109
- * @param strategy - Optional strategy filter ("conservative", "aggressive" or "yieldmaxxing")
4919
+ * @param strategy - Optional {@link Strategy} filter
4110
4920
  * @returns List of available pool names
4111
4921
  *
4112
4922
  * @example
@@ -4154,7 +4964,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4154
4964
  * calldata contains a "<RECEIVER>" placeholder that must be replaced with the
4155
4965
  * actual receiving address (e.g. the user's Safe) before sending the transaction.
4156
4966
  *
4157
- * @param params - Simulation parameters
4967
+ * @group Customization and simulation
4968
+ *
4969
+ * @remarks Data API simulation endpoint. Partner API key only.
4970
+ *
4971
+ * @param params - {@link SimulateBestPositionsParams}
4158
4972
  * @returns Chain-keyed map of simulated positions with calldata
4159
4973
  *
4160
4974
  * @example
@@ -4197,6 +5011,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4197
5011
  * Returns the pools that are currently configured for the authenticated user
4198
5012
  * for a given protocol and chain combination.
4199
5013
  *
5014
+ * @group Customization and simulation
5015
+ *
5016
+ * @remarks Execution API. Requires {@link ZyfaiSDK.connectAccount} (SIWE).
5017
+ *
4200
5018
  * @param protocolId - The protocol UUID
4201
5019
  * @param chainId - The chain ID
4202
5020
  * @returns Currently selected pools and autoselect status
@@ -4229,7 +5047,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4229
5047
  * Check if a chain ID supports the Identity Registry
4230
5048
  */
4231
5049
  isSupportedIdentityRegistryChain(chainId) {
4232
- return _ZyfaiSDK.IDENTITY_REGISTRY_CHAIN_IDS.includes(chainId);
5050
+ return _ZyfaiSDK.IDENTITY_REGISTRY_CHAIN_IDS.includes(
5051
+ chainId
5052
+ );
4233
5053
  }
4234
5054
  /**
4235
5055
  * Register an agent on the Identity Registry (ERC-8004)
@@ -4302,10 +5122,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4302
5122
  // Vault Methods (Base only)
4303
5123
  // ============================================
4304
5124
  /**
4305
- * Deposit assets into the Zyfai Vault
4306
- * Currently only supports USDC on Base chain
5125
+ * Deposit assets into the Zyfai Vault (USDC on Base by default).
5126
+ *
5127
+ * @group Vault
4307
5128
  *
4308
- * @param amount - Amount to deposit (in human readable format, e.g., "100" for 100 USDC)
5129
+ * @remarks On-chain vault flow via connected wallet. Requires {@link ZyfaiSDK.connectAccount}.
5130
+ *
5131
+ * @param amount - Human-readable amount (e.g. `"100"` USDC)
4309
5132
  * @param asset - Asset to deposit (default: "USDC")
4310
5133
  * @returns Deposit transaction result
4311
5134
  *
@@ -4326,7 +5149,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4326
5149
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
4327
5150
  const tokenAddress = getDefaultTokenAddress(chainId, asset);
4328
5151
  const decimals = 6;
4329
- const parsedAmount = BigInt(Math.floor(parseFloat(amount) * 10 ** decimals));
5152
+ const parsedAmount = BigInt(
5153
+ Math.floor(parseFloat(amount) * 10 ** decimals)
5154
+ );
4330
5155
  try {
4331
5156
  const allowance = await chainConfig.publicClient.readContract({
4332
5157
  address: tokenAddress,
@@ -4404,7 +5229,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4404
5229
  args: [userAddress]
4405
5230
  });
4406
5231
  if (maxShares === 0n) {
4407
- throw new Error("No shares available to redeem or withdrawals are paused");
5232
+ throw new Error(
5233
+ "No shares available to redeem or withdrawals are paused"
5234
+ );
4408
5235
  }
4409
5236
  sharesToRedeem = maxShares;
4410
5237
  }
@@ -4448,7 +5275,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4448
5275
  status: isClaimable ? "claimable" : "pending"
4449
5276
  };
4450
5277
  } catch (error) {
4451
- throw new Error(`Vault withdraw request failed: ${error.message}`);
5278
+ throw new Error(
5279
+ `Vault withdraw request failed: ${error.message}`
5280
+ );
4452
5281
  }
4453
5282
  }
4454
5283
  /**
@@ -4528,7 +5357,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4528
5357
  nonce
4529
5358
  };
4530
5359
  } catch (error) {
4531
- throw new Error(`Failed to get withdraw status: ${error.message}`);
5360
+ throw new Error(
5361
+ `Failed to get withdraw status: ${error.message}`
5362
+ );
4532
5363
  }
4533
5364
  }
4534
5365
  /**
@@ -4571,7 +5402,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4571
5402
  if (isClaimed) {
4572
5403
  throw new Error("This withdrawal has already been claimed");
4573
5404
  }
4574
- throw new Error("Withdrawal is not yet claimable. Please wait for processing.");
5405
+ throw new Error(
5406
+ "Withdrawal is not yet claimable. Please wait for processing."
5407
+ );
4575
5408
  }
4576
5409
  const claimTx = await this.walletClient.writeContract({
4577
5410
  address: VAULT_ADDRESS,
@@ -4611,7 +5444,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4611
5444
  async getVaultShares(userAddress, chainId = 8453) {
4612
5445
  const address = userAddress || this.walletClient?.account?.address;
4613
5446
  if (!address) {
4614
- throw new Error("User address required. Provide address or connect wallet first.");
5447
+ throw new Error(
5448
+ "User address required. Provide address or connect wallet first."
5449
+ );
4615
5450
  }
4616
5451
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
4617
5452
  const [shareBalance, tokenSymbol] = await Promise.all([
@@ -4642,9 +5477,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4642
5477
  * Events: depeg, liquidity_trap, liquidity_restored, pool_status_change,
4643
5478
  * new_collateral_detected, liquidity_drop.
4644
5479
  *
4645
- * @param handlers - Callback per event type, plus onError
4646
- * @param filters - Optional protocol/pool filter sent to the server on subscribe
4647
- * @returns Cleanup function — call it to close the connection
5480
+ * @group Realtime events
5481
+ *
5482
+ * @remarks Connects to defi-api WebSocket (`WS_ENDPOINT`). Auto-reconnects every 3s until
5483
+ * the returned cleanup function is called.
5484
+ *
5485
+ * @param handlers - {@link ZyfaiEventHandlers}
5486
+ * @param filters - Optional {@link ZyfaiEventFilters} sent on subscribe
5487
+ * @returns Cleanup function — call it to close the connection and stop reconnecting
4648
5488
  *
4649
5489
  * @example
4650
5490
  * ```typescript