-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
116 lines (105 loc) · 4.13 KB
/
background.js
File metadata and controls
116 lines (105 loc) · 4.13 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
// Function to update the badge with gas price text
function updateBadge(gasText) {
console.log('updateBadge called with gasText:', gasText);
try {
let shortGas;
if (gasText === 'Error') {
shortGas = 'Err';
} else {
const numberGas = Number.parseFloat(gasText);
// One-liner: Format based on magnitude, max 4 chars
shortGas = numberGas.toFixed(numberGas >= 100 ? 0 : (numberGas >= 10 ? 1 : 2)).slice(0, 4);
}
chrome.action.setBadgeText({ text: shortGas });
chrome.action.setBadgeBackgroundColor({ color: '#222222' }); // Dark grey
console.log('Badge updated with:', shortGas);
} catch (error) {
console.error('Error updating badge:', error);
chrome.action.setBadgeText({ text: 'Err' });
chrome.action.setBadgeBackgroundColor({ color: '#FF0000' }); // Red for error
}
}
async function fetchWithRetry(url, options = {}, maxRetries = 6, baseDelay = 1000) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch(url, options);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response;
} catch (error) {
if (attempt === maxRetries) throw error;
await new Promise(resolve => setTimeout(resolve, baseDelay * Math.pow(2, attempt - 1)));
}
}
}
async function fetchEthGasPrice(forceUpdate = false) {
console.log('fetchEthGasPrice called');
chrome.storage.local.get(['gas', 'lastUpdate'], async (result) => {
console.log('Storage data retrieved:', result);
const now = Date.now();
const lastUpdate = result.lastUpdate || 0;
console.log('Current time:', now, 'Last update:', lastUpdate);
if ((now - lastUpdate > 5 * 60 * 1000) || forceUpdate) {
console.log('Fetching new gas price from API');
try {
const response = await fetchWithRetry('https://api.blocknative.com/gasprices/blockprices?chainid=1');
console.log('API response status:', response.status);
const data = await response.json();
console.log('API response data:', data);
const blockPrices = data.blockPrices;
if (!blockPrices || blockPrices.length === 0) {
throw new Error('No block prices found in API response');
}
const estimatedPrices = blockPrices[0].estimatedPrices;
if (!estimatedPrices || estimatedPrices.length === 0) {
throw new Error('No estimated prices found in API response');
}
const price95 = estimatedPrices.find(price => price.confidence === 95);
if (!price95) {
throw new Error('Could not retrieve gas price with 95% confidence');
}
const newGas = price95.price;
console.log('New gas price (95% confidence):', newGas);
chrome.storage.local.set({ gas: newGas, lastUpdate: now }, () => {
console.log('Gas price and lastUpdate saved to storage');
});
updateBadge(newGas);
} catch (error) {
console.error('Fetch error:', error);
updateBadge('Error');
}
} else if (result.gas) {
console.log('Using cached gas price:', result.gas);
updateBadge(result.gas);
} else {
console.log('No cached gas price available');
updateBadge('Error');
}
});
}
// Add click listener to refresh gas price
chrome.action.onClicked.addListener(() => {
console.log('Icon clicked, refreshing Ethereum gas price');
fetchEthGasPrice(true);
});
chrome.runtime.onStartup.addListener(() => {
console.log('Browser started, initializing Ethereum gas price fetch');
fetchEthGasPrice();
});
chrome.idle.onStateChanged.addListener((state) => {
if (state === 'active') {
console.log('System woke from idle, refreshing Ethereum gas price');
fetchEthGasPrice();
}
});
// Initial fetch when the extension loads
console.log('Extension loaded, initiating first fetch');
fetchEthGasPrice();
// Schedule periodic updates
console.log('Creating alarm for periodic updates');
chrome.alarms.create('updateEthGasPrice', { periodInMinutes: 5 });
chrome.alarms.onAlarm.addListener((alarm) => {
console.log('Alarm triggered:', alarm.name);
if (alarm.name === 'updateEthGasPrice') {
fetchEthGasPrice();
}
});