@zyfai/sdk 0.2.44 → 0.2.46

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
@@ -460,6 +460,7 @@ var VAULT_ABI = [
460
460
  var VAULT_ADDRESS = "0xD580071c47d4a667858B5FafAb85BC9C609beC5D";
461
461
 
462
462
  // src/config/constants.ts
463
+ var ZYFI_FEE_RATE = 0.1;
463
464
  var MIN_PORTFOLIO_BALANCE = {
464
465
  1: {
465
466
  USDC: 100n * 10n ** 6n,
@@ -1012,6 +1013,310 @@ var hasMatchingPool = (data, chains, asset) => {
1012
1013
  return false;
1013
1014
  };
1014
1015
 
1016
+ // src/utils/zyfi-fees.ts
1017
+ var CHAIN_NAME_TO_ID = {
1018
+ ethereum: "1",
1019
+ "ethereum mainnet": "1",
1020
+ mainnet: "1",
1021
+ base: "8453",
1022
+ arbitrum: "42161",
1023
+ "arbitrum one": "42161"
1024
+ };
1025
+ function symbolToAssetType(symbol) {
1026
+ const upper = symbol.trim().toUpperCase();
1027
+ if (upper === "USDC") return "usdc";
1028
+ if (upper === "WETH" || upper === "ETH") return "eth";
1029
+ if (upper === "EURC") return "eurc";
1030
+ if (upper === "CBBTC") return "cbbtc";
1031
+ if (upper === "CBETH") return "cbeth";
1032
+ return symbol.trim().toLowerCase();
1033
+ }
1034
+ function assetTypeToSymbol(assetType) {
1035
+ const lower = assetType.trim().toLowerCase();
1036
+ if (lower === "usdc") return "USDC";
1037
+ if (lower === "eth") return "WETH";
1038
+ if (lower === "eurc") return "EURC";
1039
+ if (lower === "cbbtc") return "CBBTC";
1040
+ if (lower === "cbeth") return "CBETH";
1041
+ return assetType.trim().toUpperCase();
1042
+ }
1043
+ function chainNameToId(chain) {
1044
+ if (!chain) return void 0;
1045
+ const trimmed = chain.trim();
1046
+ if (/^\d+$/.test(trimmed)) return trimmed;
1047
+ return CHAIN_NAME_TO_ID[trimmed.toLowerCase()];
1048
+ }
1049
+ function parseHumanAmount(value) {
1050
+ if (typeof value === "number") {
1051
+ return Number.isFinite(value) ? value : 0;
1052
+ }
1053
+ const parsed = Number.parseFloat(String(value ?? "0"));
1054
+ return Number.isFinite(parsed) ? parsed : 0;
1055
+ }
1056
+ function humanAmountToRaw(human, decimals) {
1057
+ if (!Number.isFinite(human) || human <= 0 || decimals < 0) {
1058
+ return 0n;
1059
+ }
1060
+ const fixed = human.toFixed(decimals);
1061
+ const [whole, frac = ""] = fixed.split(".");
1062
+ const wholePart = BigInt(whole);
1063
+ const fracPart = BigInt(frac.padEnd(decimals, "0").slice(0, decimals) || "0");
1064
+ return wholePart * 10n ** BigInt(decimals) + fracPart;
1065
+ }
1066
+ function formatHumanAmount(value) {
1067
+ if (!Number.isFinite(value) || value === 0) return "0";
1068
+ const fixed = value.toFixed(18);
1069
+ return fixed.replace(/\.?0+$/, "") || "0";
1070
+ }
1071
+ function computePendingFees(currentEarningsByChain) {
1072
+ const byToken = {};
1073
+ const byChain = {};
1074
+ const byChainByToken = {};
1075
+ let total = 0;
1076
+ if (!currentEarningsByChain) {
1077
+ return { byToken, byChain, byChainByToken, total };
1078
+ }
1079
+ Object.entries(currentEarningsByChain).forEach(([chainId, chainEarnings]) => {
1080
+ const feeByToken = {};
1081
+ let chainFee = 0;
1082
+ Object.entries(chainEarnings || {}).forEach(([tokenSymbol, tokenAmount]) => {
1083
+ const numericValue = parseHumanAmount(tokenAmount);
1084
+ const tokenFee = numericValue > 0 ? numericValue * ZYFI_FEE_RATE : 0;
1085
+ feeByToken[tokenSymbol] = tokenFee;
1086
+ chainFee += tokenFee;
1087
+ byToken[tokenSymbol] = (byToken[tokenSymbol] ?? 0) + tokenFee;
1088
+ });
1089
+ byChainByToken[chainId] = feeByToken;
1090
+ byChain[chainId] = chainFee;
1091
+ total += chainFee;
1092
+ });
1093
+ return { byToken, byChain, byChainByToken, total };
1094
+ }
1095
+ function feeForAssetType(feesByToken, assetType) {
1096
+ const symbol = assetTypeToSymbol(assetType);
1097
+ if (feesByToken[symbol] !== void 0) return feesByToken[symbol] ?? 0;
1098
+ if (assetType.toLowerCase() === "eth") {
1099
+ return feesByToken["ETH"] ?? feesByToken["WETH"] ?? 0;
1100
+ }
1101
+ return feesByToken[assetType.toUpperCase()] ?? 0;
1102
+ }
1103
+ function feeForChainAsset(byChainByToken, chainId, assetType) {
1104
+ const chainFees = byChainByToken[chainId] || {};
1105
+ return feeForAssetType(chainFees, assetType);
1106
+ }
1107
+ function applyFeeToHexBalance(balanceHex, feeHuman, decimals) {
1108
+ let balance;
1109
+ try {
1110
+ balance = BigInt(balanceHex || "0x0");
1111
+ } catch {
1112
+ balance = 0n;
1113
+ }
1114
+ const feeRaw = humanAmountToRaw(feeHuman, decimals);
1115
+ const net = balance > feeRaw ? balance - feeRaw : 0n;
1116
+ return `0x${net.toString(16)}`;
1117
+ }
1118
+ function applyFeeToDecimalWei(amount, feeHuman, decimals) {
1119
+ let balance;
1120
+ try {
1121
+ balance = BigInt(amount || "0");
1122
+ } catch {
1123
+ balance = 0n;
1124
+ }
1125
+ const feeRaw = humanAmountToRaw(feeHuman, decimals);
1126
+ const net = balance > feeRaw ? balance - feeRaw : 0n;
1127
+ return net.toString();
1128
+ }
1129
+ function enrichAssetBalance(entry, feeHuman) {
1130
+ const balanceWithFee = applyFeeToHexBalance(
1131
+ entry.balance,
1132
+ feeHuman,
1133
+ entry.decimals
1134
+ );
1135
+ return {
1136
+ ...entry,
1137
+ balanceWithFee
1138
+ };
1139
+ }
1140
+ function resolvePositionSymbol(position) {
1141
+ if (position.token_symbol) return position.token_symbol;
1142
+ if (position.assetType) return assetTypeToSymbol(position.assetType);
1143
+ return void 0;
1144
+ }
1145
+ function resolvePositionDecimals(position) {
1146
+ if (typeof position.decimals === "number") return position.decimals;
1147
+ const asset = position.assetType || symbolToAssetType(position.token_symbol || "");
1148
+ if (asset === "usdc" || asset === "eurc") return 6;
1149
+ if (asset === "cbbtc") return 8;
1150
+ return 18;
1151
+ }
1152
+ function enrichPositions(positions, byChainByToken) {
1153
+ const groups = /* @__PURE__ */ new Map();
1154
+ positions.forEach((position, index) => {
1155
+ const chainId = chainNameToId(position.chain || "");
1156
+ const symbol = resolvePositionSymbol(position);
1157
+ if (!chainId || !symbol) {
1158
+ return;
1159
+ }
1160
+ const key = `${chainId}:${symbol.toUpperCase()}`;
1161
+ const list = groups.get(key) || [];
1162
+ list.push(index);
1163
+ groups.set(key, list);
1164
+ });
1165
+ const feeShareByIndex = /* @__PURE__ */ new Map();
1166
+ groups.forEach((indices, key) => {
1167
+ const [chainId, symbol] = key.split(":");
1168
+ const chainFees = byChainByToken[chainId] || {};
1169
+ let totalFee = chainFees[symbol] ?? (symbol === "WETH" ? chainFees["ETH"] : void 0) ?? (symbol === "ETH" ? chainFees["WETH"] : void 0) ?? 0;
1170
+ if (totalFee <= 0) {
1171
+ indices.forEach((i) => feeShareByIndex.set(i, 0));
1172
+ return;
1173
+ }
1174
+ let totalUnderlying = 0n;
1175
+ const underlyings = indices.map((i) => {
1176
+ try {
1177
+ return BigInt(positions[i].underlyingAmount || "0");
1178
+ } catch {
1179
+ return 0n;
1180
+ }
1181
+ });
1182
+ underlyings.forEach((u) => {
1183
+ totalUnderlying += u;
1184
+ });
1185
+ if (totalUnderlying === 0n) {
1186
+ const share = totalFee / indices.length;
1187
+ indices.forEach((i) => feeShareByIndex.set(i, share));
1188
+ return;
1189
+ }
1190
+ indices.forEach((i, idx) => {
1191
+ const share = totalFee * Number(underlyings[idx]) / Number(totalUnderlying);
1192
+ feeShareByIndex.set(i, share);
1193
+ });
1194
+ });
1195
+ return positions.map((position, index) => {
1196
+ const underlying = position.underlyingAmount;
1197
+ if (underlying === void 0) {
1198
+ return { ...position };
1199
+ }
1200
+ const feeShare = feeShareByIndex.get(index) ?? 0;
1201
+ const decimals = resolvePositionDecimals(position);
1202
+ return {
1203
+ ...position,
1204
+ underlyingAmountWithFee: applyFeeToDecimalWei(
1205
+ underlying,
1206
+ feeShare,
1207
+ decimals
1208
+ )
1209
+ };
1210
+ });
1211
+ }
1212
+ function enrichPortfolioWithFees(portfolio, currentEarningsByChain) {
1213
+ const { byToken, byChainByToken } = computePendingFees(currentEarningsByChain);
1214
+ const portfolioByAssetType = portfolio.portfolioByAssetType ? Object.fromEntries(
1215
+ Object.entries(portfolio.portfolioByAssetType).map(
1216
+ ([assetType, entry]) => [
1217
+ assetType,
1218
+ enrichAssetBalance(entry, feeForAssetType(byToken, assetType))
1219
+ ]
1220
+ )
1221
+ ) : void 0;
1222
+ const portfolioByChain = portfolio.portfolioByChain ? Object.fromEntries(
1223
+ Object.entries(portfolio.portfolioByChain).map(
1224
+ ([chainId, assets]) => [
1225
+ chainId,
1226
+ Object.fromEntries(
1227
+ Object.entries(assets).map(([assetType, entry]) => [
1228
+ assetType,
1229
+ enrichAssetBalance(
1230
+ entry,
1231
+ feeForChainAsset(byChainByToken, chainId, assetType)
1232
+ )
1233
+ ])
1234
+ )
1235
+ ]
1236
+ )
1237
+ ) : void 0;
1238
+ const positions = portfolio.positions ? enrichPositions(portfolio.positions, byChainByToken) : void 0;
1239
+ return {
1240
+ ...portfolio,
1241
+ ...portfolioByAssetType ? { portfolioByAssetType } : {},
1242
+ ...portfolioByChain ? { portfolioByChain } : {},
1243
+ ...positions ? { positions } : {}
1244
+ };
1245
+ }
1246
+ function sumCurrentByToken(currentByChain) {
1247
+ const totals = {};
1248
+ if (!currentByChain) return totals;
1249
+ Object.values(currentByChain).forEach((chainEarnings) => {
1250
+ Object.entries(chainEarnings || {}).forEach(([symbol, amount]) => {
1251
+ totals[symbol] = (totals[symbol] ?? 0) + parseHumanAmount(amount);
1252
+ });
1253
+ });
1254
+ return totals;
1255
+ }
1256
+ function enrichOnchainEarningsTotals(apiData) {
1257
+ const lifetimeByToken = apiData.lifetime_earnings_by_token || {};
1258
+ const lifetimeByChain = apiData.lifetime_earnings_by_chain || {};
1259
+ const currentByChain = apiData.current_earnings_by_chain || {};
1260
+ const unrealizedByChain = apiData.unrealized_earnings_by_chain || apiData.unrealized_earnings || {};
1261
+ const currentByToken = apiData.current_earnings_by_token && Object.keys(apiData.current_earnings_by_token).length > 0 ? Object.fromEntries(
1262
+ Object.entries(apiData.current_earnings_by_token).map(([k, v]) => [
1263
+ k,
1264
+ parseHumanAmount(v)
1265
+ ])
1266
+ ) : sumCurrentByToken(currentByChain);
1267
+ const unrealizedByToken = apiData.unrealized_earnings_by_token && Object.keys(apiData.unrealized_earnings_by_token).length > 0 ? Object.fromEntries(
1268
+ Object.entries(apiData.unrealized_earnings_by_token).map(([k, v]) => [
1269
+ k,
1270
+ parseHumanAmount(v)
1271
+ ])
1272
+ ) : sumCurrentByToken(unrealizedByChain);
1273
+ const keepRate = 1 - ZYFI_FEE_RATE;
1274
+ const tokenKeys = /* @__PURE__ */ new Set([
1275
+ ...Object.keys(lifetimeByToken),
1276
+ ...Object.keys(unrealizedByToken),
1277
+ ...Object.keys(currentByToken)
1278
+ ]);
1279
+ const totalEarningsByTokenWithFee = {};
1280
+ tokenKeys.forEach((symbol) => {
1281
+ const lifetime = parseHumanAmount(lifetimeByToken[symbol]);
1282
+ const unrealized = unrealizedByToken[symbol] ?? 0;
1283
+ const current = currentByToken[symbol] ?? 0;
1284
+ totalEarningsByTokenWithFee[symbol] = formatHumanAmount(
1285
+ lifetime + unrealized + current * keepRate
1286
+ );
1287
+ });
1288
+ const chainKeys = /* @__PURE__ */ new Set([
1289
+ ...Object.keys(lifetimeByChain),
1290
+ ...Object.keys(unrealizedByChain),
1291
+ ...Object.keys(currentByChain)
1292
+ ]);
1293
+ const totalEarningsByChainWithFee = {};
1294
+ chainKeys.forEach((chainId) => {
1295
+ const lifetimeTokens = lifetimeByChain[chainId] || {};
1296
+ const unrealizedTokens = unrealizedByChain[chainId] || {};
1297
+ const currentTokens = currentByChain[chainId] || {};
1298
+ const symbols = /* @__PURE__ */ new Set([
1299
+ ...Object.keys(lifetimeTokens),
1300
+ ...Object.keys(unrealizedTokens),
1301
+ ...Object.keys(currentTokens)
1302
+ ]);
1303
+ const chainMap = {};
1304
+ symbols.forEach((symbol) => {
1305
+ const lifetime = parseHumanAmount(lifetimeTokens[symbol]);
1306
+ const unrealized = parseHumanAmount(unrealizedTokens[symbol]);
1307
+ const current = parseHumanAmount(currentTokens[symbol]);
1308
+ chainMap[symbol] = formatHumanAmount(
1309
+ lifetime + unrealized + current * keepRate
1310
+ );
1311
+ });
1312
+ totalEarningsByChainWithFee[chainId] = chainMap;
1313
+ });
1314
+ return {
1315
+ totalEarningsByTokenWithFee,
1316
+ totalEarningsByChainWithFee
1317
+ };
1318
+ }
1319
+
1015
1320
  // src/core/ZyfaiSDK.ts
1016
1321
  import { SiweMessage } from "siwe";
1017
1322
  var _ZyfaiSDK = class _ZyfaiSDK {
@@ -1104,7 +1409,6 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1104
1409
  }
1105
1410
  this.httpClient.setAuthToken(authToken);
1106
1411
  this.authenticatedUserId = loginResponse.userId || null;
1107
- console.log("this.authenticatedUserId", loginResponse);
1108
1412
  this.hasActiveSessionKey = loginResponse.hasActiveSessionKey || false;
1109
1413
  this.isPredeployed = loginResponse.predeployed || false;
1110
1414
  this.connectedSmartWallet = loginResponse.smartWallet || null;
@@ -2062,12 +2366,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2062
2366
  * Deposit funds from EOA to Safe smart wallet
2063
2367
  * Transfers tokens from the connected wallet to the user's Safe and logs the deposit
2064
2368
  *
2065
- * Token is automatically selected based on chain (USDC by default):
2066
- * - Ethereum Mainnet (1), Base (8453), Arbitrum (42161)
2369
+ * Token address is selected from `asset` for the given chain:
2370
+ * - Ethereum Mainnet (1), Base (8453), Arbitrum (42161): USDC or WETH
2371
+ * - Ethereum Mainnet (1), Base (8453): EURC
2067
2372
  *
2068
2373
  * On the account's first deposit (USDC profile has no chains yet), patches
2069
2374
  * protocol selection for USDC, WETH, and EURC across all supported chains
2070
2375
  * (EURC on Mainnet/Base only) before the transfer and log_deposit.
2376
+ * Pass `strategy` to select protocols for that first-deposit setup
2377
+ * (same role as the former `deploySafe` strategy argument).
2071
2378
  *
2072
2379
  * Minimum portfolio balance enforced (Safe balance + deposit amount),
2073
2380
  * configured per-chain in `MIN_PORTFOLIO_BALANCE`:
@@ -2080,8 +2387,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2080
2387
  * @param userAddress - User's address (owner of the Safe)
2081
2388
  * @param chainId - Target chain ID
2082
2389
  * @param amount - Amount in least decimal units (e.g., "100000000" for 100 USDC with 6 decimals)
2083
- * @param asset - Optional asset symbol ("USDC", "WETH", or "EURC"). Defaults to "USDC".
2390
+ * @param asset - Asset symbol: "USDC", "WETH", or "EURC".
2084
2391
  * EURC is supported on Ethereum Mainnet and Base only.
2392
+ * @param strategy - Optional strategy for first-deposit protocol patching:
2393
+ * "conservative" (default) or "aggressive"
2085
2394
  * @returns Deposit response with transaction hash
2086
2395
  *
2087
2396
  * @example
@@ -2090,11 +2399,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2090
2399
  * const result = await sdk.depositFunds(
2091
2400
  * "0xUser...",
2092
2401
  * 8453,
2093
- * "10000000000" // 10,000 USDC = 10_000 * 10^6
2402
+ * "10000000000",
2403
+ * "USDC"
2094
2404
  * );
2405
+ *
2406
+ * // First deposit with aggressive strategy
2407
+ * await sdk.depositFunds(userAddress, 8453, "10000000000", "USDC", "aggressive");
2095
2408
  * ```
2096
2409
  */
2097
- async depositFunds(userAddress, chainId, amount, asset) {
2410
+ async depositFunds(userAddress, chainId, amount, asset, strategy) {
2098
2411
  try {
2099
2412
  if (!userAddress) {
2100
2413
  throw new Error("User address is required");
@@ -2105,7 +2418,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2105
2418
  if (!amount || isNaN(Number(amount)) || Number(amount) <= 0) {
2106
2419
  throw new Error("Valid amount is required");
2107
2420
  }
2108
- const assetSymbol = (asset || "USDC").toUpperCase();
2421
+ if (!asset) {
2422
+ throw new Error("Asset is required (USDC, WETH, or EURC)");
2423
+ }
2424
+ if (strategy !== void 0 && !isValidPublicStrategy(strategy)) {
2425
+ throw new Error(
2426
+ `Invalid strategy: ${strategy}. Must be "conservative" or "aggressive".`
2427
+ );
2428
+ }
2429
+ const assetSymbol = asset.toUpperCase();
2109
2430
  const assetConfig = ASSET_CONFIGS[assetSymbol];
2110
2431
  if (!assetConfig) {
2111
2432
  throw new Error(
@@ -2129,7 +2450,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2129
2450
  try {
2130
2451
  const usdcDetails = await this.getUserDetails("USDC");
2131
2452
  if ((usdcDetails.chains?.length ?? 0) === 0) {
2132
- await this.updateUserProtocols();
2453
+ await this.updateUserProtocols(strategy);
2133
2454
  }
2134
2455
  } catch (protocolError) {
2135
2456
  console.warn(
@@ -2169,12 +2490,6 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2169
2490
  hash: txHash
2170
2491
  });
2171
2492
  try {
2172
- console.log("Logging deposit to backend", {
2173
- chainId,
2174
- transaction: txHash,
2175
- token,
2176
- amount
2177
- });
2178
2493
  await this.httpClient.post(ENDPOINTS.LOG_DEPOSIT, {
2179
2494
  chainId,
2180
2495
  transaction: txHash,
@@ -2314,7 +2629,6 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2314
2629
  tokenSymbol
2315
2630
  });
2316
2631
  } else {
2317
- console.log("Full withdrawal", tokenSymbol);
2318
2632
  response = await this.httpClient.get(ENDPOINTS.USER_WITHDRAW, {
2319
2633
  params: { chainId, tokenSymbol }
2320
2634
  });
@@ -2413,19 +2727,23 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2413
2727
  }
2414
2728
  }
2415
2729
  /**
2416
- * Get all active positions and portfolio for a user
2730
+ * Get portfolio positions and balances for a user, enriched with
2731
+ * net-of-pending-fee fields (`balanceWithFee`, `underlyingAmountWithFee`).
2732
+ *
2733
+ * Pending fee is derived from onchain `current` earnings × fee rate.
2734
+ * Gross balances are unchanged. If earnings cannot be fetched, `*WithFee`
2735
+ * equals the gross value so the response shape stays stable.
2736
+ *
2737
+ * Note: portfolio balances are live; earnings used for the fee may be from
2738
+ * a snapshot, so net values can differ slightly from a fully live calc.
2417
2739
  *
2418
2740
  * @param userAddress - User's EOA address
2419
- * @param chainId - Optional: Filter by specific chain ID
2420
- * @returns User's positions across all protocols
2741
+ * @returns Portfolio with optional fee-adjusted balance fields
2421
2742
  *
2422
2743
  * @example
2423
2744
  * ```typescript
2424
- * // Get all positions across all chains
2425
- * const positions = await sdk.getPositions(userAddress);
2426
- *
2427
- * // Get positions on a specific chain
2428
- * const basePositions = await sdk.getPositions(userAddress, 8453);
2745
+ * const { portfolio } = await sdk.getPortfolio(userAddress);
2746
+ * console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
2429
2747
  * ```
2430
2748
  */
2431
2749
  async getPortfolio(userAddress) {
@@ -2441,18 +2759,27 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2441
2759
  portfolio: {}
2442
2760
  };
2443
2761
  }
2444
- console.log("Getting portfolio for", smartWalletInfo.smartWallet);
2445
- const response = await this.httpClient.get(
2446
- ENDPOINTS.DATA_PORTFOLIO(smartWalletInfo.smartWallet)
2447
- );
2762
+ const smartWallet = smartWalletInfo.smartWallet;
2763
+ const [response, earningsResult] = await Promise.all([
2764
+ this.httpClient.get(
2765
+ ENDPOINTS.DATA_PORTFOLIO(smartWallet)
2766
+ ),
2767
+ this.httpClient.dataGet(DATA_ENDPOINTS.ONCHAIN_EARNINGS(smartWallet)).catch(() => null)
2768
+ ]);
2448
2769
  const convertedResponse = removeUnusedFields(response);
2770
+ const earningsData = earningsResult?.data || earningsResult;
2771
+ const currentEarningsByChain = earningsData?.current_earnings_by_chain ?? null;
2772
+ const portfolio = enrichPortfolioWithFees(
2773
+ convertedResponse,
2774
+ currentEarningsByChain
2775
+ );
2449
2776
  return {
2450
2777
  success: true,
2451
2778
  userAddress,
2452
- portfolio: convertedResponse
2779
+ portfolio
2453
2780
  };
2454
2781
  } catch (error) {
2455
- throw new Error(`Failed to get positions: ${error.message}`);
2782
+ throw new Error(`Failed to get portfolio: ${error.message}`);
2456
2783
  }
2457
2784
  }
2458
2785
  // ============================================================================
@@ -2751,6 +3078,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2751
3078
  /**
2752
3079
  * Get onchain earnings for a wallet
2753
3080
  *
3081
+ * Includes gross totals plus net-of-fee totals:
3082
+ * `totalEarningsByTokenWithFee = lifetime + unrealized + current × (1 - feeRate)`.
3083
+ * Lifetime and unrealized are never multiplied by the keep-rate.
3084
+ *
2754
3085
  * @param walletAddress - Smart wallet address
2755
3086
  * @returns Onchain earnings data with per-token breakdowns
2756
3087
  *
@@ -2758,6 +3089,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2758
3089
  * ```typescript
2759
3090
  * const earnings = await sdk.getOnchainEarnings("0x...");
2760
3091
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
3092
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
2761
3093
  * console.log("Total on Arbitrum:", earnings.data.totalEarningsByChain?.["42161"]);
2762
3094
  * ```
2763
3095
  */
@@ -2770,12 +3102,16 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2770
3102
  DATA_ENDPOINTS.ONCHAIN_EARNINGS(walletAddress)
2771
3103
  );
2772
3104
  const data = response.data || response;
3105
+ console.log(JSON.stringify(data, null, 2));
3106
+ const withFee = enrichOnchainEarningsTotals(data);
2773
3107
  return {
2774
3108
  success: true,
2775
3109
  data: {
2776
3110
  walletAddress,
2777
3111
  totalEarningsByToken: data.total_earnings_by_token || {},
2778
3112
  totalEarningsByChain: data.total_earnings_by_chain || {},
3113
+ totalEarningsByTokenWithFee: withFee.totalEarningsByTokenWithFee,
3114
+ totalEarningsByChainWithFee: withFee.totalEarningsByChainWithFee,
2779
3115
  lastCheckTimestamp: data.last_check_timestamp,
2780
3116
  lastLogDate: data.last_log_date
2781
3117
  }
@@ -2788,7 +3124,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2788
3124
  }
2789
3125
  /**
2790
3126
  * Calculate/refresh onchain earnings for a wallet
2791
- * This triggers a recalculation of earnings on the backend
3127
+ * This triggers a recalculation of earnings on the backend.
3128
+ * Response shape matches `getOnchainEarnings` (includes `*WithFee` nets).
2792
3129
  *
2793
3130
  * @param walletAddress - Smart wallet address
2794
3131
  * @returns Updated onchain earnings data with per-token breakdowns
@@ -2797,7 +3134,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2797
3134
  * ```typescript
2798
3135
  * const earnings = await sdk.calculateOnchainEarnings("0x...");
2799
3136
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
2800
- * console.log("Per-chain total:", earnings.data.totalEarningsByChain);
3137
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
2801
3138
  * ```
2802
3139
  */
2803
3140
  async calculateOnchainEarnings(walletAddress) {
@@ -2810,12 +3147,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2810
3147
  {}
2811
3148
  );
2812
3149
  const data = response.data || response;
3150
+ const withFee = enrichOnchainEarningsTotals(data);
2813
3151
  return {
2814
3152
  success: true,
2815
3153
  data: {
2816
3154
  walletAddress,
2817
3155
  totalEarningsByToken: data.total_earnings_by_token || {},
2818
3156
  totalEarningsByChain: data.total_earnings_by_chain || {},
3157
+ totalEarningsByTokenWithFee: withFee.totalEarningsByTokenWithFee,
3158
+ totalEarningsByChainWithFee: withFee.totalEarningsByChainWithFee,
2819
3159
  lastCheckTimestamp: data.last_check_timestamp,
2820
3160
  lastLogDate: data.last_log_date
2821
3161
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zyfai/sdk",
3
- "version": "0.2.44",
3
+ "version": "0.2.46",
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",