forked from dcSpark/paima-dice
-
Notifications
You must be signed in to change notification settings - Fork 2
/
change-db.js
57 lines (51 loc) · 1.79 KB
/
change-db.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
const fs = require('fs');
const https = require('https');
// RPC command
const getBlockHeight = (url, command) =>
new Promise((resolve, reject) => {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': JSON.stringify(command).length,
},
};
const req = https.request(url, options, response => {
let result = '';
response.on('data', chunk => (result += chunk));
response.on('end', () => resolve(parseInt(JSON.parse(result).result.number, 16)));
});
req.on('error', err => reject(err));
req.write(JSON.stringify(command));
req.end();
});
// Update .env START_BLOCKHEIGHT with latest value from RPC command: "eth_getBlockByNumber"
const updateEnvFile = async file => {
const dataEnv = await fs.promises.readFile(__dirname + '/' + file, 'utf8');
const url = dataEnv.match(/CHAIN_URI="(.+)"/)[1];
if (!url) throw new Error('CHAIN_URI not found');
const START_BLOCKHEIGHT = await getBlockHeight(url, {
jsonrpc: '2.0',
method: 'eth_getBlockByNumber',
params: ['latest', false],
id: 1,
});
const ndataEnv = dataEnv.replace(
/START_BLOCKHEIGHT="\d+"/,
`START_BLOCKHEIGHT="${START_BLOCKHEIGHT}"`
);
await fs.promises.writeFile(file, ndataEnv, 'utf8');
};
// Update docker compose volume with unique new name.
const updateDockerFile = async file => {
const data = await fs.promises.readFile(__dirname + '/' + file, 'utf8');
const ndata = data.replace(/generic-.+?-db/g, 'generic-' + new Date().getTime() + '-db');
await fs.promises.writeFile(file, ndata, 'utf8');
};
const start = async () => {
await updateEnvFile('../.env.development');
await updateDockerFile('db/docker/docker-compose.yml');
};
start()
.then()
.catch(e => console.log('Error:', e));