-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockchainAPI.js
More file actions
232 lines (214 loc) · 6.15 KB
/
BlockchainAPI.js
File metadata and controls
232 lines (214 loc) · 6.15 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
const axios = require('axios');
class BlockchainAPI {
constructor(cacheDuration = 60000) {
this.baseURL = 'https://blockchain.info';
this.cache = new Map();
this.cacheDuration = cacheDuration; // Default: 1 minute
}
/**
* Get cached data or fetch new data
* @private
*/
_getCached(key, fetchFunction) {
const cached = this.cache.get(key);
if (cached && Date.now() - cached.timestamp < this.cacheDuration) {
return Promise.resolve(cached.data);
}
return fetchFunction().then(data => {
this.cache.set(key, { data, timestamp: Date.now() });
return data;
});
}
/**
* Clear all cached data
*/
clearCache() {
this.cache.clear();
}
/**
* Clear cache for specific key
*/
clearCacheKey(key) {
this.cache.delete(key);
}
/**
* Add delay between requests
* @private
*/
_delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* Get balance for a single address in BTC
* @param {string} address - Bitcoin address
* @returns {Promise<number>} Balance in BTC
*/
async getAddressBalance(address) {
const cacheKey = `balance_${address}`;
return this._getCached(cacheKey, async () => {
try {
const response = await axios.get(`${this.baseURL}/q/addressbalance/${address}`);
const satoshis = parseInt(response.data);
return satoshis / 100000000; // Convert to BTC
} catch (error) {
console.error('Error fetching balance:', error.message);
throw error;
}
});
}
/**
* Get detailed information about an address
* @param {string} address - Bitcoin address
* @param {number} limit - Number of transactions to return (default: 50)
* @returns {Promise<Object>} Address details including transactions
*/
async getAddressDetails(address, limit = 50) {
const cacheKey = `details_${address}_${limit}`;
return this._getCached(cacheKey, async () => {
try {
const response = await axios.get(
`${this.baseURL}/rawaddr/${address}?limit=${limit}`
);
return response.data;
} catch (error) {
console.error('Error fetching address details:', error.message);
throw error;
}
});
}
/**
* Get balances for multiple addresses
* @param {string[]} addresses - Array of Bitcoin addresses
* @returns {Promise<Object>} Object with addresses as keys
*/
async getMultipleBalances(addresses) {
const cacheKey = `multi_${addresses.sort().join('|')}`;
return this._getCached(cacheKey, async () => {
try {
const addressString = addresses.join('|');
const response = await axios.get(
`${this.baseURL}/balance?active=${addressString}`
);
return response.data;
} catch (error) {
console.error('Error fetching multiple balances:', error.message);
throw error;
}
});
}
/**
* Get unspent transaction outputs (UTXOs) for an address
* @param {string} address - Bitcoin address
* @returns {Promise<Object>} Unspent outputs
*/
async getUnspentOutputs(address) {
const cacheKey = `unspent_${address}`;
return this._getCached(cacheKey, async () => {
try {
const response = await axios.get(
`${this.baseURL}/unspent?active=${address}`
);
return response.data;
} catch (error) {
console.error('Error fetching unspent outputs:', error.message);
throw error;
}
});
}
/**
* Get transaction details
* @param {string} txHash - Transaction hash
* @returns {Promise<Object>} Transaction details
*/
async getTransaction(txHash) {
const cacheKey = `tx_${txHash}`;
return this._getCached(cacheKey, async () => {
try {
const response = await axios.get(`${this.baseURL}/rawtx/${txHash}`);
return response.data;
} catch (error) {
console.error('Error fetching transaction:', error.message);
throw error;
}
});
}
/**
* Get latest block information
* @returns {Promise<Object>} Latest block data
*/
async getLatestBlock() {
const cacheKey = 'latest_block';
return this._getCached(cacheKey, async () => {
try {
const response = await axios.get(`${this.baseURL}/latestblock`);
return response.data;
} catch (error) {
console.error('Error fetching latest block:', error.message);
throw error;
}
});
}
/**
* Get block at specific height
* @param {number} height - Block height
* @returns {Promise<Object>} Block data
*/
async getBlockAtHeight(height) {
const cacheKey = `block_height_${height}`;
return this._getCached(cacheKey, async () => {
try {
const response = await axios.get(
`${this.baseURL}/block-height/${height}?format=json`
);
return response.data;
} catch (error) {
console.error('Error fetching block:', error.message);
throw error;
}
});
}
/**
* Batch fetch balances with delay between requests
* @param {string[]} addresses - Array of Bitcoin addresses
* @param {number} delayMs - Delay between requests in milliseconds (default: 1000)
* @returns {Promise<Array>} Array of balances
*/
async batchFetchBalances(addresses, delayMs = 1000) {
const results = [];
for (const address of addresses) {
results.push(await this.getAddressBalance(address));
if (addresses.indexOf(address) < addresses.length - 1) {
await this._delay(delayMs);
}
}
return results;
}
/**
* Format satoshis to BTC
* @param {number} satoshis - Amount in satoshis
* @returns {number} Amount in BTC
*/
satoshisToBTC(satoshis) {
return satoshis / 100000000;
}
/**
* Format BTC amount with proper decimals
* @param {number} btc - Amount in BTC
* @returns {string} Formatted BTC string
*/
formatBTC(btc) {
return btc.toFixed(8) + ' BTC';
}
/**
* Get cache statistics
* @returns {Object} Cache stats
*/
getCacheStats() {
return {
size: this.cache.size,
duration: this.cacheDuration,
keys: Array.from(this.cache.keys())
};
}
}
module.exports = BlockchainAPI;