diff options
author | Fabio Berger <me@fabioberger.com> | 2017-12-22 04:24:54 +0800 |
---|---|---|
committer | Fabio Berger <me@fabioberger.com> | 2017-12-22 04:24:54 +0800 |
commit | e01c0f054d2dbb043aec8b4cb8e1c47f83bd5eb9 (patch) | |
tree | 241b630db5044974cc17130f149ca64728d9c619 /packages/contracts/deploy | |
parent | d725de72861c6a6218c7f4822a339175a2da7403 (diff) | |
parent | cb3582289ff94857d5956bbd71dbf68ee3f42ecf (diff) | |
download | dexon-sol-tools-e01c0f054d2dbb043aec8b4cb8e1c47f83bd5eb9.tar.gz dexon-sol-tools-e01c0f054d2dbb043aec8b4cb8e1c47f83bd5eb9.tar.zst dexon-sol-tools-e01c0f054d2dbb043aec8b4cb8e1c47f83bd5eb9.zip |
Merge branch 'development' into fix/docLinks
* development:
Update and standardize contracts README
Add to CHANGELOG
Refactor toBaseUnitAmount so that it throws if user supplies unitAmount with too many decimals
Make assertion stricter so that one cannot submit invalid baseUnit amounts to `toUnitAmount`
Add some missed underscores, update changelog and comments
Add new underscore-privates rule to @0xproject/tslint-config and fix lint errors
# Conflicts:
# packages/website/ts/pages/documentation/documentation.tsx
# packages/website/ts/pages/shared/nested_sidebar_menu.tsx
Diffstat (limited to 'packages/contracts/deploy')
-rw-r--r-- | packages/contracts/deploy/src/compiler.ts | 80 | ||||
-rw-r--r-- | packages/contracts/deploy/src/deployer.ts | 66 | ||||
-rw-r--r-- | packages/contracts/deploy/src/utils/contract.ts | 46 |
3 files changed, 96 insertions, 96 deletions
diff --git a/packages/contracts/deploy/src/compiler.ts b/packages/contracts/deploy/src/compiler.ts index 333a2d0ce..02b8699b6 100644 --- a/packages/contracts/deploy/src/compiler.ts +++ b/packages/contracts/deploy/src/compiler.ts @@ -19,18 +19,18 @@ import {utils} from './utils/utils'; const SOLIDITY_FILE_EXTENSION = '.sol'; export class Compiler { - private contractsDir: string; - private networkId: number; - private optimizerEnabled: number; - private artifactsDir: string; - private contractSourcesIfExists?: ContractSources; - private solcErrors: Set<string>; + private _contractsDir: string; + private _networkId: number; + private _optimizerEnabled: number; + private _artifactsDir: string; + private _contractSourcesIfExists?: ContractSources; + private _solcErrors: Set<string>; /** * Recursively retrieves Solidity source code from directory. * @param dirPath Directory to search. * @return Mapping of contract name to contract source. */ - private static async getContractSourcesAsync(dirPath: string): Promise<ContractSources> { + private static async _getContractSourcesAsync(dirPath: string): Promise<ContractSources> { let dirContents: string[] = []; try { dirContents = await fsWrapper.readdirAsync(dirPath); @@ -52,7 +52,7 @@ export class Compiler { } } else { try { - const nestedSources = await Compiler.getContractSourcesAsync(contentPath); + const nestedSources = await Compiler._getContractSourcesAsync(contentPath); sources = { ...sources, ...nestedSources, @@ -69,7 +69,7 @@ export class Compiler { * @param source Source code of contract. * @return Solc compiler version. */ - private static parseSolidityVersion(source: string): string { + private static _parseSolidityVersion(source: string): string { const solcVersionMatch = source.match(/(?:solidity\s\^?)([0-9]{1,2}[.][0-9]{1,2}[.][0-9]{1,2})/); if (_.isNull(solcVersionMatch)) { throw new Error('Could not find Solidity version in source'); @@ -85,7 +85,7 @@ export class Compiler { * @param errMsg An error message from the compiled output. * @return The error message with directories truncated from the contract path. */ - private static getNormalizedErrMsg(errMsg: string): string { + private static _getNormalizedErrMsg(errMsg: string): string { const errPathMatch = errMsg.match(/(.*\.sol)/); if (_.isNull(errPathMatch)) { throw new Error('Could not find a path in error message'); @@ -101,26 +101,26 @@ export class Compiler { * @return An instance of the Compiler class. */ constructor(opts: CompilerOptions) { - this.contractsDir = opts.contractsDir; - this.networkId = opts.networkId; - this.optimizerEnabled = opts.optimizerEnabled; - this.artifactsDir = opts.artifactsDir; - this.solcErrors = new Set(); + this._contractsDir = opts.contractsDir; + this._networkId = opts.networkId; + this._optimizerEnabled = opts.optimizerEnabled; + this._artifactsDir = opts.artifactsDir; + this._solcErrors = new Set(); } /** * Compiles all Solidity files found in contractsDir and writes JSON artifacts to artifactsDir. */ public async compileAllAsync(): Promise<void> { - await this.createArtifactsDirIfDoesNotExistAsync(); - this.contractSourcesIfExists = await Compiler.getContractSourcesAsync(this.contractsDir); + await this._createArtifactsDirIfDoesNotExistAsync(); + this._contractSourcesIfExists = await Compiler._getContractSourcesAsync(this._contractsDir); - const contractBaseNames = _.keys(this.contractSourcesIfExists); + const contractBaseNames = _.keys(this._contractSourcesIfExists); const compiledContractPromises = _.map(contractBaseNames, async (contractBaseName: string): Promise<void> => { - return this.compileContractAsync(contractBaseName); + return this._compileContractAsync(contractBaseName); }); await Promise.all(compiledContractPromises); - this.solcErrors.forEach(errMsg => { + this._solcErrors.forEach(errMsg => { utils.consoleLog(errMsg); }); } @@ -128,14 +128,14 @@ export class Compiler { * Compiles contract and saves artifact to artifactsDir. * @param contractBaseName Name of contract with '.sol' extension. */ - private async compileContractAsync(contractBaseName: string): Promise<void> { - if (_.isUndefined(this.contractSourcesIfExists)) { + private async _compileContractAsync(contractBaseName: string): Promise<void> { + if (_.isUndefined(this._contractSourcesIfExists)) { throw new Error('Contract sources not yet initialized'); } - const source = this.contractSourcesIfExists[contractBaseName]; + const source = this._contractSourcesIfExists[contractBaseName]; const contractName = path.basename(contractBaseName, SOLIDITY_FILE_EXTENSION); - const currentArtifactPath = `${this.artifactsDir}/${contractName}.json`; + const currentArtifactPath = `${this._artifactsDir}/${contractName}.json`; const sourceHash = `0x${ethUtil.sha3(source).toString('hex')}`; let currentArtifactString: string; @@ -149,10 +149,10 @@ export class Compiler { currentArtifactString = await fsWrapper.readFileAsync(currentArtifactPath, opts); currentArtifact = JSON.parse(currentArtifactString); oldNetworks = currentArtifact.networks; - const oldNetwork: ContractData = oldNetworks[this.networkId]; + const oldNetwork: ContractData = oldNetworks[this._networkId]; shouldCompile = _.isUndefined(oldNetwork) || oldNetwork.keccak256 !== sourceHash || - oldNetwork.optimizer_enabled !== this.optimizerEnabled; + oldNetwork.optimizer_enabled !== this._optimizerEnabled; } catch (err) { shouldCompile = true; } @@ -164,7 +164,7 @@ export class Compiler { const input = { [contractBaseName]: source, }; - const solcVersion = Compiler.parseSolidityVersion(source); + const solcVersion = Compiler._parseSolidityVersion(source); const fullSolcVersion = binPaths[solcVersion]; const solcBinPath = `./../solc/solc_bin/${fullSolcVersion}`; const solcBin = require(solcBinPath); @@ -175,13 +175,13 @@ export class Compiler { sources: input, }; const compiled = solcInstance.compile(sourcesToCompile, - this.optimizerEnabled, - this.findImportsIfSourcesExist.bind(this)); + this._optimizerEnabled, + this._findImportsIfSourcesExist.bind(this)); if (!_.isUndefined(compiled.errors)) { _.each(compiled.errors, errMsg => { - const normalizedErrMsg = Compiler.getNormalizedErrMsg(errMsg); - this.solcErrors.add(normalizedErrMsg); + const normalizedErrMsg = Compiler._getNormalizedErrMsg(errMsg); + this._solcErrors.add(normalizedErrMsg); }); } @@ -192,7 +192,7 @@ export class Compiler { const contractData: ContractData = { solc_version: solcVersion, keccak256: sourceHash, - optimizer_enabled: this.optimizerEnabled, + optimizer_enabled: this._optimizerEnabled, abi, unlinked_binary, updated_at, @@ -204,14 +204,14 @@ export class Compiler { ...currentArtifact, networks: { ...oldNetworks, - [this.networkId]: contractData, + [this._networkId]: contractData, }, }; } else { newArtifact = { contract_name: contractName, networks: { - [this.networkId]: contractData, + [this._networkId]: contractData, }, }; } @@ -226,12 +226,12 @@ export class Compiler { * @param importPath Path to an imported dependency. * @return Import contents object containing source code of dependency. */ - private findImportsIfSourcesExist(importPath: string): ImportContents { - if (_.isUndefined(this.contractSourcesIfExists)) { + private _findImportsIfSourcesExist(importPath: string): ImportContents { + if (_.isUndefined(this._contractSourcesIfExists)) { throw new Error('Contract sources not yet initialized'); } const contractBaseName = path.basename(importPath); - const source = this.contractSourcesIfExists[contractBaseName]; + const source = this._contractSourcesIfExists[contractBaseName]; const importContents: ImportContents = { contents: source, }; @@ -240,10 +240,10 @@ export class Compiler { /** * Creates the artifacts directory if it does not already exist. */ - private async createArtifactsDirIfDoesNotExistAsync(): Promise<void> { - if (!fsWrapper.doesPathExistSync(this.artifactsDir)) { + private async _createArtifactsDirIfDoesNotExistAsync(): Promise<void> { + if (!fsWrapper.doesPathExistSync(this._artifactsDir)) { utils.consoleLog('Creating artifacts directory...'); - await fsWrapper.mkdirAsync(this.artifactsDir); + await fsWrapper.mkdirAsync(this._artifactsDir); } } } diff --git a/packages/contracts/deploy/src/deployer.ts b/packages/contracts/deploy/src/deployer.ts index 991504972..ea1de59d3 100644 --- a/packages/contracts/deploy/src/deployer.ts +++ b/packages/contracts/deploy/src/deployer.ts @@ -18,19 +18,19 @@ const EXTRA_GAS = 200000; export class Deployer { public web3Wrapper: Web3Wrapper; - private artifactsDir: string; - private jsonrpcPort: number; - private networkId: number; - private defaults: Partial<TxData>; + private _artifactsDir: string; + private _jsonrpcPort: number; + private _networkId: number; + private _defaults: Partial<TxData>; constructor(opts: DeployerOptions) { - this.artifactsDir = opts.artifactsDir; - this.jsonrpcPort = opts.jsonrpcPort; - this.networkId = opts.networkId; - const jsonrpcUrl = `http://localhost:${this.jsonrpcPort}`; + this._artifactsDir = opts.artifactsDir; + this._jsonrpcPort = opts.jsonrpcPort; + this._networkId = opts.networkId; + const jsonrpcUrl = `http://localhost:${this._jsonrpcPort}`; const web3Provider = new Web3.providers.HttpProvider(jsonrpcUrl); - this.defaults = opts.defaults; - this.web3Wrapper = new Web3Wrapper(web3Provider, this.defaults); + this._defaults = opts.defaults; + this.web3Wrapper = new Web3Wrapper(web3Provider, this._defaults); } /** * Loads contract artifact and deploys contract with given arguments. @@ -39,21 +39,21 @@ export class Deployer { * @return Deployed contract instance. */ public async deployAsync(contractName: string, args: any[] = []): Promise<Web3.ContractInstance> { - const contractArtifact: ContractArtifact = this.loadContractArtifactIfExists(contractName); - const contractData: ContractData = this.getContractDataFromArtifactIfExists(contractArtifact); + const contractArtifact: ContractArtifact = this._loadContractArtifactIfExists(contractName); + const contractData: ContractData = this._getContractDataFromArtifactIfExists(contractArtifact); const data = contractData.unlinked_binary; - const from = await this.getFromAddressAsync(); - const gas = await this.getAllowableGasEstimateAsync(data); + const from = await this._getFromAddressAsync(); + const gas = await this._getAllowableGasEstimateAsync(data); const txData = { - gasPrice: this.defaults.gasPrice, + gasPrice: this._defaults.gasPrice, from, data, gas, }; const abi = contractData.abi; - const web3ContractInstance = await this.deployFromAbiAsync(abi, args, txData); + const web3ContractInstance = await this._deployFromAbiAsync(abi, args, txData); utils.consoleLog(`${contractName}.sol successfully deployed at ${web3ContractInstance.address}`); - const contractInstance = new Contract(web3ContractInstance, this.defaults); + const contractInstance = new Contract(web3ContractInstance, this._defaults); return contractInstance; } /** @@ -64,7 +64,7 @@ export class Deployer { */ public async deployAndSaveAsync(contractName: string, args: any[] = []): Promise<Web3.ContractInstance> { const contractInstance = await this.deployAsync(contractName, args); - await this.saveContractDataToArtifactAsync(contractName, contractInstance.address, args); + await this._saveContractDataToArtifactAsync(contractName, contractInstance.address, args); return contractInstance; } /** @@ -74,7 +74,7 @@ export class Deployer { * @param txData Tx options used for deployment. * @return Promise that resolves to a web3 contract instance. */ - private async deployFromAbiAsync(abi: Web3.ContractAbi, args: any[], txData: Web3.TxData): Promise<any> { + private async _deployFromAbiAsync(abi: Web3.ContractAbi, args: any[], txData: Web3.TxData): Promise<any> { const contract: Web3.Contract<Web3.ContractInstance> = this.web3Wrapper.getContractFromAbi(abi); const deployPromise = new Promise((resolve, reject) => { /** @@ -99,10 +99,10 @@ export class Deployer { * @param contractAddress Contract address to save to artifact. * @param args Contract constructor arguments that will be encoded and saved to artifact. */ - private async saveContractDataToArtifactAsync(contractName: string, - contractAddress: string, args: any[]): Promise<void> { - const contractArtifact: ContractArtifact = this.loadContractArtifactIfExists(contractName); - const contractData: ContractData = this.getContractDataFromArtifactIfExists(contractArtifact); + private async _saveContractDataToArtifactAsync(contractName: string, + contractAddress: string, args: any[]): Promise<void> { + const contractArtifact: ContractArtifact = this._loadContractArtifactIfExists(contractName); + const contractData: ContractData = this._getContractDataFromArtifactIfExists(contractArtifact); const abi = contractData.abi; const encodedConstructorArgs = encoder.encodeConstructorArgsFromAbi(args, abi); const newContractData = { @@ -114,11 +114,11 @@ export class Deployer { ...contractArtifact, networks: { ...contractArtifact.networks, - [this.networkId]: newContractData, + [this._networkId]: newContractData, }, }; const artifactString = utils.stringifyWithFormatting(newArtifact); - const artifactPath = `${this.artifactsDir}/${contractName}.json`; + const artifactPath = `${this._artifactsDir}/${contractName}.json`; await fsWrapper.writeFileAsync(artifactPath, artifactString); } /** @@ -126,8 +126,8 @@ export class Deployer { * @param contractName Name of the contract, without the extension. * @return The contract artifact. */ - private loadContractArtifactIfExists(contractName: string): ContractArtifact { - const artifactPath = `${this.artifactsDir}/${contractName}.json`; + private _loadContractArtifactIfExists(contractName: string): ContractArtifact { + const artifactPath = `${this._artifactsDir}/${contractName}.json`; try { const contractArtifact: ContractArtifact = require(artifactPath); return contractArtifact; @@ -140,8 +140,8 @@ export class Deployer { * @param contractArtifact The contract artifact. * @return Network specific contract data. */ - private getContractDataFromArtifactIfExists(contractArtifact: ContractArtifact): ContractData { - const contractData = contractArtifact.networks[this.networkId]; + private _getContractDataFromArtifactIfExists(contractArtifact: ContractArtifact): ContractData { + const contractData = contractArtifact.networks[this._networkId]; if (_.isUndefined(contractData)) { throw new Error(`Data not found in artifact for contract: ${contractArtifact.contract_name}`); } @@ -151,13 +151,13 @@ export class Deployer { * Gets the address to use for sending a transaction. * @return The default from address. If not specified, returns the first address accessible by web3. */ - private async getFromAddressAsync(): Promise<string> { + private async _getFromAddressAsync(): Promise<string> { let from: string; - if (_.isUndefined(this.defaults.from)) { + if (_.isUndefined(this._defaults.from)) { const accounts = await this.web3Wrapper.getAvailableAddressesAsync(); from = accounts[0]; } else { - from = this.defaults.from; + from = this._defaults.from; } return from; } @@ -167,7 +167,7 @@ export class Deployer { * @param data Bytecode to estimate gas for. * @return Gas estimate for transaction data. */ - private async getAllowableGasEstimateAsync(data: string): Promise<number> { + private async _getAllowableGasEstimateAsync(data: string): Promise<number> { const block = await this.web3Wrapper.getBlockAsync('latest'); let gas: number; try { diff --git a/packages/contracts/deploy/src/utils/contract.ts b/packages/contracts/deploy/src/utils/contract.ts index 7b6098cea..ffad9ed70 100644 --- a/packages/contracts/deploy/src/utils/contract.ts +++ b/packages/contracts/deploy/src/utils/contract.ts @@ -8,55 +8,55 @@ import {AbiType} from './types'; export class Contract implements Web3.ContractInstance { public address: string; public abi: Web3.ContractAbi; - private contract: Web3.ContractInstance; - private defaults: Partial<Web3.TxData>; - private validator: SchemaValidator; + private _contract: Web3.ContractInstance; + private _defaults: Partial<Web3.TxData>; + private _validator: SchemaValidator; // This class instance is going to be populated with functions and events depending on the ABI // and we don't know their types in advance [name: string]: any; constructor(web3ContractInstance: Web3.ContractInstance, defaults: Partial<Web3.TxData>) { - this.contract = web3ContractInstance; + this._contract = web3ContractInstance; this.address = web3ContractInstance.address; this.abi = web3ContractInstance.abi; - this.defaults = defaults; - this.populateEvents(); - this.populateFunctions(); - this.validator = new SchemaValidator(); + this._defaults = defaults; + this._populateEvents(); + this._populateFunctions(); + this._validator = new SchemaValidator(); } - private populateFunctions(): void { + private _populateFunctions(): void { const functionsAbi = _.filter(this.abi, abiPart => abiPart.type === AbiType.Function); _.forEach(functionsAbi, (functionAbi: Web3.MethodAbi) => { if (functionAbi.constant) { - const cbStyleCallFunction = this.contract[functionAbi.name].call; + const cbStyleCallFunction = this._contract[functionAbi.name].call; this[functionAbi.name] = { - callAsync: promisify(cbStyleCallFunction, this.contract), + callAsync: promisify(cbStyleCallFunction, this._contract), }; } else { - const cbStyleFunction = this.contract[functionAbi.name]; - const cbStyleEstimateGasFunction = this.contract[functionAbi.name].estimateGas; + const cbStyleFunction = this._contract[functionAbi.name]; + const cbStyleEstimateGasFunction = this._contract[functionAbi.name].estimateGas; this[functionAbi.name] = { - estimateGasAsync: promisify(cbStyleEstimateGasFunction, this.contract), - sendTransactionAsync: this.promisifyWithDefaultParams(cbStyleFunction), + estimateGasAsync: promisify(cbStyleEstimateGasFunction, this._contract), + sendTransactionAsync: this._promisifyWithDefaultParams(cbStyleFunction), }; } }); } - private populateEvents(): void { + private _populateEvents(): void { const eventsAbi = _.filter(this.abi, abiPart => abiPart.type === AbiType.Event); _.forEach(eventsAbi, (eventAbi: Web3.EventAbi) => { - this[eventAbi.name] = this.contract[eventAbi.name]; + this[eventAbi.name] = this._contract[eventAbi.name]; }); } - private promisifyWithDefaultParams(fn: (...args: any[]) => void): (...args: any[]) => Promise<any> { + private _promisifyWithDefaultParams(fn: (...args: any[]) => void): (...args: any[]) => Promise<any> { const promisifiedWithDefaultParams = async (...args: any[]) => { const promise = new Promise((resolve, reject) => { const lastArg = args[args.length - 1]; let txData: Partial<Web3.TxData> = {}; - if (this.isTxData(lastArg)) { + if (this._isTxData(lastArg)) { txData = args.pop(); } txData = { - ...this.defaults, + ...this._defaults, ...txData, }; const callback = (err: Error, data: any) => { @@ -68,14 +68,14 @@ export class Contract implements Web3.ContractInstance { }; args.push(txData); args.push(callback); - fn.apply(this.contract, args); + fn.apply(this._contract, args); }); return promise; }; return promisifiedWithDefaultParams; } - private isTxData(lastArg: any): boolean { - const isValid = this.validator.isValid(lastArg, schemas.txDataSchema); + private _isTxData(lastArg: any): boolean { + const isValid = this._validator.isValid(lastArg, schemas.txDataSchema); return isValid; } } |