// tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable import { AwaitTransactionSuccessOpts, ContractFunctionObj, ContractTxFunctionObj, SendTransactionOpts, BaseContract, SubscriptionManager, PromiseWithTransactionHash, methodAbiToFunctionSignature, } from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, BlockParamLiteral, BlockRange, CallData, ContractAbi, ContractArtifact, DecodedLogArgs, LogWithDecodedArgs, MethodAbi, TransactionReceiptWithDecodedLogs, TxData, TxDataPayable, SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; // tslint:enable:no-unused-variable export type ERC20TokenEventArgs = ERC20TokenTransferEventArgs | ERC20TokenApprovalEventArgs; export enum ERC20TokenEvents { Transfer = 'Transfer', Approval = 'Approval', } export interface ERC20TokenTransferEventArgs extends DecodedLogArgs { _from: string; _to: string; _value: BigNumber; } export interface ERC20TokenApprovalEventArgs extends DecodedLogArgs { _owner: string; _spender: string; _value: BigNumber; } /* istanbul ignore next */ // tslint:disable:no-parameter-reassignment // tslint:disable-next-line:class-name export class ERC20TokenContract extends BaseContract { /** * @ignore */ public static deployedBytecode: string | undefined; public static contractName = 'ERC20Token'; private readonly _methodABIIndex: { [name: string]: number } = {}; private readonly _subscriptionManager: SubscriptionManager; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, supportedProvider: SupportedProvider, txDefaults: Partial, logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, ): Promise { assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [ schemas.addressSchema, schemas.numberSchema, schemas.jsNumber, ]); if (artifact.compilerOutput === undefined) { throw new Error('Compiler output not found in the artifact file'); } const provider = providerUtils.standardizeOrThrow(supportedProvider); const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; if (Object.keys(logDecodeDependencies) !== undefined) { for (const key of Object.keys(logDecodeDependencies)) { logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; } } return ERC20TokenContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly); } public static async deployAsync( bytecode: string, abi: ContractAbi, supportedProvider: SupportedProvider, txDefaults: Partial, logDecodeDependencies: { [contractName: string]: ContractAbi }, ): Promise { assert.isHexString('bytecode', bytecode); assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema, [ schemas.addressSchema, schemas.numberSchema, schemas.jsNumber, ]); const provider = providerUtils.standardizeOrThrow(supportedProvider); const constructorAbi = BaseContract._lookupConstructorAbi(abi); [] = BaseContract._formatABIDataItemList(constructorAbi.inputs, [], BaseContract._bigNumberToString); const iface = new ethers.utils.Interface(abi); const deployInfo = iface.deployFunction; const txData = deployInfo.encode(bytecode, []); const web3Wrapper = new Web3Wrapper(provider); const txDataWithDefaults = await BaseContract._applyDefaultsToContractTxDataAsync( { data: txData, ...txDefaults, }, web3Wrapper.estimateGasAsync.bind(web3Wrapper), ); const txHash = await web3Wrapper.sendTransactionAsync(txDataWithDefaults); logUtils.log(`transactionHash: ${txHash}`); const txReceipt = await web3Wrapper.awaitTransactionSuccessAsync(txHash); logUtils.log(`ERC20Token successfully deployed at ${txReceipt.contractAddress}`); const contractInstance = new ERC20TokenContract( txReceipt.contractAddress as string, provider, txDefaults, logDecodeDependencies, ); contractInstance.constructorArgs = []; return contractInstance; } /** * @returns The contract ABI */ public static ABI(): ContractAbi { const abi = [ { constant: false, inputs: [ { name: '_spender', type: 'address', }, { name: '_value', type: 'uint256', }, ], name: 'approve', outputs: [ { name: '', type: 'bool', }, ], payable: false, stateMutability: 'nonpayable', type: 'function', }, { constant: true, inputs: [], name: 'totalSupply', outputs: [ { name: '', type: 'uint256', }, ], payable: false, stateMutability: 'view', type: 'function', }, { constant: false, inputs: [ { name: '_from', type: 'address', }, { name: '_to', type: 'address', }, { name: '_value', type: 'uint256', }, ], name: 'transferFrom', outputs: [ { name: '', type: 'bool', }, ], payable: false, stateMutability: 'nonpayable', type: 'function', }, { constant: true, inputs: [ { name: '_owner', type: 'address', }, ], name: 'balanceOf', outputs: [ { name: '', type: 'uint256', }, ], payable: false, stateMutability: 'view', type: 'function', }, { constant: false, inputs: [ { name: '_to', type: 'address', }, { name: '_value', type: 'uint256', }, ], name: 'transfer', outputs: [ { name: '', type: 'bool', }, ], payable: false, stateMutability: 'nonpayable', type: 'function', }, { constant: true, inputs: [ { name: '_owner', type: 'address', }, { name: '_spender', type: 'address', }, ], name: 'allowance', outputs: [ { name: '', type: 'uint256', }, ], payable: false, stateMutability: 'view', type: 'function', }, { anonymous: false, inputs: [ { name: '_from', type: 'address', indexed: true, }, { name: '_to', type: 'address', indexed: true, }, { name: '_value', type: 'uint256', indexed: false, }, ], name: 'Transfer', outputs: [], type: 'event', }, { anonymous: false, inputs: [ { name: '_owner', type: 'address', indexed: true, }, { name: '_spender', type: 'address', indexed: true, }, { name: '_value', type: 'uint256', indexed: false, }, ], name: 'Approval', outputs: [], type: 'event', }, ] as ContractAbi; return abi; } public getFunctionSignature(methodName: string): string { const index = this._methodABIIndex[methodName]; const methodAbi = ERC20TokenContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion const functionSignature = methodAbiToFunctionSignature(methodAbi); return functionSignature; } public getABIDecodedTransactionData(methodName: string, callData: string): T { const functionSignature = this.getFunctionSignature(methodName); const self = (this as any) as ERC20TokenContract; const abiEncoder = self._lookupAbiEncoder(functionSignature); const abiDecodedCallData = abiEncoder.strictDecode(callData); return abiDecodedCallData; } public getABIDecodedReturnData(methodName: string, callData: string): T { const functionSignature = this.getFunctionSignature(methodName); const self = (this as any) as ERC20TokenContract; const abiEncoder = self._lookupAbiEncoder(functionSignature); const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); return abiDecodedCallData; } public getSelector(methodName: string): string { const functionSignature = this.getFunctionSignature(methodName); const self = (this as any) as ERC20TokenContract; const abiEncoder = self._lookupAbiEncoder(functionSignature); return abiEncoder.getSelector(); } /** * `msg.sender` approves `_spender` to spend `_value` tokens * @param _spender The address of the account able to transfer the tokens * @param _value The amount of wei to be approved for transfer * @returns Always true if the call has enough gas to complete execution */ public approve(_spender: string, _value: BigNumber): ContractTxFunctionObj { const self = (this as any) as ERC20TokenContract; assert.isString('_spender', _spender); assert.isBigNumber('_value', _value); const functionSignature = 'approve(address,uint256)'; return { async sendTransactionAsync( txData?: Partial | undefined, opts: SendTransactionOpts = { shouldValidate: true }, ): Promise { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( { ...txData, data: this.getABIEncodedTransactionData() }, this.estimateGasAsync.bind(this), ); if (opts.shouldValidate !== false) { await this.callAsync(txDataWithDefaults); } return self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); }, awaitTransactionSuccessAsync( txData?: Partial, opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, ): PromiseWithTransactionHash { return self._promiseWithTransactionHash(this.sendTransactionAsync(txData, opts), opts); }, async estimateGasAsync(txData?: Partial | undefined): Promise { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({ ...txData, data: this.getABIEncodedTransactionData(), }); return self._web3Wrapper.estimateGasAsync(txDataWithDefaults); }, async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { ...callData, data: this.getABIEncodedTransactionData() }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); return abiEncoder.strictDecodeReturnValue(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, [_spender.toLowerCase(), _value]); }, }; } /** * Query total supply of token * @returns Total supply of token */ public totalSupply(): ContractFunctionObj { const self = (this as any) as ERC20TokenContract; const functionSignature = 'totalSupply()'; return { async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { ...callData, data: this.getABIEncodedTransactionData() }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); return abiEncoder.strictDecodeReturnValue(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, []); }, }; } /** * send `value` token to `to` from `from` on the condition it is approved by `from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @returns True if transfer was successful */ public transferFrom(_from: string, _to: string, _value: BigNumber): ContractTxFunctionObj { const self = (this as any) as ERC20TokenContract; assert.isString('_from', _from); assert.isString('_to', _to); assert.isBigNumber('_value', _value); const functionSignature = 'transferFrom(address,address,uint256)'; return { async sendTransactionAsync( txData?: Partial | undefined, opts: SendTransactionOpts = { shouldValidate: true }, ): Promise { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( { ...txData, data: this.getABIEncodedTransactionData() }, this.estimateGasAsync.bind(this), ); if (opts.shouldValidate !== false) { await this.callAsync(txDataWithDefaults); } return self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); }, awaitTransactionSuccessAsync( txData?: Partial, opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, ): PromiseWithTransactionHash { return self._promiseWithTransactionHash(this.sendTransactionAsync(txData, opts), opts); }, async estimateGasAsync(txData?: Partial | undefined): Promise { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({ ...txData, data: this.getABIEncodedTransactionData(), }); return self._web3Wrapper.estimateGasAsync(txDataWithDefaults); }, async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { ...callData, data: this.getABIEncodedTransactionData() }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); return abiEncoder.strictDecodeReturnValue(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, [_from.toLowerCase(), _to.toLowerCase(), _value]); }, }; } /** * Query the balance of owner * @param _owner The address from which the balance will be retrieved * @returns Balance of owner */ public balanceOf(_owner: string): ContractFunctionObj { const self = (this as any) as ERC20TokenContract; assert.isString('_owner', _owner); const functionSignature = 'balanceOf(address)'; return { async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { ...callData, data: this.getABIEncodedTransactionData() }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); return abiEncoder.strictDecodeReturnValue(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, [_owner.toLowerCase()]); }, }; } /** * send `value` token to `to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @returns True if transfer was successful */ public transfer(_to: string, _value: BigNumber): ContractTxFunctionObj { const self = (this as any) as ERC20TokenContract; assert.isString('_to', _to); assert.isBigNumber('_value', _value); const functionSignature = 'transfer(address,uint256)'; return { async sendTransactionAsync( txData?: Partial | undefined, opts: SendTransactionOpts = { shouldValidate: true }, ): Promise { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( { ...txData, data: this.getABIEncodedTransactionData() }, this.estimateGasAsync.bind(this), ); if (opts.shouldValidate !== false) { await this.callAsync(txDataWithDefaults); } return self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); }, awaitTransactionSuccessAsync( txData?: Partial, opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, ): PromiseWithTransactionHash { return self._promiseWithTransactionHash(this.sendTransactionAsync(txData, opts), opts); }, async estimateGasAsync(txData?: Partial | undefined): Promise { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({ ...txData, data: this.getABIEncodedTransactionData(), }); return self._web3Wrapper.estimateGasAsync(txDataWithDefaults); }, async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { ...callData, data: this.getABIEncodedTransactionData() }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); return abiEncoder.strictDecodeReturnValue(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, [_to.toLowerCase(), _value]); }, }; } public allowance(_owner: string, _spender: string): ContractFunctionObj { const self = (this as any) as ERC20TokenContract; assert.isString('_owner', _owner); assert.isString('_spender', _spender); const functionSignature = 'allowance(address,address)'; return { async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { ...callData, data: this.getABIEncodedTransactionData() }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); return abiEncoder.strictDecodeReturnValue(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, [_owner.toLowerCase(), _spender.toLowerCase()]); }, }; } /** * Subscribe to an event type emitted by the ERC20Token contract. * @param eventName The ERC20Token contract event you would like to subscribe to. * @param indexFilterValues An object where the keys are indexed args returned by the event and * the value is the value you are interested in. E.g `{maker: aUserAddressHex}` * @param callback Callback that gets called when a log is added/removed * @param isVerbose Enable verbose subscription warnings (e.g recoverable network issues encountered) * @return Subscription token used later to unsubscribe */ public subscribe( eventName: ERC20TokenEvents, indexFilterValues: IndexedFilterValues, callback: EventCallback, isVerbose: boolean = false, blockPollingIntervalMs?: number, ): string { assert.doesBelongToStringEnum('eventName', eventName, ERC20TokenEvents); assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); assert.isFunction('callback', callback); const subscriptionToken = this._subscriptionManager.subscribe( this.address, eventName, indexFilterValues, ERC20TokenContract.ABI(), callback, isVerbose, blockPollingIntervalMs, ); return subscriptionToken; } /** * Cancel a subscription * @param subscriptionToken Subscription token returned by `subscribe()` */ public unsubscribe(subscriptionToken: string): void { this._subscriptionManager.unsubscribe(subscriptionToken); } /** * Cancels all existing subscriptions */ public unsubscribeAll(): void { this._subscriptionManager.unsubscribeAll(); } /** * Gets historical logs without creating a subscription * @param eventName The ERC20Token contract event you would like to subscribe to. * @param blockRange Block range to get logs from. * @param indexFilterValues An object where the keys are indexed args returned by the event and * the value is the value you are interested in. E.g `{_from: aUserAddressHex}` * @return Array of logs that match the parameters */ public async getLogsAsync( eventName: ERC20TokenEvents, blockRange: BlockRange, indexFilterValues: IndexedFilterValues, ): Promise>> { assert.doesBelongToStringEnum('eventName', eventName, ERC20TokenEvents); assert.doesConformToSchema('blockRange', blockRange, schemas.blockRangeSchema); assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); const logs = await this._subscriptionManager.getLogsAsync( this.address, eventName, blockRange, indexFilterValues, ERC20TokenContract.ABI(), ); return logs; } constructor( address: string, supportedProvider: SupportedProvider, txDefaults?: Partial, logDecodeDependencies?: { [contractName: string]: ContractAbi }, deployedBytecode: string | undefined = ERC20TokenContract.deployedBytecode, ) { super( 'ERC20Token', ERC20TokenContract.ABI(), address, supportedProvider, txDefaults, logDecodeDependencies, deployedBytecode, ); classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); this._subscriptionManager = new SubscriptionManager( ERC20TokenContract.ABI(), this._web3Wrapper, ); ERC20TokenContract.ABI().forEach((item, index) => { if (item.type === 'function') { const methodAbi = item as MethodAbi; this._methodABIIndex[methodAbi.name] = index; } }); } } // tslint:disable:max-file-line-count // tslint:enable:no-unbound-method no-parameter-reassignment no-consecutive-blank-lines ordered-imports align // tslint:enable:trailing-comma whitespace no-trailing-whitespace