Skip to content

Instantly share code, notes, and snippets.

@kermankohli
Last active October 28, 2018 07:13
Show Gist options
  • Save kermankohli/48a218173c83415926764bb7948481d0 to your computer and use it in GitHub Desktop.
Save kermankohli/48a218173c83415926764bb7948481d0 to your computer and use it in GitHub Desktop.
Contract.mustache
import { promisify } from '@0xproject/utils';
import { BigNumber } from 'bignumber.js';
import * as Web3 from 'web3';
import { {{contractName}} as ContractArtifacts } from '../abi/ts/{{contractName}}';
import { BaseContract, CONTRACT_WRAPPER_ERRORS } from '@your-project/base-contract';
import { TxData, TxDataPayable, classUtils } from '@your-project/types';
import { Web3Utils } from '../../utils/Web3Utils';
export class {{contractName}}Contract extends BaseContract {
{{#each methods}}
{{#this.constant}}
{{> call contractName=../contractName}}
{{/this.constant}}
{{^this.constant}}
{{> tx contractName=../contractName}}
{{/this.constant}}
{{/each}}
async deploy(...args: any[]): Promise<any> {
const wrapper = this;
return new Promise((resolve, reject) => {
wrapper.web3ContractInstance.new(
wrapper.defaults,
(err: string, contract: Web3.ContractInstance) => {
if (err) {
reject(err);
} else if (contract.address) {
wrapper.web3ContractInstance = wrapper.web3ContractInstance.at(contract.address);
wrapper.address = contract.address;
resolve();
}
},
);
});
}
static async deployed(web3: Web3, defaults: Partial<TxData>): Promise<{{contractName}}Contract> {
const currentNetwork = web3.version.network;
const { abi, networks }: { abi: any; networks: any } = ContractArtifacts;
const web3ContractInstance = web3.eth.contract(abi).at(networks[currentNetwork].address);
return new {{contractName}}Contract(web3ContractInstance, defaults);
}
static async at(
address: string,
web3: Web3,
defaults: Partial<TxData>,
): Promise<{{contractName}}Contract> {
const { abi }: { abi: any } = ContractArtifacts;
const web3Utils = new Web3Utils(web3);
const contractExists = await web3Utils.doesContractExistAtAddressAsync(address);
const currentNetwork = await web3Utils.getNetworkIdAsync();
if (contractExists) {
const web3ContractInstance = web3.eth.contract(abi).at(address);
return new {{contractName}}Contract(web3ContractInstance, defaults);
} else {
throw new Error(
CONTRACT_WRAPPER_ERRORS.CONTRACT_NOT_FOUND_ON_NETWORK('{{contractName}}', currentNetwork),
);
}
}
constructor(web3ContractInstance: Web3.ContractInstance, defaults: Partial<TxData>) {
super(web3ContractInstance, defaults);
classUtils.bindAll(this, ['web3ContractInstance', 'defaults']);
}
} // tslint:disable:max-file-line-count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment