-
Notifications
You must be signed in to change notification settings - Fork 228
/
deploymentUtils.js
102 lines (94 loc) · 2.32 KB
/
deploymentUtils.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
const {
web3Home,
web3Foreign,
deploymentPrivateKey,
FOREIGN_RPC_URL,
HOME_RPC_URL,
GAS_LIMIT,
GAS_PRICE,
GET_RECEIPT_INTERVAL_IN_MILLISECONDS
} = require('./web3');
const Tx = require('ethereumjs-tx');
const Web3Utils = require('web3-utils');
const fetch = require('node-fetch');
async function deployContract(contractJson, args, {from, network, nonce}) {
let web3, url;
if(network === 'foreign'){
web3 = web3Foreign
url = FOREIGN_RPC_URL
} else {
web3 = web3Home
url = HOME_RPC_URL
}
const options = {
from,
gasPrice: GAS_PRICE,
gas: GAS_LIMIT
};
let instance = new web3.eth.Contract(contractJson.abi, options);
const result = await instance.deploy({
data: contractJson.bytecode,
arguments: args
}).encodeABI()
const tx = await sendRawTx({
data: result,
nonce: Web3Utils.toHex(nonce),
to: null,
privateKey: deploymentPrivateKey,
url
})
if(tx.status !== '0x1'){
throw new Error('Tx failed');
}
instance.options.address = tx.contractAddress;
instance.deployedBlockNumber = tx.blockNumber
return instance;
}
async function sendRawTx({data, nonce, to, privateKey, url}) {
var rawTx = {
nonce,
gasPrice: Web3Utils.toHex(GAS_PRICE),
gasLimit: Web3Utils.toHex('6700000'),
to,
data
}
var tx = new Tx(rawTx);
tx.sign(privateKey);
var serializedTx = tx.serialize();
const txHash = await sendNodeRequest(url, "eth_sendRawTransaction", '0x' + serializedTx.toString('hex'));
const receipt = await getReceipt(txHash, url);
return receipt
}
async function sendNodeRequest(url, method, signedData){
const request = await fetch(url, {
headers: {
'Content-type': 'application/json'
},
method: 'POST',
body: JSON.stringify({
jsonrpc: "2.0",
method,
params: [signedData],
id: 1
})
});
const json = await request.json()
return json.result;
}
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function getReceipt(txHash, url) {
await timeout(GET_RECEIPT_INTERVAL_IN_MILLISECONDS);
let receipt = await sendNodeRequest(url, "eth_getTransactionReceipt", txHash);
if(receipt === null) {
receipt = await getReceipt(txHash, url);
}
return receipt;
}
module.exports = {
deployContract,
sendNodeRequest,
getReceipt,
sendRawTx
}