aboutsummaryrefslogtreecommitdiffstats
path: root/src/ts/contract_wrappers/contract_wrapper.ts
blob: 225cb960fef85f0c716a8f9073c91c0158698264 (plain) (blame)
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
import * as _ from 'lodash';
import contract = require('truffle-contract');
import {Web3Wrapper} from '../web3_wrapper';
import {ZeroExError} from '../types';
import {utils} from '../utils/utils';

export class ContractWrapper {
    public web3Wrapper: Web3Wrapper;
    constructor(web3Wrapper: Web3Wrapper) {
        this.web3Wrapper = web3Wrapper;
    }
    protected async instantiateContractIfExistsAsync(artifact: Artifact, address?: string): Promise<ContractInstance> {
        const c = await contract(artifact);
        const providerObj = this.web3Wrapper.getCurrentProvider();
        c.setProvider(providerObj);

        const networkIdIfExists = await this.web3Wrapper.getNetworkIdIfExistsAsync();
        const artifactNetworkConfigs = _.isUndefined(networkIdIfExists) ?
                                       undefined :
                                       artifact.networks[networkIdIfExists];
        let contractAddress;
        if (!_.isUndefined(address)) {
            contractAddress = address;
        } else if (!_.isUndefined(artifactNetworkConfigs)) {
            contractAddress = artifactNetworkConfigs.address;
        }

        if (!_.isUndefined(contractAddress)) {
            const doesContractExist = await this.web3Wrapper.doesContractExistAtAddressAsync(contractAddress);
            if (!doesContractExist) {
                throw new Error(ZeroExError.CONTRACT_DOES_NOT_EXIST);
            }
        }

        try {
            let contractInstance;
            if (_.isUndefined(address)) {
                contractInstance = await c.deployed();
            } else {
                contractInstance = await c.at(address);
            }
            return contractInstance;
        } catch (err) {
            const errMsg = `${err}`;
            if (_.includes(errMsg, 'not been deployed to detected network')) {
                throw new Error(ZeroExError.CONTRACT_DOES_NOT_EXIST);
            } else {
                utils.consoleLog(`Notice: Error encountered: ${err} ${err.stack}`);
                throw new Error(ZeroExError.UNHANDLED_ERROR);
            }
        }
    }
}