-
Notifications
You must be signed in to change notification settings - Fork 0
/
dev.js
336 lines (319 loc) · 9.67 KB
/
dev.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
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
var argv = require('yargs').argv;
var fs = require('fs');
var path = require('path');
var readlineSync = require('readline-sync');
var Socket = require('net').Socket;
var solc = require('solc');
var spawn = require('child_process').spawn;
var Web3 = require('web3');
var webpack = require('webpack');
var geth, server;
process.on('exit', () => {
server && server.close();
geth && geth.close();
});
if (argv.sync) {
if (argv.network == 'mainnet') {
startMainnetServer(() => {});
}
else if (argv.network == 'testnet') {
startTestnetServer(argv.mine, () => {});
}
else if (argv.network == 'privnet') {
startPrivnetServer(() => {});
}
}
else if (argv.serve) {
buildFrontend();
}
else if (argv.deploy) {
var network = argv.network || '';
var mode = argv.contracts || 'all';
var socket = new Socket();
deploy(network, mode, socket, (error) => {
if (error) {
console.log(error.toString());
}
socket.end();
});
}
else {
console.error(
'\nCommands:\n'+
'\t--sync --network=[mainnet|testnet|privnet] [--mine]\n'+
'\t--serve\n'+
'\t--deploy --network=[mainnet|testnet|privnet] --contracts=[all|read]\n'
);
}
function startPrivnetServer(callback) {
geth = spawn('./geth', [
'--datadir', './privnet/node/datadir',
'init', './privnet/node/genesis.json'
]);
geth.on('close', (code) => {
geth = spawn('./geth', [
'--datadir=./privnet/node/datadir',
'--ipcpath='+getIPCPath(),
'--rpc',
'--rpccorsdomain=*',
'--nodiscover',
'--networkid=1337',
'--verbosity=4',
'js', './privnet/node/miner.js'
]);
callback();
geth.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
geth.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
})
}
function startTestnetServer(mine, callback) {
geth = spawn('./geth', [
'--datadir', './testnet/node/datadir',
'init', './testnet/node/genesis.json'
]);
geth.on('close', (code) => {
geth = spawn('./geth', [
'--datadir=./testnet/node/datadir',
'--ipcpath='+getIPCPath(),
'--networkid=3',
'--verbosity=4'
].concat( mine ? ['js', './testnet/node/miner.js'] : [] ));
// Create an account if this is a fresh sync with no accounts
if (mine) {
var socket = new Socket();
var web3 = new Web3(new Web3.providers.IpcProvider(getIPCPath(), socket));
(function getAccount() {
web3.eth.getAccounts((error, result) => {
if (error) {
setTimeout(getAccount, 1000);
}
else if (result.length == 0) {
web3.personal.newAccount(readlineSync.question(`> Password for new account: `, { hideEchoBack: true, mask: '' }), () => {
socket.end();
callback();
});
}
else {
socket.end();
callback();
}
});
})();
}
else {
callback();
}
geth.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
geth.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
})
}
function startMainnetServer(callback) {
geth = spawn('./geth', [
// '--ipcdisable',
// '--port=30304',
'--ipcpath='+getIPCPath(),
'--cache=1024',
'--fast',
'--verbosity=4'
]);
callback();
geth.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
geth.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
}
function buildFrontend() {
server = spawn('python', ['-m', 'SimpleHTTPServer']);
webpack({
devtool: 'source-map',
entry: './app/src/scripts/initialize.jsx',
module: {
preLoaders: [
{ test: /\.json$/, /*exclude: /node_modules/,*/ loader: 'json'},
],
loaders: [
{
test: /\.(js|jsx)$/,
// Brittle, but improves performance:
exclude: /node_modules/,
include: [
/app\/src/,
/node_modules\/autolinker/,
/node_modules\/marked/,
/node_modules\/medium-editor/,
/node_modules\/react/,
/node_modules\/web3-provider-engine/
],
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
output: { path: './app/dist/', filename: 'bundle.js' },
plugins: [
// TODO make use of these plugins configuration driven
// new webpack.DefinePlugin({
// 'process.env': {
// NODE_ENV: JSON.stringify('production')
// }
// }),
// new webpack.optimize.UglifyJsPlugin({
// compress: { warnings: true }
// })
],
watch: true
}, function (err, stats) {
var errors = stats.compilation.errors;
if (errors.length == 0) {
console.log(`Successful build at ${new Date().toLocaleTimeString()}`);
}
else {
console.log(`Failed build at ${new Date().toLocaleTimeString()}`);
console.log(stats.compilation.errors.toString());
}
});
}
function getIPCPath() {
// Geth Testnet uses a different IPC path than mainnet by default
// Overwrite the default so the integration with Mist doesn't break
if (process.platform === 'darwin') {
return path.resolve(process.env['HOME'], 'Library/Ethereum/geth.ipc');
}
else if (process.platform === 'freebsd' || process.platform === 'linux' || process.platform === 'sunos') {
return path.resolve(process.env['HOME'], '.ethereum/geth.ipc');
}
else if (process.platform === 'win32') {
return '\\\\.\\pipe\\geth.ipc';
}
else {
throw new Error('Unsupported platform');
}
}
function deploy(network, mode, socket, done) {
var web3 = new Web3(new Web3.providers.IpcProvider(getIPCPath(), socket));
var sources = {};
(function readContracts(base, sub) {
fs.readdirSync(base + sub).forEach(function(file) {
var path = sub + file;
if (fs.statSync(base + path).isDirectory()) {
readContracts(base, path + '/');
}
else if (path.slice(-4) == '.sol') {
sources[path] = fs.readFileSync(base + path, 'utf-8')
}
});
})('./contracts/', '');
console.log(`* Loaded ${Object.keys(sources).length} contracts`);
var compiled = {};
var compilation = solc.compile({sources: sources});
if (compilation.errors) {
console.log('x Failed to compile contracts');
done(compilation.errors);
return;
}
console.log('* Compiled contracts');
//!
// return;
var account;
var password;
var contracts = {};
var oldContracts = {};
(function getAccount() {
web3.eth.getAccounts((error, result) => {
if (error) {
setTimeout(getAccount, 1000);
}
else if (result.length == 0) {
throw new Error('No accounts available');
}
else {
account = result[0];
password = readlineSync.question(`> Account password (${account}): `, { hideEchoBack: true, mask: '' });
try {
oldContracts = JSON.parse(fs.readFileSync(path.resolve(network == 'mainnet' ? '' : network, 'contracts.json'), 'utf-8'));
}
catch (e) { }
if (mode == 'all') {
deployContract('Feed', [], () => {
deployContract('Read', [ contracts.Feed.address ], () => {
deployContract('Post', [ contracts.Feed.address ], () => {
let feedContract = web3.eth.contract(contracts.Feed.interface).at(contracts.Feed.address);
feedContract.updatePublishContract(contracts.Post.address, { from: account, gas: 200000 }, () => {
feedContract.updateChannelMinimum(0, 1, { from: account, gas: 200000 }, writeContracts);
});
})
});
});
}
else if (mode == 'read') {
contracts = {
'Feed': oldContracts['Feed'],
'Post': oldContracts['Post']
};
deployContract('Read', [ contracts.Feed.address ], writeContracts);
}
else {
throw new Error(`Deploy mode ${mode} not defined`);
}
}
});
})();
function deployContract(symbolName, constructorArgs, callback) {
var compiledContract = compilation.contracts[symbolName + '.sol:'+symbolName];
var interface = JSON.parse(compiledContract.interface);
var bytecode = compiledContract.bytecode;
var dependencies = {};
Object.keys(contracts).forEach((symbol) => {
dependencies[symbol] = contracts[symbol].address;
});
var contract = web3.eth.contract(interface);
bytecode = contract.new.getData.apply(this, constructorArgs.concat({
data: solc.linkBytecode(bytecode, dependencies)
}));
web3.personal.unlockAccount(account, password, 300, (error) => {
if (error) {
done(error.toString());
return;
}
web3.eth.estimateGas({data: bytecode, from: account}, (error, gasEstimate) => {
if (error) {
done(error.toString());
return;
}
contract.new({data: bytecode, from: account, gas: gasEstimate + 100000}, (error, result) => {
if (error) {
done(error.toString());
return;
}
if (result.address && !contracts.hasOwnProperty(symbolName)) {
contracts[symbolName] = {
address: result.address,
interface: interface
};
console.log(`* Deployed ${symbolName} contract`);
callback();
}
});
});
});
}
function writeContracts() {
var directory = network == 'mainnet' ? '' : network;
var filepath = path.resolve(process.cwd(), directory, 'contracts.json');
fs.writeFileSync(filepath, JSON.stringify(contracts));
console.log(`* Contract interfaces written to: ${filepath}`);
done();
}
}