This repository has been archived by the owner on Dec 9, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
web3Utilities.js
314 lines (270 loc) · 10.9 KB
/
web3Utilities.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
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
const ethUtil = require('ethereumjs-util')
const ethSigUtil = require('eth-sig-util')
const listeners = require('./web3Listeners')
const ERC20ABI = [{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"}] // eslint-disable-line
const networkDataById = {
1: {
name: 'Mainnet',
type: 'PoW',
etherscanPrefix: ''
},
3: {
name: 'Ropsten',
type: 'PoW',
etherscanPrefix: 'ropsten.'
},
4: {
name: 'Rinkeby',
type: 'PoA',
etherscanPrefix: 'rinkeby.'
},
42: {
name: 'Kovan',
type: 'PoA',
etherscanPrefix: 'kovan.'
}
}
const getEthereumVariables = {
web3js: () => { return listeners.getWeb3js() },
account: () => { return listeners.getAccount() },
networkId: () => { return listeners.getNetworkId() }
}
const _setEthereumVariableGetters = (getters) => {
Object.keys(getters).forEach(getter => {
getEthereumVariables[getter] = getters[getter]
})
}
const sendTransaction = (method, handlers) => {
let requiredHandlers = ['error']
let optionalHandlers = ['transactionHash', 'receipt', 'confirmation']
let allHandlers = requiredHandlers.concat(optionalHandlers)
// ensure an error handler was passed
if (!requiredHandlers.every(handler => { return Object.keys(handlers).includes(handler) })) {
throw Error('Please provide an \'error\' handler.')
}
// ensure only allowed handlers can be passed
if (!Object.keys(handlers).every(handler => { return allHandlers.includes(handler) })) {
throw Error(`Invalid handler passed. Allowed handlers are: '${allHandlers.toString().join(`', '`)}'.`)
}
// for all handlers that weren't passed, set them as empty functions
for (let i = 0; i < allHandlers.length; i++) {
if (handlers[allHandlers[i]] === undefined) handlers[allHandlers[i]] = () => {}
}
// define promises for the variables we need to validate/send the transaction
const gasPricePromise = () => {
return getEthereumVariables.web3js().eth.getGasPrice()
.catch(error => {
handlers['error'](error, 'Could not fetch gas price.')
return null
})
}
const gasPromise = () => {
return method.estimateGas({ from: getEthereumVariables.account() })
.catch(error => {
handlers['error'](error, 'The transaction would fail.')
return null
})
}
const balanceWeiPromise = () => {
return getBalance(undefined, 'wei')
.catch(error => {
handlers['error'](error, 'Could not fetch sending address balance.')
return null
})
}
const handledErrorName = 'HandledError'
return Promise.all([gasPricePromise(), gasPromise(), balanceWeiPromise()])
.then(results => {
// ensure that none of the promises failed
if (results.some(result => { return result === null })) {
let error = Error('This error was already handled.')
error.name = handledErrorName
throw error
}
// extract variables
const [gasPrice, gas, balanceWei] = results
// ensure the sender has enough ether to pay gas
const safeGas = parseInt(gas * 1.1)
const requiredWei = new ethUtil.BN(gasPrice).mul(new ethUtil.BN(safeGas))
if (new ethUtil.BN(balanceWei).lt(requiredWei)) {
const requiredEth = toDecimal(requiredWei.toString(), '18')
const errorMessage = `Insufficient balance. Ensure you have at least ${requiredEth} ETH.`
handlers['error'](Error(errorMessage), errorMessage)
return
}
// send the transaction
method.send({ from: getEthereumVariables.account(), gasPrice: gasPrice, gas: safeGas })
.on('transactionHash', transactionHash => {
handlers['transactionHash'](transactionHash)
})
.on('receipt', (receipt) => {
handlers['receipt'](receipt)
})
.on('confirmation', (confirmationNumber, receipt) => {
handlers['confirmation'](confirmationNumber, receipt)
})
.on('error', error => {
handlers['error'](error, 'Unable to send transaction.')
})
})
.catch(error => {
if (error.name !== handledErrorName) { handlers['error'](error, 'Unexpected error.') }
})
}
const signPersonal = (message) => {
const from = getEthereumVariables.account()
if (!ethUtil.isValidChecksumAddress(from)) throw Error(`Current account '${from}' has an invalid checksum.`)
let encodedMessage
if (Buffer.isBuffer(message)) {
encodedMessage = ethUtil.addHexPrefix(message.toString('hex'))
} else if (message.slice(0, 2) === '0x') {
encodedMessage = message
} else {
encodedMessage = ethUtil.bufferToHex(Buffer.from(message, 'utf8'))
}
return new Promise((resolve, reject) => {
getEthereumVariables.web3js().currentProvider.sendAsync({
method: 'personal_sign',
params: [encodedMessage, from],
from: from
}, (error, result) => {
if (error) return reject(error)
if (result.error) return reject(result.error.message)
let returnData = {}
returnData.signature = result.result
// ensure that the signature matches
const signature = ethUtil.fromRpcSig(returnData.signature)
const messageHash = ethUtil.hashPersonalMessage(ethUtil.toBuffer(encodedMessage))
const recovered = ethUtil.ecrecover(
messageHash,
signature.v, signature.r, signature.s
)
const recoveredAddress = ethUtil.toChecksumAddress(ethUtil.pubToAddress(recovered).toString('hex'))
if (recoveredAddress !== from) {
return reject(Error(
`The returned signature '${returnData.signature}' originated from '${recoveredAddress}', not '${from}'.`
))
}
returnData.r = ethUtil.addHexPrefix(signature.r.toString('hex'))
returnData.s = ethUtil.addHexPrefix(signature.s.toString('hex'))
returnData.v = signature.v
returnData.from = from
returnData.messageHash = ethUtil.addHexPrefix(messageHash.toString('hex'))
resolve(returnData)
})
})
}
const signTypedData = (typedData) => {
const from = getEthereumVariables.account()
if (!ethUtil.isValidChecksumAddress(from)) throw Error(`Current account '${from}' has an invalid checksum.`)
return new Promise((resolve, reject) => {
getEthereumVariables.web3js().currentProvider.sendAsync({
method: 'eth_signTypedData',
params: [typedData, from],
from: from
}, (error, result) => {
if (error) return reject(error)
if (result.error) return reject(result.error.message)
let returnData = {}
returnData.signature = result.result
// ensure that the signature matches
const recoveredAddress = ethUtil.toChecksumAddress(ethSigUtil.recoverTypedSignature({
data: typedData,
sig: returnData.signature
}))
if (ethUtil.toChecksumAddress(recoveredAddress) !== from) {
return reject(Error(
`The returned signature '${returnData.signature}' originated from '${recoveredAddress}', not '${from}'.`
))
}
returnData.from = from
returnData.messageHash = ethSigUtil.typedSignatureHash(typedData)
const signature = ethUtil.fromRpcSig(returnData.signature)
returnData.r = ethUtil.addHexPrefix(Buffer.from(signature.r).toString('hex'))
returnData.s = ethUtil.addHexPrefix(Buffer.from(signature.s).toString('hex'))
returnData.v = signature.v
resolve(returnData)
})
})
}
const getBalance = (account, format) => {
if (account === undefined) account = getEthereumVariables.account()
if (format === undefined) format = 'ether'
return getEthereumVariables.web3js().eth.getBalance(account)
.then(balance => {
return getEthereumVariables.web3js().utils.fromWei(balance, format)
})
}
const getERC20Balance = (ERC20Address, account) => {
if (account === undefined) account = getEthereumVariables.account()
let ERC20 = getContract(ERC20ABI, ERC20Address)
let decimalsPromise = () => { return ERC20.methods.decimals().call() }
let balancePromise = () => { return ERC20.methods.balanceOf(account).call() }
return Promise.all([balancePromise(), decimalsPromise()])
.then(([balance, decimals]) => {
return toDecimal(balance, decimals)
})
}
const toDecimal = (number, decimals) => {
if (number.length < decimals) {
number = '0'.repeat(decimals - number.length) + number
}
let difference = number.length - decimals
let integer = difference === 0 ? '0' : number.slice(0, difference)
let fraction = number.slice(difference).replace(/0+$/g, '')
return integer + (fraction === '' ? '' : '.') + fraction
}
const fromDecimal = (number, decimals) => {
var [integer, fraction] = number.split('.')
fraction = fraction === undefined ? '' : fraction
if (fraction.length > decimals) throw new Error('The fractional amount of the passed number was too high')
fraction = fraction + '0'.repeat(decimals - fraction.length)
return integer + fraction
}
const getNetworkName = (networkId) => {
networkId = networkId === undefined ? String(getEthereumVariables.networkId()) : String(networkId)
if (!Object.keys(networkDataById).includes(networkId)) throw Error(`Network id '${networkId}' is invalid.`)
return networkDataById[networkId].name
}
const getNetworkType = (networkId) => {
networkId = networkId === undefined ? String(getEthereumVariables.networkId()) : String(networkId)
if (!Object.keys(networkDataById).includes(networkId)) throw Error(`Network id '${networkId}' is invalid.`)
return networkDataById[networkId].type
}
const getContract = (ABI, address, options) => {
let web3js = getEthereumVariables.web3js()
return new web3js.eth.Contract(ABI, address, options)
}
const etherscanFormat = (type, data, networkId) => {
if (!['transaction', 'address', 'token'].includes(type)) throw Error(`Type '${type}' is invalid.`)
networkId = networkId === undefined ? String(getEthereumVariables.networkId()) : String(networkId)
if (!Object.keys(networkDataById).includes(networkId)) throw Error(`Network id '${networkId}' is invalid.`)
let prefix = networkDataById[networkId].etherscanPrefix
var path
if (type === 'transaction') {
path = 'tx'
} else if (type === 'address') {
path = 'address'
} else {
path = 'token'
}
return `https://${prefix}etherscan.io/${path}/${data}`
}
module.exports = {
_setEthereumVariableGetters: _setEthereumVariableGetters,
signPersonal: signPersonal,
signTypedData: signTypedData,
getBalance: getBalance,
getERC20Balance: getERC20Balance,
getNetworkName: getNetworkName,
getNetworkType: getNetworkType,
getContract: getContract,
sendTransaction: sendTransaction,
toDecimal: toDecimal,
fromDecimal: fromDecimal,
etherscanFormat: etherscanFormat,
libraries: {
'eth-sig-util': ethSigUtil,
'ethereumjs-util': ethUtil
}
}