@zyfai/sdk 0.2.47 → 0.2.49

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
@@ -322,7 +322,7 @@ Deploy a Safe smart wallet for a user. **Deployment is handled by the backend AP
322
322
 
323
323
  - User must be authenticated (automatically done via `connectAccount()`)
324
324
  - Backend handles all RPC calls, avoiding rate limiting
325
- - Protocol / asset patching is **not** done in `deploySafe` — it runs once on the account's **first** `depositFunds` call (see Deposit Funds below)
325
+ - Protocol / asset patching runs in `deploySafe` (all paths). `depositFunds` still patches on the account's **first** deposit if USDC `chains` are empty (see Deposit Funds below)
326
326
 
327
327
  ##### `addWalletToSdk(walletAddress: string): Promise<AddWalletToSdkResponse>`
328
328
 
@@ -380,7 +380,7 @@ console.log("User ID:", result.userId);
380
380
  - User must be authenticated (automatically done via `connectAccount()`)
381
381
  - The SDK proactively checks if the user already has an active session key and returns early without requiring any signature if one exists
382
382
  - The user record must have `smartWallet` and `chainId` set (predeployed assignment / first deposit)
383
- - Protocol selection is **not** touched by `createSessionKey` — it's set on the first `depositFunds` call
383
+ - Protocol selection is **not** touched by `createSessionKey` — it's set by `deploySafe` and on the first `depositFunds` call if USDC `chains` are still empty
384
384
  - **Deprecated**: prefer `depositFunds()` for partner onboarding; `createSessionKey` remains for legacy flows
385
385
  - When `alreadyActive` is `true`, `sessionKeyAddress` and `signature` are not available in the response
386
386
 
@@ -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
  }
@@ -836,8 +849,8 @@ declare class ZyfaiSDK {
836
849
  */
837
850
  updateMinSplits(minSplits: number): Promise<UpdateUserProfileResponse>;
838
851
  /**
839
- * Initialize user after Safe deployment
840
- * This method is automatically called after deploySafe to initialize user state
852
+ * Initialize earnings tracking for a smart wallet on the Data API.
853
+ * Called from `deploySafe` after a fresh deploy and for predeployed wallets.
841
854
  *
842
855
  * @param smartWallet - Safe smart wallet address
843
856
  * @param chainId - Target chain ID
@@ -979,7 +992,8 @@ declare class ZyfaiSDK {
979
992
  * asset/chain/strategy combo.
980
993
  * 4. Persist via `updateUserProfile` (writes `assetTypeSettings`).
981
994
  *
982
- * Called once from `depositFunds` on the account's first deposit.
995
+ * Called from `deploySafe` after every path, and from `depositFunds` on
996
+ * the account's first deposit (when USDC chains are still empty).
983
997
  *
984
998
  * @internal
985
999
  */
@@ -1175,19 +1189,23 @@ declare class ZyfaiSDK {
1175
1189
  */
1176
1190
  getPositions(userAddress: string, chainId?: SupportedChainId): Promise<PortfolioResponse>;
1177
1191
  /**
1178
- * Get all active positions and portfolio for a user
1192
+ * Get portfolio positions and balances for a user, enriched with
1193
+ * net-of-pending-fee fields (`balanceWithFee`, `underlyingAmountWithFee`).
1194
+ *
1195
+ * Pending fee is derived from onchain `current` earnings × fee rate.
1196
+ * Gross balances are unchanged. If earnings cannot be fetched, `*WithFee`
1197
+ * equals the gross value so the response shape stays stable.
1198
+ *
1199
+ * Note: portfolio balances are live; earnings used for the fee may be from
1200
+ * a snapshot, so net values can differ slightly from a fully live calc.
1179
1201
  *
1180
1202
  * @param userAddress - User's EOA address
1181
- * @param chainId - Optional: Filter by specific chain ID
1182
- * @returns User's positions across all protocols
1203
+ * @returns Portfolio with optional fee-adjusted balance fields
1183
1204
  *
1184
1205
  * @example
1185
1206
  * ```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);
1207
+ * const { portfolio } = await sdk.getPortfolio(userAddress);
1208
+ * console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
1191
1209
  * ```
1192
1210
  */
1193
1211
  getPortfolio(userAddress: string): Promise<PortfolioDetailedResponse>;
@@ -1310,6 +1328,10 @@ declare class ZyfaiSDK {
1310
1328
  /**
1311
1329
  * Get onchain earnings for a wallet
1312
1330
  *
1331
+ * Includes gross totals plus net-of-fee totals:
1332
+ * `totalEarningsByTokenWithFee = lifetime + unrealized + current × (1 - feeRate)`.
1333
+ * Lifetime and unrealized are never multiplied by the keep-rate.
1334
+ *
1313
1335
  * @param walletAddress - Smart wallet address
1314
1336
  * @returns Onchain earnings data with per-token breakdowns
1315
1337
  *
@@ -1317,13 +1339,15 @@ declare class ZyfaiSDK {
1317
1339
  * ```typescript
1318
1340
  * const earnings = await sdk.getOnchainEarnings("0x...");
1319
1341
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
1342
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
1320
1343
  * console.log("Total on Arbitrum:", earnings.data.totalEarningsByChain?.["42161"]);
1321
1344
  * ```
1322
1345
  */
1323
1346
  getOnchainEarnings(walletAddress: string): Promise<OnchainEarningsResponse>;
1324
1347
  /**
1325
1348
  * Calculate/refresh onchain earnings for a wallet
1326
- * This triggers a recalculation of earnings on the backend
1349
+ * This triggers a recalculation of earnings on the backend.
1350
+ * Response shape matches `getOnchainEarnings` (includes `*WithFee` nets).
1327
1351
  *
1328
1352
  * @param walletAddress - Smart wallet address
1329
1353
  * @returns Updated onchain earnings data with per-token breakdowns
@@ -1332,7 +1356,7 @@ declare class ZyfaiSDK {
1332
1356
  * ```typescript
1333
1357
  * const earnings = await sdk.calculateOnchainEarnings("0x...");
1334
1358
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
1335
- * console.log("Per-chain total:", earnings.data.totalEarningsByChain);
1359
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
1336
1360
  * ```
1337
1361
  */
1338
1362
  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
  }
@@ -836,8 +849,8 @@ declare class ZyfaiSDK {
836
849
  */
837
850
  updateMinSplits(minSplits: number): Promise<UpdateUserProfileResponse>;
838
851
  /**
839
- * Initialize user after Safe deployment
840
- * This method is automatically called after deploySafe to initialize user state
852
+ * Initialize earnings tracking for a smart wallet on the Data API.
853
+ * Called from `deploySafe` after a fresh deploy and for predeployed wallets.
841
854
  *
842
855
  * @param smartWallet - Safe smart wallet address
843
856
  * @param chainId - Target chain ID
@@ -979,7 +992,8 @@ declare class ZyfaiSDK {
979
992
  * asset/chain/strategy combo.
980
993
  * 4. Persist via `updateUserProfile` (writes `assetTypeSettings`).
981
994
  *
982
- * Called once from `depositFunds` on the account's first deposit.
995
+ * Called from `deploySafe` after every path, and from `depositFunds` on
996
+ * the account's first deposit (when USDC chains are still empty).
983
997
  *
984
998
  * @internal
985
999
  */
@@ -1175,19 +1189,23 @@ declare class ZyfaiSDK {
1175
1189
  */
1176
1190
  getPositions(userAddress: string, chainId?: SupportedChainId): Promise<PortfolioResponse>;
1177
1191
  /**
1178
- * Get all active positions and portfolio for a user
1192
+ * Get portfolio positions and balances for a user, enriched with
1193
+ * net-of-pending-fee fields (`balanceWithFee`, `underlyingAmountWithFee`).
1194
+ *
1195
+ * Pending fee is derived from onchain `current` earnings × fee rate.
1196
+ * Gross balances are unchanged. If earnings cannot be fetched, `*WithFee`
1197
+ * equals the gross value so the response shape stays stable.
1198
+ *
1199
+ * Note: portfolio balances are live; earnings used for the fee may be from
1200
+ * a snapshot, so net values can differ slightly from a fully live calc.
1179
1201
  *
1180
1202
  * @param userAddress - User's EOA address
1181
- * @param chainId - Optional: Filter by specific chain ID
1182
- * @returns User's positions across all protocols
1203
+ * @returns Portfolio with optional fee-adjusted balance fields
1183
1204
  *
1184
1205
  * @example
1185
1206
  * ```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);
1207
+ * const { portfolio } = await sdk.getPortfolio(userAddress);
1208
+ * console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
1191
1209
  * ```
1192
1210
  */
1193
1211
  getPortfolio(userAddress: string): Promise<PortfolioDetailedResponse>;
@@ -1310,6 +1328,10 @@ declare class ZyfaiSDK {
1310
1328
  /**
1311
1329
  * Get onchain earnings for a wallet
1312
1330
  *
1331
+ * Includes gross totals plus net-of-fee totals:
1332
+ * `totalEarningsByTokenWithFee = lifetime + unrealized + current × (1 - feeRate)`.
1333
+ * Lifetime and unrealized are never multiplied by the keep-rate.
1334
+ *
1313
1335
  * @param walletAddress - Smart wallet address
1314
1336
  * @returns Onchain earnings data with per-token breakdowns
1315
1337
  *
@@ -1317,13 +1339,15 @@ declare class ZyfaiSDK {
1317
1339
  * ```typescript
1318
1340
  * const earnings = await sdk.getOnchainEarnings("0x...");
1319
1341
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
1342
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
1320
1343
  * console.log("Total on Arbitrum:", earnings.data.totalEarningsByChain?.["42161"]);
1321
1344
  * ```
1322
1345
  */
1323
1346
  getOnchainEarnings(walletAddress: string): Promise<OnchainEarningsResponse>;
1324
1347
  /**
1325
1348
  * Calculate/refresh onchain earnings for a wallet
1326
- * This triggers a recalculation of earnings on the backend
1349
+ * This triggers a recalculation of earnings on the backend.
1350
+ * Response shape matches `getOnchainEarnings` (includes `*WithFee` nets).
1327
1351
  *
1328
1352
  * @param walletAddress - Smart wallet address
1329
1353
  * @returns Updated onchain earnings data with per-token breakdowns
@@ -1332,7 +1356,7 @@ declare class ZyfaiSDK {
1332
1356
  * ```typescript
1333
1357
  * const earnings = await sdk.calculateOnchainEarnings("0x...");
1334
1358
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
1335
- * console.log("Per-chain total:", earnings.data.totalEarningsByChain);
1359
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
1336
1360
  * ```
1337
1361
  */
1338
1362
  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 {
@@ -1401,8 +1706,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1401
1706
  }
1402
1707
  }
1403
1708
  /**
1404
- * Initialize user after Safe deployment
1405
- * This method is automatically called after deploySafe to initialize user state
1709
+ * Initialize earnings tracking for a smart wallet on the Data API.
1710
+ * Called from `deploySafe` after a fresh deploy and for predeployed wallets.
1406
1711
  *
1407
1712
  * @param smartWallet - Safe smart wallet address
1408
1713
  * @param chainId - Target chain ID
@@ -1728,6 +2033,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1728
2033
  userAddress,
1729
2034
  chainId
1730
2035
  );
2036
+ try {
2037
+ await this.initializeUser(predeployedAddress, chainId);
2038
+ } catch (initError) {
2039
+ console.warn(
2040
+ "Failed to initialize user after Safe deployment:",
2041
+ initError.message
2042
+ );
2043
+ }
1731
2044
  await this.updateUserProtocols(strategy);
1732
2045
  return {
1733
2046
  success: true,
@@ -1789,6 +2102,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1789
2102
  initError.message
1790
2103
  );
1791
2104
  }
2105
+ await this.updateUserProtocols(strategy);
1792
2106
  let sessionKeyCreated = false;
1793
2107
  if (createSessionKey) {
1794
2108
  try {
@@ -1978,7 +2292,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1978
2292
  * asset/chain/strategy combo.
1979
2293
  * 4. Persist via `updateUserProfile` (writes `assetTypeSettings`).
1980
2294
  *
1981
- * Called once from `depositFunds` on the account's first deposit.
2295
+ * Called from `deploySafe` after every path, and from `depositFunds` on
2296
+ * the account's first deposit (when USDC chains are still empty).
1982
2297
  *
1983
2298
  * @internal
1984
2299
  */
@@ -2506,19 +2821,23 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2506
2821
  }
2507
2822
  }
2508
2823
  /**
2509
- * Get all active positions and portfolio for a user
2824
+ * Get portfolio positions and balances for a user, enriched with
2825
+ * net-of-pending-fee fields (`balanceWithFee`, `underlyingAmountWithFee`).
2826
+ *
2827
+ * Pending fee is derived from onchain `current` earnings × fee rate.
2828
+ * Gross balances are unchanged. If earnings cannot be fetched, `*WithFee`
2829
+ * equals the gross value so the response shape stays stable.
2830
+ *
2831
+ * Note: portfolio balances are live; earnings used for the fee may be from
2832
+ * a snapshot, so net values can differ slightly from a fully live calc.
2510
2833
  *
2511
2834
  * @param userAddress - User's EOA address
2512
- * @param chainId - Optional: Filter by specific chain ID
2513
- * @returns User's positions across all protocols
2835
+ * @returns Portfolio with optional fee-adjusted balance fields
2514
2836
  *
2515
2837
  * @example
2516
2838
  * ```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);
2839
+ * const { portfolio } = await sdk.getPortfolio(userAddress);
2840
+ * console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
2522
2841
  * ```
2523
2842
  */
2524
2843
  async getPortfolio(userAddress) {
@@ -2534,18 +2853,27 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2534
2853
  portfolio: {}
2535
2854
  };
2536
2855
  }
2537
- console.log("Getting portfolio for", smartWalletInfo.smartWallet);
2538
- const response = await this.httpClient.get(
2539
- ENDPOINTS.DATA_PORTFOLIO(smartWalletInfo.smartWallet)
2540
- );
2856
+ const smartWallet = smartWalletInfo.smartWallet;
2857
+ const [response, earningsResult] = await Promise.all([
2858
+ this.httpClient.get(
2859
+ ENDPOINTS.DATA_PORTFOLIO(smartWallet)
2860
+ ),
2861
+ this.httpClient.dataGet(DATA_ENDPOINTS.ONCHAIN_EARNINGS(smartWallet)).catch(() => null)
2862
+ ]);
2541
2863
  const convertedResponse = removeUnusedFields(response);
2864
+ const earningsData = earningsResult?.data || earningsResult;
2865
+ const currentEarningsByChain = earningsData?.current_earnings_by_chain ?? null;
2866
+ const portfolio = enrichPortfolioWithFees(
2867
+ convertedResponse,
2868
+ currentEarningsByChain
2869
+ );
2542
2870
  return {
2543
2871
  success: true,
2544
2872
  userAddress,
2545
- portfolio: convertedResponse
2873
+ portfolio
2546
2874
  };
2547
2875
  } catch (error) {
2548
- throw new Error(`Failed to get positions: ${error.message}`);
2876
+ throw new Error(`Failed to get portfolio: ${error.message}`);
2549
2877
  }
2550
2878
  }
2551
2879
  // ============================================================================
@@ -2844,6 +3172,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2844
3172
  /**
2845
3173
  * Get onchain earnings for a wallet
2846
3174
  *
3175
+ * Includes gross totals plus net-of-fee totals:
3176
+ * `totalEarningsByTokenWithFee = lifetime + unrealized + current × (1 - feeRate)`.
3177
+ * Lifetime and unrealized are never multiplied by the keep-rate.
3178
+ *
2847
3179
  * @param walletAddress - Smart wallet address
2848
3180
  * @returns Onchain earnings data with per-token breakdowns
2849
3181
  *
@@ -2851,6 +3183,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2851
3183
  * ```typescript
2852
3184
  * const earnings = await sdk.getOnchainEarnings("0x...");
2853
3185
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
3186
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
2854
3187
  * console.log("Total on Arbitrum:", earnings.data.totalEarningsByChain?.["42161"]);
2855
3188
  * ```
2856
3189
  */
@@ -2863,12 +3196,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2863
3196
  DATA_ENDPOINTS.ONCHAIN_EARNINGS(walletAddress)
2864
3197
  );
2865
3198
  const data = response.data || response;
3199
+ const withFee = enrichOnchainEarningsTotals(data);
2866
3200
  return {
2867
3201
  success: true,
2868
3202
  data: {
2869
3203
  walletAddress,
2870
3204
  totalEarningsByToken: data.total_earnings_by_token || {},
2871
3205
  totalEarningsByChain: data.total_earnings_by_chain || {},
3206
+ totalEarningsByTokenWithFee: withFee.totalEarningsByTokenWithFee,
3207
+ totalEarningsByChainWithFee: withFee.totalEarningsByChainWithFee,
2872
3208
  lastCheckTimestamp: data.last_check_timestamp,
2873
3209
  lastLogDate: data.last_log_date
2874
3210
  }
@@ -2881,7 +3217,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2881
3217
  }
2882
3218
  /**
2883
3219
  * Calculate/refresh onchain earnings for a wallet
2884
- * This triggers a recalculation of earnings on the backend
3220
+ * This triggers a recalculation of earnings on the backend.
3221
+ * Response shape matches `getOnchainEarnings` (includes `*WithFee` nets).
2885
3222
  *
2886
3223
  * @param walletAddress - Smart wallet address
2887
3224
  * @returns Updated onchain earnings data with per-token breakdowns
@@ -2890,7 +3227,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2890
3227
  * ```typescript
2891
3228
  * const earnings = await sdk.calculateOnchainEarnings("0x...");
2892
3229
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
2893
- * console.log("Per-chain total:", earnings.data.totalEarningsByChain);
3230
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
2894
3231
  * ```
2895
3232
  */
2896
3233
  async calculateOnchainEarnings(walletAddress) {
@@ -2903,12 +3240,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2903
3240
  {}
2904
3241
  );
2905
3242
  const data = response.data || response;
3243
+ const withFee = enrichOnchainEarningsTotals(data);
2906
3244
  return {
2907
3245
  success: true,
2908
3246
  data: {
2909
3247
  walletAddress,
2910
3248
  totalEarningsByToken: data.total_earnings_by_token || {},
2911
3249
  totalEarningsByChain: data.total_earnings_by_chain || {},
3250
+ totalEarningsByTokenWithFee: withFee.totalEarningsByTokenWithFee,
3251
+ totalEarningsByChainWithFee: withFee.totalEarningsByChainWithFee,
2912
3252
  lastCheckTimestamp: data.last_check_timestamp,
2913
3253
  lastLogDate: data.last_log_date
2914
3254
  }
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 {
@@ -1369,8 +1674,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1369
1674
  }
1370
1675
  }
1371
1676
  /**
1372
- * Initialize user after Safe deployment
1373
- * This method is automatically called after deploySafe to initialize user state
1677
+ * Initialize earnings tracking for a smart wallet on the Data API.
1678
+ * Called from `deploySafe` after a fresh deploy and for predeployed wallets.
1374
1679
  *
1375
1680
  * @param smartWallet - Safe smart wallet address
1376
1681
  * @param chainId - Target chain ID
@@ -1696,6 +2001,14 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1696
2001
  userAddress,
1697
2002
  chainId
1698
2003
  );
2004
+ try {
2005
+ await this.initializeUser(predeployedAddress, chainId);
2006
+ } catch (initError) {
2007
+ console.warn(
2008
+ "Failed to initialize user after Safe deployment:",
2009
+ initError.message
2010
+ );
2011
+ }
1699
2012
  await this.updateUserProtocols(strategy);
1700
2013
  return {
1701
2014
  success: true,
@@ -1757,6 +2070,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1757
2070
  initError.message
1758
2071
  );
1759
2072
  }
2073
+ await this.updateUserProtocols(strategy);
1760
2074
  let sessionKeyCreated = false;
1761
2075
  if (createSessionKey) {
1762
2076
  try {
@@ -1946,7 +2260,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
1946
2260
  * asset/chain/strategy combo.
1947
2261
  * 4. Persist via `updateUserProfile` (writes `assetTypeSettings`).
1948
2262
  *
1949
- * Called once from `depositFunds` on the account's first deposit.
2263
+ * Called from `deploySafe` after every path, and from `depositFunds` on
2264
+ * the account's first deposit (when USDC chains are still empty).
1950
2265
  *
1951
2266
  * @internal
1952
2267
  */
@@ -2474,19 +2789,23 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2474
2789
  }
2475
2790
  }
2476
2791
  /**
2477
- * Get all active positions and portfolio for a user
2792
+ * Get portfolio positions and balances for a user, enriched with
2793
+ * net-of-pending-fee fields (`balanceWithFee`, `underlyingAmountWithFee`).
2794
+ *
2795
+ * Pending fee is derived from onchain `current` earnings × fee rate.
2796
+ * Gross balances are unchanged. If earnings cannot be fetched, `*WithFee`
2797
+ * equals the gross value so the response shape stays stable.
2798
+ *
2799
+ * Note: portfolio balances are live; earnings used for the fee may be from
2800
+ * a snapshot, so net values can differ slightly from a fully live calc.
2478
2801
  *
2479
2802
  * @param userAddress - User's EOA address
2480
- * @param chainId - Optional: Filter by specific chain ID
2481
- * @returns User's positions across all protocols
2803
+ * @returns Portfolio with optional fee-adjusted balance fields
2482
2804
  *
2483
2805
  * @example
2484
2806
  * ```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);
2807
+ * const { portfolio } = await sdk.getPortfolio(userAddress);
2808
+ * console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
2490
2809
  * ```
2491
2810
  */
2492
2811
  async getPortfolio(userAddress) {
@@ -2502,18 +2821,27 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2502
2821
  portfolio: {}
2503
2822
  };
2504
2823
  }
2505
- console.log("Getting portfolio for", smartWalletInfo.smartWallet);
2506
- const response = await this.httpClient.get(
2507
- ENDPOINTS.DATA_PORTFOLIO(smartWalletInfo.smartWallet)
2508
- );
2824
+ const smartWallet = smartWalletInfo.smartWallet;
2825
+ const [response, earningsResult] = await Promise.all([
2826
+ this.httpClient.get(
2827
+ ENDPOINTS.DATA_PORTFOLIO(smartWallet)
2828
+ ),
2829
+ this.httpClient.dataGet(DATA_ENDPOINTS.ONCHAIN_EARNINGS(smartWallet)).catch(() => null)
2830
+ ]);
2509
2831
  const convertedResponse = removeUnusedFields(response);
2832
+ const earningsData = earningsResult?.data || earningsResult;
2833
+ const currentEarningsByChain = earningsData?.current_earnings_by_chain ?? null;
2834
+ const portfolio = enrichPortfolioWithFees(
2835
+ convertedResponse,
2836
+ currentEarningsByChain
2837
+ );
2510
2838
  return {
2511
2839
  success: true,
2512
2840
  userAddress,
2513
- portfolio: convertedResponse
2841
+ portfolio
2514
2842
  };
2515
2843
  } catch (error) {
2516
- throw new Error(`Failed to get positions: ${error.message}`);
2844
+ throw new Error(`Failed to get portfolio: ${error.message}`);
2517
2845
  }
2518
2846
  }
2519
2847
  // ============================================================================
@@ -2812,6 +3140,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2812
3140
  /**
2813
3141
  * Get onchain earnings for a wallet
2814
3142
  *
3143
+ * Includes gross totals plus net-of-fee totals:
3144
+ * `totalEarningsByTokenWithFee = lifetime + unrealized + current × (1 - feeRate)`.
3145
+ * Lifetime and unrealized are never multiplied by the keep-rate.
3146
+ *
2815
3147
  * @param walletAddress - Smart wallet address
2816
3148
  * @returns Onchain earnings data with per-token breakdowns
2817
3149
  *
@@ -2819,6 +3151,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2819
3151
  * ```typescript
2820
3152
  * const earnings = await sdk.getOnchainEarnings("0x...");
2821
3153
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
3154
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
2822
3155
  * console.log("Total on Arbitrum:", earnings.data.totalEarningsByChain?.["42161"]);
2823
3156
  * ```
2824
3157
  */
@@ -2831,12 +3164,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2831
3164
  DATA_ENDPOINTS.ONCHAIN_EARNINGS(walletAddress)
2832
3165
  );
2833
3166
  const data = response.data || response;
3167
+ const withFee = enrichOnchainEarningsTotals(data);
2834
3168
  return {
2835
3169
  success: true,
2836
3170
  data: {
2837
3171
  walletAddress,
2838
3172
  totalEarningsByToken: data.total_earnings_by_token || {},
2839
3173
  totalEarningsByChain: data.total_earnings_by_chain || {},
3174
+ totalEarningsByTokenWithFee: withFee.totalEarningsByTokenWithFee,
3175
+ totalEarningsByChainWithFee: withFee.totalEarningsByChainWithFee,
2840
3176
  lastCheckTimestamp: data.last_check_timestamp,
2841
3177
  lastLogDate: data.last_log_date
2842
3178
  }
@@ -2849,7 +3185,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2849
3185
  }
2850
3186
  /**
2851
3187
  * Calculate/refresh onchain earnings for a wallet
2852
- * This triggers a recalculation of earnings on the backend
3188
+ * This triggers a recalculation of earnings on the backend.
3189
+ * Response shape matches `getOnchainEarnings` (includes `*WithFee` nets).
2853
3190
  *
2854
3191
  * @param walletAddress - Smart wallet address
2855
3192
  * @returns Updated onchain earnings data with per-token breakdowns
@@ -2858,7 +3195,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2858
3195
  * ```typescript
2859
3196
  * const earnings = await sdk.calculateOnchainEarnings("0x...");
2860
3197
  * console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
2861
- * console.log("Per-chain total:", earnings.data.totalEarningsByChain);
3198
+ * console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
2862
3199
  * ```
2863
3200
  */
2864
3201
  async calculateOnchainEarnings(walletAddress) {
@@ -2871,12 +3208,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
2871
3208
  {}
2872
3209
  );
2873
3210
  const data = response.data || response;
3211
+ const withFee = enrichOnchainEarningsTotals(data);
2874
3212
  return {
2875
3213
  success: true,
2876
3214
  data: {
2877
3215
  walletAddress,
2878
3216
  totalEarningsByToken: data.total_earnings_by_token || {},
2879
3217
  totalEarningsByChain: data.total_earnings_by_chain || {},
3218
+ totalEarningsByTokenWithFee: withFee.totalEarningsByTokenWithFee,
3219
+ totalEarningsByChainWithFee: withFee.totalEarningsByChainWithFee,
2880
3220
  lastCheckTimestamp: data.last_check_timestamp,
2881
3221
  lastLogDate: data.last_log_date
2882
3222
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zyfai/sdk",
3
- "version": "0.2.47",
3
+ "version": "0.2.49",
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",