-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathTransactionSender.js
More file actions
237 lines (207 loc) · 8.34 KB
/
TransactionSender.js
File metadata and controls
237 lines (207 loc) · 8.34 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
233
234
235
236
237
var globals = require('./globals');
const { MAINNET_ID, RINKEBY_ID, ROPSTEN_ID } = require('./constants');
const Tx = require('ethereumjs-tx');
const ethUtils = require('ethereumjs-util');
const utils = require('./utils');
const CustomError = require('./CustomError');
const GasPriceEstimator = require('./GasPriceEstimator');
const fs = require('fs');
const ethereumJsTx = require('@ethereumjs/tx');
const Common = require('@ethereumjs/common').default;
module.exports = class TransactionSender {
constructor(client, logger, config, chainId) {
this.client = client;
this.logger = logger;
this.chainId = chainId;
this.config = config;
this.manuallyCheck = `${config.storagePath || __dirname}/manuallyCheck.txt`;
this.gasPriceEstimator = new GasPriceEstimator({
web3: this.client,
logger: this.logger,
etherscanApiKey: config.etherscanApiKey,
});
}
async getNonce(address) {
return await this.client.eth.getTransactionCount(address, 'pending');
}
numberToHexString(number) {
if (!number) {
return '0x0';
}
return `0x${Math.ceil(parseInt(number)).toString(16)}`;
}
async getGasPrice(chainId) {
return this.gasPriceEstimator.getGasPrice(chainId);
}
async getGasLimit(rawTx) {
const estimatedGas = await this.client.eth.estimateGas({
value: rawTx.value,
to: rawTx.to,
data: rawTx.data,
from: rawTx.from,
});
// Vote: ~70k
// Vote+execute: A little over 250k
// First side token deployment: ~3.15M
const minimum = 300000;
const gasLimit = estimatedGas < minimum ? minimum : 3500000;
return gasLimit;
}
async getChainId() {
const chainId = this.chainId || (await this.client.eth.net.getId());
return chainId;
}
getChainName(chainId) {
switch (chainId) {
case MAINNET_ID:
return 'mainnet';
case RINKEBY_ID:
return 'rinkeby';
case ROPSTEN_ID:
return 'ropsten';
default:
throw new Error('Unknown chain id');
}
}
async createRawTransaction(from, to, data, value) {
const nonce = await this.getNonce(from);
const chainId = await this.getChainId();
const chainIdInt = parseInt(chainId);
if (chainIdInt === MAINNET_ID || chainIdInt === RINKEBY_ID || chainIdInt === ROPSTEN_ID) {
const rawTxETH = await this.createETHRawTransaction(from, to, data, value, chainId);
const chainName = this.getChainName(chainIdInt);
const common = new Common({ chain: chainName, hardfork: 'london' });
const tx = ethereumJsTx.FeeMarketEIP1559Transaction.fromTxData(rawTxETH, { common });
return tx;
} else {
const gasPrice = await this.getGasPrice(chainId);
let rawTx = {
gasPrice: this.numberToHexString(gasPrice),
value: this.numberToHexString(value),
to: to,
data: data,
from: from,
nonce: this.numberToHexString(nonce),
r: 0,
s: 0,
};
rawTx.gas = this.numberToHexString(await this.getGasLimit(rawTx));
const rawTxType = new Tx(rawTx);
return rawTxType;
}
}
async createETHRawTransaction(from, to, data, value, chainId) {
const nonce = await this.getNonce(from);
const gwei = 1000000000;
const priorityFee = 2;
const sleepOnGas = this.config.sleepOnGas * 1000; //10 * 1000 ; // 10 Seconds
const maxSleepOnGas = this.config.maxSleepOnGas; //12
let sleepOnGasCounter = 0;
while (globals.currentEthGasBasePrice > globals.currentEthGasPriceAvg) {
await utils.sleep(sleepOnGas, { logger: this.logger });
sleepOnGasCounter++;
if (sleepOnGasCounter > maxSleepOnGas) {
throw new CustomError(`High Base Gas: Transaction wasn't sent`);
}
}
const rawTx = {
maxFeePerGas: this.numberToHexString(
(parseInt(globals.currentEthGasBasePrice) + priorityFee) * 1.3 * gwei
),
maxPriorityFeePerGas: this.numberToHexString(priorityFee * gwei),
value: this.numberToHexString(value),
to: to,
data: data,
from: from,
nonce: this.numberToHexString(nonce),
chainId: this.numberToHexString(parseInt(chainId)),
accessList: [],
type: '0x02',
r: 0,
s: 0,
};
rawTx.gasLimit = this.numberToHexString(await this.getGasLimit(rawTx));
this.logger.info('raw tx is:', { rawTx });
return rawTx;
}
signRawTransaction(rawTx, privateKey) {
rawTx.sign(utils.hexStringToBuffer(privateKey));
return rawTx;
}
signETHRawTransaction(rawTx, privateKey) {
const signedTx = rawTx.sign(utils.hexStringToBuffer(privateKey));
return signedTx;
}
async getAddress(privateKey) {
let address = null;
if (privateKey && privateKey.length) {
address = utils.privateToAddress(privateKey);
} else {
//If no private key provided we use personal (personal is only for testing)
let accounts = await this.client.eth.getAccounts();
address = accounts[0];
}
return address;
}
async sendTransaction(to, data, value, privateKey) {
const stack = new Error().stack;
const chainId = await this.getChainId();
var from = await this.getAddress(privateKey);
if (!from) {
throw new CustomError(
`No from address given. Is there an issue with the private key? ${stack}`
);
}
let rawTx = await this.createRawTransaction(from, to, data, value, privateKey);
let txHash;
let error = '';
let errorInfo = '';
try {
let receipt;
let signedTx;
if (privateKey && privateKey.length) {
if (parseInt(chainId) === parseInt(MAINNET_ID) || parseInt(chainId) === parseInt(RINKEBY_ID) || parseInt(chainId) === parseInt(ROPSTEN_ID)) {
signedTx = this.signETHRawTransaction(rawTx, privateKey);
} else {
signedTx = this.signRawTransaction(rawTx, privateKey);
}
const serializedTx = ethUtils.bufferToHex(signedTx.serialize());
receipt = await this.client.eth
.sendSignedTransaction(serializedTx)
.once('transactionHash', (hash) => (txHash = hash));
} else {
//If no private key provided we use personal (personal is only for testing)
delete rawTx.r;
delete rawTx.s;
delete rawTx.v;
receipt = await this.client.eth
.sendTransaction(rawTx)
.once('transactionHash', (hash) => (txHash = hash));
}
if (receipt.status == 1) {
this.logger.info(
`Transaction Successful txHash:${receipt.transactionHash} blockNumber:${receipt.blockNumber}`
);
return receipt;
}
error = 'Transaction Receipt Status Failed';
errorInfo = receipt;
} catch (err) {
if (err.message.indexOf('it might still be mined') > 0) {
this.logger
.warn(`Transaction was not mined within 750 seconds, please make sure your transaction was properly sent. Be aware that
it might still be mined. transactionHash:${txHash}`);
fs.appendFileSync(
this.manuallyCheck,
`transactionHash:${txHash} to:${to} data:${data}\n`
);
return { transactionHash: txHash };
}
error = `Send Signed Transaction Failed TxHash:${txHash}`;
errorInfo = err;
}
this.logger.error(error, errorInfo);
this.logger.error('RawTx that failed', rawTx);
throw new CustomError(`Transaction Failed: ${error} ${stack}`, errorInfo);
}
};