-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
704 lines (618 loc) · 22.6 KB
/
server.ts
File metadata and controls
704 lines (618 loc) · 22.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
import express from "express";
import { ethers } from "ethers";
const app = express();
const port = 3001;
// Enable CORS and JSON parsing
app.use(express.json());
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.header("Access-Control-Allow-Headers", "Content-Type");
next();
});
const TEZOS_WALLETS = [
{
name: "Main Wallet",
address: "tz2TYtyJR9tKkHw9r8sUecPaiDxm43pB9QWs",
},
{
name: "Temple Wallet",
address: "tz1PG1VKdDAyHC9zdLzjDTFAb5Qop36MZUDE",
},
];
const ETHERLINK_ADDRESS = "0xe1F0D4Cd256F8467EF6DD0a4EA2E6f2B767A1d96";
const ETHERLINK_RPC = "https://node.mainnet.etherlink.com";
const DEFAULT_CURRENCY = "GBP";
const SUPPORTED_CURRENCIES = ["USD", "GBP", "PLN"];
// ERC-20 ABI for balanceOf
const ERC20_ABI = [
"function balanceOf(address owner) view returns (uint256)",
"function decimals() view returns (uint8)",
"function symbol() view returns (string)",
];
// Etherlink ERC-20 token configs (address -> config)
type EtherlinkTokenConfig = {
label: string;
priceId: string;
decimals: number;
category: "wallet" | "staked" | "defi" | "superlend" | "rewards";
};
// Apple Farm uses Merkl for reward distribution
// Merkl distributes rewards through their distribution contracts
// Since rewards are "all claimed", they should be in the user's wallet as tokens
// We'll query Merkl API and also check for reward token balances
const MERKL_API_BASE = "https://api.merkl.xyz";
const ETHERLINK_TOKEN_CONFIGS: Record<string, EtherlinkTokenConfig> = {
// Add common ERC-20 tokens on Etherlink here
// Example: "0x...": { label: "USDT", priceId: "tether", decimals: 6, category: "defi" },
// Apple Farm applXTZ will be added dynamically if address is configured
};
// Superlend contract addresses
// See: https://docs.superlend.xyz/superlend-markets/etherlink-market
const SUPERLEND_POOL_ADDRESS = "0x3bD16D195786fb2F509f2E2D7F69920262EF114D";
const SUPERLEND_POOL_ADDRESSES_PROVIDER = "0x5ccF60c7E10547c5389E9cBFf543E5D0Db9F4feC";
// Superlend ABI snippets for querying user positions
// Note: Aave V3 uses getReserveData to get reserve configuration, then we query aToken directly
const SUPERLEND_POOL_ABI = [
"function getUserAccountData(address user) view returns (uint256 totalCollateralBase, uint256 totalDebtBase, uint256 availableBorrowsBase, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor)",
"function getReserveData(address asset) view returns (tuple(uint256 configuration, uint128 liquidityIndex, uint128 currentLiquidityRate, uint128 variableBorrowIndex, uint128 currentVariableBorrowRate, uint128 currentStableBorrowRate, uint40 lastUpdateTimestamp, uint16 id, address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress, address interestRateStrategyAddress, uint128 accruedToTreasury, uint128 unbacked, uint128 isolationModeTotalDebt))",
"function getReservesList() view returns (address[] memory)",
];
// aToken ABI - we'll query aToken balance directly
const ATOKEN_ABI = [
"function balanceOf(address account) view returns (uint256)",
"function UNDERLYING_ASSET_ADDRESS() view returns (address)",
"function decimals() view returns (uint8)",
];
// Debt token ABI
const DEBT_TOKEN_ABI = [
"function balanceOf(address account) view returns (uint256)",
"function scaledBalanceOf(address user) view returns (uint256)",
];
// Mapping from token symbol to CoinGecko price ID
// This helps automatically map tokens to their price IDs
const TOKEN_SYMBOL_TO_PRICE_ID: Record<string, string> = {
XTZ: "tezos",
WXTZ: "tezos", // Wrapped XTZ uses Tezos price
USDC: "usd-coin",
USDT: "tether",
WETH: "weth",
ETH: "ethereum",
DAI: "dai",
WBTC: "wrapped-bitcoin",
BTC: "bitcoin",
// Add more as needed
};
// Helper function to map token symbol to CoinGecko price ID
function getPriceIdFromSymbol(symbol: string): string {
const normalized = symbol.toUpperCase();
return TOKEN_SYMBOL_TO_PRICE_ID[normalized] || normalized.toLowerCase();
}
// Helper function to fetch Apple Farm rewards via Merkl API
// Merkl v4 API: https://api.merkl.xyz/v4/users/{address}/rewards?chainId={chainId}
// Returns: { claimed, amount, pending, proofs, breakdowns }
// Since rewards are vested and claimed via transactions, we use the 'claimed' field
async function fetchAppleFarmRewards(
provider: ethers.JsonRpcProvider,
userAddress: string
): Promise<TokenPosition[]> {
const positions: TokenPosition[] = [];
try {
// Etherlink chain ID
const chainId = 42793;
// Query Merkl v4 API for user rewards
// Docs: https://docs.merkl.xyz/integrate-merkl/app
const merklApiUrl = `${MERKL_API_BASE}/v4/users/${userAddress.toLowerCase()}/rewards?chainId=${chainId}`;
try {
const response = await fetch(merklApiUrl, {
headers: {
'Accept': 'application/json',
},
});
if (response.ok) {
const data: any = await response.json();
// Merkl API returns: [{ chain: {...}, rewards: [...] }]
// Each reward has: amount, claimed, pending, token: { symbol, decimals, price }, breakdowns
if (data && Array.isArray(data)) {
for (const chainData of data) {
if (chainData.rewards && Array.isArray(chainData.rewards)) {
for (const reward of chainData.rewards) {
// Filter for Apple Farm rewards - check token symbol (applstXTZ, applXTZ, etc.)
const tokenSymbol = reward.token?.symbol || "";
const isAppleFarm =
tokenSymbol.toLowerCase().includes("appl") ||
tokenSymbol.toLowerCase().includes("apple");
if (isAppleFarm && reward.claimed) {
// Get claimed amount (already claimed rewards)
const claimedAmount = reward.claimed;
if (claimedAmount && Number(claimedAmount) > 0) {
const decimals = reward.token?.decimals || 6;
const symbol = tokenSymbol || "applstXTZ";
// Convert from smallest unit to human-readable
const amount = Number(claimedAmount) / Math.pow(10, decimals);
if (amount > 0) {
// Check if we already have this token (sum if multiple campaigns)
const existingIndex = positions.findIndex(
(p) => p.token === symbol && p.chain === "etherlink"
);
if (existingIndex >= 0) {
// Sum amounts if same token appears multiple times
positions[existingIndex].amount += amount;
} else {
positions.push({
chain: "etherlink",
category: "rewards",
token: symbol,
amount,
priceId: "tezos", // Apple Farm tokens use Tezos price
walletName: "MetaMask",
});
}
}
}
}
}
}
}
}
} else {
console.warn(`Merkl API returned status ${response.status} for ${merklApiUrl}`);
}
} catch (apiErr) {
console.error("Error fetching from Merkl API:", apiErr);
}
} catch (err) {
console.error("Failed to fetch Apple Farm rewards:", err);
}
return positions;
}
// Helper function to fetch Superlend positions (deposits and borrows)
async function fetchSuperlendPositions(
provider: ethers.JsonRpcProvider,
userAddress: string
): Promise<TokenPosition[]> {
const positions: TokenPosition[] = [];
if (!SUPERLEND_POOL_ADDRESS) {
return positions;
}
try {
const poolContract = new ethers.Contract(
SUPERLEND_POOL_ADDRESS,
SUPERLEND_POOL_ABI,
provider
);
// Get list of all reserves/assets in the pool
const reservesList: string[] = await poolContract.getReservesList();
// For each reserve, check user positions (deposits and borrows)
for (const reserveAddress of reservesList) {
try {
// Get reserve data to find aToken and debt token addresses
const reserveData = await poolContract.getReserveData(reserveAddress);
const aTokenAddress = reserveData.aTokenAddress;
const stableDebtTokenAddress = reserveData.stableDebtTokenAddress;
const variableDebtTokenAddress = reserveData.variableDebtTokenAddress;
// Query aToken balance directly
let aTokenBalance = 0n;
try {
const aTokenContract = new ethers.Contract(
aTokenAddress,
ATOKEN_ABI,
provider
);
aTokenBalance = await aTokenContract.balanceOf(userAddress);
} catch (err) {
console.warn(`Failed to get aToken balance for ${reserveAddress}:`, err);
}
// Query stable debt token balance
let stableDebt = 0n;
try {
const stableDebtContract = new ethers.Contract(
stableDebtTokenAddress,
DEBT_TOKEN_ABI,
provider
);
stableDebt = await stableDebtContract.balanceOf(userAddress);
} catch (err) {
console.warn(`Failed to get stable debt for ${reserveAddress}:`, err);
}
// Query variable debt token balance
let variableDebt = 0n;
try {
const variableDebtContract = new ethers.Contract(
variableDebtTokenAddress,
DEBT_TOKEN_ABI,
provider
);
variableDebt = await variableDebtContract.balanceOf(userAddress);
} catch (err) {
console.warn(`Failed to get variable debt for ${reserveAddress}:`, err);
}
// Skip if user has no position in this reserve
if (
(aTokenBalance === 0n || aTokenBalance === BigInt(0)) &&
(stableDebt === 0n || stableDebt === BigInt(0)) &&
(variableDebt === 0n || variableDebt === BigInt(0))
) {
continue;
}
// Fetch token metadata from the reserve address (it's the underlying ERC20)
let tokenSymbol = "UNKNOWN";
let tokenDecimals = 18;
try {
const tokenContract = new ethers.Contract(
reserveAddress,
ERC20_ABI,
provider
);
tokenSymbol = await tokenContract.symbol();
tokenDecimals = await tokenContract.decimals();
} catch (err) {
console.warn(
`Could not fetch token metadata for ${reserveAddress}, using defaults:`,
err
);
}
const priceId = getPriceIdFromSymbol(tokenSymbol);
// Handle deposits (aToken balance represents deposited amount)
if (aTokenBalance > 0n) {
const depositAmount = Number(
ethers.formatUnits(aTokenBalance, tokenDecimals)
);
if (depositAmount > 0) {
positions.push({
chain: "etherlink",
category: "superlend",
token: tokenSymbol,
amount: depositAmount,
priceId,
walletName: "MetaMask",
});
}
}
// Handle stable debt borrows
if (stableDebt > 0n) {
const borrowAmount = Number(
ethers.formatUnits(stableDebt, tokenDecimals)
);
if (borrowAmount > 0) {
positions.push({
chain: "etherlink",
category: "superlend",
token: tokenSymbol,
amount: borrowAmount,
priceId,
walletName: "MetaMask",
isBorrow: true,
});
}
}
// Handle variable debt borrows
if (variableDebt > 0n) {
const borrowAmount = Number(
ethers.formatUnits(variableDebt, tokenDecimals)
);
if (borrowAmount > 0) {
positions.push({
chain: "etherlink",
category: "superlend",
token: tokenSymbol,
amount: borrowAmount,
priceId,
walletName: "MetaMask",
isBorrow: true,
});
}
}
} catch (err) {
// Skip this reserve if query fails
console.error(
`Failed to fetch Superlend data for reserve ${reserveAddress}:`,
err
);
}
}
} catch (err) {
console.error("Failed to fetch Superlend positions:", err);
}
return positions;
}
type TezosTokenBalance = {
token: {
contract: { address: string; alias?: string };
tokenId?: string;
metadata?: {
symbol?: string;
name?: string;
decimals?: string;
};
};
balance: string;
};
type TokenConfig = {
label: string;
priceId: string;
category: PortfolioItem["category"];
decimalsOverride?: number;
};
type TokenPosition = {
chain: PortfolioItem["chain"];
category: "wallet" | "staked" | "defi" | "superlend" | "rewards";
token: string;
amount: number;
priceId: string;
walletName?: string;
isBorrow?: boolean; // Flag to indicate if this is a borrow position
};
const TEZOS_TOKEN_CONFIGS: Record<string, TokenConfig> = {
"KT1XRPEPXbZK25r3Htzp2o1x7xdMMmfocKNW:0": {
label: "uUSD",
priceId: "youves-uusd",
category: "defi",
},
"KT1Xobej4mc6XgEjDoJoHtTKgbD1ELMvcQuL:0": {
label: "YOU",
priceId: "youves-you-governance",
category: "defi",
},
"KT1KXKhkxDezoa8G3WvPtsrgNTs5ZQwhpYZN:0": {
label: "stXTZ",
priceId: "tezos",
category: "defi",
// stXTZ has 6 decimals, but TzKT metadata does not currently expose it
decimalsOverride: 6,
},
};
type PortfolioItem = {
chain: "tezos" | "etherlink";
category: "wallet" | "staked" | "defi" | "superlend" | "rewards";
token: string;
amount: number;
price: number;
value: number;
walletName?: string;
};
type PortfolioResponse = {
currency: string;
totalValue: number;
items: PortfolioItem[];
};
app.get("/api/portfolio", async (req, res) => {
try {
// Get currency from query parameter, default to USD
const requestedCurrency = req.query.currency
? String(req.query.currency).toUpperCase().trim()
: DEFAULT_CURRENCY;
const currency = SUPPORTED_CURRENCIES.includes(requestedCurrency as any)
? requestedCurrency
: DEFAULT_CURRENCY;
console.log(`Portfolio request - requested: ${requestedCurrency}, using: ${currency}`);
const items: PortfolioItem[] = [];
const priceIds = new Set<string>(["tezos"]);
const tokenPositionsMap = new Map<string, TokenPosition>();
// Fetch Tezos XTZ and token balances for each Tezos wallet and aggregate
for (const wallet of TEZOS_WALLETS) {
const tzktAccountUrl = `https://api.tzkt.io/v1/accounts/${wallet.address}`;
const tzktResp = await fetch(tzktAccountUrl);
if (!tzktResp.ok) {
throw new Error(`Failed to fetch Tezos account data for ${wallet.name}`);
}
const tzktData: any = await tzktResp.json();
const balance = tzktData.balance ?? 0;
const stakedBalance = tzktData.stakedBalance ?? 0;
const spendableXTZ = Math.max(balance - stakedBalance, 0) / 1_000_000;
const stakedXTZ = Math.max(stakedBalance, 0) / 1_000_000;
// Create per-wallet XTZ entries (spendable + staked)
if (spendableXTZ > 0) {
items.push({
chain: "tezos",
category: "wallet",
token: "XTZ",
amount: spendableXTZ,
price: 0, // filled after price fetch
value: 0,
walletName: wallet.name,
});
}
if (stakedXTZ > 0) {
items.push({
chain: "tezos",
category: "staked",
token: "XTZ",
amount: stakedXTZ,
price: 0, // filled after price fetch
value: 0,
walletName: wallet.name,
});
}
// Fetch token balances from TzKT (FA1.2 / FA2)
const tokenBalancesResp = await fetch(
`https://api.tzkt.io/v1/tokens/balances?account=${wallet.address}&balance.gt=0&select=token,balance`
);
if (!tokenBalancesResp.ok) {
throw new Error(`Failed to fetch Tezos token balances for ${wallet.name}`);
}
const tokenBalances: TezosTokenBalance[] =
await tokenBalancesResp.json();
for (const entry of tokenBalances) {
const tokenId = entry.token.tokenId ?? "0";
const key = `${entry.token.contract.address}:${tokenId}`;
const config = TEZOS_TOKEN_CONFIGS[key];
if (!config) continue;
const decimalsRaw = entry.token.metadata?.decimals ?? "0";
const decimals =
config.decimalsOverride !== undefined
? config.decimalsOverride
: Number(decimalsRaw);
const divisor = Math.pow(10, Number.isFinite(decimals) ? decimals : 0);
const amount = Number(entry.balance) / (divisor || 1);
if (amount <= 0) continue;
priceIds.add(config.priceId);
const positionKey = `tezos:${wallet.name}:${config.category}:${config.label}:${config.priceId}`;
const existing = tokenPositionsMap.get(positionKey);
if (existing) {
existing.amount += amount;
} else {
tokenPositionsMap.set(positionKey, {
chain: "tezos",
category: config.category,
token: config.label,
amount,
priceId: config.priceId,
walletName: wallet.name,
});
}
}
}
const tokenPositions = Array.from(tokenPositionsMap.values());
// Etherlink: fetch native balance and ERC-20 tokens via public RPC
const etherlinkTokenPositions: TokenPosition[] = [];
try {
const provider = new ethers.JsonRpcProvider(ETHERLINK_RPC);
const ethBalanceWei = await provider.getBalance(ETHERLINK_ADDRESS);
const ethBalance = Number(ethers.formatEther(ethBalanceWei));
if (ethBalance > 0) {
// Etherlink native gas token is XTZ on L2, so we reuse Tezos price
// (priceIds already includes "tezos")
items.push({
chain: "etherlink",
category: "wallet",
token: "XTZ (Etherlink)",
amount: ethBalance,
price: 0, // filled after price fetch
value: 0,
walletName: "MetaMask",
});
}
// Fetch ERC-20 token balances
for (const [tokenAddress, config] of Object.entries(
ETHERLINK_TOKEN_CONFIGS
)) {
try {
const tokenContract = new ethers.Contract(
tokenAddress,
ERC20_ABI,
provider
);
const balanceWei = await tokenContract.balanceOf(ETHERLINK_ADDRESS);
const balance = Number(
ethers.formatUnits(balanceWei, config.decimals)
);
if (balance > 0) {
priceIds.add(config.priceId);
etherlinkTokenPositions.push({
chain: "etherlink",
category: config.category,
token: config.label,
amount: balance,
priceId: config.priceId,
walletName: "MetaMask",
});
}
} catch (err) {
console.error(
`Failed to fetch balance for ${config.label} (${tokenAddress}):`,
err
);
}
}
// Fetch Superlend positions (deposits/borrows)
try {
const superlendPositions = await fetchSuperlendPositions(
provider,
ETHERLINK_ADDRESS
);
for (const position of superlendPositions) {
priceIds.add(position.priceId);
etherlinkTokenPositions.push(position);
}
} catch (err) {
console.error("Error fetching Superlend positions:", err);
}
// Fetch Apple Farm rewards (applXTZ)
try {
const appleFarmPositions = await fetchAppleFarmRewards(
provider,
ETHERLINK_ADDRESS
);
for (const position of appleFarmPositions) {
priceIds.add(position.priceId);
etherlinkTokenPositions.push(position);
}
} catch (err) {
console.error("Error fetching Apple Farm rewards:", err);
}
} catch (err) {
console.error("Failed to fetch Etherlink data", err);
if (err instanceof Error) {
console.error("Etherlink error details:", err.message, err.stack);
}
}
// Fetch all prices in one batch (Tezos + Etherlink tokens)
const priceResp = await fetch(
`https://api.coingecko.com/api/v3/simple/price?ids=${[
...priceIds,
].join(",")}&vs_currencies=${currency.toLowerCase()}`
);
const priceJson: Record<string, Record<string, number>> =
(await priceResp.json()) ?? {};
const xtzPrice = priceJson.tezos?.[currency.toLowerCase()] ?? 0;
// Fill in prices for Tezos XTZ rows we already pushed
for (const item of items) {
if (item.chain === "tezos" && item.token === "XTZ") {
item.price = xtzPrice;
item.value = item.amount * xtzPrice;
}
// Fill in prices for Etherlink native XTZ
if (item.chain === "etherlink" && item.token === "XTZ (Etherlink)") {
item.price = xtzPrice;
item.value = item.amount * xtzPrice;
}
}
// Add Tezos token positions
for (const position of tokenPositions) {
const price =
priceJson[position.priceId]?.[currency.toLowerCase()] ?? 0;
if (price <= 0) continue;
items.push({
chain: position.chain,
category: position.category,
token: position.token,
amount: position.amount,
price,
value: position.amount * price,
walletName: position.walletName,
});
}
// Add Etherlink ERC-20 token positions
for (const position of etherlinkTokenPositions) {
const price =
priceJson[position.priceId]?.[currency.toLowerCase()] ?? 0;
if (price <= 0) continue;
// Check if this is a borrow (debt) - borrows reduce portfolio value
const isBorrow = position.isBorrow ?? false;
const value = position.amount * price;
items.push({
chain: position.chain,
category: position.category,
token: position.token,
amount: position.amount,
price,
value: isBorrow ? -value : value, // Negative value for borrows
walletName: position.walletName,
});
}
const totalValue = items.reduce((sum, i) => sum + i.value, 0);
const response: PortfolioResponse = {
currency,
totalValue,
items,
};
res.json(response);
} catch (e: any) {
console.error(e);
res.status(500).json({ error: e.message ?? "Internal error" });
}
});
app.listen(port, () => {
console.log(`API server listening on http://localhost:${port}`);
});