-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
206 lines (175 loc) · 5.99 KB
/
main.ts
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
import axios from 'axios';
import rateLimit from 'axios-rate-limit';
import dotenv from 'dotenv';
dotenv.config();
const apiKey: any = process.env.ETHERSCAN_API_KEY;
interface EtherscanApiResponse {
status: string;
message: string;
result: EthereumTransaction[];
}
interface EthereumTransaction {
blockNumber: string;
timeStamp: string;
hash: string;
nonce: string;
blockHash: string;
transactionIndex: string;
from: string;
to: string;
value: string;
gas: string;
gasPrice: string;
isError: string;
txreceipt_status: string;
input: string;
contractAddress: string;
cumulativeGasUsed: string;
gasUsed: string;
confirmations: string;
methodId: string;
functionName: string;
}
export interface EthereumAddress {
address: string;
balance: string;
senders: EthereumAddress[];
depth: number;
}
// Create a rate-limited Axios instance
const http = rateLimit(axios.create(), {
maxRequests: 5,
perMilliseconds: 1000,
});
async function executeRequest(url: string, params: any) {
try {
//time the request
const start = Date.now();
const response = await http.get<EtherscanApiResponse>(url, {params}); // Use the rate-limited instance
const result = response.data.result;
const elapsed = Date.now() - start;
// if params action is X, then do Y
if (params.action === 'txlist') {
console.log(`Fetched ${result.length} transactions for ${params.address} and took ${elapsed}ms`);
} else {
console.log(`Fetched balances for ${params.address} and took ${elapsed}ms`);
}
return result;
} catch (error) {
console.error(`Error fetching transactions: ${error}`);
throw error;
}
}
async function getAccountTransactions(address: string, apiKey: string): Promise<EthereumTransaction[]> {
const url = `https://api.etherscan.io/api`;
const params = {
module: 'account',
action: 'txlist',
address: address,
startblock: 0,
endblock: 99999999,
sort: 'asc',
apiKey: apiKey
};
return await executeRequest(url, params);
}
async function getAccountBalances(addresses: string[], apiKey: string): Promise<any> {
const url = `https://api.etherscan.io/api`;
const params = {
module: 'account',
action: 'balancemulti',
address: addresses.join(','),
tag: 'latest',
apiKey: apiKey
};
return executeRequest(url, params);
}
async function extractAddresses(address: string, transactions: EthereumTransaction[], depth: number, maxDepth: number): Promise<EthereumAddress> {
if (!Array.isArray(transactions) || transactions.length === 0) {
return {
address: address,
senders: [],
balance: "0",
depth: depth
};
}
let accountRelationship: EthereumAddress = {
address: address,
senders: [],
balance: "0",
depth: depth
};
if (depth >= maxDepth) {
return accountRelationship;
}
const transactionsMap = transactions.reduce((acc: any, transaction) => {
if (transaction.from === address) {
return acc;
}
if (!acc[transaction.from]) {
acc[transaction.from] = [];
}
acc[transaction.from].push(transaction);
return acc;
}, {});
for (const key of Object.keys(transactionsMap)) {
if (key !== address) {
if (depth < maxDepth - 1) {
const senderTransactions = await getAccountTransactions(key, apiKey);
const senderAddress = await extractAddresses(key, senderTransactions, depth + 1, maxDepth);
accountRelationship.senders.push(senderAddress);
} else {
accountRelationship.senders.push({address: key, senders: [], depth: depth + 1, balance: "0"});
}
}
}
return accountRelationship;
}
function chunkArray<T>(array: T[], chunkSize: number): T[][] {
const chunks = [];
for (let i = 0; i < array.length; i += chunkSize) {
chunks.push(array.slice(i, i + chunkSize));
}
return chunks;
}
function getAllUniqueAddresses(relationshipData: EthereumAddress): string[] {
const addresses = new Set<string>();
function addAddress(addressData: EthereumAddress) {
if (!addresses.has(addressData.address)) {
addresses.add(addressData.address);
addressData.senders.forEach(addAddress);
}
}
addAddress(relationshipData);
return Array.from(addresses);
}
function combineBalancesWithRelationshipData(relationshipData: EthereumAddress, balances: any[]): EthereumAddress {
const balanceMap = new Map(balances.map(b => [b.account, b.balance]));
function addBalance(addressData: EthereumAddress) {
if (balanceMap.has(addressData.address)) {
addressData.balance = weiToEther(balanceMap.get(addressData.address));
}
addressData.senders.forEach(addBalance);
}
addBalance(relationshipData);
return relationshipData;
}
export async function run(address: string, maxDepth: number): Promise<EthereumAddress> {
let transactions = await getAccountTransactions(address, apiKey);
let addresses = await extractAddresses(address, transactions, 0, maxDepth);
// Extract all unique addresses
const allAddresses = getAllUniqueAddresses(addresses);
// Chunk addresses into batches of 20
const addressChunks = chunkArray(allAddresses, 20);
// Fetch balances for each chunk
const balancePromises = addressChunks.map(chunk => getAccountBalances(chunk, apiKey));
const balanceResults = (await Promise.all(balancePromises)).flat();
//
// Combine balance data with relationship data
return combineBalancesWithRelationshipData(addresses, balanceResults);
}
function weiToEther(wei: string | number): string {
const weiPerEther = 1e18;
const ether = Number(wei) / weiPerEther;
return ether.toFixed(18);
}