update web3.js

This commit is contained in:
Iuri Matias 2018-01-05 15:10:47 -05:00
parent ae28df8f8e
commit 59c3d82260
14 changed files with 277 additions and 164 deletions

View File

@ -1,3 +1,4 @@
<%- className %>Abi = <%- abi %>;
<%- className %>Contract = web3.eth.contract(<%- className %>Abi);
<%- className %> = <%= className %>Contract.at('<%- contract.deployedAddress %>');
<%- className %> = new web3.eth.Contract(<%- className %>Abi);
<%- className %>.options.address = '<%- contract.deployedAddress %>';
<%- className %>.address = '<%- contract.deployedAddress %>';

View File

@ -1,4 +1,5 @@
let async = require('async');
//require("../utils/debug_util.js")(__filename, async);
let RunCode = require('../core/runCode.js');
@ -11,10 +12,13 @@ class Deploy {
this.contractsManager = options.contractsManager;
this.logger = options.logger;
this.env = options.env;
this.chainConfig = options.chainConfig;
}
initTracker(cb) {
this.deployTracker = new DeployTracker({
logger: options.logger, chainConfig: options.chainConfig, web3: options.web3, env: this.env
});
logger: this.logger, chainConfig: this.chainConfig, web3: this.web3, env: this.env
}, cb);
}
determineArguments(suppliedArgs) {
@ -48,15 +52,34 @@ class Deploy {
if (contract.address !== undefined) {
contract.deployedAddress = contract.address;
if (this.deployTracker) {
self.deployTracker.trackContract(contract.className, contract.realRuntimeBytecode, realArgs, contract.address);
self.deployTracker.save();
}
self.logger.contractsState(self.contractsManager.contractsState());
return callback();
}
let trackedContract = self.deployTracker.getContract(contract.className, contract.realRuntimeBytecode, realArgs);
if (!this.deployTracker) {
return self.contractToDeploy(contract, params, callback);
}
if (trackedContract && this.web3.eth.getCode(trackedContract.address) !== "0x") {
let trackedContract = self.deployTracker.getContract(contract.className, contract.realRuntimeBytecode, realArgs);
if (!trackedContract) {
return self.contractToDeploy(contract, params, callback);
}
this.web3.eth.getCode(trackedContract.address, function(_getCodeErr, codeInChain) {
if (codeInChain !== "0x") {
self.contractAlreadyDeployed(contract, trackedContract, callback);
} else {
self.contractToDeploy(contract, params, callback);
}
});
}
contractAlreadyDeployed(contract, trackedContract, callback) {
const self = this;
self.logger.info(contract.className.bold.cyan + " already deployed at ".green + trackedContract.address.bold.cyan);
contract.deployedAddress = trackedContract.address;
self.logger.contractsState(self.contractsManager.contractsState());
@ -67,9 +90,11 @@ class Deploy {
RunCode.doEval(contractCode, self.web3);
return callback();
} else {
}
realArgs = self.determineArguments(params || contract.args);
contractToDeploy(contract, params, callback) {
const self = this;
let realArgs = self.determineArguments(params || contract.args);
this.deployContract(contract, realArgs, function (err, address) {
if (err) {
@ -145,11 +170,8 @@ class Deploy {
});
}
}
deployContract(contract, params, callback) {
let self = this;
let contractObject = this.web3.eth.contract(contract.abiDefinition);
let contractParams = (params || contract.args).slice();
@ -181,21 +203,42 @@ class Deploy {
contractCode = contractCode.replace(new RegExp(toReplace, "g"), deployedAddress);
}
// TODO: probably needs to be defaultAccount
// TODO: it wouldn't necessary be the first address
// use defined blockchain address or first address
contractParams.push({
//from: this.web3.eth.coinbase,
from: accounts[0],
data: "0x" + contractCode,
gas: contract.gas,
gasPrice: contract.gasPrice
});
let contractObject = new self.web3.eth.Contract(contract.abiDefinition);
let deployObject;
//if (contractParams === [] || contractParams === undefined || contractParams.length === 0) {
// console.dir("no params");
// deployObject = contractObject.deploy({data: "0x" + contractCode});
//} else {
try {
deployObject = contractObject.deploy({arguments: contractParams, data: "0x" + contractCode});
} catch(e) {
if (e.indexOf('Invalid number of parameters for "undefined"') >= 0) {
return callback(new Error("attempted to deploy " + contractObject.className + " without specifying parameters"));
} else {
return callback(new Error(e));
}
}
//}
//// // TODO: probably needs to be defaultAccount
//// // TODO: it wouldn't necessary be the first address
//// // use defined blockchain address or first address
//// contractParams.push({
//// //from: this.web3.eth.coinbase,
//// from: accounts[0],
//// data: "0x" + contractCode,
//// gas: contract.gas,
//// gasPrice: contract.gasPrice
//// });
self.logger.info("deploying " + contract.className.bold.cyan + " with ".green + contract.gas + " gas".green);
contractParams.push(function (err, transaction) {
deployObject.send({
from: accounts[0],
gas: contract.gas,
gasPrice: contract.gasPrice
}).on('receipt', function(receipt) {
if (err) {
self.logger.error("error deploying contract: " + contract.className.cyan);
let errMsg = err.toString();
@ -206,17 +249,19 @@ class Deploy {
contract.error = errMsg;
self.logger.contractsState(self.contractsManager.contractsState());
return callback(new Error(err));
} else if (transaction.address !== undefined) {
self.logger.info(contract.className.bold.cyan + " deployed at ".green + transaction.address.bold.cyan);
contract.deployedAddress = transaction.address;
contract.transactionHash = transaction.transactionHash;
} else if (receipt.contractAddress !== undefined) {
self.logger.info(contract.className.bold.cyan + " deployed at ".green + receipt.contractAddress.bold.cyan);
contract.deployedAddress = receipt.contractAddress;
contract.transactionHash = receipt.transactionHash;
self.logger.contractsState(self.contractsManager.contractsState());
return callback(null, transaction.address);
return callback(null, receipt.contractAddress);
}
});
self.logger.contractsState(self.contractsManager.contractsState());
});
contractObject["new"].apply(contractObject, contractParams);
//contractObject["new"].apply(contractObject, contractParams);
//contractObject["deploy"].apply(contractObject, contractParams);
//contractObject["deploy"].apply(contractObject, {arguments: contractParams});
});
}
@ -234,6 +279,7 @@ class Deploy {
self.logger.error("error deploying contracts");
self.logger.error(err.message);
self.logger.debug(err.stack);
console.dir(err);
}
self.logger.info("finished deploying contracts");
self.logger.trace(arguments);

View File

@ -1,4 +1,5 @@
let async = require('async');
//require("../utils/debug_util.js")(__filename, async);
let Deploy = require('./deploy.js');
let ContractsManager = require('./contracts.js');
let RunCode = require('../core/runCode.js');
@ -38,21 +39,42 @@ class DeployManager {
if (!self.web3) {
return callback(Error("no web3 instance found"));
}
if (self.web3.currentProvider.isConnected !== undefined && !self.web3.isConnected()) {
if (self.web3.currentProvider === undefined) {
self.logger.error(("Couldn't connect to an Ethereum node are you sure it's on?").red);
self.logger.info("make sure you have an Ethereum node or simulator running. e.g 'embark blockchain'".magenta);
return callback(Error("error connecting to blockchain node"));
}
if (self.web3.currentProvider.isConnected === undefined) {
self.web3.version.getNode(function (err, _version) {
self.web3.eth.getAccounts(function(err, _accounts) {
//if (err || !self.web3.currentProvider.connected) {
if (err) {
self.logger.error(("Couldn't connect to an Ethereum node are you sure it's on?").red);
self.logger.info("make sure you have an Ethereum node or simulator running. e.g 'embark blockchain'".magenta);
return callback(Error("error connecting to blockchain node"));
}
return callback(null, contractsManager, self.web3);
});
} else {
return callback(null, contractsManager, self.web3);
}
//// //f (self.web3.currentProvider.isConnected !== undefined && !self.web3.isConnected()) {
//// console.dir('----------------');
//// console.dir(self.web3.currentProvider);
//// console.dir('----------------');
//// if (self.web3.currentProvider !== undefined && !self.web3.currentProvider.connected) {
//// self.logger.error(("Couldn't connect to an Ethereum node are you sure it's on?").red);
//// self.logger.info("make sure you have an Ethereum node or simulator running. e.g 'embark blockchain'".magenta);
//// return callback(Error("error connecting to blockchain node"));
//// }
//// //if (self.web3.currentProvider.isConnected === undefined) {
//// // self.web3.version.getNode(function (err, _version) {
//// // if (err) {
//// // return callback(Error("error connecting to blockchain node"));
//// // }
//// // return callback(null, contractsManager, self.web3);
//// // });
//// //} else {
//// return callback(null, contractsManager, self.web3);
//// //}
},
function setDefaultAccount(contractsManager, web3, callback) {
web3.eth.getAccounts(function (err, accounts) {
@ -74,12 +96,15 @@ class DeployManager {
chainConfig: self.chainConfig,
env: self.config.env
});
deploy.initTracker(function() {
deploy.deployAll(function (err) {
if (!err) {
self.events.emit('contractsDeployed', contractsManager);
}
callback(null, contractsManager, web3);
});
});
},
function runAfterDeployCommands(contractsManager, web3, callback) {
let afterDeployCmds = self.config.contractsConfig.afterDeploy || [];

View File

@ -1,7 +1,8 @@
let fs = require('../core/fs.js');
class DeployTracker {
constructor(options) {
constructor(options, cb) {
const self = this;
this.logger = options.logger;
this.env = options.env;
this.chainConfig = options.chainConfig;
@ -9,20 +10,22 @@ class DeployTracker {
if (this.chainConfig === false) {
this.currentChain = {contracts: []};
return;
return cb();
}
// TODO: need to make this async
let block = this.web3.eth.getBlock(0);
this.web3.eth.getBlock(0, function(err, block) {
let chainId = block.hash;
if (this.chainConfig[chainId] === undefined) {
this.chainConfig[chainId] = {contracts: {}};
if (self.chainConfig[chainId] === undefined) {
self.chainConfig[chainId] = {contracts: {}};
}
this.currentChain = this.chainConfig[chainId];
self.currentChain = self.chainConfig[chainId];
self.currentChain.name = self.env;
cb();
});
this.currentChain.name = this.env;
// TODO: add other params
//this.currentChain.networkId = "";
//this.currentChain.networkType = "custom"
@ -34,14 +37,14 @@ class DeployTracker {
}
trackContract(contractName, code, args, address) {
this.currentChain.contracts[this.web3.sha3(code + contractName + args.join(','))] = {
this.currentChain.contracts[this.web3.utils.sha3(code + contractName + args.join(','))] = {
name: contractName,
address: address
};
}
getContract(contractName, code, args) {
let contract = this.currentChain.contracts[this.web3.sha3(code + contractName + args.join(','))];
let contract = this.currentChain.contracts[this.web3.utils.sha3(code + contractName + args.join(','))];
if (contract && contract.address === undefined) {
return false;
}

View File

@ -191,7 +191,7 @@ class Engine {
}
self.servicesMonitor.addCheck('Ethereum', function (cb) {
if (self.web3.isConnected()) {
if (self.web3.connected) {
return cb({
name: (self.web3.version.node.split("/")[0] + " " + self.web3.version.node.split("/")[1].split("-")[0] + " (Ethereum)"),
status: 'on'
@ -201,11 +201,11 @@ class Engine {
}
});
this.registerModule('whisper', {
addCheck: this.servicesMonitor.addCheck.bind(this.servicesMonitor),
communicationConfig: this.config.communicationConfig,
web3: this.web3
});
//this.registerModule('whisper', {
// addCheck: this.servicesMonitor.addCheck.bind(this.servicesMonitor),
// communicationConfig: this.config.communicationConfig,
// web3: this.web3
//});
}
libraryManagerService(_options) {

View File

@ -1,4 +1,5 @@
var async = require('async');
//require("../utils/debug_util.js")(__filename, async);
var Web3 = require('web3');
var Engine = require('./engine.js');

View File

@ -11,6 +11,7 @@ class TestLogger {
logFunction() {
this.logs.push(arguments);
//console.dir(arguments[0]);
}
contractsState() {

View File

@ -50,7 +50,7 @@
"underscore": "^1.8.3",
"underscore.string": "^3.3.4",
"url-loader": "^0.6.2",
"web3": "^0.19.1",
"web3": "1.0.0-beta.27",
"webpack": "^2.6.1",
"window-size": "^1.1.0"
},

View File

@ -47,7 +47,7 @@ describe('embark.CodeGenerator', function() {
let withEmbarkJS = false;
it('should generate contract code', function() {
var contractCode = "\n__mainContext.__loadManagerInstance.execWhenReady(function() {\n SimpleStorageAbi = [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}];\nSimpleStorageContract = web3.eth.contract(SimpleStorageAbi);\nSimpleStorage = SimpleStorageContract.at('0x123');\n\n});\n__mainContext.__loadManagerInstance.execWhenReady(function() {\n FooAbi = [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}];\nFooContract = web3.eth.contract(FooAbi);\nFoo = FooContract.at('0x124');\n\n});\n";
var contractCode = "\n__mainContext.__loadManagerInstance.execWhenReady(function() {\n SimpleStorageAbi = [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}];\nSimpleStorage = new web3.eth.Contract(SimpleStorageAbi);\nSimpleStorage.options.address = '0x123';\nSimpleStorage.address = '0x123';\n\n});\n__mainContext.__loadManagerInstance.execWhenReady(function() {\n FooAbi = [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}];\nFoo = new web3.eth.Contract(FooAbi);\nFoo.options.address = '0x124';\nFoo.address = '0x124';\n\n});\n";
assert.equal(generator.generateContracts(withEmbarkJS), contractCode);
});
});

View File

@ -36,7 +36,7 @@
},
"Test": {
"onDeploy": [
"Test.changeAddress('$MyToken')"
"Test.methods.changeAddress('$MyToken')"
]
},
"MyToken": {
@ -55,8 +55,8 @@
}
},
"afterDeploy": [
"Test.changeAddress('$MyToken')",
"Test.changeAddress(web3.eth.accounts[0])"
"Test.methods.changeAddress('$MyToken')",
"web3.eth.getAccounts((err, accounts) => Test.methods.changeAddress(accounts[0]))"
]
},
"development": {

View File

@ -1,4 +1,5 @@
contract("AnotherStorage", function() {
this.timeout(0);
before(function(done) {
this.timeout(0);
var contractsConfig = {
@ -24,8 +25,8 @@ contract("AnotherStorage", function() {
});
it("set SimpleStorage address", function(done) {
AnotherStorage.simpleStorageAddress(function(err, result) {
assert.equal(result.toString(), SimpleStorage.address);
AnotherStorage.methods.simpleStorageAddress().call().then(function(result) {
assert.equal(result.toString(), SimpleStorage.options.address);
done();
});
});

View File

@ -1,4 +1,4 @@
describe("Test", function() {
contract("Test", function() {
before(function(done) {
this.timeout(0);
var contractsConfig = {
@ -7,14 +7,33 @@ describe("Test", function() {
},
"ZAMyLib2": {
"deploy": true
},
"SimpleStorage": {
args: [100]
},
"AnotherStorage": {
args: ["$SimpleStorage"]
},
"Token": {
deploy: false,
args: [1000]
},
"MyToken": {
instanceOf: "Token"
},
"MyToken2": {
instanceOf: "Token",
args: [2000]
}
};
EmbarkSpec.deployAll(contractsConfig, () => { done() });
});
it("should call library correctly", function(done) {
Test2.testAdd(function(err, result) {
assert.equal(result.toNumber(), 3);
Test2.methods.testAdd().call().then(function(result) {
assert.equal(result, 3);
done();
});
});

View File

@ -1,25 +1,40 @@
describe("SimpleStorage", function() {
contract("SimpleStorage", function() {
this.timeout(0);
before(function(done) {
this.timeout(0);
var contractsConfig = {
"SimpleStorage": {
args: [100]
},
"AnotherStorage": {
args: ["$SimpleStorage"]
},
"Token": {
deploy: false,
args: [1000]
},
"MyToken": {
instanceOf: "Token"
},
"MyToken2": {
instanceOf: "Token",
args: [2000]
}
};
EmbarkSpec.deployAll(contractsConfig, () => { done() });
});
it("should set constructor value", function(done) {
SimpleStorage.storedData(function(err, result) {
assert.equal(result.toNumber(), 100);
SimpleStorage.methods.storedData().call().then(function(result) {
assert.equal(result, 100);
done();
});
});
it("set storage value", function(done) {
SimpleStorage.set(150, function() {
SimpleStorage.get(function(err, result) {
assert.equal(result.toNumber(), 150);
SimpleStorage.methods.set(150).send({from: web3.eth.defaultAccount}).then(function() {
SimpleStorage.methods.get().call().then(function(result) {
assert.equal(result, 150);
done();
});
});

View File

@ -1,4 +1,5 @@
describe("Token", function() {
this.timeout(0);
before(function(done) {
this.timeout(0);
var contractsConfig = {
@ -20,12 +21,12 @@ describe("Token", function() {
args: [2000]
},
"AlreadyDeployedToken": {
"address": "0x123",
"address": "0xCAFECAFECAFECAFECAFECAFECAFECAFECAFECAFE",
instanceOf: "Token"
},
"Test": {
onDeploy: [
"Test.changeAddress('$MyToken', function(){})"
"Test.methods.changeAddress('$MyToken').send({from: web3.eth.defaultAccount})"
]
}
};
@ -38,32 +39,32 @@ describe("Token", function() {
});
it("not deploy MyToken and MyToken2", function(done) {
assert.notEqual(MyToken.address, "undefined");
assert.notEqual(MyToken2.address, "undefined");
assert.notEqual(MyToken.address, "");
assert.notEqual(MyToken2.address, "");
done();
});
it("set MyToken Balance correctly", function(done) {
MyToken._supply(function(err, result) {
assert.equal(result.toNumber(), 1000);
MyToken.methods._supply().call().then(function(result) {
assert.equal(result, 1000);
done();
});
});
it("set MyToken2 Balance correctly", function(done) {
MyToken2._supply(function(err, result) {
assert.equal(result.toNumber(), 2000);
MyToken2.methods._supply().call().then(function(result) {
assert.equal(result, 2000);
done();
});
});
it("get right address", function(done) {
assert.equal(AlreadyDeployedToken.address, "0x123");
assert.equal(AlreadyDeployedToken.address, "0xCAFECAFECAFECAFECAFECAFECAFECAFECAFECAFE");
done();
});
it("should use onDeploy", function(done) {
Test.addr(function(err, result) {
Test.methods.addr().call().then(function(result) {
assert.equal(result, MyToken.address)
done();
});