embark/packages/web3Connector/web3Connector.js
emizzle eb4da28a61 fix(@embark/core): Fix tests for shim/monorepo
When embark was running as module inside the dapp’s `node_modules`, the tests were failing due to several issues:
1. `web3` was not being set in the global namespace of vm2. `EmbarkJS.Blockchain.setProvider` was therefore failing because it relies on `global.web3` to be set. I guess somehow this works when the test app was running in a child tree of the executing program. maybe this is a security feature of vm2, but i’m not sure.
2. `embarkjs` provider code being injected to the vm twice. This really was the initial point of failure, as this piece of code is requiring embarkjs, so i’m assuming, but again not sure, that maybe it was getting a second instance of `EmbarkJS` which did not have it’s providers set up correctly (hence the error with `ENS provider not set`).

Fixes for those issues in this PR:
1. To circumvent the web3 issue, we are now setting `global.web3` for tests only (the global web3 accessible in the tests), and `web3` is now explicitly passed in to `EmbarkJS.Blockchain.setProvider`
2. To fix the `embarkjs` code being called twice, we are not re-injecting this code to the VM during test initialisations
2019-02-14 12:16:55 -05:00

59 lines
1.5 KiB
JavaScript

/*global Web3*/
const web3Connector = {};
web3Connector.init = function(_config) {
global.web3 = config.web3 || global.web3;
// Check if the global web3 object uses the old web3 (0.x)
if (global.web3 && typeof global.web3.version !== 'string') {
// If so, use a new instance using 1.0, but use its provider
this.web3 = new Web3(global.web3.currentProvider);
} else {
this.web3 = global.web3 || new Web3();
}
global.web3 = this.web3;
};
web3Connector.getInstance = function () {
return this.web3;
};
web3Connector.getAccounts = function () {
return this.web3.eth.getAccounts(...arguments);
};
web3Connector.getNewProvider = function (providerName, ...args) {
return new Web3.providers[providerName](...args);
};
web3Connector.setProvider = function (provider) {
return this.web3.setProvider(provider);
};
web3Connector.getCurrentProvider = function () {
return this.web3.currentProvider;
};
web3Connector.getDefaultAccount = function () {
return this.web3.eth.defaultAccount;
};
web3Connector.setDefaultAccount = function (account) {
this.web3.eth.defaultAccount = account;
};
web3Connector.newContract = function (options) {
return new this.web3.eth.Contract(options.abi, options.address);
};
web3Connector.send = function () {
return this.web3.eth.sendTransaction(...arguments);
};
web3Connector.toWei = function () {
return this.web3.toWei(...arguments);
};
web3Connector.getNetworkId = function () {
return this.web3.eth.net.getId();
};