@zyfai/sdk 0.2.47 → 0.2.48

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
@@ -532,6 +532,32 @@ positions.positions.forEach((bundle) => {
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
534
 
535
+ #### Get Portfolio (with fee-adjusted balances)
536
+
537
+ Returns the full wallet portfolio plus net-of-pending-fee fields. Pending fee is
538
+ `current` onchain earnings × 10%. Gross balances are unchanged.
539
+
540
+ ```typescript
541
+ const { portfolio } = await sdk.getPortfolio(userAddress);
542
+
543
+ // Gross vs net (after pending Zyfi fee)
544
+ console.log(portfolio.portfolioByAssetType?.usdc?.balance);
545
+ console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
546
+
547
+ portfolio.positions?.forEach((slot) => {
548
+ console.log(slot.pool, slot.underlyingAmount, slot.underlyingAmountWithFee);
549
+ });
550
+ ```
551
+
552
+ **Fee formula**
553
+
554
+ - Pending fee = `current_earnings × 0.1` (unrealised yield only)
555
+ - `balanceWithFee` / `underlyingAmountWithFee` = live − pending fee share
556
+ - If earnings cannot be fetched, `*WithFee` equals the gross value
557
+
558
+ **Note**: Portfolio balances are live; earnings used for the fee may come from a
559
+ snapshot, so net values can differ slightly from a fully live calculation.
560
+
535
561
  ### 8. Analytics & Data Endpoints
536
562
 
537
563
  The SDK provides access to various analytics and data endpoints:
@@ -729,13 +755,23 @@ const earnings = await sdk.getOnchainEarnings(walletAddress);
729
755
  console.log("Total by token:", earnings.data.totalEarningsByToken);
730
756
  // Per-chain totals (chain → token → amount): { "8453": { "USDC": "0.01" }, "42161": {...} }
731
757
  console.log("Total by chain:", earnings.data.totalEarningsByChain);
758
+ // Net totals: lifetime + unrealized + current × 0.9 (never total × 0.9)
759
+ console.log("Net by token:", earnings.data.totalEarningsByTokenWithFee);
760
+ console.log("Net by chain:", earnings.data.totalEarningsByChainWithFee);
732
761
  ```
733
762
 
763
+ **Fee formula for `*WithFee` earnings fields**
764
+
765
+ - `totalWithFee = lifetime + unrealized + current × 0.9`
766
+ - Do **not** apply `× 0.9` to lifetime or unrealized
767
+ - Aligns with portfolio: pending fee = `current × 0.1` only
768
+
734
769
  #### Calculate Onchain Earnings (Refresh)
735
770
 
736
771
  ```typescript
737
772
  const updated = await sdk.calculateOnchainEarnings(walletAddress);
738
773
  console.log("Updated earnings:", updated.data.totalEarningsByToken);
774
+ console.log("Net earnings:", updated.data.totalEarningsByTokenWithFee);
739
775
  ```
740
776
 
741
777
  #### Get Daily Earnings
package/dist/index.d.mts CHANGED
@@ -142,6 +142,8 @@ interface Portfolio {
142
142
  }
143
143
  interface PortfolioAssetBalance {
144
144
  balance: Hex;
145
+ /** Net balance after pending Zyfi fee (live − current × feeRate). */
146
+ balanceWithFee?: Hex;
145
147
  decimals: number;
146
148
  }
147
149
  type PortfolioByAssetType = Record<string, PortfolioAssetBalance>;
@@ -175,8 +177,12 @@ interface PositionSlot {
175
177
  token_id?: string;
176
178
  token_symbol?: string;
177
179
  token_icon?: string;
180
+ assetType?: string;
181
+ decimals?: number;
178
182
  amount?: string;
179
183
  underlyingAmount?: string;
184
+ /** Net underlying amount after this position's share of pending Zyfi fee. */
185
+ underlyingAmountWithFee?: string;
180
186
  pool_apy?: number;
181
187
  pool_tvl?: number;
182
188
  liquidity?: number;
@@ -288,6 +294,13 @@ interface OnchainEarnings {
288
294
  walletAddress: string;
289
295
  totalEarningsByToken: TokenEarnings;
290
296
  totalEarningsByChain?: ChainTokenEarnings;
297
+ /**
298
+ * Net totals: lifetime + unrealized + current × (1 - feeRate).
299
+ * Unrealized is treated like lifetime (no pending fee).
300
+ * Does not apply feeRate to lifetime (already crystallised).
301
+ */
302
+ totalEarningsByTokenWithFee: TokenEarnings;
303
+ totalEarningsByChainWithFee?: ChainTokenEarnings;
291
304
  lastCheckTimestamp?: string;
292
305
  lastLogDate?: Record<string, string | null>;
293
306
  }
@@ -1175,19 +1188,23 @@ declare class ZyfaiSDK {
1175
1188
  */
1176
1189
  getPositions(userAddress: string, chainId?: SupportedChainId): Promise<PortfolioResponse>;
1177
1190
  /**
1178
- * Get all active positions and portfolio for a user
1191
+ * Get portfolio positions and balances for a user, enriched with
1192
+ * net-of-pending-fee fields (`balanceWithFee`, `underlyingAmountWithFee`).
1193
+ *
1194
+ * Pending fee is derived from onchain `current` earnings × fee rate.
1195
+ * Gross balances are unchanged. If earnings cannot be fetched, `*WithFee`
1196
+ * equals the gross value so the response shape stays stable.
1197
+ *
1198
+ * Note: portfolio balances are live; earnings used for the fee may be from
1199
+ * a snapshot, so net values can differ slightly from a fully live calc.
1179
1200
  *
1180
1201
  * @param userAddress - User's EOA address
1181
- * @param chainId - Optional: Filter by specific chain ID
1182
- * @returns User's positions across all protocols
1202
+ * @returns Portfolio with optional fee-adjusted balance fields
1183
1203
  *
1184
1204
  * @example
1185
1205
  * ```typescript
1186
- * // Get all positions across all chains
1187
- * const positions = await sdk.getPositions(userAddress);
1188
- *
1189
- * // Get positions on a specific chain
1190
- * const basePositions = await sdk.getPositions(userAddress, 8453);
1206
+ * const { portfolio } = await sdk.getPortfolio(userAddress);
1207
+ * console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
1191
1208
  * ```
1192
1209
  */
1193
1210
  getPortfolio(userAddress: string): Promise<PortfolioDetailedResponse>;
@@ -1310,6 +1327,10 @@ declare class ZyfaiSDK {
1310
1327
  /**
1311
1328
  * Get onchain earnings for a wallet
1312
1329
  *
1330
+ * Includes gross totals plus net-of-fee totals:
1331
+ * `totalEarningsByTokenWithFee = lifetime + unrealized + current × (1 - feeRate)`.
1332
+ * Lifetime and unrealized are never multiplied by the keep-rate.
1333
+ *
1313
1334
  * @param walletAddress - Smart wallet address
1314
1335
  * @returns Onchain earnings data with per-token breakdowns
1315
1336
  *
@@ -1317,13 +1338,15 @@ declare class ZyfaiSDK {
1317
1338
  * ```typescript
1318
1339
  * const earnings = await sdk.getOnchainEarnings("0x...");
1319
1340
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
1341
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
1320
1342
  * console.log("Total on Arbitrum:", earnings.data.totalEarningsByChain?.["42161"]);
1321
1343
  * ```
1322
1344
  */
1323
1345
  getOnchainEarnings(walletAddress: string): Promise<OnchainEarningsResponse>;
1324
1346
  /**
1325
1347
  * Calculate/refresh onchain earnings for a wallet
1326
- * This triggers a recalculation of earnings on the backend
1348
+ * This triggers a recalculation of earnings on the backend.
1349
+ * Response shape matches `getOnchainEarnings` (includes `*WithFee` nets).
1327
1350
  *
1328
1351
  * @param walletAddress - Smart wallet address
1329
1352
  * @returns Updated onchain earnings data with per-token breakdowns
@@ -1332,7 +1355,7 @@ declare class ZyfaiSDK {
1332
1355
  * ```typescript
1333
1356
  * const earnings = await sdk.calculateOnchainEarnings("0x...");
1334
1357
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
1335
- * console.log("Per-chain total:", earnings.data.totalEarningsByChain);
1358
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
1336
1359
  * ```
1337
1360
  */
1338
1361
  calculateOnchainEarnings(walletAddress: string): Promise<OnchainEarningsResponse>;
package/dist/index.d.ts CHANGED
@@ -142,6 +142,8 @@ interface Portfolio {
142
142
  }
143
143
  interface PortfolioAssetBalance {
144
144
  balance: Hex;
145
+ /** Net balance after pending Zyfi fee (live − current × feeRate). */
146
+ balanceWithFee?: Hex;
145
147
  decimals: number;
146
148
  }
147
149
  type PortfolioByAssetType = Record<string, PortfolioAssetBalance>;
@@ -175,8 +177,12 @@ interface PositionSlot {
175
177
  token_id?: string;
176
178
  token_symbol?: string;
177
179
  token_icon?: string;
180
+ assetType?: string;
181
+ decimals?: number;
178
182
  amount?: string;
179
183
  underlyingAmount?: string;
184
+ /** Net underlying amount after this position's share of pending Zyfi fee. */
185
+ underlyingAmountWithFee?: string;
180
186
  pool_apy?: number;
181
187
  pool_tvl?: number;
182
188
  liquidity?: number;
@@ -288,6 +294,13 @@ interface OnchainEarnings {
288
294
  walletAddress: string;
289
295
  totalEarningsByToken: TokenEarnings;
290
296
  totalEarningsByChain?: ChainTokenEarnings;
297
+ /**
298
+ * Net totals: lifetime + unrealized + current × (1 - feeRate).
299
+ * Unrealized is treated like lifetime (no pending fee).
300
+ * Does not apply feeRate to lifetime (already crystallised).
301
+ */
302
+ totalEarningsByTokenWithFee: TokenEarnings;
303
+ totalEarningsByChainWithFee?: ChainTokenEarnings;
291
304
  lastCheckTimestamp?: string;
292
305
  lastLogDate?: Record<string, string | null>;
293
306
  }
@@ -1175,19 +1188,23 @@ declare class ZyfaiSDK {
1175
1188
  */
1176
1189
  getPositions(userAddress: string, chainId?: SupportedChainId): Promise<PortfolioResponse>;
1177
1190
  /**
1178
- * Get all active positions and portfolio for a user
1191
+ * Get portfolio positions and balances for a user, enriched with
1192
+ * net-of-pending-fee fields (`balanceWithFee`, `underlyingAmountWithFee`).
1193
+ *
1194
+ * Pending fee is derived from onchain `current` earnings × fee rate.
1195
+ * Gross balances are unchanged. If earnings cannot be fetched, `*WithFee`
1196
+ * equals the gross value so the response shape stays stable.
1197
+ *
1198
+ * Note: portfolio balances are live; earnings used for the fee may be from
1199
+ * a snapshot, so net values can differ slightly from a fully live calc.
1179
1200
  *
1180
1201
  * @param userAddress - User's EOA address
1181
- * @param chainId - Optional: Filter by specific chain ID
1182
- * @returns User's positions across all protocols
1202
+ * @returns Portfolio with optional fee-adjusted balance fields
1183
1203
  *
1184
1204
  * @example
1185
1205
  * ```typescript
1186
- * // Get all positions across all chains
1187
- * const positions = await sdk.getPositions(userAddress);
1188
- *
1189
- * // Get positions on a specific chain
1190
- * const basePositions = await sdk.getPositions(userAddress, 8453);
1206
+ * const { portfolio } = await sdk.getPortfolio(userAddress);
1207
+ * console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
1191
1208
  * ```
1192
1209
  */
1193
1210
  getPortfolio(userAddress: string): Promise<PortfolioDetailedResponse>;
@@ -1310,6 +1327,10 @@ declare class ZyfaiSDK {
1310
1327
  /**
1311
1328
  * Get onchain earnings for a wallet
1312
1329
  *
1330
+ * Includes gross totals plus net-of-fee totals:
1331
+ * `totalEarningsByTokenWithFee = lifetime + unrealized + current × (1 - feeRate)`.
1332
+ * Lifetime and unrealized are never multiplied by the keep-rate.
1333
+ *
1313
1334
  * @param walletAddress - Smart wallet address
1314
1335
  * @returns Onchain earnings data with per-token breakdowns
1315
1336
  *
@@ -1317,13 +1338,15 @@ declare class ZyfaiSDK {
1317
1338
  * ```typescript
1318
1339
  * const earnings = await sdk.getOnchainEarnings("0x...");
1319
1340
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
1341
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
1320
1342
  * console.log("Total on Arbitrum:", earnings.data.totalEarningsByChain?.["42161"]);
1321
1343
  * ```
1322
1344
  */
1323
1345
  getOnchainEarnings(walletAddress: string): Promise<OnchainEarningsResponse>;
1324
1346
  /**
1325
1347
  * Calculate/refresh onchain earnings for a wallet
1326
- * This triggers a recalculation of earnings on the backend
1348
+ * This triggers a recalculation of earnings on the backend.
1349
+ * Response shape matches `getOnchainEarnings` (includes `*WithFee` nets).
1327
1350
  *
1328
1351
  * @param walletAddress - Smart wallet address
1329
1352
  * @returns Updated onchain earnings data with per-token breakdowns
@@ -1332,7 +1355,7 @@ declare class ZyfaiSDK {
1332
1355
  * ```typescript
1333
1356
  * const earnings = await sdk.calculateOnchainEarnings("0x...");
1334
1357
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
1335
- * console.log("Per-chain total:", earnings.data.totalEarningsByChain);
1358
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
1336
1359
  * ```
1337
1360
  */
1338
1361
  calculateOnchainEarnings(walletAddress: string): Promise<OnchainEarningsResponse>;
package/dist/index.js CHANGED
@@ -515,6 +515,7 @@ var VAULT_ABI = [
515
515
  var VAULT_ADDRESS = "0xD580071c47d4a667858B5FafAb85BC9C609beC5D";
516
516
 
517
517
  // src/config/constants.ts
518
+ var ZYFI_FEE_RATE = 0.1;
518
519
  var MIN_PORTFOLIO_BALANCE = {
519
520
  1: {
520
521
  USDC: 100n * 10n ** 6n,
@@ -1047,6 +1048,310 @@ var hasMatchingPool = (data, chains, asset) => {
1047
1048
  return false;
1048
1049
  };
1049
1050
 
1051
+ // src/utils/zyfi-fees.ts
1052
+ var CHAIN_NAME_TO_ID = {
1053
+ ethereum: "1",
1054
+ "ethereum mainnet": "1",
1055
+ mainnet: "1",
1056
+ base: "8453",
1057
+ arbitrum: "42161",
1058
+ "arbitrum one": "42161"
1059
+ };
1060
+ function symbolToAssetType(symbol) {
1061
+ const upper = symbol.trim().toUpperCase();
1062
+ if (upper === "USDC") return "usdc";
1063
+ if (upper === "WETH" || upper === "ETH") return "eth";
1064
+ if (upper === "EURC") return "eurc";
1065
+ if (upper === "CBBTC") return "cbbtc";
1066
+ if (upper === "CBETH") return "cbeth";
1067
+ return symbol.trim().toLowerCase();
1068
+ }
1069
+ function assetTypeToSymbol(assetType) {
1070
+ const lower = assetType.trim().toLowerCase();
1071
+ if (lower === "usdc") return "USDC";
1072
+ if (lower === "eth") return "WETH";
1073
+ if (lower === "eurc") return "EURC";
1074
+ if (lower === "cbbtc") return "CBBTC";
1075
+ if (lower === "cbeth") return "CBETH";
1076
+ return assetType.trim().toUpperCase();
1077
+ }
1078
+ function chainNameToId(chain) {
1079
+ if (!chain) return void 0;
1080
+ const trimmed = chain.trim();
1081
+ if (/^\d+$/.test(trimmed)) return trimmed;
1082
+ return CHAIN_NAME_TO_ID[trimmed.toLowerCase()];
1083
+ }
1084
+ function parseHumanAmount(value) {
1085
+ if (typeof value === "number") {
1086
+ return Number.isFinite(value) ? value : 0;
1087
+ }
1088
+ const parsed = Number.parseFloat(String(value ?? "0"));
1089
+ return Number.isFinite(parsed) ? parsed : 0;
1090
+ }
1091
+ function humanAmountToRaw(human, decimals) {
1092
+ if (!Number.isFinite(human) || human <= 0 || decimals < 0) {
1093
+ return 0n;
1094
+ }
1095
+ const fixed = human.toFixed(decimals);
1096
+ const [whole, frac = ""] = fixed.split(".");
1097
+ const wholePart = BigInt(whole);
1098
+ const fracPart = BigInt(frac.padEnd(decimals, "0").slice(0, decimals) || "0");
1099
+ return wholePart * 10n ** BigInt(decimals) + fracPart;
1100
+ }
1101
+ function formatHumanAmount(value) {
1102
+ if (!Number.isFinite(value) || value === 0) return "0";
1103
+ const fixed = value.toFixed(18);
1104
+ return fixed.replace(/\.?0+$/, "") || "0";
1105
+ }
1106
+ function computePendingFees(currentEarningsByChain) {
1107
+ const byToken = {};
1108
+ const byChain = {};
1109
+ const byChainByToken = {};
1110
+ let total = 0;
1111
+ if (!currentEarningsByChain) {
1112
+ return { byToken, byChain, byChainByToken, total };
1113
+ }
1114
+ Object.entries(currentEarningsByChain).forEach(([chainId, chainEarnings]) => {
1115
+ const feeByToken = {};
1116
+ let chainFee = 0;
1117
+ Object.entries(chainEarnings || {}).forEach(([tokenSymbol, tokenAmount]) => {
1118
+ const numericValue = parseHumanAmount(tokenAmount);
1119
+ const tokenFee = numericValue > 0 ? numericValue * ZYFI_FEE_RATE : 0;
1120
+ feeByToken[tokenSymbol] = tokenFee;
1121
+ chainFee += tokenFee;
1122
+ byToken[tokenSymbol] = (byToken[tokenSymbol] ?? 0) + tokenFee;
1123
+ });
1124
+ byChainByToken[chainId] = feeByToken;
1125
+ byChain[chainId] = chainFee;
1126
+ total += chainFee;
1127
+ });
1128
+ return { byToken, byChain, byChainByToken, total };
1129
+ }
1130
+ function feeForAssetType(feesByToken, assetType) {
1131
+ const symbol = assetTypeToSymbol(assetType);
1132
+ if (feesByToken[symbol] !== void 0) return feesByToken[symbol] ?? 0;
1133
+ if (assetType.toLowerCase() === "eth") {
1134
+ return feesByToken["ETH"] ?? feesByToken["WETH"] ?? 0;
1135
+ }
1136
+ return feesByToken[assetType.toUpperCase()] ?? 0;
1137
+ }
1138
+ function feeForChainAsset(byChainByToken, chainId, assetType) {
1139
+ const chainFees = byChainByToken[chainId] || {};
1140
+ return feeForAssetType(chainFees, assetType);
1141
+ }
1142
+ function applyFeeToHexBalance(balanceHex, feeHuman, decimals) {
1143
+ let balance;
1144
+ try {
1145
+ balance = BigInt(balanceHex || "0x0");
1146
+ } catch {
1147
+ balance = 0n;
1148
+ }
1149
+ const feeRaw = humanAmountToRaw(feeHuman, decimals);
1150
+ const net = balance > feeRaw ? balance - feeRaw : 0n;
1151
+ return `0x${net.toString(16)}`;
1152
+ }
1153
+ function applyFeeToDecimalWei(amount, feeHuman, decimals) {
1154
+ let balance;
1155
+ try {
1156
+ balance = BigInt(amount || "0");
1157
+ } catch {
1158
+ balance = 0n;
1159
+ }
1160
+ const feeRaw = humanAmountToRaw(feeHuman, decimals);
1161
+ const net = balance > feeRaw ? balance - feeRaw : 0n;
1162
+ return net.toString();
1163
+ }
1164
+ function enrichAssetBalance(entry, feeHuman) {
1165
+ const balanceWithFee = applyFeeToHexBalance(
1166
+ entry.balance,
1167
+ feeHuman,
1168
+ entry.decimals
1169
+ );
1170
+ return {
1171
+ ...entry,
1172
+ balanceWithFee
1173
+ };
1174
+ }
1175
+ function resolvePositionSymbol(position) {
1176
+ if (position.token_symbol) return position.token_symbol;
1177
+ if (position.assetType) return assetTypeToSymbol(position.assetType);
1178
+ return void 0;
1179
+ }
1180
+ function resolvePositionDecimals(position) {
1181
+ if (typeof position.decimals === "number") return position.decimals;
1182
+ const asset = position.assetType || symbolToAssetType(position.token_symbol || "");
1183
+ if (asset === "usdc" || asset === "eurc") return 6;
1184
+ if (asset === "cbbtc") return 8;
1185
+ return 18;
1186
+ }
1187
+ function enrichPositions(positions, byChainByToken) {
1188
+ const groups = /* @__PURE__ */ new Map();
1189
+ positions.forEach((position, index) => {
1190
+ const chainId = chainNameToId(position.chain || "");
1191
+ const symbol = resolvePositionSymbol(position);
1192
+ if (!chainId || !symbol) {
1193
+ return;
1194
+ }
1195
+ const key = `${chainId}:${symbol.toUpperCase()}`;
1196
+ const list = groups.get(key) || [];
1197
+ list.push(index);
1198
+ groups.set(key, list);
1199
+ });
1200
+ const feeShareByIndex = /* @__PURE__ */ new Map();
1201
+ groups.forEach((indices, key) => {
1202
+ const [chainId, symbol] = key.split(":");
1203
+ const chainFees = byChainByToken[chainId] || {};
1204
+ let totalFee = chainFees[symbol] ?? (symbol === "WETH" ? chainFees["ETH"] : void 0) ?? (symbol === "ETH" ? chainFees["WETH"] : void 0) ?? 0;
1205
+ if (totalFee <= 0) {
1206
+ indices.forEach((i) => feeShareByIndex.set(i, 0));
1207
+ return;
1208
+ }
1209
+ let totalUnderlying = 0n;
1210
+ const underlyings = indices.map((i) => {
1211
+ try {
1212
+ return BigInt(positions[i].underlyingAmount || "0");
1213
+ } catch {
1214
+ return 0n;
1215
+ }
1216
+ });
1217
+ underlyings.forEach((u) => {
1218
+ totalUnderlying += u;
1219
+ });
1220
+ if (totalUnderlying === 0n) {
1221
+ const share = totalFee / indices.length;
1222
+ indices.forEach((i) => feeShareByIndex.set(i, share));
1223
+ return;
1224
+ }
1225
+ indices.forEach((i, idx) => {
1226
+ const share = totalFee * Number(underlyings[idx]) / Number(totalUnderlying);
1227
+ feeShareByIndex.set(i, share);
1228
+ });
1229
+ });
1230
+ return positions.map((position, index) => {
1231
+ const underlying = position.underlyingAmount;
1232
+ if (underlying === void 0) {
1233
+ return { ...position };
1234
+ }
1235
+ const feeShare = feeShareByIndex.get(index) ?? 0;
1236
+ const decimals = resolvePositionDecimals(position);
1237
+ return {
1238
+ ...position,
1239
+ underlyingAmountWithFee: applyFeeToDecimalWei(
1240
+ underlying,
1241
+ feeShare,
1242
+ decimals
1243
+ )
1244
+ };
1245
+ });
1246
+ }
1247
+ function enrichPortfolioWithFees(portfolio, currentEarningsByChain) {
1248
+ const { byToken, byChainByToken } = computePendingFees(currentEarningsByChain);
1249
+ const portfolioByAssetType = portfolio.portfolioByAssetType ? Object.fromEntries(
1250
+ Object.entries(portfolio.portfolioByAssetType).map(
1251
+ ([assetType, entry]) => [
1252
+ assetType,
1253
+ enrichAssetBalance(entry, feeForAssetType(byToken, assetType))
1254
+ ]
1255
+ )
1256
+ ) : void 0;
1257
+ const portfolioByChain = portfolio.portfolioByChain ? Object.fromEntries(
1258
+ Object.entries(portfolio.portfolioByChain).map(
1259
+ ([chainId, assets]) => [
1260
+ chainId,
1261
+ Object.fromEntries(
1262
+ Object.entries(assets).map(([assetType, entry]) => [
1263
+ assetType,
1264
+ enrichAssetBalance(
1265
+ entry,
1266
+ feeForChainAsset(byChainByToken, chainId, assetType)
1267
+ )
1268
+ ])
1269
+ )
1270
+ ]
1271
+ )
1272
+ ) : void 0;
1273
+ const positions = portfolio.positions ? enrichPositions(portfolio.positions, byChainByToken) : void 0;
1274
+ return {
1275
+ ...portfolio,
1276
+ ...portfolioByAssetType ? { portfolioByAssetType } : {},
1277
+ ...portfolioByChain ? { portfolioByChain } : {},
1278
+ ...positions ? { positions } : {}
1279
+ };
1280
+ }
1281
+ function sumCurrentByToken(currentByChain) {
1282
+ const totals = {};
1283
+ if (!currentByChain) return totals;
1284
+ Object.values(currentByChain).forEach((chainEarnings) => {
1285
+ Object.entries(chainEarnings || {}).forEach(([symbol, amount]) => {
1286
+ totals[symbol] = (totals[symbol] ?? 0) + parseHumanAmount(amount);
1287
+ });
1288
+ });
1289
+ return totals;
1290
+ }
1291
+ function enrichOnchainEarningsTotals(apiData) {
1292
+ const lifetimeByToken = apiData.lifetime_earnings_by_token || {};
1293
+ const lifetimeByChain = apiData.lifetime_earnings_by_chain || {};
1294
+ const currentByChain = apiData.current_earnings_by_chain || {};
1295
+ const unrealizedByChain = apiData.unrealized_earnings_by_chain || apiData.unrealized_earnings || {};
1296
+ const currentByToken = apiData.current_earnings_by_token && Object.keys(apiData.current_earnings_by_token).length > 0 ? Object.fromEntries(
1297
+ Object.entries(apiData.current_earnings_by_token).map(([k, v]) => [
1298
+ k,
1299
+ parseHumanAmount(v)
1300
+ ])
1301
+ ) : sumCurrentByToken(currentByChain);
1302
+ const unrealizedByToken = apiData.unrealized_earnings_by_token && Object.keys(apiData.unrealized_earnings_by_token).length > 0 ? Object.fromEntries(
1303
+ Object.entries(apiData.unrealized_earnings_by_token).map(([k, v]) => [
1304
+ k,
1305
+ parseHumanAmount(v)
1306
+ ])
1307
+ ) : sumCurrentByToken(unrealizedByChain);
1308
+ const keepRate = 1 - ZYFI_FEE_RATE;
1309
+ const tokenKeys = /* @__PURE__ */ new Set([
1310
+ ...Object.keys(lifetimeByToken),
1311
+ ...Object.keys(unrealizedByToken),
1312
+ ...Object.keys(currentByToken)
1313
+ ]);
1314
+ const totalEarningsByTokenWithFee = {};
1315
+ tokenKeys.forEach((symbol) => {
1316
+ const lifetime = parseHumanAmount(lifetimeByToken[symbol]);
1317
+ const unrealized = unrealizedByToken[symbol] ?? 0;
1318
+ const current = currentByToken[symbol] ?? 0;
1319
+ totalEarningsByTokenWithFee[symbol] = formatHumanAmount(
1320
+ lifetime + unrealized + current * keepRate
1321
+ );
1322
+ });
1323
+ const chainKeys = /* @__PURE__ */ new Set([
1324
+ ...Object.keys(lifetimeByChain),
1325
+ ...Object.keys(unrealizedByChain),
1326
+ ...Object.keys(currentByChain)
1327
+ ]);
1328
+ const totalEarningsByChainWithFee = {};
1329
+ chainKeys.forEach((chainId) => {
1330
+ const lifetimeTokens = lifetimeByChain[chainId] || {};
1331
+ const unrealizedTokens = unrealizedByChain[chainId] || {};
1332
+ const currentTokens = currentByChain[chainId] || {};
1333
+ const symbols = /* @__PURE__ */ new Set([
1334
+ ...Object.keys(lifetimeTokens),
1335
+ ...Object.keys(unrealizedTokens),
1336
+ ...Object.keys(currentTokens)
1337
+ ]);
1338
+ const chainMap = {};
1339
+ symbols.forEach((symbol) => {
1340
+ const lifetime = parseHumanAmount(lifetimeTokens[symbol]);
1341
+ const unrealized = parseHumanAmount(unrealizedTokens[symbol]);
1342
+ const current = parseHumanAmount(currentTokens[symbol]);
1343
+ chainMap[symbol] = formatHumanAmount(
1344
+ lifetime + unrealized + current * keepRate
1345
+ );
1346
+ });
1347
+ totalEarningsByChainWithFee[chainId] = chainMap;
1348
+ });
1349
+ return {
1350
+ totalEarningsByTokenWithFee,
1351
+ totalEarningsByChainWithFee
1352
+ };
1353
+ }
1354
+
1050
1355
  // src/core/ZyfaiSDK.ts
1051
1356
  var import_siwe = require("siwe");
1052
1357
  var _ZyfaiSDK = class _ZyfaiSDK {
@@ -2506,19 +2811,23 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2506
2811
  }
2507
2812
  }
2508
2813
  /**
2509
- * Get all active positions and portfolio for a user
2814
+ * Get portfolio positions and balances for a user, enriched with
2815
+ * net-of-pending-fee fields (`balanceWithFee`, `underlyingAmountWithFee`).
2816
+ *
2817
+ * Pending fee is derived from onchain `current` earnings × fee rate.
2818
+ * Gross balances are unchanged. If earnings cannot be fetched, `*WithFee`
2819
+ * equals the gross value so the response shape stays stable.
2820
+ *
2821
+ * Note: portfolio balances are live; earnings used for the fee may be from
2822
+ * a snapshot, so net values can differ slightly from a fully live calc.
2510
2823
  *
2511
2824
  * @param userAddress - User's EOA address
2512
- * @param chainId - Optional: Filter by specific chain ID
2513
- * @returns User's positions across all protocols
2825
+ * @returns Portfolio with optional fee-adjusted balance fields
2514
2826
  *
2515
2827
  * @example
2516
2828
  * ```typescript
2517
- * // Get all positions across all chains
2518
- * const positions = await sdk.getPositions(userAddress);
2519
- *
2520
- * // Get positions on a specific chain
2521
- * const basePositions = await sdk.getPositions(userAddress, 8453);
2829
+ * const { portfolio } = await sdk.getPortfolio(userAddress);
2830
+ * console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
2522
2831
  * ```
2523
2832
  */
2524
2833
  async getPortfolio(userAddress) {
@@ -2534,18 +2843,27 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2534
2843
  portfolio: {}
2535
2844
  };
2536
2845
  }
2537
- console.log("Getting portfolio for", smartWalletInfo.smartWallet);
2538
- const response = await this.httpClient.get(
2539
- ENDPOINTS.DATA_PORTFOLIO(smartWalletInfo.smartWallet)
2540
- );
2846
+ const smartWallet = smartWalletInfo.smartWallet;
2847
+ const [response, earningsResult] = await Promise.all([
2848
+ this.httpClient.get(
2849
+ ENDPOINTS.DATA_PORTFOLIO(smartWallet)
2850
+ ),
2851
+ this.httpClient.dataGet(DATA_ENDPOINTS.ONCHAIN_EARNINGS(smartWallet)).catch(() => null)
2852
+ ]);
2541
2853
  const convertedResponse = removeUnusedFields(response);
2854
+ const earningsData = earningsResult?.data || earningsResult;
2855
+ const currentEarningsByChain = earningsData?.current_earnings_by_chain ?? null;
2856
+ const portfolio = enrichPortfolioWithFees(
2857
+ convertedResponse,
2858
+ currentEarningsByChain
2859
+ );
2542
2860
  return {
2543
2861
  success: true,
2544
2862
  userAddress,
2545
- portfolio: convertedResponse
2863
+ portfolio
2546
2864
  };
2547
2865
  } catch (error) {
2548
- throw new Error(`Failed to get positions: ${error.message}`);
2866
+ throw new Error(`Failed to get portfolio: ${error.message}`);
2549
2867
  }
2550
2868
  }
2551
2869
  // ============================================================================
@@ -2844,6 +3162,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2844
3162
  /**
2845
3163
  * Get onchain earnings for a wallet
2846
3164
  *
3165
+ * Includes gross totals plus net-of-fee totals:
3166
+ * `totalEarningsByTokenWithFee = lifetime + unrealized + current × (1 - feeRate)`.
3167
+ * Lifetime and unrealized are never multiplied by the keep-rate.
3168
+ *
2847
3169
  * @param walletAddress - Smart wallet address
2848
3170
  * @returns Onchain earnings data with per-token breakdowns
2849
3171
  *
@@ -2851,6 +3173,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2851
3173
  * ```typescript
2852
3174
  * const earnings = await sdk.getOnchainEarnings("0x...");
2853
3175
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
3176
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
2854
3177
  * console.log("Total on Arbitrum:", earnings.data.totalEarningsByChain?.["42161"]);
2855
3178
  * ```
2856
3179
  */
@@ -2863,12 +3186,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2863
3186
  DATA_ENDPOINTS.ONCHAIN_EARNINGS(walletAddress)
2864
3187
  );
2865
3188
  const data = response.data || response;
3189
+ const withFee = enrichOnchainEarningsTotals(data);
2866
3190
  return {
2867
3191
  success: true,
2868
3192
  data: {
2869
3193
  walletAddress,
2870
3194
  totalEarningsByToken: data.total_earnings_by_token || {},
2871
3195
  totalEarningsByChain: data.total_earnings_by_chain || {},
3196
+ totalEarningsByTokenWithFee: withFee.totalEarningsByTokenWithFee,
3197
+ totalEarningsByChainWithFee: withFee.totalEarningsByChainWithFee,
2872
3198
  lastCheckTimestamp: data.last_check_timestamp,
2873
3199
  lastLogDate: data.last_log_date
2874
3200
  }
@@ -2881,7 +3207,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2881
3207
  }
2882
3208
  /**
2883
3209
  * Calculate/refresh onchain earnings for a wallet
2884
- * This triggers a recalculation of earnings on the backend
3210
+ * This triggers a recalculation of earnings on the backend.
3211
+ * Response shape matches `getOnchainEarnings` (includes `*WithFee` nets).
2885
3212
  *
2886
3213
  * @param walletAddress - Smart wallet address
2887
3214
  * @returns Updated onchain earnings data with per-token breakdowns
@@ -2890,7 +3217,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2890
3217
  * ```typescript
2891
3218
  * const earnings = await sdk.calculateOnchainEarnings("0x...");
2892
3219
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
2893
- * console.log("Per-chain total:", earnings.data.totalEarningsByChain);
3220
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
2894
3221
  * ```
2895
3222
  */
2896
3223
  async calculateOnchainEarnings(walletAddress) {
@@ -2903,12 +3230,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2903
3230
  {}
2904
3231
  );
2905
3232
  const data = response.data || response;
3233
+ const withFee = enrichOnchainEarningsTotals(data);
2906
3234
  return {
2907
3235
  success: true,
2908
3236
  data: {
2909
3237
  walletAddress,
2910
3238
  totalEarningsByToken: data.total_earnings_by_token || {},
2911
3239
  totalEarningsByChain: data.total_earnings_by_chain || {},
3240
+ totalEarningsByTokenWithFee: withFee.totalEarningsByTokenWithFee,
3241
+ totalEarningsByChainWithFee: withFee.totalEarningsByChainWithFee,
2912
3242
  lastCheckTimestamp: data.last_check_timestamp,
2913
3243
  lastLogDate: data.last_log_date
2914
3244
  }
package/dist/index.mjs CHANGED
@@ -463,6 +463,7 @@ var VAULT_ABI = [
463
463
  var VAULT_ADDRESS = "0xD580071c47d4a667858B5FafAb85BC9C609beC5D";
464
464
 
465
465
  // src/config/constants.ts
466
+ var ZYFI_FEE_RATE = 0.1;
466
467
  var MIN_PORTFOLIO_BALANCE = {
467
468
  1: {
468
469
  USDC: 100n * 10n ** 6n,
@@ -1015,6 +1016,310 @@ var hasMatchingPool = (data, chains, asset) => {
1015
1016
  return false;
1016
1017
  };
1017
1018
 
1019
+ // src/utils/zyfi-fees.ts
1020
+ var CHAIN_NAME_TO_ID = {
1021
+ ethereum: "1",
1022
+ "ethereum mainnet": "1",
1023
+ mainnet: "1",
1024
+ base: "8453",
1025
+ arbitrum: "42161",
1026
+ "arbitrum one": "42161"
1027
+ };
1028
+ function symbolToAssetType(symbol) {
1029
+ const upper = symbol.trim().toUpperCase();
1030
+ if (upper === "USDC") return "usdc";
1031
+ if (upper === "WETH" || upper === "ETH") return "eth";
1032
+ if (upper === "EURC") return "eurc";
1033
+ if (upper === "CBBTC") return "cbbtc";
1034
+ if (upper === "CBETH") return "cbeth";
1035
+ return symbol.trim().toLowerCase();
1036
+ }
1037
+ function assetTypeToSymbol(assetType) {
1038
+ const lower = assetType.trim().toLowerCase();
1039
+ if (lower === "usdc") return "USDC";
1040
+ if (lower === "eth") return "WETH";
1041
+ if (lower === "eurc") return "EURC";
1042
+ if (lower === "cbbtc") return "CBBTC";
1043
+ if (lower === "cbeth") return "CBETH";
1044
+ return assetType.trim().toUpperCase();
1045
+ }
1046
+ function chainNameToId(chain) {
1047
+ if (!chain) return void 0;
1048
+ const trimmed = chain.trim();
1049
+ if (/^\d+$/.test(trimmed)) return trimmed;
1050
+ return CHAIN_NAME_TO_ID[trimmed.toLowerCase()];
1051
+ }
1052
+ function parseHumanAmount(value) {
1053
+ if (typeof value === "number") {
1054
+ return Number.isFinite(value) ? value : 0;
1055
+ }
1056
+ const parsed = Number.parseFloat(String(value ?? "0"));
1057
+ return Number.isFinite(parsed) ? parsed : 0;
1058
+ }
1059
+ function humanAmountToRaw(human, decimals) {
1060
+ if (!Number.isFinite(human) || human <= 0 || decimals < 0) {
1061
+ return 0n;
1062
+ }
1063
+ const fixed = human.toFixed(decimals);
1064
+ const [whole, frac = ""] = fixed.split(".");
1065
+ const wholePart = BigInt(whole);
1066
+ const fracPart = BigInt(frac.padEnd(decimals, "0").slice(0, decimals) || "0");
1067
+ return wholePart * 10n ** BigInt(decimals) + fracPart;
1068
+ }
1069
+ function formatHumanAmount(value) {
1070
+ if (!Number.isFinite(value) || value === 0) return "0";
1071
+ const fixed = value.toFixed(18);
1072
+ return fixed.replace(/\.?0+$/, "") || "0";
1073
+ }
1074
+ function computePendingFees(currentEarningsByChain) {
1075
+ const byToken = {};
1076
+ const byChain = {};
1077
+ const byChainByToken = {};
1078
+ let total = 0;
1079
+ if (!currentEarningsByChain) {
1080
+ return { byToken, byChain, byChainByToken, total };
1081
+ }
1082
+ Object.entries(currentEarningsByChain).forEach(([chainId, chainEarnings]) => {
1083
+ const feeByToken = {};
1084
+ let chainFee = 0;
1085
+ Object.entries(chainEarnings || {}).forEach(([tokenSymbol, tokenAmount]) => {
1086
+ const numericValue = parseHumanAmount(tokenAmount);
1087
+ const tokenFee = numericValue > 0 ? numericValue * ZYFI_FEE_RATE : 0;
1088
+ feeByToken[tokenSymbol] = tokenFee;
1089
+ chainFee += tokenFee;
1090
+ byToken[tokenSymbol] = (byToken[tokenSymbol] ?? 0) + tokenFee;
1091
+ });
1092
+ byChainByToken[chainId] = feeByToken;
1093
+ byChain[chainId] = chainFee;
1094
+ total += chainFee;
1095
+ });
1096
+ return { byToken, byChain, byChainByToken, total };
1097
+ }
1098
+ function feeForAssetType(feesByToken, assetType) {
1099
+ const symbol = assetTypeToSymbol(assetType);
1100
+ if (feesByToken[symbol] !== void 0) return feesByToken[symbol] ?? 0;
1101
+ if (assetType.toLowerCase() === "eth") {
1102
+ return feesByToken["ETH"] ?? feesByToken["WETH"] ?? 0;
1103
+ }
1104
+ return feesByToken[assetType.toUpperCase()] ?? 0;
1105
+ }
1106
+ function feeForChainAsset(byChainByToken, chainId, assetType) {
1107
+ const chainFees = byChainByToken[chainId] || {};
1108
+ return feeForAssetType(chainFees, assetType);
1109
+ }
1110
+ function applyFeeToHexBalance(balanceHex, feeHuman, decimals) {
1111
+ let balance;
1112
+ try {
1113
+ balance = BigInt(balanceHex || "0x0");
1114
+ } catch {
1115
+ balance = 0n;
1116
+ }
1117
+ const feeRaw = humanAmountToRaw(feeHuman, decimals);
1118
+ const net = balance > feeRaw ? balance - feeRaw : 0n;
1119
+ return `0x${net.toString(16)}`;
1120
+ }
1121
+ function applyFeeToDecimalWei(amount, feeHuman, decimals) {
1122
+ let balance;
1123
+ try {
1124
+ balance = BigInt(amount || "0");
1125
+ } catch {
1126
+ balance = 0n;
1127
+ }
1128
+ const feeRaw = humanAmountToRaw(feeHuman, decimals);
1129
+ const net = balance > feeRaw ? balance - feeRaw : 0n;
1130
+ return net.toString();
1131
+ }
1132
+ function enrichAssetBalance(entry, feeHuman) {
1133
+ const balanceWithFee = applyFeeToHexBalance(
1134
+ entry.balance,
1135
+ feeHuman,
1136
+ entry.decimals
1137
+ );
1138
+ return {
1139
+ ...entry,
1140
+ balanceWithFee
1141
+ };
1142
+ }
1143
+ function resolvePositionSymbol(position) {
1144
+ if (position.token_symbol) return position.token_symbol;
1145
+ if (position.assetType) return assetTypeToSymbol(position.assetType);
1146
+ return void 0;
1147
+ }
1148
+ function resolvePositionDecimals(position) {
1149
+ if (typeof position.decimals === "number") return position.decimals;
1150
+ const asset = position.assetType || symbolToAssetType(position.token_symbol || "");
1151
+ if (asset === "usdc" || asset === "eurc") return 6;
1152
+ if (asset === "cbbtc") return 8;
1153
+ return 18;
1154
+ }
1155
+ function enrichPositions(positions, byChainByToken) {
1156
+ const groups = /* @__PURE__ */ new Map();
1157
+ positions.forEach((position, index) => {
1158
+ const chainId = chainNameToId(position.chain || "");
1159
+ const symbol = resolvePositionSymbol(position);
1160
+ if (!chainId || !symbol) {
1161
+ return;
1162
+ }
1163
+ const key = `${chainId}:${symbol.toUpperCase()}`;
1164
+ const list = groups.get(key) || [];
1165
+ list.push(index);
1166
+ groups.set(key, list);
1167
+ });
1168
+ const feeShareByIndex = /* @__PURE__ */ new Map();
1169
+ groups.forEach((indices, key) => {
1170
+ const [chainId, symbol] = key.split(":");
1171
+ const chainFees = byChainByToken[chainId] || {};
1172
+ let totalFee = chainFees[symbol] ?? (symbol === "WETH" ? chainFees["ETH"] : void 0) ?? (symbol === "ETH" ? chainFees["WETH"] : void 0) ?? 0;
1173
+ if (totalFee <= 0) {
1174
+ indices.forEach((i) => feeShareByIndex.set(i, 0));
1175
+ return;
1176
+ }
1177
+ let totalUnderlying = 0n;
1178
+ const underlyings = indices.map((i) => {
1179
+ try {
1180
+ return BigInt(positions[i].underlyingAmount || "0");
1181
+ } catch {
1182
+ return 0n;
1183
+ }
1184
+ });
1185
+ underlyings.forEach((u) => {
1186
+ totalUnderlying += u;
1187
+ });
1188
+ if (totalUnderlying === 0n) {
1189
+ const share = totalFee / indices.length;
1190
+ indices.forEach((i) => feeShareByIndex.set(i, share));
1191
+ return;
1192
+ }
1193
+ indices.forEach((i, idx) => {
1194
+ const share = totalFee * Number(underlyings[idx]) / Number(totalUnderlying);
1195
+ feeShareByIndex.set(i, share);
1196
+ });
1197
+ });
1198
+ return positions.map((position, index) => {
1199
+ const underlying = position.underlyingAmount;
1200
+ if (underlying === void 0) {
1201
+ return { ...position };
1202
+ }
1203
+ const feeShare = feeShareByIndex.get(index) ?? 0;
1204
+ const decimals = resolvePositionDecimals(position);
1205
+ return {
1206
+ ...position,
1207
+ underlyingAmountWithFee: applyFeeToDecimalWei(
1208
+ underlying,
1209
+ feeShare,
1210
+ decimals
1211
+ )
1212
+ };
1213
+ });
1214
+ }
1215
+ function enrichPortfolioWithFees(portfolio, currentEarningsByChain) {
1216
+ const { byToken, byChainByToken } = computePendingFees(currentEarningsByChain);
1217
+ const portfolioByAssetType = portfolio.portfolioByAssetType ? Object.fromEntries(
1218
+ Object.entries(portfolio.portfolioByAssetType).map(
1219
+ ([assetType, entry]) => [
1220
+ assetType,
1221
+ enrichAssetBalance(entry, feeForAssetType(byToken, assetType))
1222
+ ]
1223
+ )
1224
+ ) : void 0;
1225
+ const portfolioByChain = portfolio.portfolioByChain ? Object.fromEntries(
1226
+ Object.entries(portfolio.portfolioByChain).map(
1227
+ ([chainId, assets]) => [
1228
+ chainId,
1229
+ Object.fromEntries(
1230
+ Object.entries(assets).map(([assetType, entry]) => [
1231
+ assetType,
1232
+ enrichAssetBalance(
1233
+ entry,
1234
+ feeForChainAsset(byChainByToken, chainId, assetType)
1235
+ )
1236
+ ])
1237
+ )
1238
+ ]
1239
+ )
1240
+ ) : void 0;
1241
+ const positions = portfolio.positions ? enrichPositions(portfolio.positions, byChainByToken) : void 0;
1242
+ return {
1243
+ ...portfolio,
1244
+ ...portfolioByAssetType ? { portfolioByAssetType } : {},
1245
+ ...portfolioByChain ? { portfolioByChain } : {},
1246
+ ...positions ? { positions } : {}
1247
+ };
1248
+ }
1249
+ function sumCurrentByToken(currentByChain) {
1250
+ const totals = {};
1251
+ if (!currentByChain) return totals;
1252
+ Object.values(currentByChain).forEach((chainEarnings) => {
1253
+ Object.entries(chainEarnings || {}).forEach(([symbol, amount]) => {
1254
+ totals[symbol] = (totals[symbol] ?? 0) + parseHumanAmount(amount);
1255
+ });
1256
+ });
1257
+ return totals;
1258
+ }
1259
+ function enrichOnchainEarningsTotals(apiData) {
1260
+ const lifetimeByToken = apiData.lifetime_earnings_by_token || {};
1261
+ const lifetimeByChain = apiData.lifetime_earnings_by_chain || {};
1262
+ const currentByChain = apiData.current_earnings_by_chain || {};
1263
+ const unrealizedByChain = apiData.unrealized_earnings_by_chain || apiData.unrealized_earnings || {};
1264
+ const currentByToken = apiData.current_earnings_by_token && Object.keys(apiData.current_earnings_by_token).length > 0 ? Object.fromEntries(
1265
+ Object.entries(apiData.current_earnings_by_token).map(([k, v]) => [
1266
+ k,
1267
+ parseHumanAmount(v)
1268
+ ])
1269
+ ) : sumCurrentByToken(currentByChain);
1270
+ const unrealizedByToken = apiData.unrealized_earnings_by_token && Object.keys(apiData.unrealized_earnings_by_token).length > 0 ? Object.fromEntries(
1271
+ Object.entries(apiData.unrealized_earnings_by_token).map(([k, v]) => [
1272
+ k,
1273
+ parseHumanAmount(v)
1274
+ ])
1275
+ ) : sumCurrentByToken(unrealizedByChain);
1276
+ const keepRate = 1 - ZYFI_FEE_RATE;
1277
+ const tokenKeys = /* @__PURE__ */ new Set([
1278
+ ...Object.keys(lifetimeByToken),
1279
+ ...Object.keys(unrealizedByToken),
1280
+ ...Object.keys(currentByToken)
1281
+ ]);
1282
+ const totalEarningsByTokenWithFee = {};
1283
+ tokenKeys.forEach((symbol) => {
1284
+ const lifetime = parseHumanAmount(lifetimeByToken[symbol]);
1285
+ const unrealized = unrealizedByToken[symbol] ?? 0;
1286
+ const current = currentByToken[symbol] ?? 0;
1287
+ totalEarningsByTokenWithFee[symbol] = formatHumanAmount(
1288
+ lifetime + unrealized + current * keepRate
1289
+ );
1290
+ });
1291
+ const chainKeys = /* @__PURE__ */ new Set([
1292
+ ...Object.keys(lifetimeByChain),
1293
+ ...Object.keys(unrealizedByChain),
1294
+ ...Object.keys(currentByChain)
1295
+ ]);
1296
+ const totalEarningsByChainWithFee = {};
1297
+ chainKeys.forEach((chainId) => {
1298
+ const lifetimeTokens = lifetimeByChain[chainId] || {};
1299
+ const unrealizedTokens = unrealizedByChain[chainId] || {};
1300
+ const currentTokens = currentByChain[chainId] || {};
1301
+ const symbols = /* @__PURE__ */ new Set([
1302
+ ...Object.keys(lifetimeTokens),
1303
+ ...Object.keys(unrealizedTokens),
1304
+ ...Object.keys(currentTokens)
1305
+ ]);
1306
+ const chainMap = {};
1307
+ symbols.forEach((symbol) => {
1308
+ const lifetime = parseHumanAmount(lifetimeTokens[symbol]);
1309
+ const unrealized = parseHumanAmount(unrealizedTokens[symbol]);
1310
+ const current = parseHumanAmount(currentTokens[symbol]);
1311
+ chainMap[symbol] = formatHumanAmount(
1312
+ lifetime + unrealized + current * keepRate
1313
+ );
1314
+ });
1315
+ totalEarningsByChainWithFee[chainId] = chainMap;
1316
+ });
1317
+ return {
1318
+ totalEarningsByTokenWithFee,
1319
+ totalEarningsByChainWithFee
1320
+ };
1321
+ }
1322
+
1018
1323
  // src/core/ZyfaiSDK.ts
1019
1324
  import { SiweMessage } from "siwe";
1020
1325
  var _ZyfaiSDK = class _ZyfaiSDK {
@@ -2474,19 +2779,23 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2474
2779
  }
2475
2780
  }
2476
2781
  /**
2477
- * Get all active positions and portfolio for a user
2782
+ * Get portfolio positions and balances for a user, enriched with
2783
+ * net-of-pending-fee fields (`balanceWithFee`, `underlyingAmountWithFee`).
2784
+ *
2785
+ * Pending fee is derived from onchain `current` earnings × fee rate.
2786
+ * Gross balances are unchanged. If earnings cannot be fetched, `*WithFee`
2787
+ * equals the gross value so the response shape stays stable.
2788
+ *
2789
+ * Note: portfolio balances are live; earnings used for the fee may be from
2790
+ * a snapshot, so net values can differ slightly from a fully live calc.
2478
2791
  *
2479
2792
  * @param userAddress - User's EOA address
2480
- * @param chainId - Optional: Filter by specific chain ID
2481
- * @returns User's positions across all protocols
2793
+ * @returns Portfolio with optional fee-adjusted balance fields
2482
2794
  *
2483
2795
  * @example
2484
2796
  * ```typescript
2485
- * // Get all positions across all chains
2486
- * const positions = await sdk.getPositions(userAddress);
2487
- *
2488
- * // Get positions on a specific chain
2489
- * const basePositions = await sdk.getPositions(userAddress, 8453);
2797
+ * const { portfolio } = await sdk.getPortfolio(userAddress);
2798
+ * console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
2490
2799
  * ```
2491
2800
  */
2492
2801
  async getPortfolio(userAddress) {
@@ -2502,18 +2811,27 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2502
2811
  portfolio: {}
2503
2812
  };
2504
2813
  }
2505
- console.log("Getting portfolio for", smartWalletInfo.smartWallet);
2506
- const response = await this.httpClient.get(
2507
- ENDPOINTS.DATA_PORTFOLIO(smartWalletInfo.smartWallet)
2508
- );
2814
+ const smartWallet = smartWalletInfo.smartWallet;
2815
+ const [response, earningsResult] = await Promise.all([
2816
+ this.httpClient.get(
2817
+ ENDPOINTS.DATA_PORTFOLIO(smartWallet)
2818
+ ),
2819
+ this.httpClient.dataGet(DATA_ENDPOINTS.ONCHAIN_EARNINGS(smartWallet)).catch(() => null)
2820
+ ]);
2509
2821
  const convertedResponse = removeUnusedFields(response);
2822
+ const earningsData = earningsResult?.data || earningsResult;
2823
+ const currentEarningsByChain = earningsData?.current_earnings_by_chain ?? null;
2824
+ const portfolio = enrichPortfolioWithFees(
2825
+ convertedResponse,
2826
+ currentEarningsByChain
2827
+ );
2510
2828
  return {
2511
2829
  success: true,
2512
2830
  userAddress,
2513
- portfolio: convertedResponse
2831
+ portfolio
2514
2832
  };
2515
2833
  } catch (error) {
2516
- throw new Error(`Failed to get positions: ${error.message}`);
2834
+ throw new Error(`Failed to get portfolio: ${error.message}`);
2517
2835
  }
2518
2836
  }
2519
2837
  // ============================================================================
@@ -2812,6 +3130,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2812
3130
  /**
2813
3131
  * Get onchain earnings for a wallet
2814
3132
  *
3133
+ * Includes gross totals plus net-of-fee totals:
3134
+ * `totalEarningsByTokenWithFee = lifetime + unrealized + current × (1 - feeRate)`.
3135
+ * Lifetime and unrealized are never multiplied by the keep-rate.
3136
+ *
2815
3137
  * @param walletAddress - Smart wallet address
2816
3138
  * @returns Onchain earnings data with per-token breakdowns
2817
3139
  *
@@ -2819,6 +3141,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2819
3141
  * ```typescript
2820
3142
  * const earnings = await sdk.getOnchainEarnings("0x...");
2821
3143
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
3144
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
2822
3145
  * console.log("Total on Arbitrum:", earnings.data.totalEarningsByChain?.["42161"]);
2823
3146
  * ```
2824
3147
  */
@@ -2831,12 +3154,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2831
3154
  DATA_ENDPOINTS.ONCHAIN_EARNINGS(walletAddress)
2832
3155
  );
2833
3156
  const data = response.data || response;
3157
+ const withFee = enrichOnchainEarningsTotals(data);
2834
3158
  return {
2835
3159
  success: true,
2836
3160
  data: {
2837
3161
  walletAddress,
2838
3162
  totalEarningsByToken: data.total_earnings_by_token || {},
2839
3163
  totalEarningsByChain: data.total_earnings_by_chain || {},
3164
+ totalEarningsByTokenWithFee: withFee.totalEarningsByTokenWithFee,
3165
+ totalEarningsByChainWithFee: withFee.totalEarningsByChainWithFee,
2840
3166
  lastCheckTimestamp: data.last_check_timestamp,
2841
3167
  lastLogDate: data.last_log_date
2842
3168
  }
@@ -2849,7 +3175,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2849
3175
  }
2850
3176
  /**
2851
3177
  * Calculate/refresh onchain earnings for a wallet
2852
- * This triggers a recalculation of earnings on the backend
3178
+ * This triggers a recalculation of earnings on the backend.
3179
+ * Response shape matches `getOnchainEarnings` (includes `*WithFee` nets).
2853
3180
  *
2854
3181
  * @param walletAddress - Smart wallet address
2855
3182
  * @returns Updated onchain earnings data with per-token breakdowns
@@ -2858,7 +3185,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2858
3185
  * ```typescript
2859
3186
  * const earnings = await sdk.calculateOnchainEarnings("0x...");
2860
3187
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
2861
- * console.log("Per-chain total:", earnings.data.totalEarningsByChain);
3188
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
2862
3189
  * ```
2863
3190
  */
2864
3191
  async calculateOnchainEarnings(walletAddress) {
@@ -2871,12 +3198,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2871
3198
  {}
2872
3199
  );
2873
3200
  const data = response.data || response;
3201
+ const withFee = enrichOnchainEarningsTotals(data);
2874
3202
  return {
2875
3203
  success: true,
2876
3204
  data: {
2877
3205
  walletAddress,
2878
3206
  totalEarningsByToken: data.total_earnings_by_token || {},
2879
3207
  totalEarningsByChain: data.total_earnings_by_chain || {},
3208
+ totalEarningsByTokenWithFee: withFee.totalEarningsByTokenWithFee,
3209
+ totalEarningsByChainWithFee: withFee.totalEarningsByChainWithFee,
2880
3210
  lastCheckTimestamp: data.last_check_timestamp,
2881
3211
  lastLogDate: data.last_log_date
2882
3212
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zyfai/sdk",
3
- "version": "0.2.47",
3
+ "version": "0.2.48",
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",