@zyfai/sdk 0.2.45 → 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/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
  }
@@ -1149,19 +1162,23 @@ declare class ZyfaiSDK {
1149
1162
  */
1150
1163
  getPositions(userAddress: string, chainId?: SupportedChainId): Promise<PortfolioResponse>;
1151
1164
  /**
1152
- * Get all active positions and portfolio for a user
1165
+ * Get portfolio positions and balances for a user, enriched with
1166
+ * net-of-pending-fee fields (`balanceWithFee`, `underlyingAmountWithFee`).
1167
+ *
1168
+ * Pending fee is derived from onchain `current` earnings × fee rate.
1169
+ * Gross balances are unchanged. If earnings cannot be fetched, `*WithFee`
1170
+ * equals the gross value so the response shape stays stable.
1171
+ *
1172
+ * Note: portfolio balances are live; earnings used for the fee may be from
1173
+ * a snapshot, so net values can differ slightly from a fully live calc.
1153
1174
  *
1154
1175
  * @param userAddress - User's EOA address
1155
- * @param chainId - Optional: Filter by specific chain ID
1156
- * @returns User's positions across all protocols
1176
+ * @returns Portfolio with optional fee-adjusted balance fields
1157
1177
  *
1158
1178
  * @example
1159
1179
  * ```typescript
1160
- * // Get all positions across all chains
1161
- * const positions = await sdk.getPositions(userAddress);
1162
- *
1163
- * // Get positions on a specific chain
1164
- * const basePositions = await sdk.getPositions(userAddress, 8453);
1180
+ * const { portfolio } = await sdk.getPortfolio(userAddress);
1181
+ * console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
1165
1182
  * ```
1166
1183
  */
1167
1184
  getPortfolio(userAddress: string): Promise<PortfolioDetailedResponse>;
@@ -1284,6 +1301,10 @@ declare class ZyfaiSDK {
1284
1301
  /**
1285
1302
  * Get onchain earnings for a wallet
1286
1303
  *
1304
+ * Includes gross totals plus net-of-fee totals:
1305
+ * `totalEarningsByTokenWithFee = lifetime + unrealized + current × (1 - feeRate)`.
1306
+ * Lifetime and unrealized are never multiplied by the keep-rate.
1307
+ *
1287
1308
  * @param walletAddress - Smart wallet address
1288
1309
  * @returns Onchain earnings data with per-token breakdowns
1289
1310
  *
@@ -1291,13 +1312,15 @@ declare class ZyfaiSDK {
1291
1312
  * ```typescript
1292
1313
  * const earnings = await sdk.getOnchainEarnings("0x...");
1293
1314
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
1315
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
1294
1316
  * console.log("Total on Arbitrum:", earnings.data.totalEarningsByChain?.["42161"]);
1295
1317
  * ```
1296
1318
  */
1297
1319
  getOnchainEarnings(walletAddress: string): Promise<OnchainEarningsResponse>;
1298
1320
  /**
1299
1321
  * Calculate/refresh onchain earnings for a wallet
1300
- * This triggers a recalculation of earnings on the backend
1322
+ * This triggers a recalculation of earnings on the backend.
1323
+ * Response shape matches `getOnchainEarnings` (includes `*WithFee` nets).
1301
1324
  *
1302
1325
  * @param walletAddress - Smart wallet address
1303
1326
  * @returns Updated onchain earnings data with per-token breakdowns
@@ -1306,7 +1329,7 @@ declare class ZyfaiSDK {
1306
1329
  * ```typescript
1307
1330
  * const earnings = await sdk.calculateOnchainEarnings("0x...");
1308
1331
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
1309
- * console.log("Per-chain total:", earnings.data.totalEarningsByChain);
1332
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
1310
1333
  * ```
1311
1334
  */
1312
1335
  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
  }
@@ -1149,19 +1162,23 @@ declare class ZyfaiSDK {
1149
1162
  */
1150
1163
  getPositions(userAddress: string, chainId?: SupportedChainId): Promise<PortfolioResponse>;
1151
1164
  /**
1152
- * Get all active positions and portfolio for a user
1165
+ * Get portfolio positions and balances for a user, enriched with
1166
+ * net-of-pending-fee fields (`balanceWithFee`, `underlyingAmountWithFee`).
1167
+ *
1168
+ * Pending fee is derived from onchain `current` earnings × fee rate.
1169
+ * Gross balances are unchanged. If earnings cannot be fetched, `*WithFee`
1170
+ * equals the gross value so the response shape stays stable.
1171
+ *
1172
+ * Note: portfolio balances are live; earnings used for the fee may be from
1173
+ * a snapshot, so net values can differ slightly from a fully live calc.
1153
1174
  *
1154
1175
  * @param userAddress - User's EOA address
1155
- * @param chainId - Optional: Filter by specific chain ID
1156
- * @returns User's positions across all protocols
1176
+ * @returns Portfolio with optional fee-adjusted balance fields
1157
1177
  *
1158
1178
  * @example
1159
1179
  * ```typescript
1160
- * // Get all positions across all chains
1161
- * const positions = await sdk.getPositions(userAddress);
1162
- *
1163
- * // Get positions on a specific chain
1164
- * const basePositions = await sdk.getPositions(userAddress, 8453);
1180
+ * const { portfolio } = await sdk.getPortfolio(userAddress);
1181
+ * console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
1165
1182
  * ```
1166
1183
  */
1167
1184
  getPortfolio(userAddress: string): Promise<PortfolioDetailedResponse>;
@@ -1284,6 +1301,10 @@ declare class ZyfaiSDK {
1284
1301
  /**
1285
1302
  * Get onchain earnings for a wallet
1286
1303
  *
1304
+ * Includes gross totals plus net-of-fee totals:
1305
+ * `totalEarningsByTokenWithFee = lifetime + unrealized + current × (1 - feeRate)`.
1306
+ * Lifetime and unrealized are never multiplied by the keep-rate.
1307
+ *
1287
1308
  * @param walletAddress - Smart wallet address
1288
1309
  * @returns Onchain earnings data with per-token breakdowns
1289
1310
  *
@@ -1291,13 +1312,15 @@ declare class ZyfaiSDK {
1291
1312
  * ```typescript
1292
1313
  * const earnings = await sdk.getOnchainEarnings("0x...");
1293
1314
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
1315
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
1294
1316
  * console.log("Total on Arbitrum:", earnings.data.totalEarningsByChain?.["42161"]);
1295
1317
  * ```
1296
1318
  */
1297
1319
  getOnchainEarnings(walletAddress: string): Promise<OnchainEarningsResponse>;
1298
1320
  /**
1299
1321
  * Calculate/refresh onchain earnings for a wallet
1300
- * This triggers a recalculation of earnings on the backend
1322
+ * This triggers a recalculation of earnings on the backend.
1323
+ * Response shape matches `getOnchainEarnings` (includes `*WithFee` nets).
1301
1324
  *
1302
1325
  * @param walletAddress - Smart wallet address
1303
1326
  * @returns Updated onchain earnings data with per-token breakdowns
@@ -1306,7 +1329,7 @@ declare class ZyfaiSDK {
1306
1329
  * ```typescript
1307
1330
  * const earnings = await sdk.calculateOnchainEarnings("0x...");
1308
1331
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
1309
- * console.log("Per-chain total:", earnings.data.totalEarningsByChain);
1332
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
1310
1333
  * ```
1311
1334
  */
1312
1335
  calculateOnchainEarnings(walletAddress: string): Promise<OnchainEarningsResponse>;
package/dist/index.js CHANGED
@@ -512,6 +512,7 @@ var VAULT_ABI = [
512
512
  var VAULT_ADDRESS = "0xD580071c47d4a667858B5FafAb85BC9C609beC5D";
513
513
 
514
514
  // src/config/constants.ts
515
+ var ZYFI_FEE_RATE = 0.1;
515
516
  var MIN_PORTFOLIO_BALANCE = {
516
517
  1: {
517
518
  USDC: 100n * 10n ** 6n,
@@ -1044,6 +1045,310 @@ var hasMatchingPool = (data, chains, asset) => {
1044
1045
  return false;
1045
1046
  };
1046
1047
 
1048
+ // src/utils/zyfi-fees.ts
1049
+ var CHAIN_NAME_TO_ID = {
1050
+ ethereum: "1",
1051
+ "ethereum mainnet": "1",
1052
+ mainnet: "1",
1053
+ base: "8453",
1054
+ arbitrum: "42161",
1055
+ "arbitrum one": "42161"
1056
+ };
1057
+ function symbolToAssetType(symbol) {
1058
+ const upper = symbol.trim().toUpperCase();
1059
+ if (upper === "USDC") return "usdc";
1060
+ if (upper === "WETH" || upper === "ETH") return "eth";
1061
+ if (upper === "EURC") return "eurc";
1062
+ if (upper === "CBBTC") return "cbbtc";
1063
+ if (upper === "CBETH") return "cbeth";
1064
+ return symbol.trim().toLowerCase();
1065
+ }
1066
+ function assetTypeToSymbol(assetType) {
1067
+ const lower = assetType.trim().toLowerCase();
1068
+ if (lower === "usdc") return "USDC";
1069
+ if (lower === "eth") return "WETH";
1070
+ if (lower === "eurc") return "EURC";
1071
+ if (lower === "cbbtc") return "CBBTC";
1072
+ if (lower === "cbeth") return "CBETH";
1073
+ return assetType.trim().toUpperCase();
1074
+ }
1075
+ function chainNameToId(chain) {
1076
+ if (!chain) return void 0;
1077
+ const trimmed = chain.trim();
1078
+ if (/^\d+$/.test(trimmed)) return trimmed;
1079
+ return CHAIN_NAME_TO_ID[trimmed.toLowerCase()];
1080
+ }
1081
+ function parseHumanAmount(value) {
1082
+ if (typeof value === "number") {
1083
+ return Number.isFinite(value) ? value : 0;
1084
+ }
1085
+ const parsed = Number.parseFloat(String(value ?? "0"));
1086
+ return Number.isFinite(parsed) ? parsed : 0;
1087
+ }
1088
+ function humanAmountToRaw(human, decimals) {
1089
+ if (!Number.isFinite(human) || human <= 0 || decimals < 0) {
1090
+ return 0n;
1091
+ }
1092
+ const fixed = human.toFixed(decimals);
1093
+ const [whole, frac = ""] = fixed.split(".");
1094
+ const wholePart = BigInt(whole);
1095
+ const fracPart = BigInt(frac.padEnd(decimals, "0").slice(0, decimals) || "0");
1096
+ return wholePart * 10n ** BigInt(decimals) + fracPart;
1097
+ }
1098
+ function formatHumanAmount(value) {
1099
+ if (!Number.isFinite(value) || value === 0) return "0";
1100
+ const fixed = value.toFixed(18);
1101
+ return fixed.replace(/\.?0+$/, "") || "0";
1102
+ }
1103
+ function computePendingFees(currentEarningsByChain) {
1104
+ const byToken = {};
1105
+ const byChain = {};
1106
+ const byChainByToken = {};
1107
+ let total = 0;
1108
+ if (!currentEarningsByChain) {
1109
+ return { byToken, byChain, byChainByToken, total };
1110
+ }
1111
+ Object.entries(currentEarningsByChain).forEach(([chainId, chainEarnings]) => {
1112
+ const feeByToken = {};
1113
+ let chainFee = 0;
1114
+ Object.entries(chainEarnings || {}).forEach(([tokenSymbol, tokenAmount]) => {
1115
+ const numericValue = parseHumanAmount(tokenAmount);
1116
+ const tokenFee = numericValue > 0 ? numericValue * ZYFI_FEE_RATE : 0;
1117
+ feeByToken[tokenSymbol] = tokenFee;
1118
+ chainFee += tokenFee;
1119
+ byToken[tokenSymbol] = (byToken[tokenSymbol] ?? 0) + tokenFee;
1120
+ });
1121
+ byChainByToken[chainId] = feeByToken;
1122
+ byChain[chainId] = chainFee;
1123
+ total += chainFee;
1124
+ });
1125
+ return { byToken, byChain, byChainByToken, total };
1126
+ }
1127
+ function feeForAssetType(feesByToken, assetType) {
1128
+ const symbol = assetTypeToSymbol(assetType);
1129
+ if (feesByToken[symbol] !== void 0) return feesByToken[symbol] ?? 0;
1130
+ if (assetType.toLowerCase() === "eth") {
1131
+ return feesByToken["ETH"] ?? feesByToken["WETH"] ?? 0;
1132
+ }
1133
+ return feesByToken[assetType.toUpperCase()] ?? 0;
1134
+ }
1135
+ function feeForChainAsset(byChainByToken, chainId, assetType) {
1136
+ const chainFees = byChainByToken[chainId] || {};
1137
+ return feeForAssetType(chainFees, assetType);
1138
+ }
1139
+ function applyFeeToHexBalance(balanceHex, feeHuman, decimals) {
1140
+ let balance;
1141
+ try {
1142
+ balance = BigInt(balanceHex || "0x0");
1143
+ } catch {
1144
+ balance = 0n;
1145
+ }
1146
+ const feeRaw = humanAmountToRaw(feeHuman, decimals);
1147
+ const net = balance > feeRaw ? balance - feeRaw : 0n;
1148
+ return `0x${net.toString(16)}`;
1149
+ }
1150
+ function applyFeeToDecimalWei(amount, feeHuman, decimals) {
1151
+ let balance;
1152
+ try {
1153
+ balance = BigInt(amount || "0");
1154
+ } catch {
1155
+ balance = 0n;
1156
+ }
1157
+ const feeRaw = humanAmountToRaw(feeHuman, decimals);
1158
+ const net = balance > feeRaw ? balance - feeRaw : 0n;
1159
+ return net.toString();
1160
+ }
1161
+ function enrichAssetBalance(entry, feeHuman) {
1162
+ const balanceWithFee = applyFeeToHexBalance(
1163
+ entry.balance,
1164
+ feeHuman,
1165
+ entry.decimals
1166
+ );
1167
+ return {
1168
+ ...entry,
1169
+ balanceWithFee
1170
+ };
1171
+ }
1172
+ function resolvePositionSymbol(position) {
1173
+ if (position.token_symbol) return position.token_symbol;
1174
+ if (position.assetType) return assetTypeToSymbol(position.assetType);
1175
+ return void 0;
1176
+ }
1177
+ function resolvePositionDecimals(position) {
1178
+ if (typeof position.decimals === "number") return position.decimals;
1179
+ const asset = position.assetType || symbolToAssetType(position.token_symbol || "");
1180
+ if (asset === "usdc" || asset === "eurc") return 6;
1181
+ if (asset === "cbbtc") return 8;
1182
+ return 18;
1183
+ }
1184
+ function enrichPositions(positions, byChainByToken) {
1185
+ const groups = /* @__PURE__ */ new Map();
1186
+ positions.forEach((position, index) => {
1187
+ const chainId = chainNameToId(position.chain || "");
1188
+ const symbol = resolvePositionSymbol(position);
1189
+ if (!chainId || !symbol) {
1190
+ return;
1191
+ }
1192
+ const key = `${chainId}:${symbol.toUpperCase()}`;
1193
+ const list = groups.get(key) || [];
1194
+ list.push(index);
1195
+ groups.set(key, list);
1196
+ });
1197
+ const feeShareByIndex = /* @__PURE__ */ new Map();
1198
+ groups.forEach((indices, key) => {
1199
+ const [chainId, symbol] = key.split(":");
1200
+ const chainFees = byChainByToken[chainId] || {};
1201
+ let totalFee = chainFees[symbol] ?? (symbol === "WETH" ? chainFees["ETH"] : void 0) ?? (symbol === "ETH" ? chainFees["WETH"] : void 0) ?? 0;
1202
+ if (totalFee <= 0) {
1203
+ indices.forEach((i) => feeShareByIndex.set(i, 0));
1204
+ return;
1205
+ }
1206
+ let totalUnderlying = 0n;
1207
+ const underlyings = indices.map((i) => {
1208
+ try {
1209
+ return BigInt(positions[i].underlyingAmount || "0");
1210
+ } catch {
1211
+ return 0n;
1212
+ }
1213
+ });
1214
+ underlyings.forEach((u) => {
1215
+ totalUnderlying += u;
1216
+ });
1217
+ if (totalUnderlying === 0n) {
1218
+ const share = totalFee / indices.length;
1219
+ indices.forEach((i) => feeShareByIndex.set(i, share));
1220
+ return;
1221
+ }
1222
+ indices.forEach((i, idx) => {
1223
+ const share = totalFee * Number(underlyings[idx]) / Number(totalUnderlying);
1224
+ feeShareByIndex.set(i, share);
1225
+ });
1226
+ });
1227
+ return positions.map((position, index) => {
1228
+ const underlying = position.underlyingAmount;
1229
+ if (underlying === void 0) {
1230
+ return { ...position };
1231
+ }
1232
+ const feeShare = feeShareByIndex.get(index) ?? 0;
1233
+ const decimals = resolvePositionDecimals(position);
1234
+ return {
1235
+ ...position,
1236
+ underlyingAmountWithFee: applyFeeToDecimalWei(
1237
+ underlying,
1238
+ feeShare,
1239
+ decimals
1240
+ )
1241
+ };
1242
+ });
1243
+ }
1244
+ function enrichPortfolioWithFees(portfolio, currentEarningsByChain) {
1245
+ const { byToken, byChainByToken } = computePendingFees(currentEarningsByChain);
1246
+ const portfolioByAssetType = portfolio.portfolioByAssetType ? Object.fromEntries(
1247
+ Object.entries(portfolio.portfolioByAssetType).map(
1248
+ ([assetType, entry]) => [
1249
+ assetType,
1250
+ enrichAssetBalance(entry, feeForAssetType(byToken, assetType))
1251
+ ]
1252
+ )
1253
+ ) : void 0;
1254
+ const portfolioByChain = portfolio.portfolioByChain ? Object.fromEntries(
1255
+ Object.entries(portfolio.portfolioByChain).map(
1256
+ ([chainId, assets]) => [
1257
+ chainId,
1258
+ Object.fromEntries(
1259
+ Object.entries(assets).map(([assetType, entry]) => [
1260
+ assetType,
1261
+ enrichAssetBalance(
1262
+ entry,
1263
+ feeForChainAsset(byChainByToken, chainId, assetType)
1264
+ )
1265
+ ])
1266
+ )
1267
+ ]
1268
+ )
1269
+ ) : void 0;
1270
+ const positions = portfolio.positions ? enrichPositions(portfolio.positions, byChainByToken) : void 0;
1271
+ return {
1272
+ ...portfolio,
1273
+ ...portfolioByAssetType ? { portfolioByAssetType } : {},
1274
+ ...portfolioByChain ? { portfolioByChain } : {},
1275
+ ...positions ? { positions } : {}
1276
+ };
1277
+ }
1278
+ function sumCurrentByToken(currentByChain) {
1279
+ const totals = {};
1280
+ if (!currentByChain) return totals;
1281
+ Object.values(currentByChain).forEach((chainEarnings) => {
1282
+ Object.entries(chainEarnings || {}).forEach(([symbol, amount]) => {
1283
+ totals[symbol] = (totals[symbol] ?? 0) + parseHumanAmount(amount);
1284
+ });
1285
+ });
1286
+ return totals;
1287
+ }
1288
+ function enrichOnchainEarningsTotals(apiData) {
1289
+ const lifetimeByToken = apiData.lifetime_earnings_by_token || {};
1290
+ const lifetimeByChain = apiData.lifetime_earnings_by_chain || {};
1291
+ const currentByChain = apiData.current_earnings_by_chain || {};
1292
+ const unrealizedByChain = apiData.unrealized_earnings_by_chain || apiData.unrealized_earnings || {};
1293
+ const currentByToken = apiData.current_earnings_by_token && Object.keys(apiData.current_earnings_by_token).length > 0 ? Object.fromEntries(
1294
+ Object.entries(apiData.current_earnings_by_token).map(([k, v]) => [
1295
+ k,
1296
+ parseHumanAmount(v)
1297
+ ])
1298
+ ) : sumCurrentByToken(currentByChain);
1299
+ const unrealizedByToken = apiData.unrealized_earnings_by_token && Object.keys(apiData.unrealized_earnings_by_token).length > 0 ? Object.fromEntries(
1300
+ Object.entries(apiData.unrealized_earnings_by_token).map(([k, v]) => [
1301
+ k,
1302
+ parseHumanAmount(v)
1303
+ ])
1304
+ ) : sumCurrentByToken(unrealizedByChain);
1305
+ const keepRate = 1 - ZYFI_FEE_RATE;
1306
+ const tokenKeys = /* @__PURE__ */ new Set([
1307
+ ...Object.keys(lifetimeByToken),
1308
+ ...Object.keys(unrealizedByToken),
1309
+ ...Object.keys(currentByToken)
1310
+ ]);
1311
+ const totalEarningsByTokenWithFee = {};
1312
+ tokenKeys.forEach((symbol) => {
1313
+ const lifetime = parseHumanAmount(lifetimeByToken[symbol]);
1314
+ const unrealized = unrealizedByToken[symbol] ?? 0;
1315
+ const current = currentByToken[symbol] ?? 0;
1316
+ totalEarningsByTokenWithFee[symbol] = formatHumanAmount(
1317
+ lifetime + unrealized + current * keepRate
1318
+ );
1319
+ });
1320
+ const chainKeys = /* @__PURE__ */ new Set([
1321
+ ...Object.keys(lifetimeByChain),
1322
+ ...Object.keys(unrealizedByChain),
1323
+ ...Object.keys(currentByChain)
1324
+ ]);
1325
+ const totalEarningsByChainWithFee = {};
1326
+ chainKeys.forEach((chainId) => {
1327
+ const lifetimeTokens = lifetimeByChain[chainId] || {};
1328
+ const unrealizedTokens = unrealizedByChain[chainId] || {};
1329
+ const currentTokens = currentByChain[chainId] || {};
1330
+ const symbols = /* @__PURE__ */ new Set([
1331
+ ...Object.keys(lifetimeTokens),
1332
+ ...Object.keys(unrealizedTokens),
1333
+ ...Object.keys(currentTokens)
1334
+ ]);
1335
+ const chainMap = {};
1336
+ symbols.forEach((symbol) => {
1337
+ const lifetime = parseHumanAmount(lifetimeTokens[symbol]);
1338
+ const unrealized = parseHumanAmount(unrealizedTokens[symbol]);
1339
+ const current = parseHumanAmount(currentTokens[symbol]);
1340
+ chainMap[symbol] = formatHumanAmount(
1341
+ lifetime + unrealized + current * keepRate
1342
+ );
1343
+ });
1344
+ totalEarningsByChainWithFee[chainId] = chainMap;
1345
+ });
1346
+ return {
1347
+ totalEarningsByTokenWithFee,
1348
+ totalEarningsByChainWithFee
1349
+ };
1350
+ }
1351
+
1047
1352
  // src/core/ZyfaiSDK.ts
1048
1353
  var import_siwe = require("siwe");
1049
1354
  var _ZyfaiSDK = class _ZyfaiSDK {
@@ -2454,19 +2759,23 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2454
2759
  }
2455
2760
  }
2456
2761
  /**
2457
- * Get all active positions and portfolio for a user
2762
+ * Get portfolio positions and balances for a user, enriched with
2763
+ * net-of-pending-fee fields (`balanceWithFee`, `underlyingAmountWithFee`).
2764
+ *
2765
+ * Pending fee is derived from onchain `current` earnings × fee rate.
2766
+ * Gross balances are unchanged. If earnings cannot be fetched, `*WithFee`
2767
+ * equals the gross value so the response shape stays stable.
2768
+ *
2769
+ * Note: portfolio balances are live; earnings used for the fee may be from
2770
+ * a snapshot, so net values can differ slightly from a fully live calc.
2458
2771
  *
2459
2772
  * @param userAddress - User's EOA address
2460
- * @param chainId - Optional: Filter by specific chain ID
2461
- * @returns User's positions across all protocols
2773
+ * @returns Portfolio with optional fee-adjusted balance fields
2462
2774
  *
2463
2775
  * @example
2464
2776
  * ```typescript
2465
- * // Get all positions across all chains
2466
- * const positions = await sdk.getPositions(userAddress);
2467
- *
2468
- * // Get positions on a specific chain
2469
- * const basePositions = await sdk.getPositions(userAddress, 8453);
2777
+ * const { portfolio } = await sdk.getPortfolio(userAddress);
2778
+ * console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
2470
2779
  * ```
2471
2780
  */
2472
2781
  async getPortfolio(userAddress) {
@@ -2482,18 +2791,27 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2482
2791
  portfolio: {}
2483
2792
  };
2484
2793
  }
2485
- console.log("Getting portfolio for", smartWalletInfo.smartWallet);
2486
- const response = await this.httpClient.get(
2487
- ENDPOINTS.DATA_PORTFOLIO(smartWalletInfo.smartWallet)
2488
- );
2794
+ const smartWallet = smartWalletInfo.smartWallet;
2795
+ const [response, earningsResult] = await Promise.all([
2796
+ this.httpClient.get(
2797
+ ENDPOINTS.DATA_PORTFOLIO(smartWallet)
2798
+ ),
2799
+ this.httpClient.dataGet(DATA_ENDPOINTS.ONCHAIN_EARNINGS(smartWallet)).catch(() => null)
2800
+ ]);
2489
2801
  const convertedResponse = removeUnusedFields(response);
2802
+ const earningsData = earningsResult?.data || earningsResult;
2803
+ const currentEarningsByChain = earningsData?.current_earnings_by_chain ?? null;
2804
+ const portfolio = enrichPortfolioWithFees(
2805
+ convertedResponse,
2806
+ currentEarningsByChain
2807
+ );
2490
2808
  return {
2491
2809
  success: true,
2492
2810
  userAddress,
2493
- portfolio: convertedResponse
2811
+ portfolio
2494
2812
  };
2495
2813
  } catch (error) {
2496
- throw new Error(`Failed to get positions: ${error.message}`);
2814
+ throw new Error(`Failed to get portfolio: ${error.message}`);
2497
2815
  }
2498
2816
  }
2499
2817
  // ============================================================================
@@ -2792,6 +3110,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2792
3110
  /**
2793
3111
  * Get onchain earnings for a wallet
2794
3112
  *
3113
+ * Includes gross totals plus net-of-fee totals:
3114
+ * `totalEarningsByTokenWithFee = lifetime + unrealized + current × (1 - feeRate)`.
3115
+ * Lifetime and unrealized are never multiplied by the keep-rate.
3116
+ *
2795
3117
  * @param walletAddress - Smart wallet address
2796
3118
  * @returns Onchain earnings data with per-token breakdowns
2797
3119
  *
@@ -2799,6 +3121,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2799
3121
  * ```typescript
2800
3122
  * const earnings = await sdk.getOnchainEarnings("0x...");
2801
3123
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
3124
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
2802
3125
  * console.log("Total on Arbitrum:", earnings.data.totalEarningsByChain?.["42161"]);
2803
3126
  * ```
2804
3127
  */
@@ -2811,12 +3134,16 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2811
3134
  DATA_ENDPOINTS.ONCHAIN_EARNINGS(walletAddress)
2812
3135
  );
2813
3136
  const data = response.data || response;
3137
+ console.log(JSON.stringify(data, null, 2));
3138
+ const withFee = enrichOnchainEarningsTotals(data);
2814
3139
  return {
2815
3140
  success: true,
2816
3141
  data: {
2817
3142
  walletAddress,
2818
3143
  totalEarningsByToken: data.total_earnings_by_token || {},
2819
3144
  totalEarningsByChain: data.total_earnings_by_chain || {},
3145
+ totalEarningsByTokenWithFee: withFee.totalEarningsByTokenWithFee,
3146
+ totalEarningsByChainWithFee: withFee.totalEarningsByChainWithFee,
2820
3147
  lastCheckTimestamp: data.last_check_timestamp,
2821
3148
  lastLogDate: data.last_log_date
2822
3149
  }
@@ -2829,7 +3156,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2829
3156
  }
2830
3157
  /**
2831
3158
  * Calculate/refresh onchain earnings for a wallet
2832
- * This triggers a recalculation of earnings on the backend
3159
+ * This triggers a recalculation of earnings on the backend.
3160
+ * Response shape matches `getOnchainEarnings` (includes `*WithFee` nets).
2833
3161
  *
2834
3162
  * @param walletAddress - Smart wallet address
2835
3163
  * @returns Updated onchain earnings data with per-token breakdowns
@@ -2838,7 +3166,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2838
3166
  * ```typescript
2839
3167
  * const earnings = await sdk.calculateOnchainEarnings("0x...");
2840
3168
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
2841
- * console.log("Per-chain total:", earnings.data.totalEarningsByChain);
3169
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
2842
3170
  * ```
2843
3171
  */
2844
3172
  async calculateOnchainEarnings(walletAddress) {
@@ -2851,12 +3179,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2851
3179
  {}
2852
3180
  );
2853
3181
  const data = response.data || response;
3182
+ const withFee = enrichOnchainEarningsTotals(data);
2854
3183
  return {
2855
3184
  success: true,
2856
3185
  data: {
2857
3186
  walletAddress,
2858
3187
  totalEarningsByToken: data.total_earnings_by_token || {},
2859
3188
  totalEarningsByChain: data.total_earnings_by_chain || {},
3189
+ totalEarningsByTokenWithFee: withFee.totalEarningsByTokenWithFee,
3190
+ totalEarningsByChainWithFee: withFee.totalEarningsByChainWithFee,
2860
3191
  lastCheckTimestamp: data.last_check_timestamp,
2861
3192
  lastLogDate: data.last_log_date
2862
3193
  }
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 {
@@ -2422,19 +2727,23 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2422
2727
  }
2423
2728
  }
2424
2729
  /**
2425
- * 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.
2426
2739
  *
2427
2740
  * @param userAddress - User's EOA address
2428
- * @param chainId - Optional: Filter by specific chain ID
2429
- * @returns User's positions across all protocols
2741
+ * @returns Portfolio with optional fee-adjusted balance fields
2430
2742
  *
2431
2743
  * @example
2432
2744
  * ```typescript
2433
- * // Get all positions across all chains
2434
- * const positions = await sdk.getPositions(userAddress);
2435
- *
2436
- * // Get positions on a specific chain
2437
- * const basePositions = await sdk.getPositions(userAddress, 8453);
2745
+ * const { portfolio } = await sdk.getPortfolio(userAddress);
2746
+ * console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
2438
2747
  * ```
2439
2748
  */
2440
2749
  async getPortfolio(userAddress) {
@@ -2450,18 +2759,27 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2450
2759
  portfolio: {}
2451
2760
  };
2452
2761
  }
2453
- console.log("Getting portfolio for", smartWalletInfo.smartWallet);
2454
- const response = await this.httpClient.get(
2455
- ENDPOINTS.DATA_PORTFOLIO(smartWalletInfo.smartWallet)
2456
- );
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
+ ]);
2457
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
+ );
2458
2776
  return {
2459
2777
  success: true,
2460
2778
  userAddress,
2461
- portfolio: convertedResponse
2779
+ portfolio
2462
2780
  };
2463
2781
  } catch (error) {
2464
- throw new Error(`Failed to get positions: ${error.message}`);
2782
+ throw new Error(`Failed to get portfolio: ${error.message}`);
2465
2783
  }
2466
2784
  }
2467
2785
  // ============================================================================
@@ -2760,6 +3078,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2760
3078
  /**
2761
3079
  * Get onchain earnings for a wallet
2762
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
+ *
2763
3085
  * @param walletAddress - Smart wallet address
2764
3086
  * @returns Onchain earnings data with per-token breakdowns
2765
3087
  *
@@ -2767,6 +3089,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2767
3089
  * ```typescript
2768
3090
  * const earnings = await sdk.getOnchainEarnings("0x...");
2769
3091
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
3092
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
2770
3093
  * console.log("Total on Arbitrum:", earnings.data.totalEarningsByChain?.["42161"]);
2771
3094
  * ```
2772
3095
  */
@@ -2779,12 +3102,16 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2779
3102
  DATA_ENDPOINTS.ONCHAIN_EARNINGS(walletAddress)
2780
3103
  );
2781
3104
  const data = response.data || response;
3105
+ console.log(JSON.stringify(data, null, 2));
3106
+ const withFee = enrichOnchainEarningsTotals(data);
2782
3107
  return {
2783
3108
  success: true,
2784
3109
  data: {
2785
3110
  walletAddress,
2786
3111
  totalEarningsByToken: data.total_earnings_by_token || {},
2787
3112
  totalEarningsByChain: data.total_earnings_by_chain || {},
3113
+ totalEarningsByTokenWithFee: withFee.totalEarningsByTokenWithFee,
3114
+ totalEarningsByChainWithFee: withFee.totalEarningsByChainWithFee,
2788
3115
  lastCheckTimestamp: data.last_check_timestamp,
2789
3116
  lastLogDate: data.last_log_date
2790
3117
  }
@@ -2797,7 +3124,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2797
3124
  }
2798
3125
  /**
2799
3126
  * Calculate/refresh onchain earnings for a wallet
2800
- * 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).
2801
3129
  *
2802
3130
  * @param walletAddress - Smart wallet address
2803
3131
  * @returns Updated onchain earnings data with per-token breakdowns
@@ -2806,7 +3134,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2806
3134
  * ```typescript
2807
3135
  * const earnings = await sdk.calculateOnchainEarnings("0x...");
2808
3136
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
2809
- * console.log("Per-chain total:", earnings.data.totalEarningsByChain);
3137
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
2810
3138
  * ```
2811
3139
  */
2812
3140
  async calculateOnchainEarnings(walletAddress) {
@@ -2819,12 +3147,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2819
3147
  {}
2820
3148
  );
2821
3149
  const data = response.data || response;
3150
+ const withFee = enrichOnchainEarningsTotals(data);
2822
3151
  return {
2823
3152
  success: true,
2824
3153
  data: {
2825
3154
  walletAddress,
2826
3155
  totalEarningsByToken: data.total_earnings_by_token || {},
2827
3156
  totalEarningsByChain: data.total_earnings_by_chain || {},
3157
+ totalEarningsByTokenWithFee: withFee.totalEarningsByTokenWithFee,
3158
+ totalEarningsByChainWithFee: withFee.totalEarningsByChainWithFee,
2828
3159
  lastCheckTimestamp: data.last_check_timestamp,
2829
3160
  lastLogDate: data.last_log_date
2830
3161
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zyfai/sdk",
3
- "version": "0.2.45",
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",