-
Notifications
You must be signed in to change notification settings - Fork 12
/
txn.js
72 lines (66 loc) · 1.93 KB
/
txn.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
/**
* Transaction handling
* @module txn
*/
const utils = require('./utils');
function renderAsHex(value) {
return utils.addHexPrefix(value.toString('hex'));
}
/**
* Sign an unsigned transaction with the provided private key.
*
* If `tx.gas` is undefined, it will be estimated. If `tx.gasPrice` is
* undefined, a default is used. If `tx.nonce` is undefined, Web3 will
* retrieve the next nonce. And if `tx.chainId` is undefined, Web3 fills it
* in.
*
* Note that Web3 cannot fill in most of those blanks when not connected to
* a functioning node (i.e. "offline mode"), so those will have to be filled
* in by the UI or user prior to signing.
*
* @param {Web3} web3 - a web3 object.
* @param {Object} tx - an unsigned transaction.
* @param {Buffer} privateKey - a private key.
* @return {Promise<Object>} A signed transaction object with `messageHash`,
* `v`, `r`, `s`, and `rawTransaction` fields.
*/
async function signTransaction(web3, tx, privateKey) {
if (!utils.isValidPrivate(privateKey)) {
throw "Invalid key";
}
if (!tx.gas) {
let preliminary = await web3.eth.estimateGas(tx);
tx.gas = Math.floor(preliminary * 2.1);
}
let pk = renderAsHex(privateKey);
return web3.eth.accounts.signTransaction(tx, pk);
}
/**
* Forward a signed transaction to the blockchain.
* @param {Web3} web3 - a web3 object.
* @param {Object} signedTx - a signed transaction.
* @return {Promise}
*/
function sendSignedTransaction(web3, signedTx) {
let stx = signedTx.rawTransaction;
return new Promise((resolve, reject) => {
web3.eth
.sendSignedTransaction(stx)
.once('confirmation', (n, receipt) => {
if (receipt.status) {
resolve();
} else {
reject();
}
})
.on('error', (e) => {
// eslint-disable-next-line no-console
console.error(e);
reject();
});
});
}
module.exports = {
signTransaction,
sendSignedTransaction
}