@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.mjs CHANGED
@@ -46,7 +46,8 @@ var ENDPOINTS = {
46
46
  USER_ME: "/users/me",
47
47
  USER_WITHDRAW: "/users/withdraw",
48
48
  PARTIAL_WITHDRAW: "/users/partial-withdraw",
49
- LOG_DEPOSIT: "/users/log_deposit",
49
+ LOG_DEPOSIT: "/users/log_deposit/v2",
50
+ DEPOSIT_STATUS: (depositId) => `/users/deposits/${depositId}`,
50
51
  // Safe Deployment (single endpoint)
51
52
  SAFE_DEPLOY: "/users/safe-deploy",
52
53
  // Multichain deploy for predeployed (pool) wallets — deploys + rotates the
@@ -351,26 +352,30 @@ var HttpClient = class {
351
352
  }
352
353
  };
353
354
 
354
- // src/utils/eth-price.ts
355
+ // src/utils/poll.ts
356
+ function sleep(ms) {
357
+ return new Promise((resolve) => setTimeout(resolve, ms));
358
+ }
359
+
360
+ // src/utils/token-price.ts
355
361
  var PRICE_SCALE = 8;
356
- var parseEthUsdPrice = (response) => {
362
+ var parseTokenUsdPrice = (response) => {
357
363
  const priceUsd = response?.data?.price_usd;
358
364
  if (typeof priceUsd !== "number" || !Number.isFinite(priceUsd) || priceUsd <= 0) {
359
- throw new Error("ETH/USD price must be a positive number");
365
+ throw new Error("Token USD price must be a positive number");
360
366
  }
361
367
  return priceUsd;
362
368
  };
363
- var usdToWethWei = (usdAmount, ethUsd) => {
364
- if (!Number.isFinite(ethUsd) || ethUsd <= 0) {
365
- throw new Error("ETH/USD price must be positive");
369
+ var usdToTokenUnits = (usdAmount, priceUsd, decimals) => {
370
+ if (!Number.isFinite(priceUsd) || priceUsd <= 0) {
371
+ throw new Error("Token USD price must be positive");
366
372
  }
367
- const scaledPrice = BigInt(Math.round(ethUsd * 10 ** PRICE_SCALE));
373
+ const scaledPrice = BigInt(Math.round(priceUsd * 10 ** PRICE_SCALE));
368
374
  if (scaledPrice <= 0n) {
369
- throw new Error("ETH/USD price must be positive");
375
+ throw new Error("Token USD price must be positive");
370
376
  }
371
- return usdAmount * 10n ** 18n * 10n ** BigInt(PRICE_SCALE) / scaledPrice;
377
+ return usdAmount * 10n ** BigInt(decimals) * 10n ** BigInt(PRICE_SCALE) / scaledPrice;
372
378
  };
373
- var minWethWeiForUsd = (ethUsd, usdAmount) => usdToWethWei(usdAmount, ethUsd);
374
379
 
375
380
  // src/config/abis.ts
376
381
  import { parseAbi } from "viem";
@@ -563,11 +568,26 @@ var MIN_PORTFOLIO_BALANCE = {
563
568
  // 100 EURC (6 decimals)
564
569
  }
565
570
  };
566
- var MIN_WETH_USD = {
567
- 1: 10000n,
568
- 8453: 100n,
569
- 42161: 100n
571
+ var MIN_PORTFOLIO_USD = {
572
+ 1: { WETH: 10000n },
573
+ 8453: { WETH: 100n, NVDAc: 100n },
574
+ 42161: { WETH: 100n }
575
+ };
576
+ var DEPOSIT_CREDIT_INTERVAL_MS = {
577
+ 1: 2e3,
578
+ 8453: 500,
579
+ 42161: 250
570
580
  };
581
+ var DEPOSIT_CREDIT_TIMEOUT_MS = {
582
+ 1: 6e4,
583
+ // 1 minute
584
+ 8453: 2e4,
585
+ // ~10 Base blocks
586
+ 42161: 2e4
587
+ // ~10 Arbitrum blocks
588
+ };
589
+ var getDepositCreditIntervalMs = (chainId) => DEPOSIT_CREDIT_INTERVAL_MS[chainId];
590
+ var getDepositCreditTimeoutMs = (chainId) => DEPOSIT_CREDIT_TIMEOUT_MS[chainId];
571
591
  var formatMinPortfolioLabel = (raw, decimals, symbol) => {
572
592
  const base2 = 10n ** BigInt(decimals);
573
593
  const whole = raw / base2;
@@ -579,6 +599,25 @@ var formatMinPortfolioLabel = (raw, decimals, symbol) => {
579
599
  return `${whole.toString()}.${fractionStr} ${symbol}`;
580
600
  };
581
601
 
602
+ // src/config/local-dev.ts
603
+ function isLocalExecutionApiUrl(executionApiUrl) {
604
+ if (executionApiUrl === EXECUTION_API_BASE_URLS.local) {
605
+ return true;
606
+ }
607
+ try {
608
+ const { hostname } = new URL(executionApiUrl);
609
+ return hostname === "localhost" || hostname === "127.0.0.1";
610
+ } catch {
611
+ return false;
612
+ }
613
+ }
614
+ function shouldBypassMinPortfolioCheck(executionApiUrl) {
615
+ if (process.env.NODE_ENV === "production") {
616
+ return false;
617
+ }
618
+ return isLocalExecutionApiUrl(executionApiUrl);
619
+ }
620
+
582
621
  // src/core/ZyfaiSDK.ts
583
622
  import { privateKeyToAccount } from "viem/accounts";
584
623
  import {
@@ -635,6 +674,8 @@ var ASSET_CONFIGS = {
635
674
  displayName: "WETH",
636
675
  icon: "/ai-dashboard/eth-token.png",
637
676
  decimals: 18,
677
+ // Data API `/price?token=` identifier, used for USD-denominated minimums.
678
+ priceTokenSymbol: "eth",
638
679
  tokenSymbols: ["WETH", "ETH"],
639
680
  tokenSymbolsByChainId: {
640
681
  1: "WETH",
@@ -675,8 +716,39 @@ var ASSET_CONFIGS = {
675
716
  // Base
676
717
  },
677
718
  enabled: true
719
+ },
720
+ // Coinbase B20 tokenized NVIDIA equity. Base only, and only reachable through
721
+ // protocols with delayed withdrawals — see the `yieldmaxxing` strategy.
722
+ NVDAc: {
723
+ symbol: "NVDAc",
724
+ assetType: "nvdac",
725
+ displayName: "NVIDIA",
726
+ icon: "https://metadata.coinbase.com/equity_icons/1fee9b7a44e800d438dd9d96c3283e05784c925c2c871a48ff735950740b551a.png",
727
+ decimals: 8,
728
+ priceTokenSymbol: "nvdac",
729
+ tokenSymbols: ["NVDAc"],
730
+ tokenSymbolsByChainId: {
731
+ 8453: "NVDAc"
732
+ },
733
+ addresses: {
734
+ 8453: "0xb20000000000000000000078ee7ce2fE4908108C"
735
+ // Base
736
+ },
737
+ enabled: true
678
738
  }
679
739
  };
740
+ var resolveAssetSymbol = (asset) => {
741
+ const match = Object.keys(ASSET_CONFIGS).find(
742
+ (key) => key.toLowerCase() === asset.toLowerCase()
743
+ );
744
+ if (!match) {
745
+ throw new Error(
746
+ `Unsupported asset: ${asset}. Supported: ${Object.keys(ASSET_CONFIGS).join(", ")}.`
747
+ );
748
+ }
749
+ return match;
750
+ };
751
+ var getAssetChainIds = (asset) => Object.keys(ASSET_CONFIGS[asset]?.addresses ?? {}).map(Number).filter((chainId) => chainId in CHAINS);
680
752
  var getDefaultTokenAddress = (chainId, asset) => {
681
753
  const address = ASSET_CONFIGS[asset || "USDC"]?.addresses[chainId];
682
754
  if (!address || address === "0x0000000000000000000000000000000000000000") {
@@ -966,6 +1038,7 @@ var signSessionKey = async (config, sessions, allPublicClients, signingParams) =
966
1038
 
967
1039
  // src/utils/strategy.ts
968
1040
  var PUBLIC_STRATEGIES = `"conservative", "aggressive" or "yieldmaxxing"`;
1041
+ var SUPPORTED_ASSETS = `"USDC", "WETH", "EURC" or "NVDAc"`;
969
1042
  function toInternalStrategy(publicStrategy) {
970
1043
  switch (publicStrategy) {
971
1044
  case "conservative":
@@ -1054,8 +1127,11 @@ function convertAssetInternally(asset) {
1054
1127
  if (asset === "EURC") {
1055
1128
  return "eurc";
1056
1129
  }
1130
+ if (asset === "NVDAc") {
1131
+ return "nvdac";
1132
+ }
1057
1133
  throw new Error(
1058
- `Invalid asset: ${asset}. Must be "USDC", "WETH", or "EURC".`
1134
+ `Invalid asset: ${asset}. Must be ${SUPPORTED_ASSETS}.`
1059
1135
  );
1060
1136
  }
1061
1137
  function convertStrategiesToPublic(array) {
@@ -1478,8 +1554,34 @@ function enrichOnchainEarningsTotals(apiData) {
1478
1554
  };
1479
1555
  }
1480
1556
 
1557
+ // src/utils/async-withdrawals.ts
1558
+ var findBlockingAsyncRedemption = (portfolio, chainId, tokenSymbol) => {
1559
+ const matchesToken = (symbol) => !tokenSymbol || symbol?.toLowerCase() === tokenSymbol.toLowerCase();
1560
+ const blocked = (portfolio.pendingAsyncWithdrawals ?? []).filter(
1561
+ (w) => w.chainId === chainId && (w.status === "REQUESTED" || w.status === "CLAIMABLE") && matchesToken(w.token?.symbol)
1562
+ );
1563
+ if (blocked.length === 0) return void 0;
1564
+ const blockedPools = new Set(
1565
+ blocked.map((w) => w.pool?.toLowerCase()).filter(Boolean)
1566
+ );
1567
+ const hasFreePosition = (portfolio.positions ?? []).some(
1568
+ (p) => matchesToken(p.token_symbol) && Number(chainNameToId(p.chain ?? "")) === chainId && !blockedPools.has(p.pool?.toLowerCase() ?? "")
1569
+ );
1570
+ const hasIdleBalance = (portfolio.staleBalances ?? []).some(
1571
+ (b) => b.chainId === chainId && matchesToken(b.tokenSymbol) && BigInt(b.balance ?? "0") > 0n
1572
+ );
1573
+ return hasFreePosition || hasIdleBalance ? void 0 : blocked[0];
1574
+ };
1575
+
1481
1576
  // src/core/ZyfaiSDK.ts
1482
1577
  import { SiweMessage } from "siwe";
1578
+ var DepositCreditTimeoutError = class extends Error {
1579
+ constructor(depositId) {
1580
+ super(`Timed out waiting for deposit ${depositId} to be credited`);
1581
+ this.name = "DepositCreditTimeoutError";
1582
+ }
1583
+ };
1584
+ var MANAGED_ASSETS = ["USDC", "WETH", "EURC", "NVDAc"];
1483
1585
  var _ZyfaiSDK = class _ZyfaiSDK {
1484
1586
  constructor(config) {
1485
1587
  this.signer = null;
@@ -1496,12 +1598,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1496
1598
  rpcUrls,
1497
1599
  referralSource,
1498
1600
  executionApiUrl,
1499
- dataApiUrl
1601
+ dataApiUrl,
1602
+ bypassMinPortfolio
1500
1603
  } = sdkConfig;
1501
1604
  if (!apiKey) {
1502
1605
  throw new Error("API key is required");
1503
1606
  }
1504
1607
  this.executionApiUrl = executionApiUrl ?? API_ENDPOINT;
1608
+ this.bypassMinPortfolio = bypassMinPortfolio ?? shouldBypassMinPortfolioCheck(this.executionApiUrl);
1505
1609
  this.httpClient = new HttpClient(apiKey, {
1506
1610
  executionApiUrl: this.executionApiUrl,
1507
1611
  dataApiUrl
@@ -1510,12 +1614,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1510
1614
  this.referralSource = referralSource;
1511
1615
  }
1512
1616
  /**
1513
- * Warn that a legacy method is deprecated in favor of depositFunds.
1617
+ * Warn that a legacy method is deprecated in favor of sendDeposit.
1514
1618
  * Predeployed wallets no longer require deploySafe / createSessionKey.
1515
1619
  */
1516
1620
  warnDeprecatedOnboardingMethod(methodName) {
1517
1621
  console.warn(
1518
- `[ZyfaiSDK] ${methodName}() is deprecated for partner integrations. Prefer depositFunds() \u2014 predeployed Safes and session keys are handled automatically on first deposit.`
1622
+ `[ZyfaiSDK] ${methodName}() is deprecated for partner integrations. Prefer sendDeposit() \u2014 predeployed Safes and session keys are handled automatically on first deposit.`
1519
1623
  );
1520
1624
  }
1521
1625
  /**
@@ -1619,25 +1723,31 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1619
1723
  rebalanceStrategy = toInternalStrategy(request.strategy);
1620
1724
  }
1621
1725
  const assetSettings = {};
1622
- if (rebalanceStrategy !== void 0) assetSettings.rebalanceStrategy = rebalanceStrategy;
1623
- if (request.autocompounding !== void 0) assetSettings.autocompounding = request.autocompounding;
1624
- if (request.crosschainStrategy !== void 0) assetSettings.crosschainStrategy = request.crosschainStrategy;
1625
- if (request.splitting !== void 0) assetSettings.splitting = request.splitting;
1626
- if (request.minSplits !== void 0) assetSettings.minSplits = request.minSplits;
1726
+ if (rebalanceStrategy !== void 0)
1727
+ assetSettings.rebalanceStrategy = rebalanceStrategy;
1728
+ if (request.autocompounding !== void 0)
1729
+ assetSettings.autocompounding = request.autocompounding;
1730
+ if (request.crosschainStrategy !== void 0)
1731
+ assetSettings.crosschainStrategy = request.crosschainStrategy;
1732
+ if (request.splitting !== void 0)
1733
+ assetSettings.splitting = request.splitting;
1734
+ if (request.minSplits !== void 0)
1735
+ assetSettings.minSplits = request.minSplits;
1627
1736
  if (request.chains !== void 0) assetSettings.chains = request.chains;
1628
- if (request.autoSelectProtocols !== void 0) assetSettings.autoSelectProtocols = request.autoSelectProtocols;
1629
- if (request.protocols !== void 0) assetSettings.protocols = request.protocols;
1737
+ if (request.autoSelectProtocols !== void 0)
1738
+ assetSettings.autoSelectProtocols = request.autoSelectProtocols;
1739
+ if (request.protocols !== void 0)
1740
+ assetSettings.protocols = request.protocols;
1630
1741
  const payload = {
1631
1742
  assetTypeSettings: {
1632
1743
  [internalAsset]: assetSettings
1633
1744
  }
1634
1745
  };
1635
- if (request.omniAccount !== void 0) payload.omniAccount = request.omniAccount;
1636
- if (request.agentName !== void 0) payload.agentName = request.agentName;
1637
- await this.httpClient.patch(
1638
- ENDPOINTS.USER_ME,
1639
- payload
1640
- );
1746
+ if (request.omniAccount !== void 0)
1747
+ payload.omniAccount = request.omniAccount;
1748
+ if (request.agentName !== void 0)
1749
+ payload.agentName = request.agentName;
1750
+ await this.httpClient.patch(ENDPOINTS.USER_ME, payload);
1641
1751
  return await this.getUserDetails(asset);
1642
1752
  } catch (error) {
1643
1753
  throw new Error(
@@ -1665,19 +1775,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1665
1775
  */
1666
1776
  async pauseAgent() {
1667
1777
  try {
1668
- await this.updateUserProfile({
1669
- asset: "USDC",
1670
- protocols: []
1671
- });
1672
- await this.updateUserProfile({
1673
- asset: "WETH",
1674
- protocols: []
1675
- });
1676
- const response = await this.updateUserProfile({
1677
- asset: "EURC",
1678
- protocols: []
1679
- });
1680
- return response;
1778
+ let latest;
1779
+ for (const asset of MANAGED_ASSETS) {
1780
+ latest = await this.updateUserProfile({ asset, protocols: [] });
1781
+ }
1782
+ if (!latest) {
1783
+ throw new Error("No supported assets to pause");
1784
+ }
1785
+ return latest;
1681
1786
  } catch (error) {
1682
1787
  throw new Error(`Failed to pause agent: ${error.message}`);
1683
1788
  }
@@ -1702,50 +1807,22 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1702
1807
  */
1703
1808
  async resumeAgent() {
1704
1809
  try {
1705
- const userDetailsUSDC = await this.getUserDetails("USDC");
1706
- const userDetailsETH = await this.getUserDetails("WETH");
1707
- const userDetailsEURC = await this.getUserDetails("EURC");
1708
- const chains = userDetailsUSDC.chains && userDetailsUSDC.chains.length > 0 ? userDetailsUSDC.chains : [8453, 42161];
1709
- const eurcChains = userDetailsEURC.chains && userDetailsEURC.chains.length > 0 ? userDetailsEURC.chains.filter((c) => c === 1 || c === 8453) : [1, 8453];
1710
1810
  const allProtocols = await this.httpClient.get(
1711
1811
  ENDPOINTS.PROTOCOLS()
1712
1812
  );
1713
- const internalStrategyOf = (strategy) => isValidPublicStrategy(strategy ?? "") ? toInternalStrategy(strategy) : "safe_strategy";
1714
- const usdcStrategy = internalStrategyOf(userDetailsUSDC.strategy);
1715
- const ethStrategy = internalStrategyOf(userDetailsETH.strategy);
1716
- const eurcStrategy = internalStrategyOf(userDetailsEURC.strategy);
1717
- const filterProtocolsByStrategy = (strategy, selectedChains) => {
1718
- return allProtocols.filter((protocol) => {
1719
- const hasMatchingChain = protocol.chains.some(
1720
- (chain) => selectedChains.includes(chain)
1721
- );
1722
- if (!hasMatchingChain) {
1723
- return false;
1724
- }
1725
- if (strategy === "async_strategy") {
1726
- return protocol.strategies?.includes("safe_strategy") || protocol.strategies?.includes("degen_strategy") || protocol.strategies?.includes("async_strategy");
1727
- }
1728
- if (strategy === "degen_strategy") {
1729
- return protocol.strategies?.includes("safe_strategy") || protocol.strategies?.includes("degen_strategy");
1730
- }
1731
- return protocol.strategies?.includes("safe_strategy");
1732
- }).map((protocol) => protocol.id);
1733
- };
1734
- const usdcProtocols = filterProtocolsByStrategy(usdcStrategy, chains);
1735
- const ethProtocols = filterProtocolsByStrategy(ethStrategy, chains);
1736
- const eurcProtocols = filterProtocolsByStrategy(eurcStrategy, eurcChains);
1737
- await this.updateUserProfile({
1738
- asset: "USDC",
1739
- protocols: usdcProtocols
1740
- });
1741
- await this.updateUserProfile({
1742
- asset: "WETH",
1743
- protocols: ethProtocols
1744
- });
1745
- return await this.updateUserProfile({
1746
- asset: "EURC",
1747
- protocols: eurcProtocols
1748
- });
1813
+ let latest;
1814
+ for (const asset of MANAGED_ASSETS) {
1815
+ latest = await this.updateUserProtocolsForAsset(
1816
+ asset,
1817
+ getAssetChainIds(asset),
1818
+ void 0,
1819
+ allProtocols
1820
+ );
1821
+ }
1822
+ if (!latest) {
1823
+ throw new Error("No supported assets to resume");
1824
+ }
1825
+ return latest;
1749
1826
  } catch (error) {
1750
1827
  throw new Error(`Failed to resume agent: ${error.message}`);
1751
1828
  }
@@ -1780,7 +1857,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1780
1857
  });
1781
1858
  return response;
1782
1859
  } catch (error) {
1783
- throw new Error(`Failed to enable splitting: ${error.message}`);
1860
+ throw new Error(
1861
+ `Failed to enable splitting: ${error.message}`
1862
+ );
1784
1863
  }
1785
1864
  }
1786
1865
  /**
@@ -1808,7 +1887,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1808
1887
  });
1809
1888
  return response;
1810
1889
  } catch (error) {
1811
- throw new Error(`Failed to disable splitting: ${error.message}`);
1890
+ throw new Error(
1891
+ `Failed to disable splitting: ${error.message}`
1892
+ );
1812
1893
  }
1813
1894
  }
1814
1895
  /**
@@ -1840,7 +1921,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1840
1921
  });
1841
1922
  return response;
1842
1923
  } catch (error) {
1843
- throw new Error(`Failed to update min splits: ${error.message}`);
1924
+ throw new Error(
1925
+ `Failed to update min splits: ${error.message}`
1926
+ );
1844
1927
  }
1845
1928
  }
1846
1929
  /**
@@ -2138,7 +2221,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2138
2221
  /**
2139
2222
  * Deploy Safe Smart Wallet for a user
2140
2223
  *
2141
- * @deprecated Prefer `depositFunds()`. Predeployed Safes and session keys are
2224
+ * @deprecated Prefer `sendDeposit()`. Predeployed Safes and session keys are
2142
2225
  * managed automatically on first deposit. This method remains available for
2143
2226
  * legacy flows.
2144
2227
  *
@@ -2150,8 +2233,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2150
2233
  *
2151
2234
  * @example
2152
2235
  * ```typescript
2153
- * // Preferred: depositFunds handles predeployed wallet onboarding
2154
- * await sdk.depositFunds(userAddress, 8453, amount, "USDC");
2236
+ * // Preferred: sendDeposit handles predeployed wallet onboarding
2237
+ * const sent = await sdk.sendDeposit(userAddress, 8453, amount, "USDC");
2238
+ * await sdk.waitForDepositCredit(sent.registration.id, 8453);
2155
2239
  *
2156
2240
  * // Legacy: deploy with default conservative strategy
2157
2241
  * await sdk.deploySafe(userAddress, 8453);
@@ -2269,7 +2353,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2269
2353
  } catch (error) {
2270
2354
  console.error("Safe deployment failed:", error);
2271
2355
  throw new Error(
2272
- `Safe deployment failed: ${error.message}. deploySafe() is deprecated \u2014 prefer depositFunds() for predeployed wallet onboarding.`
2356
+ `Safe deployment failed: ${error.message}. deploySafe() is deprecated \u2014 prefer sendDeposit() for predeployed wallet onboarding.`
2273
2357
  );
2274
2358
  }
2275
2359
  }
@@ -2277,7 +2361,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2277
2361
  * Create session key with auto-fetched configuration from Zyfai API
2278
2362
  * This is the simplified method that automatically fetches session configuration
2279
2363
  *
2280
- * @deprecated Prefer `depositFunds()`. Predeployed wallets already have the
2364
+ * @deprecated Prefer `sendDeposit()`. Predeployed wallets already have the
2281
2365
  * agent session enabled; session activation is handled after first deposit.
2282
2366
  * This method remains available for legacy flows.
2283
2367
  *
@@ -2287,8 +2371,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2287
2371
  *
2288
2372
  * @example
2289
2373
  * ```typescript
2290
- * // Preferred: depositFunds handles session onboarding for predeployed wallets
2291
- * await sdk.depositFunds(userAddress, 8453, amount, "USDC");
2374
+ * // Preferred: sendDeposit handles session onboarding for predeployed wallets
2375
+ * const sent = await sdk.sendDeposit(userAddress, 8453, amount, "USDC");
2376
+ * await sdk.waitForDepositCredit(sent.registration.id, 8453);
2292
2377
  *
2293
2378
  * // Legacy:
2294
2379
  * const result = await sdk.createSessionKey(userAddress, 8453);
@@ -2369,7 +2454,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2369
2454
  };
2370
2455
  } catch (error) {
2371
2456
  throw new Error(
2372
- `Failed to create session key: ${error.message}. createSessionKey() is deprecated \u2014 prefer depositFunds() for predeployed wallet onboarding.`
2457
+ `Failed to create session key: ${error.message}. createSessionKey() is deprecated \u2014 prefer sendDeposit() for predeployed wallet onboarding.`
2373
2458
  );
2374
2459
  }
2375
2460
  }
@@ -2436,34 +2521,46 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2436
2521
  * asset/chain/strategy combo.
2437
2522
  * 4. Persist via `updateUserProfile` (writes `assetTypeSettings`).
2438
2523
  *
2439
- * Called from `deploySafe` after every path, and from `depositFunds` on
2524
+ * Called from `deploySafe` after every path, and from `sendDeposit` on
2440
2525
  * the account's first deposit (when USDC chains are still empty).
2441
2526
  *
2442
2527
  * @internal
2443
2528
  */
2444
- async updateUserProtocols(strategy) {
2529
+ async updateUserProtocols(strategy, options) {
2530
+ const strict = options?.strict ?? false;
2531
+ const assetErrors = [];
2445
2532
  try {
2446
2533
  const allProtocols = await this.httpClient.get(
2447
2534
  ENDPOINTS.PROTOCOLS()
2448
2535
  );
2449
- const allChains = [1, 8453, 42161];
2450
- const assets = ["USDC", "WETH", "EURC"];
2451
- for (const asset of assets) {
2536
+ for (const asset of MANAGED_ASSETS) {
2452
2537
  try {
2453
- const chainsForAsset = asset === "EURC" ? [1, 8453] : allChains;
2454
2538
  await this.updateUserProtocolsForAsset(
2455
2539
  asset,
2456
- chainsForAsset,
2540
+ getAssetChainIds(asset),
2457
2541
  strategy,
2458
2542
  allProtocols
2459
2543
  );
2460
2544
  } catch (assetError) {
2461
- console.warn(
2462
- `Failed to update ${asset} protocols: ${assetError.message}`
2463
- );
2545
+ const message = assetError.message;
2546
+ if (strict) {
2547
+ assetErrors.push(`${asset}: ${message}`);
2548
+ } else {
2549
+ console.warn(`Failed to update ${asset} protocols: ${message}`);
2550
+ }
2464
2551
  }
2465
2552
  }
2553
+ if (strict && assetErrors.length > 0) {
2554
+ throw new Error(
2555
+ `Failed to configure user protocols for first deposit: ${assetErrors.join(
2556
+ "; "
2557
+ )}`
2558
+ );
2559
+ }
2466
2560
  } catch (error) {
2561
+ if (strict) {
2562
+ throw error;
2563
+ }
2467
2564
  console.warn(
2468
2565
  `Failed to update user protocols: ${error.message}`
2469
2566
  );
@@ -2493,13 +2590,83 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2493
2590
  asset,
2494
2591
  internalStrategy
2495
2592
  );
2496
- await this.updateUserProfile({
2593
+ return await this.updateUserProfile({
2497
2594
  asset,
2498
2595
  protocols: withPools,
2499
2596
  chains: effectiveChains,
2500
2597
  ...strategy !== void 0 && { strategy }
2501
2598
  });
2502
2599
  }
2600
+ /**
2601
+ * Switch one asset to a strategy and select the protocols that go with it.
2602
+ *
2603
+ * `updateUserProfile` stores a strategy but does not compute a protocol
2604
+ * list, so on its own it leaves the asset with nothing to deploy into. This
2605
+ * method does both in one call: it resolves the protocols that support the
2606
+ * asset on the requested chains under the requested strategy, drops those
2607
+ * with no pool available, and persists strategy, chains and protocols
2608
+ * together.
2609
+ *
2610
+ * Mostly needed for assets that are not set up by the account's first
2611
+ * deposit, or to change an existing account's strategy — `sendDeposit`
2612
+ * ignores its `strategy` argument after the first deposit.
2613
+ *
2614
+ * @param params.asset - Asset to configure
2615
+ * @param params.strategy - Strategy to apply; defaults to the one already
2616
+ * stored for this asset (`"conservative"` on a fresh account), which lets
2617
+ * you recompute a protocol list without changing the strategy
2618
+ * @param params.chains - Chains to enable. Defaults to every chain the asset
2619
+ * exists on. **Additive**: chains already enabled are kept, so this cannot
2620
+ * be used to disable one.
2621
+ * @returns The updated profile for that asset
2622
+ *
2623
+ * @example
2624
+ * ```typescript
2625
+ * // NVDAc only lives in async protocols, so it needs "yieldmaxxing".
2626
+ * // Chains default to Base, the only chain it exists on.
2627
+ * const profile = await sdk.setAssetStrategy({
2628
+ * asset: "NVDAc",
2629
+ * strategy: "yieldmaxxing",
2630
+ * });
2631
+ * console.log(profile.protocols); // Ipor + Superform
2632
+ * ```
2633
+ */
2634
+ async setAssetStrategy(params) {
2635
+ const { asset, strategy, chains } = params;
2636
+ try {
2637
+ if (strategy !== void 0 && !isValidPublicStrategy(strategy)) {
2638
+ throw new Error(
2639
+ `Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
2640
+ );
2641
+ }
2642
+ const supported = getAssetChainIds(asset);
2643
+ if (supported.length === 0) {
2644
+ throw new Error(`Unsupported asset: ${asset}.`);
2645
+ }
2646
+ const targetChains = chains ?? supported;
2647
+ const unsupported = targetChains.filter((c) => !supported.includes(c));
2648
+ if (unsupported.length > 0) {
2649
+ throw new Error(
2650
+ `${asset} is not available on chain ${unsupported.join(
2651
+ ", "
2652
+ )}. Supported chains: ${supported.join(", ")}.`
2653
+ );
2654
+ }
2655
+ const allProtocols = await this.httpClient.get(
2656
+ ENDPOINTS.PROTOCOLS()
2657
+ );
2658
+ return await this.updateUserProtocolsForAsset(
2659
+ asset,
2660
+ targetChains,
2661
+ strategy,
2662
+ allProtocols
2663
+ );
2664
+ } catch (error) {
2665
+ throw new Error(
2666
+ `Failed to set ${asset} strategy: ${error.message}`
2667
+ );
2668
+ }
2669
+ }
2503
2670
  /**
2504
2671
  * Drop protocols that have no pools on any of the selected chains for the
2505
2672
  * requested asset. The /customization/pools endpoint filters server-side on
@@ -2554,55 +2721,6 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2554
2721
  return value;
2555
2722
  });
2556
2723
  }
2557
- /**
2558
- * Deposit funds from EOA to Safe smart wallet
2559
- * Transfers tokens from the connected wallet to the user's Safe and logs the deposit
2560
- *
2561
- * Token address is selected from `asset` for the given chain:
2562
- * - Ethereum Mainnet (1), Base (8453), Arbitrum (42161): USDC or WETH
2563
- * - Ethereum Mainnet (1), Base (8453): EURC
2564
- *
2565
- * On the account's first deposit (USDC profile has no chains yet), patches
2566
- * protocol selection for USDC, WETH, and EURC across all supported chains
2567
- * (EURC on Mainnet/Base only) before the transfer and log_deposit.
2568
- * Pass `strategy` to select protocols for that first-deposit setup
2569
- * (same role as the former `deploySafe` strategy argument). On every later
2570
- * deposit the argument is ignored without error, since re-running the patch
2571
- * would overwrite a protocol selection the user may have customised. To
2572
- * change the strategy of an existing account, call
2573
- * `updateUserProfile({ asset, strategy })`.
2574
- *
2575
- * Minimum portfolio balance enforced (Safe balance + deposit amount):
2576
- * - Stablecoins: `MIN_PORTFOLIO_BALANCE` (Mainnet 10,000 USDC/EURC; Base/Arbitrum 100)
2577
- * - WETH: about $10,000 on Mainnet, $100 on Base/Arbitrum, from Data API `/price?token=eth`
2578
- *
2579
- * @param userAddress - User's address (owner of the Safe)
2580
- * @param chainId - Target chain ID
2581
- * @param amount - Amount in least decimal units (e.g., "100000000" for 100 USDC with 6 decimals)
2582
- * @param asset - Asset symbol: "USDC", "WETH", or "EURC".
2583
- * EURC is supported on Ethereum Mainnet and Base only.
2584
- * @param strategy - Optional strategy for first-deposit protocol patching:
2585
- * "conservative" (default), "aggressive" or "yieldmaxxing". Ignored on
2586
- * later deposits — use `updateUserProfile` to change an existing account.
2587
- * @returns Deposit response with transaction hash
2588
- *
2589
- * @example
2590
- * ```typescript
2591
- * // Deposit 10,000 USDC (6 decimals) to Safe on Base
2592
- * const result = await sdk.depositFunds(
2593
- * "0xUser...",
2594
- * 8453,
2595
- * "10000000000",
2596
- * "USDC"
2597
- * );
2598
- *
2599
- * // First deposit with aggressive strategy
2600
- * await sdk.depositFunds(userAddress, 8453, "10000000000", "USDC", "aggressive");
2601
- *
2602
- * // Changing the strategy of an account that has already deposited
2603
- * await sdk.updateUserProfile({ asset: "USDC", strategy: "yieldmaxxing" });
2604
- * ```
2605
- */
2606
2724
  /**
2607
2725
  * Deploy the connected predeployed (pool) wallet on one or more chains.
2608
2726
  *
@@ -2613,7 +2731,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2613
2731
  * resolves once all requested chains have landed on-chain. Idempotent — chains
2614
2732
  * already deployed are a no-op.
2615
2733
  *
2616
- * Optional for deposits: `depositFunds` no longer pre-deploys the target chain — the ERC20
2734
+ * Optional for deposits: `sendDeposit` no longer pre-deploys the target chain — the ERC20
2617
2735
  * transfer lands on the counterfactual address and the backend deploys + hands over on first
2618
2736
  * deposit (report-deposit). Use this only to pre-provision chains ahead of time.
2619
2737
  *
@@ -2629,7 +2747,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2629
2747
  await this.authenticateUser();
2630
2748
  return this.httpClient.post(ENDPOINTS.DEPLOY_CHAINS, { chainIds });
2631
2749
  }
2632
- async depositFunds(userAddress, chainId, amount, asset, strategy) {
2750
+ /**
2751
+ * Send a deposit from an EOA to its Safe smart wallet.
2752
+ *
2753
+ * Confirms the ERC-20 transfer and starts the custody-credit lifecycle. Use
2754
+ * `waitForDepositCredit(result.registration.id, chainId)` to await credit.
2755
+ */
2756
+ async sendDeposit(userAddress, chainId, amount, asset, strategy) {
2633
2757
  try {
2634
2758
  if (!userAddress) {
2635
2759
  throw new Error("User address is required");
@@ -2648,35 +2772,51 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2648
2772
  `Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
2649
2773
  );
2650
2774
  }
2651
- const assetSymbol = asset.toUpperCase();
2775
+ const assetSymbol = resolveAssetSymbol(asset);
2652
2776
  const assetConfig = ASSET_CONFIGS[assetSymbol];
2653
- if (!assetConfig) {
2777
+ const assetChains = getAssetChainIds(assetSymbol);
2778
+ if (!assetChains.includes(chainId)) {
2654
2779
  throw new Error(
2655
- `Unsupported asset: ${assetSymbol}. Supported: USDC, WETH, EURC.`
2656
- );
2657
- }
2658
- let minRequired = MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
2659
- if (assetSymbol === "WETH") {
2660
- const priceResponse = await this.httpClient.dataGet(
2661
- DATA_ENDPOINTS.TOKEN_PRICE("eth")
2662
- );
2663
- minRequired = minWethWeiForUsd(
2664
- parseEthUsdPrice(priceResponse),
2665
- MIN_WETH_USD[chainId]
2780
+ `${assetSymbol} is not available on chain ${chainId}. Supported chains: ${assetChains.join(
2781
+ ", "
2782
+ )}.`
2666
2783
  );
2667
2784
  }
2785
+ let minRequired = this.bypassMinPortfolio ? void 0 : MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
2786
+ const minUsd = this.bypassMinPortfolio ? void 0 : MIN_PORTFOLIO_USD[chainId]?.[assetSymbol];
2668
2787
  const token = getDefaultTokenAddress(chainId, assetSymbol);
2669
2788
  const walletClient = this.getWalletClient();
2670
- await this.authenticateUser();
2671
2789
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
2790
+ if (minUsd !== void 0) {
2791
+ const [, priceResponse] = await Promise.all([
2792
+ this.authenticateUser(),
2793
+ this.httpClient.dataGet(
2794
+ DATA_ENDPOINTS.TOKEN_PRICE(assetConfig.priceTokenSymbol)
2795
+ )
2796
+ ]);
2797
+ minRequired = usdToTokenUnits(
2798
+ minUsd,
2799
+ parseTokenUsdPrice(priceResponse),
2800
+ assetConfig.decimals
2801
+ );
2802
+ } else {
2803
+ await this.authenticateUser();
2804
+ }
2672
2805
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
2673
2806
  if (!safeAddress) {
2674
2807
  throw new Error("Smart wallet address is not available");
2675
2808
  }
2676
- const isDeployed = await isSafeDeployed(
2677
- safeAddress,
2678
- chainConfig.publicClient
2679
- );
2809
+ const amountBigInt = BigInt(amount);
2810
+ const [isDeployed, currentSafeBalance] = await Promise.all([
2811
+ isSafeDeployed(safeAddress, chainConfig.publicClient),
2812
+ minRequired !== void 0 ? chainConfig.publicClient.readContract({
2813
+ address: token,
2814
+ abi: ERC20_ABI,
2815
+ functionName: "balanceOf",
2816
+ args: [safeAddress]
2817
+ }) : Promise.resolve(void 0),
2818
+ this.prepareFirstDeposit(strategy)
2819
+ ]).then(([deployed, balance]) => [deployed, balance]);
2680
2820
  if (!isDeployed) {
2681
2821
  if (!(this.isPredeployed && this.isConnectedUser(userAddress))) {
2682
2822
  throw new Error(
@@ -2684,26 +2824,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2684
2824
  );
2685
2825
  }
2686
2826
  }
2687
- try {
2688
- const usdcDetails = await this.getUserDetails("USDC");
2689
- if ((usdcDetails.chains?.length ?? 0) === 0) {
2690
- await this.updateUserProtocols(strategy);
2691
- }
2692
- } catch (protocolError) {
2693
- console.warn(
2694
- "Failed to update user protocols before deposit:",
2695
- protocolError.message
2696
- );
2697
- }
2698
- const amountBigInt = BigInt(amount);
2699
2827
  if (minRequired !== void 0) {
2700
- const currentSafeBalance = await chainConfig.publicClient.readContract({
2701
- address: token,
2702
- abi: ERC20_ABI,
2703
- functionName: "balanceOf",
2704
- args: [safeAddress]
2705
- });
2706
- const totalAfterDeposit = currentSafeBalance + amountBigInt;
2828
+ const safeBalance = currentSafeBalance;
2829
+ const totalAfterDeposit = safeBalance + amountBigInt;
2707
2830
  if (totalAfterDeposit < minRequired) {
2708
2831
  const minLabel = formatMinPortfolioLabel(
2709
2832
  minRequired,
@@ -2711,7 +2834,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2711
2834
  assetSymbol
2712
2835
  );
2713
2836
  throw new Error(
2714
- `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).`
2837
+ `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).`
2715
2838
  );
2716
2839
  }
2717
2840
  }
@@ -2729,27 +2852,208 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2729
2852
  if (receipt.status !== "success") {
2730
2853
  throw new Error("Deposit transaction failed");
2731
2854
  }
2732
- try {
2733
- await this.logDeposit(chainId, txHash, amount, token);
2734
- } catch (logError) {
2735
- throw new Error(
2736
- `On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}") to retry.`
2737
- );
2738
- }
2855
+ const registration = await this.registerDeposit(
2856
+ chainId,
2857
+ txHash,
2858
+ amount,
2859
+ token
2860
+ );
2739
2861
  return {
2740
2862
  success: true,
2741
2863
  txHash,
2742
2864
  smartWallet: safeAddress,
2743
- amount: amountBigInt.toString()
2865
+ amount: amountBigInt.toString(),
2866
+ registration
2744
2867
  };
2745
2868
  } catch (error) {
2746
2869
  throw new Error(`Deposit failed: ${error.message}`);
2747
2870
  }
2748
2871
  }
2872
+ /**
2873
+ * @deprecated Compatibility convenience method. Prefer `sendDeposit()` followed by
2874
+ * `waitForDepositCredit()` when the caller owns the completion UX.
2875
+ */
2876
+ async depositFunds(userAddress, chainId, amount, asset, strategy) {
2877
+ this.warnDeprecatedOnboardingMethod("depositFunds");
2878
+ const sent = await this.sendDeposit(
2879
+ userAddress,
2880
+ chainId,
2881
+ amount,
2882
+ asset,
2883
+ strategy
2884
+ );
2885
+ return {
2886
+ ...sent,
2887
+ registration: await this.waitForDepositCredit(
2888
+ sent.registration.id,
2889
+ chainId
2890
+ )
2891
+ };
2892
+ }
2893
+ /**
2894
+ * Prepare ERC-20 transfer calldata for builders using a custom signer,
2895
+ * sponsored transaction provider, or mobile wallet. Most custom-wallet
2896
+ * integrations can compose this with `ensureFirstDepositSetup()` and
2897
+ * `logDeposit()` instead.
2898
+ */
2899
+ async buildDepositTransfer(params) {
2900
+ const { userAddress, chainId, amount, asset } = params;
2901
+ if (!userAddress || !amount || BigInt(amount) <= 0n) {
2902
+ throw new Error("A user address and positive amount are required");
2903
+ }
2904
+ if (!isSupportedChain(chainId)) {
2905
+ throw new Error(`Unsupported chain ID: ${chainId}`);
2906
+ }
2907
+ const assetSymbol = resolveAssetSymbol(asset);
2908
+ const assetChains = getAssetChainIds(assetSymbol);
2909
+ if (!assetChains.includes(chainId)) {
2910
+ throw new Error(
2911
+ `${assetSymbol} is not available on chain ${chainId}. Supported chains: ${assetChains.join(
2912
+ ", "
2913
+ )}.`
2914
+ );
2915
+ }
2916
+ const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
2917
+ if (!safeAddress) {
2918
+ throw new Error("Smart wallet address is not available");
2919
+ }
2920
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
2921
+ const isDeployed = await isSafeDeployed(
2922
+ safeAddress,
2923
+ chainConfig.publicClient
2924
+ );
2925
+ if (!(isDeployed || this.isPredeployed && this.isConnectedUser(userAddress))) {
2926
+ throw new Error(
2927
+ `Safe not available for ${userAddress} on chain ${chainId}.`
2928
+ );
2929
+ }
2930
+ const amountBigInt = BigInt(amount);
2931
+ await this.enforceMinimumPortfolioBalance(
2932
+ chainId,
2933
+ asset,
2934
+ amountBigInt,
2935
+ safeAddress
2936
+ );
2937
+ const tokenAddress = getDefaultTokenAddress(
2938
+ chainId,
2939
+ assetSymbol
2940
+ );
2941
+ return {
2942
+ safeAddress,
2943
+ tokenAddress,
2944
+ to: tokenAddress,
2945
+ data: encodeFunctionData({
2946
+ abi: ERC20_ABI,
2947
+ functionName: "transfer",
2948
+ args: [safeAddress, amountBigInt]
2949
+ }),
2950
+ value: "0"
2951
+ };
2952
+ }
2953
+ /** Apply the same per-asset minimum portfolio rule as sendDeposit. */
2954
+ async enforceMinimumPortfolioBalance(chainId, asset, amount, safeAddress) {
2955
+ if (this.bypassMinPortfolio) {
2956
+ return;
2957
+ }
2958
+ const assetSymbol = resolveAssetSymbol(asset);
2959
+ const assetConfig = ASSET_CONFIGS[assetSymbol];
2960
+ let minRequired = MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
2961
+ const minUsd = MIN_PORTFOLIO_USD[chainId]?.[assetSymbol];
2962
+ if (minUsd !== void 0) {
2963
+ const [, priceResponse] = await Promise.all([
2964
+ this.authenticateUser(),
2965
+ this.httpClient.dataGet(
2966
+ DATA_ENDPOINTS.TOKEN_PRICE(assetConfig.priceTokenSymbol)
2967
+ )
2968
+ ]);
2969
+ minRequired = usdToTokenUnits(
2970
+ minUsd,
2971
+ parseTokenUsdPrice(priceResponse),
2972
+ assetConfig.decimals
2973
+ );
2974
+ }
2975
+ if (minRequired === void 0) return;
2976
+ const chainConfig = getChainConfig(chainId, this.rpcUrls);
2977
+ const token = getDefaultTokenAddress(chainId, assetSymbol);
2978
+ const currentSafeBalance = await chainConfig.publicClient.readContract({
2979
+ address: token,
2980
+ abi: ERC20_ABI,
2981
+ functionName: "balanceOf",
2982
+ args: [safeAddress]
2983
+ });
2984
+ const totalAfterDeposit = currentSafeBalance + amount;
2985
+ if (totalAfterDeposit < minRequired) {
2986
+ const minLabel = formatMinPortfolioLabel(
2987
+ minRequired,
2988
+ assetConfig.decimals,
2989
+ assetSymbol
2990
+ );
2991
+ throw new Error(
2992
+ `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).`
2993
+ );
2994
+ }
2995
+ }
2996
+ /**
2997
+ * Idempotently apply the first-deposit profile configuration for builders
2998
+ * composing an advanced custom transfer flow. Most custom-wallet
2999
+ * integrations can use this with `buildDepositTransfer()` and `logDeposit()`.
3000
+ *
3001
+ * When setup runs (`applied: true`), protocol configuration is persisted
3002
+ * before returning. Failures throw so callers can abort before submitting a
3003
+ * transfer. High-level deposit methods still treat setup as best-effort.
3004
+ */
3005
+ async ensureFirstDepositSetup(strategy) {
3006
+ if (strategy !== void 0 && !isValidPublicStrategy(strategy)) {
3007
+ throw new Error(
3008
+ `Invalid strategy: ${strategy}. Must be "conservative", "aggressive" or "yieldmaxxing".`
3009
+ );
3010
+ }
3011
+ await this.authenticateUser();
3012
+ const usdcDetails = await this.getUserDetails("USDC");
3013
+ if ((usdcDetails.chains?.length ?? 0) > 0) {
3014
+ return { applied: false };
3015
+ }
3016
+ await this.updateUserProtocols(strategy, { strict: true });
3017
+ const usdcAfterSetup = await this.getUserDetails("USDC");
3018
+ if ((usdcAfterSetup.chains?.length ?? 0) === 0) {
3019
+ throw new Error(
3020
+ "First-deposit setup did not persist USDC chain configuration."
3021
+ );
3022
+ }
3023
+ return { applied: true };
3024
+ }
3025
+ /** Best-effort first-deposit setup shared by both high-level deposit flows. */
3026
+ async prepareFirstDeposit(strategy) {
3027
+ try {
3028
+ await this.ensureFirstDepositSetup(strategy);
3029
+ } catch (protocolError) {
3030
+ console.warn(
3031
+ "Failed to update user protocols before deposit:",
3032
+ protocolError.message
3033
+ );
3034
+ }
3035
+ }
3036
+ /** Shared post-transfer registration path for every deposit flow. */
3037
+ async registerDeposit(chainId, txHash, amount, tokenAddress) {
3038
+ let registration;
3039
+ try {
3040
+ registration = await this.logDeposit(
3041
+ chainId,
3042
+ txHash,
3043
+ amount,
3044
+ tokenAddress
3045
+ );
3046
+ } catch (logError) {
3047
+ throw new Error(
3048
+ `On-chain deposit succeeded (tx=${txHash}) but backend registration failed: ${logError.message}. Call connectAccount() then logDeposit(${chainId}, "${txHash}", "${amount}") to retry.`
3049
+ );
3050
+ }
3051
+ return registration.deposit;
3052
+ }
2749
3053
  /**
2750
3054
  * Log a deposit that was executed client-side.
2751
3055
  *
2752
- * `depositFunds()` already calls this after the ERC20 transfer. If you send the
3056
+ * `sendDeposit()` already calls this after the ERC20 transfer. If you send the
2753
3057
  * transfer yourself (front, Privy, Biconomy, custom wallet) you **must** call
2754
3058
  * `logDeposit` — otherwise the backend never sees the deposit: a reserved pool
2755
3059
  * wallet stays reserved (no ownership rotation), and yield/agent tracking does
@@ -2806,20 +3110,77 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2806
3110
  }
2807
3111
  const token = tokenAddress || getDefaultTokenAddress(chainId);
2808
3112
  await this.authenticateUser();
2809
- await this.httpClient.post(ENDPOINTS.LOG_DEPOSIT, {
2810
- chainId,
2811
- transaction: txHash,
2812
- token,
2813
- amount
2814
- });
3113
+ const deposit = await this.httpClient.post(
3114
+ ENDPOINTS.LOG_DEPOSIT,
3115
+ {
3116
+ chainId,
3117
+ transaction: txHash,
3118
+ token,
3119
+ amount
3120
+ }
3121
+ );
2815
3122
  return {
2816
3123
  success: true,
2817
- message: "Deposit logged successfully"
3124
+ message: deposit.status === "credited" ? "Deposit credited successfully" : "Deposit accepted; custody handover is pending",
3125
+ deposit
2818
3126
  };
2819
3127
  } catch (error) {
2820
3128
  throw new Error(`Log deposit failed: ${error.message}`);
2821
3129
  }
2822
3130
  }
3131
+ /**
3132
+ * Fetch the custody handover and balance-credit lifecycle for a registered
3133
+ * deposit. A status of `credited` is required before funds are investable.
3134
+ */
3135
+ async getDepositStatus(depositId) {
3136
+ if (!depositId) {
3137
+ throw new Error("Deposit ID is required");
3138
+ }
3139
+ await this.authenticateUser();
3140
+ return this.httpClient.get(
3141
+ ENDPOINTS.DEPOSIT_STATUS(depositId)
3142
+ );
3143
+ }
3144
+ /**
3145
+ * Await deposit credit after `logDeposit` returns `handover_pending`.
3146
+ *
3147
+ * Polls `getDepositStatus` until `status === "credited"` and
3148
+ * `balanceCredited === true`. Rejects on recovery, timeout, or poll errors.
3149
+ *
3150
+ * Poll interval and timeout are chain-specific. Mainnet defaults to a 2s
3151
+ * interval and 1 minute ceiling; Base/Arbitrum use tighter polling (~500ms /
3152
+ * ~250ms) with a ~20 second completion window. Override `timeoutMs` when a
3153
+ * caller intentionally wants to wait longer than the normal UX window.
3154
+ *
3155
+ * Requires `connectAccount()` on the same SDK instance first.
3156
+ */
3157
+ async waitForDepositCredit(depositId, chainId, options) {
3158
+ if (!depositId) {
3159
+ throw new Error("Deposit ID is required");
3160
+ }
3161
+ if (!isSupportedChain(chainId)) {
3162
+ throw new Error(`Unsupported chain ID: ${chainId}`);
3163
+ }
3164
+ const intervalMs = options?.intervalMs ?? getDepositCreditIntervalMs(chainId);
3165
+ const timeoutMs = options?.timeoutMs ?? getDepositCreditTimeoutMs(chainId);
3166
+ const started = Date.now();
3167
+ while (Date.now() - started < timeoutMs) {
3168
+ const status = await this.getDepositStatus(depositId);
3169
+ if (status.status === "credited" && status.balanceCredited) {
3170
+ return status;
3171
+ }
3172
+ if (status.status === "recovered_to_eoa") {
3173
+ throw new Error(
3174
+ `Deposit ${depositId} recovered to EOA (status=${status.status}); balance was not credited`
3175
+ );
3176
+ }
3177
+ if (Date.now() - started >= timeoutMs) {
3178
+ break;
3179
+ }
3180
+ await sleep(intervalMs);
3181
+ }
3182
+ throw new DepositCreditTimeoutError(depositId);
3183
+ }
2823
3184
  /**
2824
3185
  * Withdraw funds from Safe smart wallet
2825
3186
  * Initiates a withdrawal request to the Zyfai API
@@ -2839,6 +3200,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2839
3200
  * When every source is an async pool nothing settles on-chain at that point,
2840
3201
  * so `txHash` is `undefined` on a successful call.
2841
3202
  *
3203
+ * **One redemption per pool at a time.** While an entry for a pool is
3204
+ * `REQUESTED` or `CLAIMABLE`, the backend drops a further withdrawal aimed at
3205
+ * that same pool — the protocols behind it (ERC-7540) hold a single request
3206
+ * slot per user. This method throws rather than reporting that no-op as a
3207
+ * success. It only throws when nothing the call could reach is withdrawable:
3208
+ * another pool, another asset or an idle Safe balance still goes through.
3209
+ *
2842
3210
  * Once requested, that amount can no longer be withdrawn: it is gone from
2843
3211
  * both the position snapshot and the Safe balance, so a second call silently
2844
3212
  * returns only what is left. Validate user-entered amounts against
@@ -2887,6 +3255,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2887
3255
  );
2888
3256
  }
2889
3257
  await this.authenticateUser();
3258
+ await this.assertAsyncRedemptionSlotFree(
3259
+ userAddress,
3260
+ chainId,
3261
+ tokenSymbol
3262
+ );
2890
3263
  let response = {};
2891
3264
  if (amount) {
2892
3265
  response = await this.httpClient.post(ENDPOINTS.PARTIAL_WITHDRAW, {
@@ -2914,6 +3287,31 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2914
3287
  throw new Error(`Withdrawal failed: ${error.message}`);
2915
3288
  }
2916
3289
  }
3290
+ /**
3291
+ * Turn a withdrawal the backend would silently drop — one aimed only at
3292
+ * async pools that already hold an in-flight redemption — into an error, so
3293
+ * the caller gets an answer rather than a `success: true` no-op.
3294
+ *
3295
+ * @internal
3296
+ */
3297
+ async assertAsyncRedemptionSlotFree(userAddress, chainId, tokenSymbol) {
3298
+ let portfolio;
3299
+ try {
3300
+ ({ portfolio } = await this.getPortfolio(userAddress));
3301
+ } catch {
3302
+ return;
3303
+ }
3304
+ const blocking = findBlockingAsyncRedemption(
3305
+ portfolio,
3306
+ chainId,
3307
+ tokenSymbol
3308
+ );
3309
+ if (!blocking) return;
3310
+ const eta = blocking.estimatedClaimAt ? ` Estimated settlement: ${blocking.estimatedClaimAt}.` : "";
3311
+ throw new Error(
3312
+ `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}`
3313
+ );
3314
+ }
2917
3315
  /**
2918
3316
  * Get available DeFi protocols and pools for a specific chain
2919
3317
  *
@@ -3219,7 +3617,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3219
3617
  */
3220
3618
  async getVolume(assetType = "usdc") {
3221
3619
  try {
3222
- const response = await this.httpClient.get(ENDPOINTS.DATA_VOLUME(assetType));
3620
+ const response = await this.httpClient.get(
3621
+ ENDPOINTS.DATA_VOLUME(assetType)
3622
+ );
3223
3623
  return {
3224
3624
  success: true,
3225
3625
  volumeInUSD: response.volumeInUSD || "0"
@@ -3996,9 +4396,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
3996
4396
  }
3997
4397
  };
3998
4398
  } catch (error) {
3999
- throw new Error(
4000
- `Failed to get SDK key TVL: ${error.message}`
4001
- );
4399
+ throw new Error(`Failed to get SDK key TVL: ${error.message}`);
4002
4400
  }
4003
4401
  }
4004
4402
  // ============================================================================
@@ -4181,7 +4579,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4181
4579
  * Check if a chain ID supports the Identity Registry
4182
4580
  */
4183
4581
  isSupportedIdentityRegistryChain(chainId) {
4184
- return _ZyfaiSDK.IDENTITY_REGISTRY_CHAIN_IDS.includes(chainId);
4582
+ return _ZyfaiSDK.IDENTITY_REGISTRY_CHAIN_IDS.includes(
4583
+ chainId
4584
+ );
4185
4585
  }
4186
4586
  /**
4187
4587
  * Register an agent on the Identity Registry (ERC-8004)
@@ -4278,7 +4678,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4278
4678
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
4279
4679
  const tokenAddress = getDefaultTokenAddress(chainId, asset);
4280
4680
  const decimals = 6;
4281
- const parsedAmount = BigInt(Math.floor(parseFloat(amount) * 10 ** decimals));
4681
+ const parsedAmount = BigInt(
4682
+ Math.floor(parseFloat(amount) * 10 ** decimals)
4683
+ );
4282
4684
  try {
4283
4685
  const allowance = await chainConfig.publicClient.readContract({
4284
4686
  address: tokenAddress,
@@ -4356,7 +4758,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4356
4758
  args: [userAddress]
4357
4759
  });
4358
4760
  if (maxShares === 0n) {
4359
- throw new Error("No shares available to redeem or withdrawals are paused");
4761
+ throw new Error(
4762
+ "No shares available to redeem or withdrawals are paused"
4763
+ );
4360
4764
  }
4361
4765
  sharesToRedeem = maxShares;
4362
4766
  }
@@ -4400,7 +4804,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4400
4804
  status: isClaimable ? "claimable" : "pending"
4401
4805
  };
4402
4806
  } catch (error) {
4403
- throw new Error(`Vault withdraw request failed: ${error.message}`);
4807
+ throw new Error(
4808
+ `Vault withdraw request failed: ${error.message}`
4809
+ );
4404
4810
  }
4405
4811
  }
4406
4812
  /**
@@ -4480,7 +4886,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4480
4886
  nonce
4481
4887
  };
4482
4888
  } catch (error) {
4483
- throw new Error(`Failed to get withdraw status: ${error.message}`);
4889
+ throw new Error(
4890
+ `Failed to get withdraw status: ${error.message}`
4891
+ );
4484
4892
  }
4485
4893
  }
4486
4894
  /**
@@ -4523,7 +4931,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4523
4931
  if (isClaimed) {
4524
4932
  throw new Error("This withdrawal has already been claimed");
4525
4933
  }
4526
- throw new Error("Withdrawal is not yet claimable. Please wait for processing.");
4934
+ throw new Error(
4935
+ "Withdrawal is not yet claimable. Please wait for processing."
4936
+ );
4527
4937
  }
4528
4938
  const claimTx = await this.walletClient.writeContract({
4529
4939
  address: VAULT_ADDRESS,
@@ -4563,7 +4973,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
4563
4973
  async getVaultShares(userAddress, chainId = 8453) {
4564
4974
  const address = userAddress || this.walletClient?.account?.address;
4565
4975
  if (!address) {
4566
- throw new Error("User address required. Provide address or connect wallet first.");
4976
+ throw new Error(
4977
+ "User address required. Provide address or connect wallet first."
4978
+ );
4567
4979
  }
4568
4980
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
4569
4981
  const [shareBalance, tokenSymbol] = await Promise.all([