-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
366 lines (337 loc) · 13 KB
/
index.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
var solc = require('solc')
const fs = require('fs')
var ethUtil = require('ethereumjs-util')
var menu = require('appendable-cli-menu')
require('dotenv').config()
const files = require("./files.js")
var config = require('./config.js')
var dynamicApi = require('./dynamic-api.js')
var scenarioName,
scenarioYamlFilename,
scenarioJsonFilename,
compiledContractsFilename,
deployedContractsFilename,
yaml2JsonObject,
contractCollection,
transactionCollection,
_events = 0,
compiledContracts,
safeCompiledContracts,
deployedContracts,
safeDeployedContracts,
finishedDeploying = 0,
returns = 0,
verbose = true
var Web3 = require('web3'), web3
var fromAcountIndex = process.env.ACCOUNT_INDEX || 0, fromAccount
var web3Provider = process.env.LEDGER_NODE || "http://localhost:8545"
function initWeb3() {
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
web3 = new Web3(new Web3.providers.HttpProvider(web3Provider));
fromAccount = web3.eth.accounts[fromAcountIndex]
}
}
initWeb3()
var meta = {
from: fromAccount
}
function writeFile(fileName, data) {
writeFileSync(fileName, data, function () { })
}
function writeFileSync(fileName, data, cb) {
fs.writeFile(fileName, data, "utf8", function (err) {
return cb()
})
}
function compileContractCollection(collectionIndex, contractCollection, cb) {
var input = {}
var collection = contractCollection[collectionIndex].contract
//console.log(collection)
var sources = collection.sources
var name = collection.name
sources.forEach(function (contract, index) {
fs.readFile(config.contractsDirectory + contract, 'utf8', function (err, data) {
input[contract] = data
if (index === sources.length - 1) {
let compiledContract = solc.compile({ sources: input }, 1)
let key = extractKey(name, compiledContract.contracts)
if (verbose) {
console.log("key", key, compiledContract, name)
console.log("======> Debug", compiledContract.contracts, key)
}
let abi = compiledContract.contracts[key].interface;
let bytecode = compiledContract.contracts[key].bytecode;
let gasEstimate = web3.eth.estimateGas({ data: bytecode });
let Contract = web3.eth.contract(JSON.parse(abi));
compiledContracts[compiledContracts.length] = {
contract: Contract,
name: key,
abi: abi,
bytecode: bytecode,
gasEstimate: gasEstimate,
index: collectionIndex,
preComputedAddress: computeContractAddress(collectionIndex)
}
safeCompiledContracts[safeCompiledContracts.length] = { name: key, abi: abi, bytecode: bytecode, gasEstimate: gasEstimate, index: collectionIndex, preComputedAddress: computeContractAddress(collectionIndex) }
//console.log("Compiled contract", name, compiledContracts.length, "of", contractCollection.length)
if (collectionIndex === contractCollection.length - 1) {
writeFileSync(compiledContractsFilename, JSON.stringify(safeCompiledContracts, null, 4), function () {
deployContracts(compiledContracts, 0, cb)
})
} else {
compileContractCollection(collectionIndex + 1, contractCollection, cb)
}
}
})
})
}
function extractKey(name, contracts) {
for (var key in contracts) {
if (contracts.hasOwnProperty(key)) {
if (key.split(":")[1] === name)
return key
}
}
}
function deployContracts(compiledContracts, deployIndex, _cb) {
console.log("DEPLOYING")
var context = compiledContracts[deployIndex]
var args = contractCollection[deployIndex].contract.args
var argValues = []
args.forEach(function (key) {
argValues[argValues.length] = getDeployedPoiValue(key)
})
function next() {
if (deployIndex === compiledContracts.length - 1) {
writeFile(deployedContractsFilename, JSON.stringify(safeDeployedContracts, null, 4))
if (transactionCollection.length > 0) {
performTransactions(deployedContracts, 0, _cb)
} else {
return _cb()
}
} else {
deployContracts(compiledContracts, deployIndex + 1, _cb)
}
}
var cb = function (err, Contract) {
var computedAddress = computeContractAddress(deployIndex)
if (!err) {
if (!Contract.address) {
console.log("Deployed", context.name)
} else {
deployedContracts[deployedContracts.length] = { name: context.name.split(":")[1], txid: Contract.transactionHash, address: Contract.address, contract: Contract, preComputedAddress: computedAddress }
safeDeployedContracts[safeDeployedContracts.length] = { name: context.name.split(":")[1], txid: Contract.transactionHash, address: Contract.address, preComputedAddress: computedAddress }
//watchContract(Contract, context.name.split(":")[1], _cb)
next()
}
} else {
console.log(err)
next()
}
}
//console.log(argValues)
context.contract.new(argValues, {
from: fromAccount,
data: context.bytecode,
gas: context.gasEstimate
}, cb)
}
function performTransactions(deployedContracts, transactionIndex, cb) {
var tx = transactionCollection[transactionIndex]
var target = deployedContracts.filter(function (contract) {
return contract.name === tx.where
})[0]
var targetContract = target.contract
var method = tx.call.split("(")[0]
//console.log(target.name, method, getDeployedPoiValue(tx.args[0]), transactionIndex)
var on = deployedContracts.filter(function (contract) { return contract.name === target.name })[0]
var dynamic = on.contract[method]
_events += 1
dynamic(getDeployedPoiValue(tx.args[0]), meta, function (err, result) {
returns = returns + 1
//console.log(_events, returns)
//console.log(target.name, "return value", result)
if (_events === returns) {
return cb()
}
})
if (transactionIndex === transactionCollection.length - 1) {
} else {
performTransactions(deployedContracts, transactionIndex + 1, cb)
}
}
function watchAllContracts() {
deployedContracts.forEach(function (context) {
console.log("Logging events for", context.name)
var events = context.contract.allEvents(function (err, log) {
console.log(context.name, log);
})
})
}
function watchContract(contract, name) {
return
console.log("Logging events for", name)
var events = contract.allEvents(function (err, log) {
console.log(name, log);
})
}
function getContractByName(name) {
return deployedContracts.filter(function (contract) { return contract.name === name })[0]["contract"]
}
function createFunctionCall(name, method, args, multiplier) {
var context = deployedContracts.filter(function (contract) { return contract.name === name })[0]
var dynamic = context.contract[method]
if (dynamic) {
args[args.length] = { from: fromAccount, gas: 3000000 }
args[args.length] = function (err, result) {
if (err) {
console.log(err.toString())
} else {
console.log("Called", name, method, "with", args.splice(0, args.length - 2))
console.log(" `- Txid", result)
}
}
return dynamic
} else {
console.log("Error")
}
}
function getDeployedPoiValue(key) {
var pieces = key.split(".")
if (pieces.length > 1) {
var poi = deployedContracts.filter(function (contract) { return contract.name == pieces[0] })[0]
return poi[pieces[1]]
} else return key
}
function computeContractAddress(providedIndex) {
console.log("Calculate address", providedIndex)
//process.exit()
var modifier = providedIndex || -1
var currentNonce = web3.eth.getTransactionCount(fromAccount) + modifier
console.log("current nonce", currentNonce, fromAccount)
//process.exit()
var calculated = ethUtil.generateAddress(fromAccount, currentNonce)
console.log("Calculated", calculated)
return ethUtil.bufferToHex(calculated)
}
function makeMenu(title, items, type, cb) {
var _menu = menu(title, cb)
items.forEach(function (item, index) {
_type = type
if (typeof (_type) === "object") {
_type = type[index]
item = item
}
_menu.add({ name: item, value: index, type: _type })
})
return _menu
}
function startEngine() {
process.stdout.write('\x1B[2J\x1B[0f');
if (process.argv[2] === "web") {
return startDynamicWebApi()
}
if (process.argv[2] === "info") {
return displayNetworkDetails()
}
makeMenu("Select a task", [
"Compile & Deploy Scenario",
"Compile & Deploy single Contract",
"Interact with deployed Contract CLI",
"Interact with deployed Contracts REST Api",
"Display Web3 Network Details"
], "Action", function (result) {
if (result.name === "Compile & Deploy Scenario") {
startCompileScenario()
} else if (result.name === "Compile & Deploy single Contract") {
startCompileContract()
} else if (result.name === "Interact with deployed Contract CLI") {
startDynamicApi()
} else if (result.name === "Interact with deployed Contracts REST Api") {
startDynamicWebApi()
} else if (result.name === "Display Web3 Network Details") {
displayNetworkDetails()
}
})
}
function displayNetworkDetails(){
var networkInfo = {
account: web3.eth.accounts[fromAcountIndex],
accountIndex: fromAcountIndex,
accountBalance: web3.eth.getBalance(web3.eth.accounts[fromAcountIndex]).toNumber(),
isMining: web3.eth.mining,
lastBlock: web3.eth.blockNumber,
provider: JSON.parse(JSON.stringify(web3._requestManager.provider)).host,
}
console.log(JSON.stringify(networkInfo, null, 4))
}
function startCompileScenario() {
dynamicApi.loadFiles(config.scenariosDirectory, ".yaml", function (files) {
_files = adjustFilenames(files, ".yaml")
makeMenu("Select Scenario", _files, "Scenario", function (result) {
scenarioName = result.name
initFiles(scenarioName, function () {
compileContractCollection(0, contractCollection, function () {
startEngine()
})
})
})
})
}
function startCompileContract() {
dynamicApi.loadFiles(config.contractsDirectory, ".sol", function (files) {
_files = adjustFilenames(files, ".sol")
makeMenu("Select Contract", _files, "Contract", function (result) {
console.log("Mocked")
startEngine()
})
})
}
function startDynamicApi() {
//var fork = require('child_process').fork
//var child = fork('./dynamic-api.js')
dynamicApi.exec()
}
function startDynamicWebApi() {
//var fork = require('child_process').fork
//var child = fork('./dynamic-api.js',['web'])
dynamicApi.exec(["web"])
}
function adjustFilenames(files, ext) {
var _files = []
files.forEach(function (file) {
var pieces = file.split("/")
_files[_files.length] = pieces[pieces.length - 1].replace(ext, "")
})
return _files
}
function initFiles(scenarioName, cb) {
//scenarioName = process.env.scenario || "Scenario2"
events = 0
contractCollection = []
scenarioYamlFilename = scenarioName + ".yaml"
scenarioJsonFilename = scenarioName + ".yaml.json"
compiledContractsFilename = scenarioName + ".compiled.json"
deployedContractsFilename = scenarioName + ".deployed.json"
yaml2JsonObject = dynamicApi.YAML.load(config.scenariosDirectory + scenarioYamlFilename)
contractCollection = yaml2JsonObject.filter(function (item) { return item.contract !== undefined })
transactionCollection = yaml2JsonObject.filter(function (item) { return item.contract === undefined || item.call })
writeFile(scenarioJsonFilename, JSON.stringify(yaml2JsonObject, null, 4))
compiledContracts = []
safeCompiledContracts = []
deployedContracts = []
safeDeployedContracts = []
finishedDeploying = 0
return cb()
}
if (!module.parent) {
startEngine()
}
module.exports.compiler = startEngine
module.exports.interact = dynamicApi.exec
module.exports.handleDynamicApiCall = dynamicApi.handleDynamicApiCall
module.exports.setDir = dynamicApi.setDir
module.exports.chooseAction = dynamicApi.chooseAction
module.exports.loadSelectedDeployment = dynamicApi.loadSelectedDeployment