-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherc20portfoliotracker.js
More file actions
294 lines (252 loc) Β· 8.82 KB
/
erc20portfoliotracker.js
File metadata and controls
294 lines (252 loc) Β· 8.82 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
const { createPublicClient, http, formatEther, formatUnits } = require("viem");
const { mainnet } = require("viem/chains");
const client = createPublicClient({
chain: mainnet,
transport: http("https://eth-mainnet.g.alchemy.com/v2/your-api-key") // Replace with your RPC
});
// Common token addresses and decimals
const TOKENS = {
ETH: { address: null, decimals: 18, symbol: "ETH" },
USDC: { address: "0xA0b86a33E6441c8EBb6E6c8c8c9c5C8C8c8c8c8c", decimals: 6, symbol: "USDC" },
USDT: { address: "0xdAC17F958D2ee523a2206206994597C13D831ec7", decimals: 6, symbol: "USDT" },
WETH: { address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", decimals: 18, symbol: "WETH" },
UNI: { address: "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984", decimals: 18, symbol: "UNI" },
LINK: { address: "0x514910771AF9Ca656af840dff83E8264EcF986CA", decimals: 18, symbol: "LINK" },
AAVE: { address: "0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9", decimals: 18, symbol: "AAVE" },
COMP: { address: "0xc00e94Cb662C3520282E6f5717214004A7f26888", decimals: 18, symbol: "COMP" }
};
// ERC-20 ABI for balance checks
const ERC20_ABI = [
{
name: "balanceOf",
type: "function",
stateMutability: "view",
inputs: [{ name: "account", type: "address" }],
outputs: [{ name: "", type: "uint256" }]
},
{
name: "decimals",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint8" }]
},
{
name: "symbol",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "string" }]
}
];
class PortfolioTracker {
constructor() {
this.wallets = [];
this.portfolioData = {};
this.priceCache = {};
}
addWallet(address, label = "") {
this.wallets.push({ address: address.toLowerCase(), label });
}
async getTokenPrice(tokenSymbol) {
// Simple price fetching from CoinGecko (free tier)
if (this.priceCache[tokenSymbol]) {
return this.priceCache[tokenSymbol];
}
try {
const response = await fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${this.getCoingeckoId(tokenSymbol)}&vs_currencies=usd`);
const data = await response.json();
const price = data[this.getCoingeckoId(tokenSymbol)]?.usd || 0;
this.priceCache[tokenSymbol] = price;
return price;
} catch (error) {
console.log(`Failed to fetch price for ${tokenSymbol}`);
return 0;
}
}
getCoingeckoId(symbol) {
const mapping = {
ETH: "ethereum",
USDC: "usd-coin",
USDT: "tether",
WETH: "weth",
UNI: "uniswap",
LINK: "chainlink",
AAVE: "aave",
COMP: "compound-governance-token"
};
return mapping[symbol] || symbol.toLowerCase();
}
async getETHBalance(address) {
try {
const balance = await client.getBalance({ address });
return formatEther(balance);
} catch (error) {
console.log(`Failed to get ETH balance for ${address}`);
return "0";
}
}
async getTokenBalance(tokenAddress, walletAddress) {
try {
const balance = await client.readContract({
address: tokenAddress,
abi: ERC20_ABI,
functionName: "balanceOf",
args: [walletAddress]
});
return balance;
} catch (error) {
console.log(`Failed to get token balance for ${tokenAddress}`);
return BigInt(0);
}
}
async getWalletBalances(walletAddress) {
const balances = {};
// Get ETH balance
const ethBalance = await this.getETHBalance(walletAddress);
if (parseFloat(ethBalance) > 0) {
balances.ETH = {
balance: ethBalance,
symbol: "ETH",
decimals: 18
};
}
// Get token balances
for (const [symbol, token] of Object.entries(TOKENS)) {
if (token.address) {
const balance = await this.getTokenBalance(token.address, walletAddress);
if (balance > 0n) {
const formattedBalance = formatUnits(balance, token.decimals);
if (parseFloat(formattedBalance) > 0.001) { // Only show significant balances
balances[symbol] = {
balance: formattedBalance,
symbol: token.symbol,
decimals: token.decimals
};
}
}
}
}
return balances;
}
async aggregatePortfolio() {
console.log("π Scanning wallets for token balances...\n");
const aggregatedBalances = {};
const walletDetails = [];
for (const wallet of this.wallets) {
console.log(`π Scanning ${wallet.label || wallet.address}...`);
const balances = await this.getWalletBalances(wallet.address);
walletDetails.push({
address: wallet.address,
label: wallet.label,
balances
});
// Aggregate balances across all wallets
for (const [symbol, data] of Object.entries(balances)) {
if (!aggregatedBalances[symbol]) {
aggregatedBalances[symbol] = {
balance: "0",
symbol: data.symbol,
decimals: data.decimals
};
}
aggregatedBalances[symbol].balance = (
parseFloat(aggregatedBalances[symbol].balance) + parseFloat(data.balance)
).toString();
}
}
this.portfolioData = { aggregatedBalances, walletDetails };
return this.portfolioData;
}
async calculatePortfolioValue() {
if (!this.portfolioData.aggregatedBalances) {
await this.aggregatePortfolio();
}
console.log("\nπ° Calculating portfolio value...\n");
let totalValue = 0;
const valueBreakdown = [];
for (const [symbol, data] of Object.entries(this.portfolioData.aggregatedBalances)) {
const price = await this.getTokenPrice(symbol);
const balance = parseFloat(data.balance);
const value = balance * price;
totalValue += value;
valueBreakdown.push({
symbol,
balance: balance.toFixed(6),
price: price.toFixed(2),
value: value.toFixed(2),
percentage: 0 // Will calculate after we have total
});
}
// Calculate percentages
valueBreakdown.forEach(item => {
item.percentage = ((parseFloat(item.value) / totalValue) * 100).toFixed(2);
});
// Sort by value
valueBreakdown.sort((a, b) => parseFloat(b.value) - parseFloat(a.value));
return { totalValue, valueBreakdown };
}
async displayPortfolio() {
const { totalValue, valueBreakdown } = await this.calculatePortfolioValue();
console.log("=" * 80);
console.log("π¦ MULTI-WALLET PORTFOLIO SUMMARY");
console.log("=" * 80);
console.log(`π Total Portfolio Value: $${totalValue.toFixed(2)}\n`);
console.log("π Asset Breakdown:");
console.log("-".repeat(80));
console.log(sprintf("%-8s %-15s %-12s %-15s %-10s", "Symbol", "Balance", "Price", "Value", "% Portfolio"));
console.log("-".repeat(80));
valueBreakdown.forEach(item => {
console.log(sprintf("%-8s %-15s $%-11s $%-14s %-10s%%",
item.symbol,
item.balance,
item.price,
item.value,
item.percentage
));
});
console.log("\nπ± Wallet Breakdown:");
console.log("-".repeat(80));
this.portfolioData.walletDetails.forEach((wallet, index) => {
console.log(`\n${index + 1}. ${wallet.label || "Wallet"} (${wallet.address})`);
if (Object.keys(wallet.balances).length === 0) {
console.log(" No significant balances found");
} else {
Object.entries(wallet.balances).forEach(([symbol, data]) => {
console.log(` ${symbol}: ${parseFloat(data.balance).toFixed(6)}`);
});
}
});
}
// Utility method to track P&L (requires historical data)
trackPnL(purchaseData) {
console.log("\nπ P&L Tracking (requires historical purchase data):");
console.log("To implement P&L tracking, provide purchase data in format:");
console.log("{ symbol: 'ETH', amount: 1.5, purchasePrice: 2000, date: '2024-01-01' }");
// This would calculate current value vs purchase value
// Implementation would require storing historical purchase data
}
}
// Helper function for string formatting
function sprintf(format, ...args) {
return format.replace(/%[-+#0 ]*\*?(?:\d+|\*)?(?:\.(?:\d+|\*))?[hlL]?[%bcdiouxXeEfFgGaAcspn]/g, function(match, index) {
return args[index] || '';
});
}
// Usage Example
async function main() {
const tracker = new PortfolioTracker();
// Add your wallet addresses here
tracker.addWallet("0x742d35Cc6634C0532925a3b8D3Ac28E4FbC7C6e6", "Main Wallet");
tracker.addWallet("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "DeFi Wallet");
tracker.addWallet("0x8ba1f109551bD432803012645Hac136c22C57B9a", "Trading Wallet");
// Add more wallets as needed
try {
await tracker.displayPortfolio();
} catch (error) {
console.error("Error tracking portfolio:", error);
}
}
// Uncomment to run
// main();
module.exports = PortfolioTracker;