@zyfai/sdk 0.2.44 → 0.2.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -3
- package/dist/index.d.mts +47 -15
- package/dist/index.d.ts +47 -15
- package/dist/index.js +371 -31
- package/dist/index.mjs +371 -31
- package/package.json +1 -1
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 {
|
|
@@ -1136,7 +1441,6 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
1136
1441
|
}
|
|
1137
1442
|
this.httpClient.setAuthToken(authToken);
|
|
1138
1443
|
this.authenticatedUserId = loginResponse.userId || null;
|
|
1139
|
-
console.log("this.authenticatedUserId", loginResponse);
|
|
1140
1444
|
this.hasActiveSessionKey = loginResponse.hasActiveSessionKey || false;
|
|
1141
1445
|
this.isPredeployed = loginResponse.predeployed || false;
|
|
1142
1446
|
this.connectedSmartWallet = loginResponse.smartWallet || null;
|
|
@@ -2094,12 +2398,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2094
2398
|
* Deposit funds from EOA to Safe smart wallet
|
|
2095
2399
|
* Transfers tokens from the connected wallet to the user's Safe and logs the deposit
|
|
2096
2400
|
*
|
|
2097
|
-
* Token is
|
|
2098
|
-
* - Ethereum Mainnet (1), Base (8453), Arbitrum (42161)
|
|
2401
|
+
* Token address is selected from `asset` for the given chain:
|
|
2402
|
+
* - Ethereum Mainnet (1), Base (8453), Arbitrum (42161): USDC or WETH
|
|
2403
|
+
* - Ethereum Mainnet (1), Base (8453): EURC
|
|
2099
2404
|
*
|
|
2100
2405
|
* On the account's first deposit (USDC profile has no chains yet), patches
|
|
2101
2406
|
* protocol selection for USDC, WETH, and EURC across all supported chains
|
|
2102
2407
|
* (EURC on Mainnet/Base only) before the transfer and log_deposit.
|
|
2408
|
+
* Pass `strategy` to select protocols for that first-deposit setup
|
|
2409
|
+
* (same role as the former `deploySafe` strategy argument).
|
|
2103
2410
|
*
|
|
2104
2411
|
* Minimum portfolio balance enforced (Safe balance + deposit amount),
|
|
2105
2412
|
* configured per-chain in `MIN_PORTFOLIO_BALANCE`:
|
|
@@ -2112,8 +2419,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2112
2419
|
* @param userAddress - User's address (owner of the Safe)
|
|
2113
2420
|
* @param chainId - Target chain ID
|
|
2114
2421
|
* @param amount - Amount in least decimal units (e.g., "100000000" for 100 USDC with 6 decimals)
|
|
2115
|
-
* @param asset -
|
|
2422
|
+
* @param asset - Asset symbol: "USDC", "WETH", or "EURC".
|
|
2116
2423
|
* EURC is supported on Ethereum Mainnet and Base only.
|
|
2424
|
+
* @param strategy - Optional strategy for first-deposit protocol patching:
|
|
2425
|
+
* "conservative" (default) or "aggressive"
|
|
2117
2426
|
* @returns Deposit response with transaction hash
|
|
2118
2427
|
*
|
|
2119
2428
|
* @example
|
|
@@ -2122,11 +2431,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2122
2431
|
* const result = await sdk.depositFunds(
|
|
2123
2432
|
* "0xUser...",
|
|
2124
2433
|
* 8453,
|
|
2125
|
-
* "10000000000"
|
|
2434
|
+
* "10000000000",
|
|
2435
|
+
* "USDC"
|
|
2126
2436
|
* );
|
|
2437
|
+
*
|
|
2438
|
+
* // First deposit with aggressive strategy
|
|
2439
|
+
* await sdk.depositFunds(userAddress, 8453, "10000000000", "USDC", "aggressive");
|
|
2127
2440
|
* ```
|
|
2128
2441
|
*/
|
|
2129
|
-
async depositFunds(userAddress, chainId, amount, asset) {
|
|
2442
|
+
async depositFunds(userAddress, chainId, amount, asset, strategy) {
|
|
2130
2443
|
try {
|
|
2131
2444
|
if (!userAddress) {
|
|
2132
2445
|
throw new Error("User address is required");
|
|
@@ -2137,7 +2450,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2137
2450
|
if (!amount || isNaN(Number(amount)) || Number(amount) <= 0) {
|
|
2138
2451
|
throw new Error("Valid amount is required");
|
|
2139
2452
|
}
|
|
2140
|
-
|
|
2453
|
+
if (!asset) {
|
|
2454
|
+
throw new Error("Asset is required (USDC, WETH, or EURC)");
|
|
2455
|
+
}
|
|
2456
|
+
if (strategy !== void 0 && !isValidPublicStrategy(strategy)) {
|
|
2457
|
+
throw new Error(
|
|
2458
|
+
`Invalid strategy: ${strategy}. Must be "conservative" or "aggressive".`
|
|
2459
|
+
);
|
|
2460
|
+
}
|
|
2461
|
+
const assetSymbol = asset.toUpperCase();
|
|
2141
2462
|
const assetConfig = ASSET_CONFIGS[assetSymbol];
|
|
2142
2463
|
if (!assetConfig) {
|
|
2143
2464
|
throw new Error(
|
|
@@ -2161,7 +2482,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2161
2482
|
try {
|
|
2162
2483
|
const usdcDetails = await this.getUserDetails("USDC");
|
|
2163
2484
|
if ((usdcDetails.chains?.length ?? 0) === 0) {
|
|
2164
|
-
await this.updateUserProtocols();
|
|
2485
|
+
await this.updateUserProtocols(strategy);
|
|
2165
2486
|
}
|
|
2166
2487
|
} catch (protocolError) {
|
|
2167
2488
|
console.warn(
|
|
@@ -2201,12 +2522,6 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2201
2522
|
hash: txHash
|
|
2202
2523
|
});
|
|
2203
2524
|
try {
|
|
2204
|
-
console.log("Logging deposit to backend", {
|
|
2205
|
-
chainId,
|
|
2206
|
-
transaction: txHash,
|
|
2207
|
-
token,
|
|
2208
|
-
amount
|
|
2209
|
-
});
|
|
2210
2525
|
await this.httpClient.post(ENDPOINTS.LOG_DEPOSIT, {
|
|
2211
2526
|
chainId,
|
|
2212
2527
|
transaction: txHash,
|
|
@@ -2346,7 +2661,6 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2346
2661
|
tokenSymbol
|
|
2347
2662
|
});
|
|
2348
2663
|
} else {
|
|
2349
|
-
console.log("Full withdrawal", tokenSymbol);
|
|
2350
2664
|
response = await this.httpClient.get(ENDPOINTS.USER_WITHDRAW, {
|
|
2351
2665
|
params: { chainId, tokenSymbol }
|
|
2352
2666
|
});
|
|
@@ -2445,19 +2759,23 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2445
2759
|
}
|
|
2446
2760
|
}
|
|
2447
2761
|
/**
|
|
2448
|
-
* Get
|
|
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.
|
|
2449
2771
|
*
|
|
2450
2772
|
* @param userAddress - User's EOA address
|
|
2451
|
-
* @
|
|
2452
|
-
* @returns User's positions across all protocols
|
|
2773
|
+
* @returns Portfolio with optional fee-adjusted balance fields
|
|
2453
2774
|
*
|
|
2454
2775
|
* @example
|
|
2455
2776
|
* ```typescript
|
|
2456
|
-
*
|
|
2457
|
-
*
|
|
2458
|
-
*
|
|
2459
|
-
* // Get positions on a specific chain
|
|
2460
|
-
* const basePositions = await sdk.getPositions(userAddress, 8453);
|
|
2777
|
+
* const { portfolio } = await sdk.getPortfolio(userAddress);
|
|
2778
|
+
* console.log(portfolio.portfolioByAssetType?.usdc?.balanceWithFee);
|
|
2461
2779
|
* ```
|
|
2462
2780
|
*/
|
|
2463
2781
|
async getPortfolio(userAddress) {
|
|
@@ -2473,18 +2791,27 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2473
2791
|
portfolio: {}
|
|
2474
2792
|
};
|
|
2475
2793
|
}
|
|
2476
|
-
|
|
2477
|
-
const response = await
|
|
2478
|
-
|
|
2479
|
-
|
|
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
|
+
]);
|
|
2480
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
|
+
);
|
|
2481
2808
|
return {
|
|
2482
2809
|
success: true,
|
|
2483
2810
|
userAddress,
|
|
2484
|
-
portfolio
|
|
2811
|
+
portfolio
|
|
2485
2812
|
};
|
|
2486
2813
|
} catch (error) {
|
|
2487
|
-
throw new Error(`Failed to get
|
|
2814
|
+
throw new Error(`Failed to get portfolio: ${error.message}`);
|
|
2488
2815
|
}
|
|
2489
2816
|
}
|
|
2490
2817
|
// ============================================================================
|
|
@@ -2783,6 +3110,10 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2783
3110
|
/**
|
|
2784
3111
|
* Get onchain earnings for a wallet
|
|
2785
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
|
+
*
|
|
2786
3117
|
* @param walletAddress - Smart wallet address
|
|
2787
3118
|
* @returns Onchain earnings data with per-token breakdowns
|
|
2788
3119
|
*
|
|
@@ -2790,6 +3121,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2790
3121
|
* ```typescript
|
|
2791
3122
|
* const earnings = await sdk.getOnchainEarnings("0x...");
|
|
2792
3123
|
* console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
|
|
3124
|
+
* console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
|
|
2793
3125
|
* console.log("Total on Arbitrum:", earnings.data.totalEarningsByChain?.["42161"]);
|
|
2794
3126
|
* ```
|
|
2795
3127
|
*/
|
|
@@ -2802,12 +3134,16 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2802
3134
|
DATA_ENDPOINTS.ONCHAIN_EARNINGS(walletAddress)
|
|
2803
3135
|
);
|
|
2804
3136
|
const data = response.data || response;
|
|
3137
|
+
console.log(JSON.stringify(data, null, 2));
|
|
3138
|
+
const withFee = enrichOnchainEarningsTotals(data);
|
|
2805
3139
|
return {
|
|
2806
3140
|
success: true,
|
|
2807
3141
|
data: {
|
|
2808
3142
|
walletAddress,
|
|
2809
3143
|
totalEarningsByToken: data.total_earnings_by_token || {},
|
|
2810
3144
|
totalEarningsByChain: data.total_earnings_by_chain || {},
|
|
3145
|
+
totalEarningsByTokenWithFee: withFee.totalEarningsByTokenWithFee,
|
|
3146
|
+
totalEarningsByChainWithFee: withFee.totalEarningsByChainWithFee,
|
|
2811
3147
|
lastCheckTimestamp: data.last_check_timestamp,
|
|
2812
3148
|
lastLogDate: data.last_log_date
|
|
2813
3149
|
}
|
|
@@ -2820,7 +3156,8 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2820
3156
|
}
|
|
2821
3157
|
/**
|
|
2822
3158
|
* Calculate/refresh onchain earnings for a wallet
|
|
2823
|
-
* 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).
|
|
2824
3161
|
*
|
|
2825
3162
|
* @param walletAddress - Smart wallet address
|
|
2826
3163
|
* @returns Updated onchain earnings data with per-token breakdowns
|
|
@@ -2829,7 +3166,7 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2829
3166
|
* ```typescript
|
|
2830
3167
|
* const earnings = await sdk.calculateOnchainEarnings("0x...");
|
|
2831
3168
|
* console.log("Total USDC:", earnings.data.totalEarningsByToken["USDC"]);
|
|
2832
|
-
* console.log("
|
|
3169
|
+
* console.log("Net USDC:", earnings.data.totalEarningsByTokenWithFee["USDC"]);
|
|
2833
3170
|
* ```
|
|
2834
3171
|
*/
|
|
2835
3172
|
async calculateOnchainEarnings(walletAddress) {
|
|
@@ -2842,12 +3179,15 @@ var _ZyfaiSDK = class _ZyfaiSDK {
|
|
|
2842
3179
|
{}
|
|
2843
3180
|
);
|
|
2844
3181
|
const data = response.data || response;
|
|
3182
|
+
const withFee = enrichOnchainEarningsTotals(data);
|
|
2845
3183
|
return {
|
|
2846
3184
|
success: true,
|
|
2847
3185
|
data: {
|
|
2848
3186
|
walletAddress,
|
|
2849
3187
|
totalEarningsByToken: data.total_earnings_by_token || {},
|
|
2850
3188
|
totalEarningsByChain: data.total_earnings_by_chain || {},
|
|
3189
|
+
totalEarningsByTokenWithFee: withFee.totalEarningsByTokenWithFee,
|
|
3190
|
+
totalEarningsByChainWithFee: withFee.totalEarningsByChainWithFee,
|
|
2851
3191
|
lastCheckTimestamp: data.last_check_timestamp,
|
|
2852
3192
|
lastLogDate: data.last_log_date
|
|
2853
3193
|
}
|