@zyfai/sdk 0.2.52 → 0.2.54

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/README.md CHANGED
@@ -393,10 +393,11 @@ Transfer tokens to your Safe smart wallet. Token address is automatically select
393
393
 
394
394
  **Minimum portfolio balance (enforced on Safe balance + deposit amount):**
395
395
 
396
- - Ethereum Mainnet (1) / USDC: 5 USDC (test threshold — will be raised before production)
397
- - All other (chain, asset) pairs: no minimum enforced
396
+ - Ethereum Mainnet (1) / USDC or EURC: 10,000 units
397
+ - Base (8453) and Arbitrum (42161) / USDC or EURC: 100 units
398
+ - WETH: about **$10,000** of ETH on Ethereum Mainnet, **$100** on Base and Arbitrum, using the live USD price from Data API `GET /api/v2/price?token=eth` (same API key as the SDK)
398
399
 
399
- Only deposits on Mainnet in USDC that would leave the Safe below 5 USDC are rejected. Deposits on Base or Arbitrum, or in WETH/EURC, have no minimum today.
400
+ Top-ups smaller than the minimum are allowed if the Safe already holds enough of the asset to meet it after the deposit.
400
401
 
401
402
  ```typescript
402
403
  // Deposit 10 USDC (6 decimals) to Safe on Base — no minimum on Base
@@ -420,7 +421,7 @@ if (result.success) {
420
421
 
421
422
  - Amount must be in least decimal units. For USDC (6 decimals): 1 USDC = 1000000
422
423
  - `asset` is required (`"USDC"`, `"WETH"`, or `"EURC"` — EURC on Mainnet/Base only); token address is selected from that for the chain
423
- - On Ethereum Mainnet, the total Safe balance in USDC must be at least 5 USDC after the deposit (test threshold); smaller top-ups are allowed if the Safe already holds enough USDC to meet the minimum
424
+ - The total Safe balance must meet the per-asset minimum after the deposit (see above). WETH uses a live ETH/USD price, so the wei threshold moves with the market.
424
425
  - The SDK automatically authenticates via SIWE before logging the deposit with Zyfai's API, so no extra steps are required on your end once the transfer confirms
425
426
  - **First deposit only** (before transfer + `log_deposit`): if the USDC profile has no `chains` yet, the SDK patches protocols for **USDC, WETH, and EURC** across all supported chains (EURC on Mainnet/Base only → `assetTypeSettings.[usdc|eth|eurc]`). Pass optional `strategy` (`"conservative"` default or `"aggressive"`) — same role as the former `deploySafe` strategy argument. Later deposits skip this.
426
427
 
@@ -530,7 +531,7 @@ positions.positions.forEach((bundle) => {
530
531
  });
531
532
  ```
532
533
 
533
- **Note**: This endpoint uses `/api/v1/data/position?walletAddress={address}` (Smart wallet address) and returns bundles with nested slot data. Use each slot's `underlyingAmount` for the canonical token balance.
534
+ **Note**: This endpoint uses `/api/v1/data/position?walletAddress={address}` (Smart wallet address) and returns bundles with nested slot data. Use each slot's `underlyingAmount` for the canonical token balance. The Safe is resolved via `getSafeAddressFor` (backend-assigned for predeployed wallets, registered agent for legacy). An EOA with no agent returns an empty portfolio — the SDK does not derive a CREATE2 address. Optional `chainId` defaults to Base (8453) for that resolution only.
534
535
 
535
536
  #### Get Portfolio (with fee-adjusted balances)
536
537
 
@@ -749,6 +750,10 @@ history.data.forEach((tx) => {
749
750
  console.log(tx.rebalanceLog.oldApy, tx.rebalanceLog.oldApy_withFee);
750
751
  console.log(tx.rebalanceLog.newApy, tx.rebalanceLog.newApy_withFee);
751
752
  }
753
+ tx.positions?.forEach((pos) => {
754
+ console.log(pos.amount); // resulting position balance after the action
755
+ console.log(pos.deltaAmount); // amount actually moved by the action (optional, not on older entries)
756
+ });
752
757
  });
753
758
  ```
754
759
 
package/dist/index.d.mts CHANGED
@@ -266,6 +266,12 @@ interface HistoryPosition {
266
266
  token_symbol?: string;
267
267
  protocol_icon?: string;
268
268
  protocol_name?: string;
269
+ /**
270
+ * The amount actually moved by this action (deposit/withdraw/rebalance delta),
271
+ * as opposed to `amount`, which is the resulting position balance after the action.
272
+ * Optional: not present on older history entries or actions that predate this field.
273
+ */
274
+ deltaAmount?: string;
269
275
  }
270
276
  interface HistoryFeeData {
271
277
  gasCostInToken?: string;
@@ -939,13 +945,9 @@ declare class ZyfaiSDK {
939
945
  */
940
946
  private isConnectedUser;
941
947
  /**
942
- * Resolve the Safe smart wallet address for a user on a chain.
943
- *
944
- * Predeployed (pool) wallets are provisioned and owned by the backend at
945
- * deploy time, so their address CANNOT be derived from the user's EOA with
946
- * getDeterministicSafeAddress (CREATE2 from the EOA yields the wrong address).
947
- * For the connected predeployed user we always use the backend-assigned
948
- * address. Legacy wallets keep the API-first, deterministic-fallback behavior.
948
+ * Resolve the Safe address: backend-assigned for the connected predeployed
949
+ * user, registered agent for everyone else. If none, CREATE2-derive when
950
+ * `deriveIfMissing` is true; otherwise return null (read paths).
949
951
  * @private
950
952
  */
951
953
  private getSafeAddressFor;
@@ -1063,13 +1065,9 @@ declare class ZyfaiSDK {
1063
1065
  * Pass `strategy` to select protocols for that first-deposit setup
1064
1066
  * (same role as the former `deploySafe` strategy argument).
1065
1067
  *
1066
- * Minimum portfolio balance enforced (Safe balance + deposit amount),
1067
- * configured per-chain in `MIN_PORTFOLIO_BALANCE`:
1068
- * - Ethereum Mainnet (1): 5 USDC (test threshold)
1069
- * - Base (8453) & Arbitrum (42161): no minimum
1070
- *
1071
- * If no minimum is configured for a given (chainId, asset) pair,
1072
- * the check is skipped.
1068
+ * Minimum portfolio balance enforced (Safe balance + deposit amount):
1069
+ * - Stablecoins: `MIN_PORTFOLIO_BALANCE` (Mainnet 10,000 USDC/EURC; Base/Arbitrum 100)
1070
+ * - WETH: about $10,000 on Mainnet, $100 on Base/Arbitrum, from Data API `/price?token=eth`
1073
1071
  *
1074
1072
  * @param userAddress - User's address (owner of the Safe)
1075
1073
  * @param chainId - Target chain ID
@@ -1104,8 +1102,9 @@ declare class ZyfaiSDK {
1104
1102
  * resolves once all requested chains have landed on-chain. Idempotent — chains
1105
1103
  * already deployed are a no-op.
1106
1104
  *
1107
- * `depositFunds` calls this automatically when the target chain isn't deployed,
1108
- * so most integrations never need it directly; use it to pre-provision chains.
1105
+ * Optional for deposits: `depositFunds` no longer pre-deploys the target chain — the ERC20
1106
+ * transfer lands on the counterfactual address and the backend deploys + hands over on first
1107
+ * deposit (report-deposit). Use this only to pre-provision chains ahead of time.
1109
1108
  *
1110
1109
  * @param chainIds - Chain IDs to deploy the wallet on (e.g. [1, 42161])
1111
1110
  */
@@ -1115,11 +1114,6 @@ declare class ZyfaiSDK {
1115
1114
  chains: number[];
1116
1115
  status: string;
1117
1116
  }>;
1118
- /**
1119
- * Poll until the Safe has code on-chain. The backend awaits landing before it
1120
- * responds, so this only guards against read-after-write RPC lag.
1121
- */
1122
- private waitForSafeDeployed;
1123
1117
  depositFunds(userAddress: string, chainId: SupportedChainId, amount: string, asset: string, strategy?: Strategy): Promise<DepositResponse>;
1124
1118
  /**
1125
1119
  * Log a deposit that was executed client-side
@@ -1205,7 +1199,7 @@ declare class ZyfaiSDK {
1205
1199
  * Get all active DeFi positions for a user
1206
1200
  *
1207
1201
  * @param userAddress - User's EOA address
1208
- * @param chainId - Optional: Filter by specific chain ID
1202
+ * @param chainId - Optional chain used to resolve the Safe address (defaults to Base 8453)
1209
1203
  * @returns User's positions across all protocols
1210
1204
  *
1211
1205
  * @example
package/dist/index.d.ts CHANGED
@@ -266,6 +266,12 @@ interface HistoryPosition {
266
266
  token_symbol?: string;
267
267
  protocol_icon?: string;
268
268
  protocol_name?: string;
269
+ /**
270
+ * The amount actually moved by this action (deposit/withdraw/rebalance delta),
271
+ * as opposed to `amount`, which is the resulting position balance after the action.
272
+ * Optional: not present on older history entries or actions that predate this field.
273
+ */
274
+ deltaAmount?: string;
269
275
  }
270
276
  interface HistoryFeeData {
271
277
  gasCostInToken?: string;
@@ -939,13 +945,9 @@ declare class ZyfaiSDK {
939
945
  */
940
946
  private isConnectedUser;
941
947
  /**
942
- * Resolve the Safe smart wallet address for a user on a chain.
943
- *
944
- * Predeployed (pool) wallets are provisioned and owned by the backend at
945
- * deploy time, so their address CANNOT be derived from the user's EOA with
946
- * getDeterministicSafeAddress (CREATE2 from the EOA yields the wrong address).
947
- * For the connected predeployed user we always use the backend-assigned
948
- * address. Legacy wallets keep the API-first, deterministic-fallback behavior.
948
+ * Resolve the Safe address: backend-assigned for the connected predeployed
949
+ * user, registered agent for everyone else. If none, CREATE2-derive when
950
+ * `deriveIfMissing` is true; otherwise return null (read paths).
949
951
  * @private
950
952
  */
951
953
  private getSafeAddressFor;
@@ -1063,13 +1065,9 @@ declare class ZyfaiSDK {
1063
1065
  * Pass `strategy` to select protocols for that first-deposit setup
1064
1066
  * (same role as the former `deploySafe` strategy argument).
1065
1067
  *
1066
- * Minimum portfolio balance enforced (Safe balance + deposit amount),
1067
- * configured per-chain in `MIN_PORTFOLIO_BALANCE`:
1068
- * - Ethereum Mainnet (1): 5 USDC (test threshold)
1069
- * - Base (8453) & Arbitrum (42161): no minimum
1070
- *
1071
- * If no minimum is configured for a given (chainId, asset) pair,
1072
- * the check is skipped.
1068
+ * Minimum portfolio balance enforced (Safe balance + deposit amount):
1069
+ * - Stablecoins: `MIN_PORTFOLIO_BALANCE` (Mainnet 10,000 USDC/EURC; Base/Arbitrum 100)
1070
+ * - WETH: about $10,000 on Mainnet, $100 on Base/Arbitrum, from Data API `/price?token=eth`
1073
1071
  *
1074
1072
  * @param userAddress - User's address (owner of the Safe)
1075
1073
  * @param chainId - Target chain ID
@@ -1104,8 +1102,9 @@ declare class ZyfaiSDK {
1104
1102
  * resolves once all requested chains have landed on-chain. Idempotent — chains
1105
1103
  * already deployed are a no-op.
1106
1104
  *
1107
- * `depositFunds` calls this automatically when the target chain isn't deployed,
1108
- * so most integrations never need it directly; use it to pre-provision chains.
1105
+ * Optional for deposits: `depositFunds` no longer pre-deploys the target chain — the ERC20
1106
+ * transfer lands on the counterfactual address and the backend deploys + hands over on first
1107
+ * deposit (report-deposit). Use this only to pre-provision chains ahead of time.
1109
1108
  *
1110
1109
  * @param chainIds - Chain IDs to deploy the wallet on (e.g. [1, 42161])
1111
1110
  */
@@ -1115,11 +1114,6 @@ declare class ZyfaiSDK {
1115
1114
  chains: number[];
1116
1115
  status: string;
1117
1116
  }>;
1118
- /**
1119
- * Poll until the Safe has code on-chain. The backend awaits landing before it
1120
- * responds, so this only guards against read-after-write RPC lag.
1121
- */
1122
- private waitForSafeDeployed;
1123
1117
  depositFunds(userAddress: string, chainId: SupportedChainId, amount: string, asset: string, strategy?: Strategy): Promise<DepositResponse>;
1124
1118
  /**
1125
1119
  * Log a deposit that was executed client-side
@@ -1205,7 +1199,7 @@ declare class ZyfaiSDK {
1205
1199
  * Get all active DeFi positions for a user
1206
1200
  *
1207
1201
  * @param userAddress - User's EOA address
1208
- * @param chainId - Optional: Filter by specific chain ID
1202
+ * @param chainId - Optional chain used to resolve the Safe address (defaults to Base 8453)
1209
1203
  * @returns User's positions across all protocols
1210
1204
  *
1211
1205
  * @example
package/dist/index.js CHANGED
@@ -151,6 +151,8 @@ var DATA_ENDPOINTS = {
151
151
  if (options?.tokenSymbol) params.push(`tokenSymbol=${options.tokenSymbol}`);
152
152
  return params.length > 0 ? `/rebalance/rebalance-info?${params.join("&")}` : "/rebalance/rebalance-info";
153
153
  },
154
+ // Token USD price (e.g. token=eth)
155
+ TOKEN_PRICE: (token) => `/price?token=${encodeURIComponent(token)}`,
154
156
  // APY Per Strategy
155
157
  APY_PER_STRATEGY: (options = {}) => {
156
158
  const params = [];
@@ -347,6 +349,27 @@ var HttpClient = class {
347
349
  }
348
350
  };
349
351
 
352
+ // src/utils/eth-price.ts
353
+ var PRICE_SCALE = 8;
354
+ var parseEthUsdPrice = (response) => {
355
+ const priceUsd = response?.data?.price_usd;
356
+ if (typeof priceUsd !== "number" || !Number.isFinite(priceUsd) || priceUsd <= 0) {
357
+ throw new Error("ETH/USD price must be a positive number");
358
+ }
359
+ return priceUsd;
360
+ };
361
+ var usdToWethWei = (usdAmount, ethUsd) => {
362
+ if (!Number.isFinite(ethUsd) || ethUsd <= 0) {
363
+ throw new Error("ETH/USD price must be positive");
364
+ }
365
+ const scaledPrice = BigInt(Math.round(ethUsd * 10 ** PRICE_SCALE));
366
+ if (scaledPrice <= 0n) {
367
+ throw new Error("ETH/USD price must be positive");
368
+ }
369
+ return usdAmount * 10n ** 18n * 10n ** BigInt(PRICE_SCALE) / scaledPrice;
370
+ };
371
+ var minWethWeiForUsd = (ethUsd, usdAmount) => usdToWethWei(usdAmount, ethUsd);
372
+
350
373
  // src/config/abis.ts
351
374
  var import_viem = require("viem");
352
375
  var OWNABLE_VALIDATOR_ABI = [
@@ -520,12 +543,29 @@ var ZYFI_FEE_RATE = 0.1;
520
543
  var ALLOWED_HISTORY_DAYS = [7, 14, 30, 60, 120, 180];
521
544
  var MIN_PORTFOLIO_BALANCE = {
522
545
  1: {
546
+ USDC: 10000n * 10n ** 6n,
547
+ // 10,000 USDC (6 decimals)
548
+ EURC: 10000n * 10n ** 6n
549
+ // 10,000 EURC (6 decimals)
550
+ },
551
+ 8453: {
552
+ USDC: 100n * 10n ** 6n,
553
+ // 100 USDC (6 decimals)
554
+ EURC: 100n * 10n ** 6n
555
+ // 100 EURC (6 decimals)
556
+ },
557
+ 42161: {
523
558
  USDC: 100n * 10n ** 6n,
524
559
  // 100 USDC (6 decimals)
525
- WETH: 5n * 10n ** 15n
526
- // 0.005 WETH (18 decimals)
560
+ EURC: 100n * 10n ** 6n
561
+ // 100 EURC (6 decimals)
527
562
  }
528
563
  };
564
+ var MIN_WETH_USD = {
565
+ 1: 10000n,
566
+ 8453: 100n,
567
+ 42161: 100n
568
+ };
529
569
  var formatMinPortfolioLabel = (raw, decimals, symbol) => {
530
570
  const base2 = 10n ** BigInt(decimals);
531
571
  const whole = raw / base2;
@@ -1953,16 +1993,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1953
1993
  return !!connected && connected.toLowerCase() === userAddress.toLowerCase();
1954
1994
  }
1955
1995
  /**
1956
- * Resolve the Safe smart wallet address for a user on a chain.
1957
- *
1958
- * Predeployed (pool) wallets are provisioned and owned by the backend at
1959
- * deploy time, so their address CANNOT be derived from the user's EOA with
1960
- * getDeterministicSafeAddress (CREATE2 from the EOA yields the wrong address).
1961
- * For the connected predeployed user we always use the backend-assigned
1962
- * address. Legacy wallets keep the API-first, deterministic-fallback behavior.
1996
+ * Resolve the Safe address: backend-assigned for the connected predeployed
1997
+ * user, registered agent for everyone else. If none, CREATE2-derive when
1998
+ * `deriveIfMissing` is true; otherwise return null (read paths).
1963
1999
  * @private
1964
2000
  */
1965
- async getSafeAddressFor(userAddress, chainId) {
2001
+ async getSafeAddressFor(userAddress, chainId, deriveIfMissing = true) {
1966
2002
  if (this.isPredeployed && this.isConnectedUser(userAddress)) {
1967
2003
  if (this.connectedSmartWallet) return this.connectedSmartWallet;
1968
2004
  try {
@@ -1970,6 +2006,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1970
2006
  if (info.smartWallet) return info.smartWallet;
1971
2007
  } catch {
1972
2008
  }
2009
+ if (!deriveIfMissing) return null;
1973
2010
  throw new Error(
1974
2011
  "Predeployed smart wallet address is not available from the API yet. Ensure the user has signed in so the pool can reserve their wallet."
1975
2012
  );
@@ -1979,6 +2016,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1979
2016
  if (info.smartWallet) return info.smartWallet;
1980
2017
  } catch {
1981
2018
  }
2019
+ if (!deriveIfMissing) return null;
1982
2020
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
1983
2021
  return getDeterministicSafeAddress({
1984
2022
  safeOwnerAddress: userAddress,
@@ -2006,6 +2044,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2006
2044
  }
2007
2045
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
2008
2046
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
2047
+ if (!safeAddress) {
2048
+ throw new Error("Smart wallet address is not available");
2049
+ }
2009
2050
  const isDeployed = await isSafeDeployed(
2010
2051
  safeAddress,
2011
2052
  chainConfig.publicClient
@@ -2058,6 +2099,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2058
2099
  userAddress,
2059
2100
  chainId
2060
2101
  );
2102
+ if (!predeployedAddress) {
2103
+ throw new Error(
2104
+ "Predeployed smart wallet address is not available from the API yet. Ensure the user has signed in so the pool can reserve their wallet."
2105
+ );
2106
+ }
2061
2107
  try {
2062
2108
  await this.initializeUser(predeployedAddress, chainId);
2063
2109
  } catch (initError) {
@@ -2446,13 +2492,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2446
2492
  * Pass `strategy` to select protocols for that first-deposit setup
2447
2493
  * (same role as the former `deploySafe` strategy argument).
2448
2494
  *
2449
- * Minimum portfolio balance enforced (Safe balance + deposit amount),
2450
- * configured per-chain in `MIN_PORTFOLIO_BALANCE`:
2451
- * - Ethereum Mainnet (1): 5 USDC (test threshold)
2452
- * - Base (8453) & Arbitrum (42161): no minimum
2453
- *
2454
- * If no minimum is configured for a given (chainId, asset) pair,
2455
- * the check is skipped.
2495
+ * Minimum portfolio balance enforced (Safe balance + deposit amount):
2496
+ * - Stablecoins: `MIN_PORTFOLIO_BALANCE` (Mainnet 10,000 USDC/EURC; Base/Arbitrum 100)
2497
+ * - WETH: about $10,000 on Mainnet, $100 on Base/Arbitrum, from Data API `/price?token=eth`
2456
2498
  *
2457
2499
  * @param userAddress - User's address (owner of the Safe)
2458
2500
  * @param chainId - Target chain ID
@@ -2487,8 +2529,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2487
2529
  * resolves once all requested chains have landed on-chain. Idempotent — chains
2488
2530
  * already deployed are a no-op.
2489
2531
  *
2490
- * `depositFunds` calls this automatically when the target chain isn't deployed,
2491
- * so most integrations never need it directly; use it to pre-provision chains.
2532
+ * Optional for deposits: `depositFunds` no longer pre-deploys the target chain — the ERC20
2533
+ * transfer lands on the counterfactual address and the backend deploys + hands over on first
2534
+ * deposit (report-deposit). Use this only to pre-provision chains ahead of time.
2492
2535
  *
2493
2536
  * @param chainIds - Chain IDs to deploy the wallet on (e.g. [1, 42161])
2494
2537
  */
@@ -2502,17 +2545,6 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2502
2545
  await this.authenticateUser();
2503
2546
  return this.httpClient.post(ENDPOINTS.DEPLOY_CHAINS, { chainIds });
2504
2547
  }
2505
- /**
2506
- * Poll until the Safe has code on-chain. The backend awaits landing before it
2507
- * responds, so this only guards against read-after-write RPC lag.
2508
- */
2509
- async waitForSafeDeployed(safeAddress, publicClient, tries = 5, delayMs = 2e3) {
2510
- for (let i = 0; i < tries; i++) {
2511
- if (await isSafeDeployed(safeAddress, publicClient)) return true;
2512
- await new Promise((r) => setTimeout(r, delayMs));
2513
- }
2514
- return isSafeDeployed(safeAddress, publicClient);
2515
- }
2516
2548
  async depositFunds(userAddress, chainId, amount, asset, strategy) {
2517
2549
  try {
2518
2550
  if (!userAddress) {
@@ -2539,28 +2571,29 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2539
2571
  `Unsupported asset: ${assetSymbol}. Supported: USDC, WETH, EURC.`
2540
2572
  );
2541
2573
  }
2542
- const minRequired = MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
2574
+ let minRequired = MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
2575
+ if (assetSymbol === "WETH") {
2576
+ const priceResponse = await this.httpClient.dataGet(
2577
+ DATA_ENDPOINTS.TOKEN_PRICE("eth")
2578
+ );
2579
+ minRequired = minWethWeiForUsd(
2580
+ parseEthUsdPrice(priceResponse),
2581
+ MIN_WETH_USD[chainId]
2582
+ );
2583
+ }
2543
2584
  const token = getDefaultTokenAddress(chainId, assetSymbol);
2544
2585
  const walletClient = this.getWalletClient();
2545
2586
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
2546
2587
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
2588
+ if (!safeAddress) {
2589
+ throw new Error("Smart wallet address is not available");
2590
+ }
2547
2591
  const isDeployed = await isSafeDeployed(
2548
2592
  safeAddress,
2549
2593
  chainConfig.publicClient
2550
2594
  );
2551
2595
  if (!isDeployed) {
2552
- if (this.isPredeployed && this.isConnectedUser(userAddress)) {
2553
- await this.deployOnChains([chainId]);
2554
- const landed = await this.waitForSafeDeployed(
2555
- safeAddress,
2556
- chainConfig.publicClient
2557
- );
2558
- if (!landed) {
2559
- throw new Error(
2560
- `Safe deploy on chain ${chainId} for ${userAddress} did not land \u2014 retry the deposit.`
2561
- );
2562
- }
2563
- } else {
2596
+ if (!(this.isPredeployed && this.isConnectedUser(userAddress))) {
2564
2597
  throw new Error(
2565
2598
  `Safe not available for ${userAddress} on chain ${chainId}.`
2566
2599
  );
@@ -2730,6 +2763,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2730
2763
  }
2731
2764
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
2732
2765
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
2766
+ if (!safeAddress) {
2767
+ throw new Error("Smart wallet address is not available");
2768
+ }
2733
2769
  const isDeployed = await isSafeDeployed(
2734
2770
  safeAddress,
2735
2771
  chainConfig.publicClient
@@ -2804,7 +2840,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2804
2840
  * Get all active DeFi positions for a user
2805
2841
  *
2806
2842
  * @param userAddress - User's EOA address
2807
- * @param chainId - Optional: Filter by specific chain ID
2843
+ * @param chainId - Optional chain used to resolve the Safe address (defaults to Base 8453)
2808
2844
  * @returns User's positions across all protocols
2809
2845
  *
2810
2846
  * @example
@@ -2824,8 +2860,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2824
2860
  if (chainId && !isSupportedChain(chainId)) {
2825
2861
  throw new Error(`Unsupported chain ID: ${chainId}`);
2826
2862
  }
2827
- const smartWalletInfo = await this.getSmartWalletByEOA(userAddress);
2828
- if (!smartWalletInfo.smartWallet) {
2863
+ const targetChainId = chainId ?? 8453;
2864
+ const smartWallet = await this.getSafeAddressFor(
2865
+ userAddress,
2866
+ targetChainId,
2867
+ false
2868
+ );
2869
+ if (!smartWallet) {
2829
2870
  return {
2830
2871
  success: true,
2831
2872
  userAddress,
@@ -2833,7 +2874,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2833
2874
  };
2834
2875
  }
2835
2876
  const response = await this.httpClient.get(
2836
- ENDPOINTS.DATA_POSITION(smartWalletInfo.smartWallet)
2877
+ ENDPOINTS.DATA_POSITION(smartWallet)
2837
2878
  );
2838
2879
  const convertedPosition = response ? convertStrategyToPublic(response) : void 0;
2839
2880
  return {
@@ -2871,15 +2912,18 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2871
2912
  if (!userAddress) {
2872
2913
  throw new Error("User address is required");
2873
2914
  }
2874
- const smartWalletInfo = await this.getSmartWalletByEOA(userAddress);
2875
- if (!smartWalletInfo.smartWallet) {
2915
+ const smartWallet = await this.getSafeAddressFor(
2916
+ userAddress,
2917
+ 8453,
2918
+ false
2919
+ );
2920
+ if (!smartWallet) {
2876
2921
  return {
2877
2922
  success: true,
2878
2923
  userAddress,
2879
2924
  portfolio: {}
2880
2925
  };
2881
2926
  }
2882
- const smartWallet = smartWalletInfo.smartWallet;
2883
2927
  const [response, earningsResult] = await Promise.all([
2884
2928
  this.httpClient.get(
2885
2929
  ENDPOINTS.DATA_PORTFOLIO(smartWallet)
package/dist/index.mjs CHANGED
@@ -98,6 +98,8 @@ var DATA_ENDPOINTS = {
98
98
  if (options?.tokenSymbol) params.push(`tokenSymbol=${options.tokenSymbol}`);
99
99
  return params.length > 0 ? `/rebalance/rebalance-info?${params.join("&")}` : "/rebalance/rebalance-info";
100
100
  },
101
+ // Token USD price (e.g. token=eth)
102
+ TOKEN_PRICE: (token) => `/price?token=${encodeURIComponent(token)}`,
101
103
  // APY Per Strategy
102
104
  APY_PER_STRATEGY: (options = {}) => {
103
105
  const params = [];
@@ -294,6 +296,27 @@ var HttpClient = class {
294
296
  }
295
297
  };
296
298
 
299
+ // src/utils/eth-price.ts
300
+ var PRICE_SCALE = 8;
301
+ var parseEthUsdPrice = (response) => {
302
+ const priceUsd = response?.data?.price_usd;
303
+ if (typeof priceUsd !== "number" || !Number.isFinite(priceUsd) || priceUsd <= 0) {
304
+ throw new Error("ETH/USD price must be a positive number");
305
+ }
306
+ return priceUsd;
307
+ };
308
+ var usdToWethWei = (usdAmount, ethUsd) => {
309
+ if (!Number.isFinite(ethUsd) || ethUsd <= 0) {
310
+ throw new Error("ETH/USD price must be positive");
311
+ }
312
+ const scaledPrice = BigInt(Math.round(ethUsd * 10 ** PRICE_SCALE));
313
+ if (scaledPrice <= 0n) {
314
+ throw new Error("ETH/USD price must be positive");
315
+ }
316
+ return usdAmount * 10n ** 18n * 10n ** BigInt(PRICE_SCALE) / scaledPrice;
317
+ };
318
+ var minWethWeiForUsd = (ethUsd, usdAmount) => usdToWethWei(usdAmount, ethUsd);
319
+
297
320
  // src/config/abis.ts
298
321
  import { parseAbi } from "viem";
299
322
  var OWNABLE_VALIDATOR_ABI = [
@@ -467,12 +490,29 @@ var ZYFI_FEE_RATE = 0.1;
467
490
  var ALLOWED_HISTORY_DAYS = [7, 14, 30, 60, 120, 180];
468
491
  var MIN_PORTFOLIO_BALANCE = {
469
492
  1: {
493
+ USDC: 10000n * 10n ** 6n,
494
+ // 10,000 USDC (6 decimals)
495
+ EURC: 10000n * 10n ** 6n
496
+ // 10,000 EURC (6 decimals)
497
+ },
498
+ 8453: {
499
+ USDC: 100n * 10n ** 6n,
500
+ // 100 USDC (6 decimals)
501
+ EURC: 100n * 10n ** 6n
502
+ // 100 EURC (6 decimals)
503
+ },
504
+ 42161: {
470
505
  USDC: 100n * 10n ** 6n,
471
506
  // 100 USDC (6 decimals)
472
- WETH: 5n * 10n ** 15n
473
- // 0.005 WETH (18 decimals)
507
+ EURC: 100n * 10n ** 6n
508
+ // 100 EURC (6 decimals)
474
509
  }
475
510
  };
511
+ var MIN_WETH_USD = {
512
+ 1: 10000n,
513
+ 8453: 100n,
514
+ 42161: 100n
515
+ };
476
516
  var formatMinPortfolioLabel = (raw, decimals, symbol) => {
477
517
  const base2 = 10n ** BigInt(decimals);
478
518
  const whole = raw / base2;
@@ -1920,16 +1960,12 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1920
1960
  return !!connected && connected.toLowerCase() === userAddress.toLowerCase();
1921
1961
  }
1922
1962
  /**
1923
- * Resolve the Safe smart wallet address for a user on a chain.
1924
- *
1925
- * Predeployed (pool) wallets are provisioned and owned by the backend at
1926
- * deploy time, so their address CANNOT be derived from the user's EOA with
1927
- * getDeterministicSafeAddress (CREATE2 from the EOA yields the wrong address).
1928
- * For the connected predeployed user we always use the backend-assigned
1929
- * address. Legacy wallets keep the API-first, deterministic-fallback behavior.
1963
+ * Resolve the Safe address: backend-assigned for the connected predeployed
1964
+ * user, registered agent for everyone else. If none, CREATE2-derive when
1965
+ * `deriveIfMissing` is true; otherwise return null (read paths).
1930
1966
  * @private
1931
1967
  */
1932
- async getSafeAddressFor(userAddress, chainId) {
1968
+ async getSafeAddressFor(userAddress, chainId, deriveIfMissing = true) {
1933
1969
  if (this.isPredeployed && this.isConnectedUser(userAddress)) {
1934
1970
  if (this.connectedSmartWallet) return this.connectedSmartWallet;
1935
1971
  try {
@@ -1937,6 +1973,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1937
1973
  if (info.smartWallet) return info.smartWallet;
1938
1974
  } catch {
1939
1975
  }
1976
+ if (!deriveIfMissing) return null;
1940
1977
  throw new Error(
1941
1978
  "Predeployed smart wallet address is not available from the API yet. Ensure the user has signed in so the pool can reserve their wallet."
1942
1979
  );
@@ -1946,6 +1983,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1946
1983
  if (info.smartWallet) return info.smartWallet;
1947
1984
  } catch {
1948
1985
  }
1986
+ if (!deriveIfMissing) return null;
1949
1987
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
1950
1988
  return getDeterministicSafeAddress({
1951
1989
  safeOwnerAddress: userAddress,
@@ -1973,6 +2011,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1973
2011
  }
1974
2012
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
1975
2013
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
2014
+ if (!safeAddress) {
2015
+ throw new Error("Smart wallet address is not available");
2016
+ }
1976
2017
  const isDeployed = await isSafeDeployed(
1977
2018
  safeAddress,
1978
2019
  chainConfig.publicClient
@@ -2025,6 +2066,11 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2025
2066
  userAddress,
2026
2067
  chainId
2027
2068
  );
2069
+ if (!predeployedAddress) {
2070
+ throw new Error(
2071
+ "Predeployed smart wallet address is not available from the API yet. Ensure the user has signed in so the pool can reserve their wallet."
2072
+ );
2073
+ }
2028
2074
  try {
2029
2075
  await this.initializeUser(predeployedAddress, chainId);
2030
2076
  } catch (initError) {
@@ -2413,13 +2459,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2413
2459
  * Pass `strategy` to select protocols for that first-deposit setup
2414
2460
  * (same role as the former `deploySafe` strategy argument).
2415
2461
  *
2416
- * Minimum portfolio balance enforced (Safe balance + deposit amount),
2417
- * configured per-chain in `MIN_PORTFOLIO_BALANCE`:
2418
- * - Ethereum Mainnet (1): 5 USDC (test threshold)
2419
- * - Base (8453) & Arbitrum (42161): no minimum
2420
- *
2421
- * If no minimum is configured for a given (chainId, asset) pair,
2422
- * the check is skipped.
2462
+ * Minimum portfolio balance enforced (Safe balance + deposit amount):
2463
+ * - Stablecoins: `MIN_PORTFOLIO_BALANCE` (Mainnet 10,000 USDC/EURC; Base/Arbitrum 100)
2464
+ * - WETH: about $10,000 on Mainnet, $100 on Base/Arbitrum, from Data API `/price?token=eth`
2423
2465
  *
2424
2466
  * @param userAddress - User's address (owner of the Safe)
2425
2467
  * @param chainId - Target chain ID
@@ -2454,8 +2496,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2454
2496
  * resolves once all requested chains have landed on-chain. Idempotent — chains
2455
2497
  * already deployed are a no-op.
2456
2498
  *
2457
- * `depositFunds` calls this automatically when the target chain isn't deployed,
2458
- * so most integrations never need it directly; use it to pre-provision chains.
2499
+ * Optional for deposits: `depositFunds` no longer pre-deploys the target chain — the ERC20
2500
+ * transfer lands on the counterfactual address and the backend deploys + hands over on first
2501
+ * deposit (report-deposit). Use this only to pre-provision chains ahead of time.
2459
2502
  *
2460
2503
  * @param chainIds - Chain IDs to deploy the wallet on (e.g. [1, 42161])
2461
2504
  */
@@ -2469,17 +2512,6 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2469
2512
  await this.authenticateUser();
2470
2513
  return this.httpClient.post(ENDPOINTS.DEPLOY_CHAINS, { chainIds });
2471
2514
  }
2472
- /**
2473
- * Poll until the Safe has code on-chain. The backend awaits landing before it
2474
- * responds, so this only guards against read-after-write RPC lag.
2475
- */
2476
- async waitForSafeDeployed(safeAddress, publicClient, tries = 5, delayMs = 2e3) {
2477
- for (let i = 0; i < tries; i++) {
2478
- if (await isSafeDeployed(safeAddress, publicClient)) return true;
2479
- await new Promise((r) => setTimeout(r, delayMs));
2480
- }
2481
- return isSafeDeployed(safeAddress, publicClient);
2482
- }
2483
2515
  async depositFunds(userAddress, chainId, amount, asset, strategy) {
2484
2516
  try {
2485
2517
  if (!userAddress) {
@@ -2506,28 +2538,29 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2506
2538
  `Unsupported asset: ${assetSymbol}. Supported: USDC, WETH, EURC.`
2507
2539
  );
2508
2540
  }
2509
- const minRequired = MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
2541
+ let minRequired = MIN_PORTFOLIO_BALANCE[chainId]?.[assetSymbol];
2542
+ if (assetSymbol === "WETH") {
2543
+ const priceResponse = await this.httpClient.dataGet(
2544
+ DATA_ENDPOINTS.TOKEN_PRICE("eth")
2545
+ );
2546
+ minRequired = minWethWeiForUsd(
2547
+ parseEthUsdPrice(priceResponse),
2548
+ MIN_WETH_USD[chainId]
2549
+ );
2550
+ }
2510
2551
  const token = getDefaultTokenAddress(chainId, assetSymbol);
2511
2552
  const walletClient = this.getWalletClient();
2512
2553
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
2513
2554
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
2555
+ if (!safeAddress) {
2556
+ throw new Error("Smart wallet address is not available");
2557
+ }
2514
2558
  const isDeployed = await isSafeDeployed(
2515
2559
  safeAddress,
2516
2560
  chainConfig.publicClient
2517
2561
  );
2518
2562
  if (!isDeployed) {
2519
- if (this.isPredeployed && this.isConnectedUser(userAddress)) {
2520
- await this.deployOnChains([chainId]);
2521
- const landed = await this.waitForSafeDeployed(
2522
- safeAddress,
2523
- chainConfig.publicClient
2524
- );
2525
- if (!landed) {
2526
- throw new Error(
2527
- `Safe deploy on chain ${chainId} for ${userAddress} did not land \u2014 retry the deposit.`
2528
- );
2529
- }
2530
- } else {
2563
+ if (!(this.isPredeployed && this.isConnectedUser(userAddress))) {
2531
2564
  throw new Error(
2532
2565
  `Safe not available for ${userAddress} on chain ${chainId}.`
2533
2566
  );
@@ -2697,6 +2730,9 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2697
2730
  }
2698
2731
  const chainConfig = getChainConfig(chainId, this.rpcUrls);
2699
2732
  const safeAddress = await this.getSafeAddressFor(userAddress, chainId);
2733
+ if (!safeAddress) {
2734
+ throw new Error("Smart wallet address is not available");
2735
+ }
2700
2736
  const isDeployed = await isSafeDeployed(
2701
2737
  safeAddress,
2702
2738
  chainConfig.publicClient
@@ -2771,7 +2807,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2771
2807
  * Get all active DeFi positions for a user
2772
2808
  *
2773
2809
  * @param userAddress - User's EOA address
2774
- * @param chainId - Optional: Filter by specific chain ID
2810
+ * @param chainId - Optional chain used to resolve the Safe address (defaults to Base 8453)
2775
2811
  * @returns User's positions across all protocols
2776
2812
  *
2777
2813
  * @example
@@ -2791,8 +2827,13 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2791
2827
  if (chainId && !isSupportedChain(chainId)) {
2792
2828
  throw new Error(`Unsupported chain ID: ${chainId}`);
2793
2829
  }
2794
- const smartWalletInfo = await this.getSmartWalletByEOA(userAddress);
2795
- if (!smartWalletInfo.smartWallet) {
2830
+ const targetChainId = chainId ?? 8453;
2831
+ const smartWallet = await this.getSafeAddressFor(
2832
+ userAddress,
2833
+ targetChainId,
2834
+ false
2835
+ );
2836
+ if (!smartWallet) {
2796
2837
  return {
2797
2838
  success: true,
2798
2839
  userAddress,
@@ -2800,7 +2841,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2800
2841
  };
2801
2842
  }
2802
2843
  const response = await this.httpClient.get(
2803
- ENDPOINTS.DATA_POSITION(smartWalletInfo.smartWallet)
2844
+ ENDPOINTS.DATA_POSITION(smartWallet)
2804
2845
  );
2805
2846
  const convertedPosition = response ? convertStrategyToPublic(response) : void 0;
2806
2847
  return {
@@ -2838,15 +2879,18 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2838
2879
  if (!userAddress) {
2839
2880
  throw new Error("User address is required");
2840
2881
  }
2841
- const smartWalletInfo = await this.getSmartWalletByEOA(userAddress);
2842
- if (!smartWalletInfo.smartWallet) {
2882
+ const smartWallet = await this.getSafeAddressFor(
2883
+ userAddress,
2884
+ 8453,
2885
+ false
2886
+ );
2887
+ if (!smartWallet) {
2843
2888
  return {
2844
2889
  success: true,
2845
2890
  userAddress,
2846
2891
  portfolio: {}
2847
2892
  };
2848
2893
  }
2849
- const smartWallet = smartWalletInfo.smartWallet;
2850
2894
  const [response, earningsResult] = await Promise.all([
2851
2895
  this.httpClient.get(
2852
2896
  ENDPOINTS.DATA_PORTFOLIO(smartWallet)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zyfai/sdk",
3
- "version": "0.2.52",
3
+ "version": "0.2.54",
4
4
  "description": "TypeScript SDK for Zyfai Yield Optimization Engine - Deploy Safe smart wallets, manage session keys, and interact with DeFi protocols",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",