/
web3Helpers.js
208 lines (174 loc) · 5.68 KB
/
web3Helpers.js
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
const Web3 = require('web3');
const logger = require('winston');
const EventEmitter = require('events');
const THIRTY_SECONDS = 30 * 1000;
/**
* remove 0x prefix = require(hex string if present
*
* @param {string} hex
*/
const removeHexPrefix = hex => {
if (hex && typeof hex === 'string' && hex.toLowerCase().startsWith('0x')) {
return hex.substring(2);
}
return hex;
};
/**
* recursively execute all requests in batches of 100
*
* @param {object} web3 Web3 instance
* @param {array} requests array of Web3 request objects
*/
function batchAndExecuteRequests(web3, requests) {
if (requests.length === 0) return;
const batch = new web3.BatchRequest();
requests.splice(0, 100).forEach(r => batch.add(r));
batch.execute();
batchAndExecuteRequests(web3, requests);
}
/**
* Adds an account to the wallet of the provided web3 instance
* if it has not be previously added
*
* @param {object} web3 Web3 instance
* @param {string} privateKey pk of the account to add to the wallet
* @returns {object} web3 account instance
*/
const addAccountToWallet = (web3, privateKey) => {
let account = [].find.call(web3.eth.accounts.wallet, a => a.privateKey === privateKey);
if (account) return account;
if (web3.eth.accounts.wallet.length === 0 && privateKey) {
account = web3.eth.accounts.privateKeyToAccount(privateKey);
web3.eth.accounts.wallet.add(account);
}
return account;
};
const blockCache = {};
const blockListeners = {};
/**
* fetches the ts for the given blockNumber.
*
* caches the last 100 ts
*
* first checks if the ts is in the cache.
* if it misses, we fetch the block using web3 and cache the result.
*
* if we are currently fetching a given block, we will not fetch it twice.
* instead, we resolve the promise after we fetch the ts for the block.
*
* @param {number} blockNumber the blockNumber to fetch the ts of
*/
const getBlockTimestamp = async (web3, blockNumber) => {
if (blockCache[blockNumber]) return blockCache[blockNumber];
// if we are already fetching the block, don't do it twice
if (blockListeners[blockNumber]) {
return new Promise(resolve => {
// attach a listener which is executed when we get the block ts
blockListeners[blockNumber].push(resolve);
});
}
blockListeners[blockNumber] = [];
const block = await web3.eth.getBlock(blockNumber);
const ts = new Date(block.timestamp * 1000);
blockCache[blockNumber] = ts;
// only keep 100 block ts cached
if (Object.keys(blockCache).length > 100) {
Object.keys(blockCache)
.sort((a, b) => b - a)
.forEach(key => delete blockCache[key]);
}
// execute any listeners for the block
blockListeners[blockNumber].forEach(cb => cb(ts));
delete blockListeners[blockNumber];
return ts;
};
// if the websocket connection drops, attempt to re-connect
// upon successful re-connection, we re-start all listeners
const reconnectOnEnd = (web3, nodeUrl) => {
web3.currentProvider.on('end', e => {
if (web3.reconnectInterval) return;
web3.emit(web3.DISCONNECT_EVENT);
logger.error(`connection closed reason: ${e.reason}, code: ${e.code}`);
web3.pingInterval = undefined;
web3.reconnectInterval = setInterval(() => {
logger.info('attempting to reconnect');
const newProvider = new web3.providers.WebsocketProvider(nodeUrl);
newProvider.on('connect', () => {
logger.info('successfully connected');
clearInterval(web3.reconnectInterval);
web3.reconnectInterval = undefined;
// note: "connection not open on send()" will appear in the logs when setProvider is called
// This is because web3.setProvider will attempt to clear any subscriptions on the currentProvider
// before setting the newProvider. Our currentProvider has been disconnected, so thus the not open
// error is logged
web3.setProvider(newProvider);
// attach reconnection logic to newProvider
reconnectOnEnd(web3, nodeUrl);
web3.emit(web3.RECONNECT_EVENT);
});
}, THIRTY_SECONDS);
});
};
function instantiateWeb3(nodeUrl) {
const provider =
nodeUrl && nodeUrl.startsWith('ws')
? new Web3.providers.WebsocketProvider(nodeUrl, {
clientConfig: {
maxReceivedFrameSize: 100000000,
maxReceivedMessageSize: 100000000,
},
})
: nodeUrl;
const w3 = Object.assign(new Web3(provider), EventEmitter.prototype);
if (w3.currentProvider.on) {
w3.currentProvider.on('connect', () => {
// keep geth node connection alive
w3.pingInterval = setInterval(w3.eth.net.getId, 45 * 1000);
});
// attach the re-connection logic to the current web3 provider
reconnectOnEnd(w3, nodeUrl);
Object.assign(w3, {
DISCONNECT_EVENT: 'disconnect',
RECONNECT_EVENT: 'reconnect',
});
}
return w3;
}
let web3;
let homeWeb3;
/**
* returns the cached web3 instance or instantiates a new one.
*
* This web3 instance will emit the following events:
* - disconnect
* - reconnect
* @param {object} app feathers application object
*/
function getWeb3(app) {
if (web3) return web3;
const { nodeUrl } = app.get('blockchain');
web3 = instantiateWeb3(nodeUrl);
return web3;
}
/**
* returns the cached homeWeb3 instance or instantiates a new one.
*
* This web3 instance will emit the following events:
* - disconnect
* - reconnect
* @param {object} app feathers application object
*/
function getHomeWeb3(app) {
if (homeWeb3) return homeWeb3;
const { homeNodeUrl } = app.get('blockchain');
homeWeb3 = instantiateWeb3(homeNodeUrl);
return homeWeb3;
}
module.exports = {
getWeb3,
getHomeWeb3,
batchAndExecuteRequests,
removeHexPrefix,
addAccountToWallet,
getBlockTimestamp,
};