@zyfai/sdk 0.2.57 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -114,7 +114,8 @@ var ENDPOINTS = {
114
114
  USER_ME: "/users/me",
115
115
  USER_WITHDRAW: "/users/withdraw",
116
116
  PARTIAL_WITHDRAW: "/users/partial-withdraw",
117
- LOG_DEPOSIT: "/users/log_deposit",
117
+ LOG_DEPOSIT: "/users/log_deposit/v2",
118
+ DEPOSIT_STATUS: (depositId) => `/users/deposits/${depositId}`,
118
119
  // Safe Deployment (single endpoint)
119
120
  SAFE_DEPLOY: "/users/safe-deploy",
120
121
  // Multichain deploy for predeployed (pool) wallets — deploys + rotates the
@@ -419,26 +420,30 @@ var HttpClient = class {
419
420
  }
420
421
  };
421
422
 
422
- // src/utils/eth-price.ts
423
+ // src/utils/poll.ts
424
+ function sleep(ms) {
425
+ return new Promise((resolve) => setTimeout(resolve, ms));
426
+ }
427
+
428
+ // src/utils/token-price.ts
423
429
  var PRICE_SCALE = 8;
424
- var parseEthUsdPrice = (response) => {
430
+ var parseTokenUsdPrice = (response) => {
425
431
  const priceUsd = response?.data?.price_usd;
426
432
  if (typeof priceUsd !== "number" || !Number.isFinite(priceUsd) || priceUsd <= 0) {
427
- throw new Error("ETH/USD price must be a positive number");
433
+ throw new Error("Token USD price must be a positive number");
428
434
  }
429
435
  return priceUsd;
430
436
  };
431
- var usdToWethWei = (usdAmount, ethUsd) => {
432
- if (!Number.isFinite(ethUsd) || ethUsd <= 0) {
433
- throw new Error("ETH/USD price must be positive");
437
+ var usdToTokenUnits = (usdAmount, priceUsd, decimals) => {
438
+ if (!Number.isFinite(priceUsd) || priceUsd <= 0) {
439
+ throw new Error("Token USD price must be positive");
434
440
  }
435
- const scaledPrice = BigInt(Math.round(ethUsd * 10 ** PRICE_SCALE));
441
+ const scaledPrice = BigInt(Math.round(priceUsd * 10 ** PRICE_SCALE));
436
442
  if (scaledPrice <= 0n) {
437
- throw new Error("ETH/USD price must be positive");
443
+ throw new Error("Token USD price must be positive");
438
444
  }
439
- return usdAmount * 10n ** 18n * 10n ** BigInt(PRICE_SCALE) / scaledPrice;
445
+ return usdAmount * 10n ** BigInt(decimals) * 10n ** BigInt(PRICE_SCALE) / scaledPrice;
440
446
  };
441
- var minWethWeiForUsd = (ethUsd, usdAmount) => usdToWethWei(usdAmount, ethUsd);
442
447
 
443
448
  // src/config/abis.ts
444
449
  var import_viem = require("viem");
@@ -631,11 +636,26 @@ var MIN_PORTFOLIO_BALANCE = {
631
636
  // 100 EURC (6 decimals)
632
637
  }
633
638
  };
634
- var MIN_WETH_USD = {
635
- 1: 10000n,
636
- 8453: 100n,
637
- 42161: 100n
639
+ var MIN_PORTFOLIO_USD = {
640
+ 1: { WETH: 10000n },
641
+ 8453: { WETH: 100n, NVDAc: 100n },
642
+ 42161: { WETH: 100n }
643
+ };
644
+ var DEPOSIT_CREDIT_INTERVAL_MS = {
645
+ 1: 2e3,
646
+ 8453: 500,
647
+ 42161: 250
638
648
  };
649
+ var DEPOSIT_CREDIT_TIMEOUT_MS = {
650
+ 1: 6e4,
651
+ // 1 minute
652
+ 8453: 2e4,
653
+ // ~10 Base blocks
654
+ 42161: 2e4
655
+ // ~10 Arbitrum blocks
656
+ };
657
+ var getDepositCreditIntervalMs = (chainId) => DEPOSIT_CREDIT_INTERVAL_MS[chainId];
658
+ var getDepositCreditTimeoutMs = (chainId) => DEPOSIT_CREDIT_TIMEOUT_MS[chainId];
639
659
  var formatMinPortfolioLabel = (raw, decimals, symbol) => {
640
660
  const base2 = 10n ** BigInt(decimals);
641
661
  const whole = raw / base2;
@@ -647,6 +667,25 @@ var formatMinPortfolioLabel = (raw, decimals, symbol) => {
647
667
  return `${whole.toString()}.${fractionStr} ${symbol}`;
648
668
  };
649
669
 
670
+ // src/config/local-dev.ts
671
+ function isLocalExecutionApiUrl(executionApiUrl) {
672
+ if (executionApiUrl === EXECUTION_API_BASE_URLS.local) {
673
+ return true;
674
+ }
675
+ try {
676
+ const { hostname } = new URL(executionApiUrl);
677
+ return hostname === "localhost" || hostname === "127.0.0.1";
678
+ } catch {
679
+ return false;
680
+ }
681
+ }
682
+ function shouldBypassMinPortfolioCheck(executionApiUrl) {
683
+ if (process.env.NODE_ENV === "production") {
684
+ return false;
685
+ }
686
+ return isLocalExecutionApiUrl(executionApiUrl);
687
+ }
688
+
650
689
  // src/core/ZyfaiSDK.ts
651
690
  var import_accounts2 = require("viem/accounts");
652
691
  var import_viem4 = require("viem");
@@ -697,6 +736,8 @@ var ASSET_CONFIGS = {
697
736
  displayName: "WETH",
698
737
  icon: "/ai-dashboard/eth-token.png",
699
738
  decimals: 18,
739
+ // Data API `/price?token=` identifier, used for USD-denominated minimums.
740
+ priceTokenSymbol: "eth",
700
741
  tokenSymbols: ["WETH", "ETH"],
701
742
  tokenSymbolsByChainId: {
702
743
  1: "WETH",
@@ -737,8 +778,39 @@ var ASSET_CONFIGS = {
737
778
  // Base
738
779
  },
739
780
  enabled: true
781
+ },
782
+ // Coinbase B20 tokenized NVIDIA equity. Base only, and only reachable through
783
+ // protocols with delayed withdrawals — see the `yieldmaxxing` strategy.
784
+ NVDAc: {
785
+ symbol: "NVDAc",
786
+ assetType: "nvdac",
787
+ displayName: "NVIDIA",
788
+ icon: "https://metadata.coinbase.com/equity_icons/1fee9b7a44e800d438dd9d96c3283e05784c925c2c871a48ff735950740b551a.png",
789
+ decimals: 8,
790
+ priceTokenSymbol: "nvdac",
791
+ tokenSymbols: ["NVDAc"],
792
+ tokenSymbolsByChainId: {
793
+ 8453: "NVDAc"
794
+ },
795
+ addresses: {
796
+ 8453: "0xb20000000000000000000078ee7ce2fE4908108C"
797
+ // Base
798
+ },
799
+ enabled: true
740
800
  }
741
801
  };
802
+ var resolveAssetSymbol = (asset) => {
803
+ const match = Object.keys(ASSET_CONFIGS).find(
804
+ (key) => key.toLowerCase() === asset.toLowerCase()
805
+ );
806
+ if (!match) {
807
+ throw new Error(
808
+ `Unsupported asset: ${asset}. Supported: ${Object.keys(ASSET_CONFIGS).join(", ")}.`
809
+ );
810
+ }
811
+ return match;
812
+ };
813
+ var getAssetChainIds = (asset) => Object.keys(ASSET_CONFIGS[asset]?.addresses ?? {}).map(Number).filter((chainId) => chainId in CHAINS);
742
814
  var getDefaultTokenAddress = (chainId, asset) => {
743
815
  const address = ASSET_CONFIGS[asset || "USDC"]?.addresses[chainId];
744
816
  if (!address || address === "0x0000000000000000000000000000000000000000") {
@@ -1014,6 +1086,7 @@ var signSessionKey = async (config, sessions, allPublicClients, signingParams) =
1014
1086
 
1015
1087
  // src/utils/strategy.ts
1016
1088
  var PUBLIC_STRATEGIES = `"conservative", "aggressive" or "yieldmaxxing"`;
1089
+ var SUPPORTED_ASSETS = `"USDC", "WETH", "EURC" or "NVDAc"`;
1017
1090
  function toInternalStrategy(publicStrategy) {
1018
1091
  switch (publicStrategy) {
1019
1092
  case "conservative":
@@ -1102,8 +1175,11 @@ function convertAssetInternally(asset) {
1102
1175
  if (asset === "EURC") {
1103
1176
  return "eurc";
1104
1177
  }
1178
+ if (asset === "NVDAc") {
1179
+ return "nvdac";
1180
+ }
1105
1181
  throw new Error(
1106
- `Invalid asset: ${asset}. Must be "USDC", "WETH", or "EURC".`
1182
+ `Invalid asset: ${asset}. Must be ${SUPPORTED_ASSETS}.`
1107
1183
  );
1108
1184
  }
1109
1185
  function convertStrategiesToPublic(array) {
@@ -1526,8 +1602,34 @@ function enrichOnchainEarningsTotals(apiData) {
1526
1602
  };
1527
1603
  }
1528
1604
 
1605
+ // src/utils/async-withdrawals.ts
1606
+ var findBlockingAsyncRedemption = (portfolio, chainId, tokenSymbol) => {
1607
+ const matchesToken = (symbol) => !tokenSymbol || symbol?.toLowerCase() === tokenSymbol.toLowerCase();
1608
+ const blocked = (portfolio.pendingAsyncWithdrawals ?? []).filter(
1609
+ (w) => w.chainId === chainId && (w.status === "REQUESTED" || w.status === "CLAIMABLE") && matchesToken(w.token?.symbol)
1610
+ );
1611
+ if (blocked.length === 0) return void 0;
1612
+ const blockedPools = new Set(
1613
+ blocked.map((w) => w.pool?.toLowerCase()).filter(Boolean)
1614
+ );
1615
+ const hasFreePosition = (portfolio.positions ?? []).some(
1616
+ (p) => matchesToken(p.token_symbol) && Number(chainNameToId(p.chain ?? "")) === chainId && !blockedPools.has(p.pool?.toLowerCase() ?? "")
1617
+ );
1618
+ const hasIdleBalance = (portfolio.staleBalances ?? []).some(
1619
+ (b) => b.chainId === chainId && matchesToken(b.tokenSymbol) && BigInt(b.balance ?? "0") > 0n
1620
+ );
1621
+ return hasFreePosition || hasIdleBalance ? void 0 : blocked[0];
1622
+ };
1623
+
1529
1624
  // src/core/ZyfaiSDK.ts
1530
1625
  var import_siwe = require("siwe");
1626
+ var DepositCreditTimeoutError = class extends Error {
1627
+ constructor(depositId) {
1628
+ super(`Timed out waiting for deposit ${depositId} to be credited`);
1629
+ this.name = "DepositCreditTimeoutError";
1630
+ }
1631
+ };
1632
+ var MANAGED_ASSETS = ["USDC", "WETH", "EURC", "NVDAc"];
1531
1633
  var _ZyfaiSDK = class _ZyfaiSDK {
1532
1634
  constructor(config) {
1533
1635
  this.signer = null;
@@ -1544,12 +1646,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1544
1646
  rpcUrls,
1545
1647
  referralSource,
1546
1648
  executionApiUrl,
1547
- dataApiUrl
1649
+ dataApiUrl,
1650
+ bypassMinPortfolio
1548
1651
  } = sdkConfig;
1549
1652
  if (!apiKey) {
1550
1653
  throw new Error("API key is required");
1551
1654
  }
1552
1655
  this.executionApiUrl = executionApiUrl ?? API_ENDPOINT;
1656
+ this.bypassMinPortfolio = bypassMinPortfolio ?? shouldBypassMinPortfolioCheck(this.executionApiUrl);
1553
1657
  this.httpClient = new HttpClient(apiKey, {
1554
1658
  executionApiUrl: this.executionApiUrl,
1555
1659
  dataApiUrl
@@ -1558,12 +1662,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1558
1662
  this.referralSource = referralSource;
1559
1663
  }
1560
1664
  /**
1561
- * Warn that a legacy method is deprecated in favor of depositFunds.
1665
+ * Warn that a legacy method is deprecated in favor of sendDeposit.
1562
1666
  * Predeployed wallets no longer require deploySafe / createSessionKey.
1563
1667
  */
1564
1668
  warnDeprecatedOnboardingMethod(methodName) {
1565
1669
  console.warn(
1566
- `[ZyfaiSDK] ${methodName}() is deprecated for partner integrations. Prefer depositFunds() \u2014 predeployed Safes and session keys are handled automatically on first deposit.`
1670
+ `[ZyfaiSDK] ${methodName}() is deprecated for partner integrations. Prefer sendDeposit() \u2014 predeployed Safes and session keys are handled automatically on first deposit.`
1567
1671
  );
1568
1672
  }
1569
1673
  /**
@@ -1667,25 +1771,31 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1667
1771
  rebalanceStrategy = toInternalStrategy(request.strategy);
1668
1772
  }
1669
1773
  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;
1774
+ if (rebalanceStrategy !== void 0)
1775
+ assetSettings.rebalanceStrategy = rebalanceStrategy;
1776
+ if (request.autocompounding !== void 0)
1777
+ assetSettings.autocompounding = request.autocompounding;
1778
+ if (request.crosschainStrategy !== void 0)
1779
+ assetSettings.crosschainStrategy = request.crosschainStrategy;
1780
+ if (request.splitting !== void 0)
1781
+ assetSettings.splitting = request.splitting;
1782
+ if (request.minSplits !== void 0)
1783
+ assetSettings.minSplits = request.minSplits;
1675
1784
  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;
1785
+ if (request.autoSelectProtocols !== void 0)
1786
+ assetSettings.autoSelectProtocols = request.autoSelectProtocols;
1787
+ if (request.protocols !== void 0)
1788
+ assetSettings.protocols = request.protocols;
1678
1789
  const payload = {
1679
1790
  assetTypeSettings: {
1680
1791
  [internalAsset]: assetSettings
1681
1792
  }
1682
1793
  };
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
- );
1794
+ if (request.omniAccount !== void 0)
1795
+ payload.omniAccount = request.omniAccount;
1796
+ if (request.agentName !== void 0)
1797
+ payload.agentName = request.agentName;
1798
+ await this.httpClient.patch(ENDPOINTS.USER_ME, payload);
1689
1799
  return await this.getUserDetails(asset);
1690
1800
  } catch (error) {
1691
1801
  throw new Error(
@@ -1713,19 +1823,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1713
1823
  */
1714
1824
  async pauseAgent() {
1715
1825
  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;
1826
+ let latest;
1827
+ for (const asset of MANAGED_ASSETS) {
1828
+ latest = await this.updateUserProfile({ asset, protocols: [] });
1829
+ }
1830
+ if (!latest) {
1831
+ throw new Error("No supported assets to pause");
1832
+ }
1833
+ return latest;
1729
1834
  } catch (error) {
1730
1835
  throw new Error(`Failed to pause agent: ${error.message}`);
1731
1836
  }
@@ -1750,50 +1855,22 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1750
1855
  */
1751
1856
  async resumeAgent() {
1752
1857
  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
1858
  const allProtocols = await this.httpClient.get(
1759
1859
  ENDPOINTS.PROTOCOLS()
1760
1860
  );
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
- });
1861
+ let latest;
1862
+ for (const asset of MANAGED_ASSETS) {
1863
+ latest = await this.updateUserProtocolsForAsset(
1864
+ asset,
1865
+ getAssetChainIds(asset),
1866
+ void 0,
1867
+ allProtocols
1868
+ );
1869
+ }
1870
+ if (!latest) {
1871
+ throw new Error("No supported assets to resume");
1872
+ }
1873
+ return latest;
1797
1874
  } catch (error) {
1798
1875
  throw new Error(`Failed to resume agent: ${error.message}`);
1799
1876
  }
@@ -1828,7 +1905,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1828
1905
  });
1829
1906
  return response;
1830
1907
  } catch (error) {
1831
- throw new Error(`Failed to enable splitting: ${error.message}`);
1908
+ throw new Error(
1909
+ `Failed to enable splitting: ${error.message}`
1910
+ );
1832
1911
  }
1833
1912
  }
1834
1913
  /**
@@ -1856,7 +1935,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1856
1935
  });
1857
1936
  return response;
1858
1937
  } catch (error) {
1859
- throw new Error(`Failed to disable splitting: ${error.message}`);
1938
+ throw new Error(
1939
+ `Failed to disable splitting: ${error.message}`
1940
+ );
1860
1941
  }
1861
1942
  }
1862
1943
  /**
@@ -1888,7 +1969,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1888
1969
  });
1889
1970
  return response;
1890
1971
  } catch (error) {
1891
- throw new Error(`Failed to update min splits: ${error.message}`);
1972
+ throw new Error(
1973
+ `Failed to update min splits: ${error.message}`
1974
+ );
1892
1975
  }
1893
1976
  }
1894
1977
  /**
@@ -2186,7 +2269,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2186
2269
  /**
2187
2270
  * Deploy Safe Smart Wallet for a user
2188
2271
  *
2189
- * @deprecated Prefer `depositFunds()`. Predeployed Safes and session keys are
2272
+ * @deprecated Prefer `sendDeposit()`. Predeployed Safes and session keys are
2190
2273
  * managed automatically on first deposit. This method remains available for
2191
2274
  * legacy flows.
2192
2275
  *
@@ -2198,8 +2281,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2198
2281
  *
2199
2282
  * @example
2200
2283
  * ```typescript
2201
- * // Preferred: depositFunds handles predeployed wallet onboarding
2202
- * await sdk.depositFunds(userAddress, 8453, amount, "USDC");
2284
+ * // Preferred: sendDeposit handles predeployed wallet onboarding
2285
+ * const sent = await sdk.sendDeposit(userAddress, 8453, amount, "USDC");
2286
+ * await sdk.waitForDepositCredit(sent.registration.id, 8453);
2203
2287
  *
2204
2288
  * // Legacy: deploy with default conservative strategy
2205
2289
  * await sdk.deploySafe(userAddress, 8453);
@@ -2317,7 +2401,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2317
2401
  } catch (error) {
2318
2402
  console.error("Safe deployment failed:", error);
2319
2403
  throw new Error(
2320
- `Safe deployment failed: ${error.message}. deploySafe() is deprecated \u2014 prefer depositFunds() for predeployed wallet onboarding.`
2404
+ `Safe deployment failed: ${error.message}. deploySafe() is deprecated \u2014 prefer sendDeposit() for predeployed wallet onboarding.`
2321
2405
  );
2322
2406
  }
2323
2407
  }
@@ -2325,7 +2409,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2325
2409
  * Create session key with auto-fetched configuration from Zyfai API
2326
2410
  * This is the simplified method that automatically fetches session configuration
2327
2411
  *
2328
- * @deprecated Prefer `depositFunds()`. Predeployed wallets already have the
2412
+ * @deprecated Prefer `sendDeposit()`. Predeployed wallets already have the
2329
2413
  * agent session enabled; session activation is handled after first deposit.
2330
2414
  * This method remains available for legacy flows.
2331
2415
  *
@@ -2335,8 +2419,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2335
2419
  *
2336
2420
  * @example
2337
2421
  * ```typescript
2338
- * // Preferred: depositFunds handles session onboarding for predeployed wallets
2339
- * await sdk.depositFunds(userAddress, 8453, amount, "USDC");
2422
+ * // Preferred: sendDeposit handles session onboarding for predeployed wallets
2423
+ * const sent = await sdk.sendDeposit(userAddress, 8453, amount, "USDC");
2424
+ * await sdk.waitForDepositCredit(sent.registration.id, 8453);
2340
2425
  *
2341
2426
  * // Legacy:
2342
2427
  * const result = await sdk.createSessionKey(userAddress, 8453);
@@ -2417,7 +2502,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2417
2502
  };
2418
2503
  } catch (error) {
2419
2504
  throw new Error(
2420
- `Failed to create session key: ${error.message}. createSessionKey() is deprecated \u2014 prefer depositFunds() for predeployed wallet onboarding.`
2505
+ `Failed to create session key: ${error.message}. createSessionKey() is deprecated \u2014 prefer sendDeposit() for predeployed wallet onboarding.`
2421
2506
  );
2422
2507
  }
2423
2508
  }
@@ -2484,34 +2569,46 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2484
2569
  * asset/chain/strategy combo.
2485
2570
  * 4. Persist via `updateUserProfile` (writes `assetTypeSettings`).
2486
2571
  *
2487
- * Called from `deploySafe` after every path, and from `depositFunds` on
2572
+ * Called from `deploySafe` after every path, and from `sendDeposit` on
2488
2573
  * the account's first deposit (when USDC chains are still empty).
2489
2574
  *
2490
2575
  * @internal
2491
2576
  */
2492
- async updateUserProtocols(strategy) {
2577
+ async updateUserProtocols(strategy, options) {
2578
+ const strict = options?.strict ?? false;
2579
+ const assetErrors = [];
2493
2580
  try {
2494
2581
  const allProtocols = await this.httpClient.get(
2495
2582
  ENDPOINTS.PROTOCOLS()
2496
2583
  );
2497
- const allChains = [1, 8453, 42161];
2498
- const assets = ["USDC", "WETH", "EURC"];
2499
- for (const asset of assets) {
2584
+ for (const asset of MANAGED_ASSETS) {
2500
2585
  try {
2501
- const chainsForAsset = asset === "EURC" ? [1, 8453] : allChains;
2502
2586
  await this.updateUserProtocolsForAsset(
2503
2587
  asset,
2504
- chainsForAsset,
2588
+ getAssetChainIds(asset),
2505
2589
  strategy,
2506
2590
  allProtocols
2507
2591
  );
2508
2592
  } catch (assetError) {
2509
- console.warn(
2510
- `Failed to update ${asset} protocols: ${assetError.message}`
2511
- );
2593
+ const message = assetError.message;
2594
+ if (strict) {
2595
+ assetErrors.push(`${asset}: ${message}`);
2596
+ } else {
2597
+ console.warn(`Failed to update ${asset} protocols: ${message}`);
2598
+ }
2512
2599
  }
2513
2600
  }
2601
+ if (strict && assetErrors.length > 0) {
2602
+ throw new Error(
2603
+ `Failed to configure user protocols for first deposit: ${assetErrors.join(
2604
+ "; "
2605
+ )}`
2606
+ );
2607
+ }
2514
2608
  } catch (error) {
2609
+ if (strict) {
2610
+ throw error;
2611
+ }
2515
2612
  console.warn(
2516
2613
  `Failed to update user protocols: ${error.message}`
2517
2614
  );
@@ -2541,13 +2638,83 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2541
2638
  asset,
2542
2639
  internalStrategy
2543
2640
  );
2544
- await this.updateUserProfile({
2641
+ return await this.updateUserProfile({
2545
2642
  asset,
2546
2643
  protocols: withPools,
2547
2644
  chains: effectiveChains,
2548
2645
  ...strategy !== void 0 && { strategy }
2549
2646
  });
2550
2647
  }
2648
+ /**
2649
+ * Switch one asset to a strategy and select the protocols that go with it.
2650
+ *
2651
+ * `updateUserProfile` stores a strategy but does not compute a protocol
2652
+ * list, so on its own it leaves the asset with nothing to deploy into. This
2653
+ * method does both in one call: it resolves the protocols that support the
2654
+ * asset on the requested chains under the requested strategy, drops those
2655
+ * with no pool available, and persists strategy, chains and protocols
2656
+ * together.
2657
+ *
2658
+ * Mostly needed for assets that are not set up by the account's first
2659
+ * deposit, or to change an existing account's strategy — `sendDeposit`
2660
+ * ignores its `strategy` argument after the first deposit.
2661
+ *
2662
+ * @param params.asset - Asset to configure
2663
+ * @param params.strategy - Strategy to apply; defaults to the one already
2664
+ * stored for this asset (`"conservative"` on a fresh account), which lets
2665
+ * you recompute a protocol list without changing the strategy
2666
+ * @param params.chains - Chains to enable. Defaults to every chain the asset
2667
+ * exists on. **Additive**: chains already enabled are kept, so this cannot
2668
+ * be used to disable one.
2669
+ * @returns The updated profile for that asset
2670
+ *
2671
+ * @example
2672
+ * ```typescript
2673
+ * // NVDAc only lives in async protocols, so it needs "yieldmaxxing".
2674
+ * // Chains default to Base, the only chain it exists on.
2675
+ * const profile = await sdk.setAssetStrategy({
2676
+ * asset: "NVDAc",
2677
+ * strategy: "yieldmaxxing",
2678
+ * });
2679
+ * console.log(profile.protocols); // Ipor + Superform
2680
+ * ```
2681
+ */
2682
+ async setAssetStrategy(params) {
2683
+ const { asset, strategy, chains } = params;
2684
+ try {
2685
+ if (strategy !== void 0 && !isValidPublicStrategy(strategy)) {
2686
+ throw new Error(
2687
+ `Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
2688
+ );
2689
+ }
2690
+ const supported = getAssetChainIds(asset);
2691
+ if (supported.length === 0) {
2692
+ throw new Error(`Unsupported asset: ${asset}.`);
2693
+ }
2694
+ const targetChains = chains ?? supported;
2695
+ const unsupported = targetChains.filter((c) => !supported.includes(c));
2696
+ if (unsupported.length > 0) {
2697
+ throw new Error(
2698
+ `${asset} is not available on chain ${unsupported.join(
2699
+ ", "
2700
+ )}. Supported chains: ${supported.join(", ")}.`
2701
+ );
2702
+ }
2703
+ const allProtocols = await this.httpClient.get(
2704
+ ENDPOINTS.PROTOCOLS()
2705
+ );
2706
+ return await this.updateUserProtocolsForAsset(
2707
+ asset,
2708
+ targetChains,
2709
+ strategy,
2710
+ allProtocols
2711
+ );
2712
+ } catch (error) {
2713
+ throw new Error(
2714
+ `Failed to set ${asset} strategy: ${error.message}`
2715
+ );
2716
+ }
2717
+ }
2551
2718
  /**
2552
2719
  * Drop protocols that have no pools on any of the selected chains for the
2553
2720
  * requested asset. The /customization/pools endpoint filters server-side on
@@ -2602,55 +2769,6 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2602
2769
  return value;
2603
2770
  });
2604
2771
  }
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
2772
  /**
2655
2773
  * Deploy the connected predeployed (pool) wallet on one or more chains.
2656
2774
  *
@@ -2661,7 +2779,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2661
2779
  * resolves once all requested chains have landed on-chain. Idempotent — chains
2662
2780
  * already deployed are a no-op.
2663
2781
  *
2664
- * Optional for deposits: `depositFunds` no longer pre-deploys the target chain — the ERC20
2782
+ * Optional for deposits: `sendDeposit` no longer pre-deploys the target chain — the ERC20
2665
2783
  * transfer lands on the counterfactual address and the backend deploys + hands over on first
2666
2784
  * deposit (report-deposit). Use this only to pre-provision chains ahead of time.
2667
2785
  *
@@ -2677,7 +2795,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2677
2795
  await this.authenticateUser();
2678
2796
  return this.httpClient.post(ENDPOINTS.DEPLOY_CHAINS, { chainIds });
2679
2797
  }
2680
- async depositFunds(userAddress, chainId, amount, asset, strategy) {
2798
+ /**
2799
+ * Send a deposit from an EOA to its Safe smart wallet.
2800
+ *
2801
+ * Confirms the ERC-20 transfer and starts the custody-credit lifecycle. Use
2802
+ * `waitForDepositCredit(result.registration.id, chainId)` to await credit.
2803
+ */
2804
+ async sendDeposit(userAddress, chainId, amount, asset, strategy) {
2681
2805
  try {
2682
2806
  if (!userAddress) {
2683
2807
  throw new Error("User address is required");
@@ -2696,35 +2820,51 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2696
2820
  `Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
2697
2821
  );
2698
2822
  }
2699
- const assetSymbol = asset.toUpperCase();
2823
+ const assetSymbol = resolveAssetSymbol(asset);
2700
2824
  const assetConfig = ASSET_CONFIGS[assetSymbol];
2701
- if (!assetConfig) {
2825
+ const assetChains = getAssetChainIds(assetSymbol);
2826
+ if (!assetChains.includes(chainId)) {
2702
2827
  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]
2828
+ `${assetSymbol} is not available on chain ${chainId}. Supported chains: ${assetChains.join(
2829
+ ", "
2830
+ )}.`
2714
2831
  );
2715
2832
  }
2833
+ let minRequired = this.bypassMinPortfolio ? void 0 : MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
2834
+ const minUsd = this.bypassMinPortfolio ? void 0 : MIN_PORTFOLIO_USD[chainId]?.[assetSymbol];
2716
2835
  const token = getDefaultTokenAddress(chainId, assetSymbol);
2717
2836
  const walletClient = this.getWalletClient();
2718
- await this.authenticateUser();
2719
2837
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
2838
+ if (minUsd !== void 0) {
2839
+ const [, priceResponse] = await Promise.all([
2840
+ this.authenticateUser(),
2841
+ this.httpClient.dataGet(
2842
+ DATA_ENDPOINTS.TOKEN_PRICE(assetConfig.priceTokenSymbol)
2843
+ )
2844
+ ]);
2845
+ minRequired = usdToTokenUnits(
2846
+ minUsd,
2847
+ parseTokenUsdPrice(priceResponse),
2848
+ assetConfig.decimals
2849
+ );
2850
+ } else {
2851
+ await this.authenticateUser();
2852
+ }
2720
2853
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
2721
2854
  if (!safeAddress) {
2722
2855
  throw new Error("Smart wallet address is not available");
2723
2856
  }
2724
- const isDeployed = await isSafeDeployed(
2725
- safeAddress,
2726
- chainConfig.publicClient
2727
- );
2857
+ const amountBigInt = BigInt(amount);
2858
+ const [isDeployed, currentSafeBalance] = await Promise.all([
2859
+ isSafeDeployed(safeAddress, chainConfig.publicClient),
2860
+ minRequired !== void 0 ? chainConfig.publicClient.readContract({
2861
+ address: token,
2862
+ abi: ERC20_ABI,
2863
+ functionName: "balanceOf",
2864
+ args: [safeAddress]
2865
+ }) : Promise.resolve(void 0),
2866
+ this.prepareFirstDeposit(strategy)
2867
+ ]).then(([deployed, balance]) => [deployed, balance]);
2728
2868
  if (!isDeployed) {
2729
2869
  if (!(this.isPredeployed && this.isConnectedUser(userAddress))) {
2730
2870
  throw new Error(
@@ -2732,26 +2872,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2732
2872
  );
2733
2873
  }
2734
2874
  }
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
2875
  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;
2876
+ const safeBalance = currentSafeBalance;
2877
+ const totalAfterDeposit = safeBalance + amountBigInt;
2755
2878
  if (totalAfterDeposit < minRequired) {
2756
2879
  const minLabel = formatMinPortfolioLabel(
2757
2880
  minRequired,
@@ -2759,7 +2882,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2759
2882
  assetSymbol
2760
2883
  );
2761
2884
  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).`
2885
+ `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
2886
  );
2764
2887
  }
2765
2888
  }
@@ -2777,27 +2900,208 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2777
2900
  if (receipt.status !== "success") {
2778
2901
  throw new Error("Deposit transaction failed");
2779
2902
  }
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
- }
2903
+ const registration = await this.registerDeposit(
2904
+ chainId,
2905
+ txHash,
2906
+ amount,
2907
+ token
2908
+ );
2787
2909
  return {
2788
2910
  success: true,
2789
2911
  txHash,
2790
2912
  smartWallet: safeAddress,
2791
- amount: amountBigInt.toString()
2913
+ amount: amountBigInt.toString(),
2914
+ registration
2792
2915
  };
2793
2916
  } catch (error) {
2794
2917
  throw new Error(`Deposit failed: ${error.message}`);
2795
2918
  }
2796
2919
  }
2920
+ /**
2921
+ * @deprecated Compatibility convenience method. Prefer `sendDeposit()` followed by
2922
+ * `waitForDepositCredit()` when the caller owns the completion UX.
2923
+ */
2924
+ async depositFunds(userAddress, chainId, amount, asset, strategy) {
2925
+ this.warnDeprecatedOnboardingMethod("depositFunds");
2926
+ const sent = await this.sendDeposit(
2927
+ userAddress,
2928
+ chainId,
2929
+ amount,
2930
+ asset,
2931
+ strategy
2932
+ );
2933
+ return {
2934
+ ...sent,
2935
+ registration: await this.waitForDepositCredit(
2936
+ sent.registration.id,
2937
+ chainId
2938
+ )
2939
+ };
2940
+ }
2941
+ /**
2942
+ * Prepare ERC-20 transfer calldata for builders using a custom signer,
2943
+ * sponsored transaction provider, or mobile wallet. Most custom-wallet
2944
+ * integrations can compose this with `ensureFirstDepositSetup()` and
2945
+ * `logDeposit()` instead.
2946
+ */
2947
+ async buildDepositTransfer(params) {
2948
+ const { userAddress, chainId, amount, asset } = params;
2949
+ if (!userAddress || !amount || BigInt(amount) <= 0n) {
2950
+ throw new Error("A user address and positive amount are required");
2951
+ }
2952
+ if (!isSupportedChain(chainId)) {
2953
+ throw new Error(`Unsupported chain ID: ${chainId}`);
2954
+ }
2955
+ const assetSymbol = resolveAssetSymbol(asset);
2956
+ const assetChains = getAssetChainIds(assetSymbol);
2957
+ if (!assetChains.includes(chainId)) {
2958
+ throw new Error(
2959
+ `${assetSymbol} is not available on chain ${chainId}. Supported chains: ${assetChains.join(
2960
+ ", "
2961
+ )}.`
2962
+ );
2963
+ }
2964
+ const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
2965
+ if (!safeAddress) {
2966
+ throw new Error("Smart wallet address is not available");
2967
+ }
2968
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
2969
+ const isDeployed = await isSafeDeployed(
2970
+ safeAddress,
2971
+ chainConfig.publicClient
2972
+ );
2973
+ if (!(isDeployed || this.isPredeployed && this.isConnectedUser(userAddress))) {
2974
+ throw new Error(
2975
+ `Safe not available for ${userAddress} on chain ${chainId}.`
2976
+ );
2977
+ }
2978
+ const amountBigInt = BigInt(amount);
2979
+ await this.enforceMinimumPortfolioBalance(
2980
+ chainId,
2981
+ asset,
2982
+ amountBigInt,
2983
+ safeAddress
2984
+ );
2985
+ const tokenAddress = getDefaultTokenAddress(
2986
+ chainId,
2987
+ assetSymbol
2988
+ );
2989
+ return {
2990
+ safeAddress,
2991
+ tokenAddress,
2992
+ to: tokenAddress,
2993
+ data: (0, import_viem4.encodeFunctionData)({
2994
+ abi: ERC20_ABI,
2995
+ functionName: "transfer",
2996
+ args: [safeAddress, amountBigInt]
2997
+ }),
2998
+ value: "0"
2999
+ };
3000
+ }
3001
+ /** Apply the same per-asset minimum portfolio rule as sendDeposit. */
3002
+ async enforceMinimumPortfolioBalance(chainId, asset, amount, safeAddress) {
3003
+ if (this.bypassMinPortfolio) {
3004
+ return;
3005
+ }
3006
+ const assetSymbol = resolveAssetSymbol(asset);
3007
+ const assetConfig = ASSET_CONFIGS[assetSymbol];
3008
+ let minRequired = MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
3009
+ const minUsd = MIN_PORTFOLIO_USD[chainId]?.[assetSymbol];
3010
+ if (minUsd !== void 0) {
3011
+ const [, priceResponse] = await Promise.all([
3012
+ this.authenticateUser(),
3013
+ this.httpClient.dataGet(
3014
+ DATA_ENDPOINTS.TOKEN_PRICE(assetConfig.priceTokenSymbol)
3015
+ )
3016
+ ]);
3017
+ minRequired = usdToTokenUnits(
3018
+ minUsd,
3019
+ parseTokenUsdPrice(priceResponse),
3020
+ assetConfig.decimals
3021
+ );
3022
+ }
3023
+ if (minRequired === void 0) return;
3024
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
3025
+ const token = getDefaultTokenAddress(chainId, assetSymbol);
3026
+ const currentSafeBalance = await chainConfig.publicClient.readContract({
3027
+ address: token,
3028
+ abi: ERC20_ABI,
3029
+ functionName: "balanceOf",
3030
+ args: [safeAddress]
3031
+ });
3032
+ const totalAfterDeposit = currentSafeBalance + amount;
3033
+ if (totalAfterDeposit < minRequired) {
3034
+ const minLabel = formatMinPortfolioLabel(
3035
+ minRequired,
3036
+ assetConfig.decimals,
3037
+ assetSymbol
3038
+ );
3039
+ throw new Error(
3040
+ `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).`
3041
+ );
3042
+ }
3043
+ }
3044
+ /**
3045
+ * Idempotently apply the first-deposit profile configuration for builders
3046
+ * composing an advanced custom transfer flow. Most custom-wallet
3047
+ * integrations can use this with `buildDepositTransfer()` and `logDeposit()`.
3048
+ *
3049
+ * When setup runs (`applied: true`), protocol configuration is persisted
3050
+ * before returning. Failures throw so callers can abort before submitting a
3051
+ * transfer. High-level deposit methods still treat setup as best-effort.
3052
+ */
3053
+ async ensureFirstDepositSetup(strategy) {
3054
+ if (strategy !== void 0 && !isValidPublicStrategy(strategy)) {
3055
+ throw new Error(
3056
+ `Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
3057
+ );
3058
+ }
3059
+ await this.authenticateUser();
3060
+ const usdcDetails = await this.getUserDetails("USDC");
3061
+ if ((usdcDetails.chains?.length ?? 0) > 0) {
3062
+ return { applied: false };
3063
+ }
3064
+ await this.updateUserProtocols(strategy, { strict: true });
3065
+ const usdcAfterSetup = await this.getUserDetails("USDC");
3066
+ if ((usdcAfterSetup.chains?.length ?? 0) === 0) {
3067
+ throw new Error(
3068
+ "First-deposit setup did not persist USDC chain configuration."
3069
+ );
3070
+ }
3071
+ return { applied: true };
3072
+ }
3073
+ /** Best-effort first-deposit setup shared by both high-level deposit flows. */
3074
+ async prepareFirstDeposit(strategy) {
3075
+ try {
3076
+ await this.ensureFirstDepositSetup(strategy);
3077
+ } catch (protocolError) {
3078
+ console.warn(
3079
+ "Failed to update user protocols before deposit:",
3080
+ protocolError.message
3081
+ );
3082
+ }
3083
+ }
3084
+ /** Shared post-transfer registration path for every deposit flow. */
3085
+ async registerDeposit(chainId, txHash, amount, tokenAddress) {
3086
+ let registration;
3087
+ try {
3088
+ registration = await this.logDeposit(
3089
+ chainId,
3090
+ txHash,
3091
+ amount,
3092
+ tokenAddress
3093
+ );
3094
+ } catch (logError) {
3095
+ throw new Error(
3096
+ `On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}") to retry.`
3097
+ );
3098
+ }
3099
+ return registration.deposit;
3100
+ }
2797
3101
  /**
2798
3102
  * Log a deposit that was executed client-side.
2799
3103
  *
2800
- * `depositFunds()` already calls this after the ERC20 transfer. If you send the
3104
+ * `sendDeposit()` already calls this after the ERC20 transfer. If you send the
2801
3105
  * transfer yourself (front, Privy, Biconomy, custom wallet) you **must** call
2802
3106
  * `logDeposit` — otherwise the backend never sees the deposit: a reserved pool
2803
3107
  * wallet stays reserved (no ownership rotation), and yield/agent tracking does
@@ -2854,20 +3158,77 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2854
3158
  }
2855
3159
  const token = tokenAddress || getDefaultTokenAddress(chainId);
2856
3160
  await this.authenticateUser();
2857
- await this.httpClient.post(ENDPOINTS.LOG_DEPOSIT, {
2858
- chainId,
2859
- transaction: txHash,
2860
- token,
2861
- amount
2862
- });
3161
+ const deposit = await this.httpClient.post(
3162
+ ENDPOINTS.LOG_DEPOSIT,
3163
+ {
3164
+ chainId,
3165
+ transaction: txHash,
3166
+ token,
3167
+ amount
3168
+ }
3169
+ );
2863
3170
  return {
2864
3171
  success: true,
2865
- message: "Deposit logged successfully"
3172
+ message: deposit.status === "credited" ? "Deposit credited successfully" : "Deposit accepted; custody handover is pending",
3173
+ deposit
2866
3174
  };
2867
3175
  } catch (error) {
2868
3176
  throw new Error(`Log deposit failed: ${error.message}`);
2869
3177
  }
2870
3178
  }
3179
+ /**
3180
+ * Fetch the custody handover and balance-credit lifecycle for a registered
3181
+ * deposit. A status of `credited` is required before funds are investable.
3182
+ */
3183
+ async getDepositStatus(depositId) {
3184
+ if (!depositId) {
3185
+ throw new Error("Deposit ID is required");
3186
+ }
3187
+ await this.authenticateUser();
3188
+ return this.httpClient.get(
3189
+ ENDPOINTS.DEPOSIT_STATUS(depositId)
3190
+ );
3191
+ }
3192
+ /**
3193
+ * Await deposit credit after `logDeposit` returns `handover_pending`.
3194
+ *
3195
+ * Polls `getDepositStatus` until `status === "credited"` and
3196
+ * `balanceCredited === true`. Rejects on recovery, timeout, or poll errors.
3197
+ *
3198
+ * Poll interval and timeout are chain-specific. Mainnet defaults to a 2s
3199
+ * interval and 1 minute ceiling; Base/Arbitrum use tighter polling (~500ms /
3200
+ * ~250ms) with a ~20 second completion window. Override `timeoutMs` when a
3201
+ * caller intentionally wants to wait longer than the normal UX window.
3202
+ *
3203
+ * Requires `connectAccount()` on the same SDK instance first.
3204
+ */
3205
+ async waitForDepositCredit(depositId, chainId, options) {
3206
+ if (!depositId) {
3207
+ throw new Error("Deposit ID is required");
3208
+ }
3209
+ if (!isSupportedChain(chainId)) {
3210
+ throw new Error(`Unsupported chain ID: ${chainId}`);
3211
+ }
3212
+ const intervalMs = options?.intervalMs ?? getDepositCreditIntervalMs(chainId);
3213
+ const timeoutMs = options?.timeoutMs ?? getDepositCreditTimeoutMs(chainId);
3214
+ const started = Date.now();
3215
+ while (Date.now() - started < timeoutMs) {
3216
+ const status = await this.getDepositStatus(depositId);
3217
+ if (status.status === "credited" && status.balanceCredited) {
3218
+ return status;
3219
+ }
3220
+ if (status.status === "recovered_to_eoa") {
3221
+ throw new Error(
3222
+ `Deposit ${depositId} recovered to EOA (status=${status.status}); balance was not credited`
3223
+ );
3224
+ }
3225
+ if (Date.now() - started >= timeoutMs) {
3226
+ break;
3227
+ }
3228
+ await sleep(intervalMs);
3229
+ }
3230
+ throw new DepositCreditTimeoutError(depositId);
3231
+ }
2871
3232
  /**
2872
3233
  * Withdraw funds from Safe smart wallet
2873
3234
  * Initiates a withdrawal request to the Zyfai API
@@ -2887,6 +3248,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2887
3248
  * When every source is an async pool nothing settles on-chain at that point,
2888
3249
  * so `txHash` is `undefined` on a successful call.
2889
3250
  *
3251
+ * **One redemption per pool at a time.** While an entry for a pool is
3252
+ * `REQUESTED` or `CLAIMABLE`, the backend drops a further withdrawal aimed at
3253
+ * that same pool — the protocols behind it (ERC-7540) hold a single request
3254
+ * slot per user. This method throws rather than reporting that no-op as a
3255
+ * success. It only throws when nothing the call could reach is withdrawable:
3256
+ * another pool, another asset or an idle Safe balance still goes through.
3257
+ *
2890
3258
  * Once requested, that amount can no longer be withdrawn: it is gone from
2891
3259
  * both the position snapshot and the Safe balance, so a second call silently
2892
3260
  * returns only what is left. Validate user-entered amounts against
@@ -2935,6 +3303,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2935
3303
  );
2936
3304
  }
2937
3305
  await this.authenticateUser();
3306
+ await this.assertAsyncRedemptionSlotFree(
3307
+ userAddress,
3308
+ chainId,
3309
+ tokenSymbol
3310
+ );
2938
3311
  let response = {};
2939
3312
  if (amount) {
2940
3313
  response = await this.httpClient.post(ENDPOINTS.PARTIAL_WITHDRAW, {
@@ -2962,6 +3335,31 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2962
3335
  throw new Error(`Withdrawal failed: ${error.message}`);
2963
3336
  }
2964
3337
  }
3338
+ /**
3339
+ * Turn a withdrawal the backend would silently drop — one aimed only at
3340
+ * async pools that already hold an in-flight redemption — into an error, so
3341
+ * the caller gets an answer rather than a `success: true` no-op.
3342
+ *
3343
+ * @internal
3344
+ */
3345
+ async assertAsyncRedemptionSlotFree(userAddress, chainId, tokenSymbol) {
3346
+ let portfolio;
3347
+ try {
3348
+ ({ portfolio } = await this.getPortfolio(userAddress));
3349
+ } catch {
3350
+ return;
3351
+ }
3352
+ const blocking = findBlockingAsyncRedemption(
3353
+ portfolio,
3354
+ chainId,
3355
+ tokenSymbol
3356
+ );
3357
+ if (!blocking) return;
3358
+ const eta = blocking.estimatedClaimAt ? ` Estimated settlement: ${blocking.estimatedClaimAt}.` : "";
3359
+ throw new Error(
3360
+ `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}`
3361
+ );
3362
+ }
2965
3363
  /**
2966
3364
  * Get available DeFi protocols and pools for a specific chain
2967
3365
  *
@@ -3267,7 +3665,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3267
3665
  */
3268
3666
  async getVolume(assetType = "usdc") {
3269
3667
  try {
3270
- const response = await this.httpClient.get(ENDPOINTS.DATA_VOLUME(assetType));
3668
+ const response = await this.httpClient.get(
3669
+ ENDPOINTS.DATA_VOLUME(assetType)
3670
+ );
3271
3671
  return {
3272
3672
  success: true,
3273
3673
  volumeInUSD: response.volumeInUSD || "0"
@@ -4044,9 +4444,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4044
4444
  }
4045
4445
  };
4046
4446
  } catch (error) {
4047
- throw new Error(
4048
- `Failed to get SDK key TVL: ${error.message}`
4049
- );
4447
+ throw new Error(`Failed to get SDK key TVL: ${error.message}`);
4050
4448
  }
4051
4449
  }
4052
4450
  // ============================================================================
@@ -4229,7 +4627,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4229
4627
  * Check if a chain ID supports the Identity Registry
4230
4628
  */
4231
4629
  isSupportedIdentityRegistryChain(chainId) {
4232
- return _ZyfaiSDK.IDENTITY_REGISTRY_CHAIN_IDS.includes(chainId);
4630
+ return _ZyfaiSDK.IDENTITY_REGISTRY_CHAIN_IDS.includes(
4631
+ chainId
4632
+ );
4233
4633
  }
4234
4634
  /**
4235
4635
  * Register an agent on the Identity Registry (ERC-8004)
@@ -4326,7 +4726,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4326
4726
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
4327
4727
  const tokenAddress = getDefaultTokenAddress(chainId, asset);
4328
4728
  const decimals = 6;
4329
- const parsedAmount = BigInt(Math.floor(parseFloat(amount) * 10 ** decimals));
4729
+ const parsedAmount = BigInt(
4730
+ Math.floor(parseFloat(amount) * 10 ** decimals)
4731
+ );
4330
4732
  try {
4331
4733
  const allowance = await chainConfig.publicClient.readContract({
4332
4734
  address: tokenAddress,
@@ -4404,7 +4806,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4404
4806
  args: [userAddress]
4405
4807
  });
4406
4808
  if (maxShares === 0n) {
4407
- throw new Error("No shares available to redeem or withdrawals are paused");
4809
+ throw new Error(
4810
+ "No shares available to redeem or withdrawals are paused"
4811
+ );
4408
4812
  }
4409
4813
  sharesToRedeem = maxShares;
4410
4814
  }
@@ -4448,7 +4852,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4448
4852
  status: isClaimable ? "claimable" : "pending"
4449
4853
  };
4450
4854
  } catch (error) {
4451
- throw new Error(`Vault withdraw request failed: ${error.message}`);
4855
+ throw new Error(
4856
+ `Vault withdraw request failed: ${error.message}`
4857
+ );
4452
4858
  }
4453
4859
  }
4454
4860
  /**
@@ -4528,7 +4934,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4528
4934
  nonce
4529
4935
  };
4530
4936
  } catch (error) {
4531
- throw new Error(`Failed to get withdraw status: ${error.message}`);
4937
+ throw new Error(
4938
+ `Failed to get withdraw status: ${error.message}`
4939
+ );
4532
4940
  }
4533
4941
  }
4534
4942
  /**
@@ -4571,7 +4979,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4571
4979
  if (isClaimed) {
4572
4980
  throw new Error("This withdrawal has already been claimed");
4573
4981
  }
4574
- throw new Error("Withdrawal is not yet claimable. Please wait for processing.");
4982
+ throw new Error(
4983
+ "Withdrawal is not yet claimable. Please wait for processing."
4984
+ );
4575
4985
  }
4576
4986
  const claimTx = await this.walletClient.writeContract({
4577
4987
  address: VAULT_ADDRESS,
@@ -4611,7 +5021,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4611
5021
  async getVaultShares(userAddress, chainId = 8453) {
4612
5022
  const address = userAddress || this.walletClient?.account?.address;
4613
5023
  if (!address) {
4614
- throw new Error("User address required. Provide address or connect wallet first.");
5024
+ throw new Error(
5025
+ "User address required. Provide address or connect wallet first."
5026
+ );
4615
5027
  }
4616
5028
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
4617
5029
  const [shareBalance, tokenSymbol] = await Promise.all([