-
Notifications
You must be signed in to change notification settings - Fork 214
/
sender.js
192 lines (163 loc) · 5.49 KB
/
sender.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
require('../env')
const path = require('path')
const { connectSenderToQueue } = require('./services/amqpClient')
const { redis, redlock } = require('./services/redisClient')
const GasPrice = require('./services/gasPrice')
const logger = require('./services/logger')
const rpcUrlsManager = require('./services/getRpcUrlsManager')
const { sendTx } = require('./tx/sendTx')
const { getNonce, getChainId } = require('./tx/web3')
const {
addExtraGas,
checkHTTPS,
privateKeyToAddress,
syncForEach,
waitForFunds,
watchdog
} = require('./utils/utils')
const { EXIT_CODES, EXTRA_GAS_PERCENTAGE } = require('./utils/constants')
const { VALIDATOR_ADDRESS_PRIVATE_KEY, REDIS_LOCK_TTL } = process.env
const VALIDATOR_ADDRESS = privateKeyToAddress(VALIDATOR_ADDRESS_PRIVATE_KEY)
if (process.argv.length < 3) {
logger.error('Please check the number of arguments, config file was not provided')
process.exit(EXIT_CODES.GENERAL_ERROR)
}
const config = require(path.join('../config/', process.argv[2]))
const web3Instance = config.web3
const nonceLock = `lock:${config.id}:nonce`
const nonceKey = `${config.id}:nonce`
let chainId = 0
async function initialize() {
try {
const checkHttps = checkHTTPS(process.env.ALLOW_HTTP, logger)
rpcUrlsManager.homeUrls.forEach(checkHttps('home'))
rpcUrlsManager.foreignUrls.forEach(checkHttps('foreign'))
GasPrice.start(config.id)
chainId = await getChainId(config.id)
connectSenderToQueue({
queueName: config.queue,
cb: options => {
if (config.maxProcessingTime) {
return watchdog(() => main(options), config.maxProcessingTime, () => {
logger.fatal('Max processing time reached')
process.exit(EXIT_CODES.MAX_TIME_REACHED)
})
}
return main(options)
}
})
} catch (e) {
logger.error(e.message)
process.exit(EXIT_CODES.GENERAL_ERROR)
}
}
function resume(newBalance) {
logger.info(
`Validator balance changed. New balance is ${newBalance}. Resume messages processing.`
)
initialize()
}
async function readNonce(forceUpdate) {
logger.debug('Reading nonce')
if (forceUpdate) {
logger.debug('Forcing update of nonce')
return getNonce(web3Instance, VALIDATOR_ADDRESS)
}
const nonce = await redis.get(nonceKey)
if (nonce) {
logger.debug({ nonce }, 'Nonce found in the DB')
return Number(nonce)
} else {
logger.debug("Nonce wasn't found in the DB")
return getNonce(web3Instance, VALIDATOR_ADDRESS)
}
}
function updateNonce(nonce) {
return redis.set(nonceKey, nonce)
}
async function main({ msg, ackMsg, nackMsg, sendToQueue, channel }) {
try {
if (redis.status !== 'ready') {
nackMsg(msg)
return
}
const txArray = JSON.parse(msg.content)
logger.info(`Msg received with ${txArray.length} Tx to send`)
const gasPrice = GasPrice.getPrice()
const ttl = REDIS_LOCK_TTL * txArray.length
logger.debug('Acquiring lock')
const lock = await redlock.lock(nonceLock, ttl)
let nonce = await readNonce()
let insufficientFunds = false
let minimumBalance = null
const failedTx = []
logger.debug(`Sending ${txArray.length} transactions`)
await syncForEach(txArray, async job => {
const gasLimit = addExtraGas(job.gasEstimate, EXTRA_GAS_PERCENTAGE)
try {
logger.info(`Sending transaction with nonce ${nonce}`)
const txHash = await sendTx({
chain: config.id,
data: job.data,
nonce,
gasPrice: gasPrice.toString(10),
amount: '0',
gasLimit,
privateKey: VALIDATOR_ADDRESS_PRIVATE_KEY,
to: job.to,
chainId,
web3: web3Instance
})
nonce++
logger.info(
{ eventTransactionHash: job.transactionReference, generatedTransactionHash: txHash },
`Tx generated ${txHash} for event Tx ${job.transactionReference}`
)
} catch (e) {
logger.error(
{ eventTransactionHash: job.transactionReference, error: e.message },
`Tx Failed for event Tx ${job.transactionReference}.`,
e.message
)
if (!e.message.includes('Transaction with the same hash was already imported')) {
failedTx.push(job)
}
if (e.message.includes('Insufficient funds')) {
insufficientFunds = true
const currentBalance = await web3Instance.eth.getBalance(VALIDATOR_ADDRESS)
minimumBalance = gasLimit.multipliedBy(gasPrice)
logger.error(
`Insufficient funds: ${currentBalance}. Stop processing messages until the balance is at least ${minimumBalance}.`
)
} else if (
e.message.includes('Transaction nonce is too low') ||
e.message.includes('transaction with same nonce in the queue')
) {
nonce = await readNonce(true)
}
}
})
logger.debug('Updating nonce')
await updateNonce(nonce)
logger.debug('Releasing lock')
await lock.unlock()
if (failedTx.length) {
logger.info(`Sending ${failedTx.length} Failed Tx to Queue`)
await sendToQueue(failedTx)
}
ackMsg(msg)
logger.debug(`Finished processing msg`)
if (insufficientFunds) {
logger.warn(
'Insufficient funds. Stop sending transactions until the account has the minimum balance'
)
channel.close()
waitForFunds(web3Instance, VALIDATOR_ADDRESS, minimumBalance, resume, logger)
}
} catch (e) {
logger.error(e)
nackMsg(msg)
}
logger.debug('Finished')
}
initialize()