Skip to content

Commit

Permalink
setup compile tasks
Browse files Browse the repository at this point in the history
  • Loading branch information
danijelthales committed May 10, 2021
1 parent 88ad11b commit 0765c8b
Show file tree
Hide file tree
Showing 127 changed files with 314,912 additions and 15,204 deletions.
5 changes: 5 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
build
.coverage_*
coverage
.circleci/src
.circleci/config.template.yml
37 changes: 37 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"overrides": [
{
"files": "*.sol",
"options": {
"printWidth": 125,
"tabWidth": 4,
"useTabs": false,
"singleQuote": false,
"bracketSpacing": false,
"explicitTypes": "preserve"
}
},
{
"files": ["*.js", "*.md"],
"options": {
"printWidth": 100,
"semi": true,
"singleQuote": true,
"bracketSpacing": true,
"trailingComma": "es5"
}
},
{
"files": ["*.js", "*.json"],
"options": {
"useTabs": true
}
},
{
"files": "*.md",
"options": {
"useTabs": false
}
}
]
}
23 changes: 23 additions & 0 deletions .solcover.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const {
constants: { inflationStartTimestampInSecs },
} = require('.');

module.exports = {
port: 8545,
skipFiles: [
],
providerOptions: {
default_balance_ether: 10000000000000, // extra zero just in case (coverage consumes more gas)
time: new Date(inflationStartTimestampInSecs * 1000),
network_id: 55,
},
mocha: {
grep: '@cov-skip', // Find everything with this tag
invert: true, // Run the grep's inverse set.
timeout: 360e3,
},
// Reduce instrumentation footprint - volume of solidity code
// passed to compiler causes it to crash (See discussion PR #732)
// Line and branch coverage will still be reported.
measureStatementCoverage: false,
};
22 changes: 22 additions & 0 deletions .solhint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"extends": ["solhint:recommended"],
"plugins": [],
"rules": {
"avoid-call-value": "off",
"compiler-version": ["error", "^0.5.0"],
"const-name-snakecase": "off",
"func-order": "off",
"func-param-name-mixedcase": "off",
"imports-on-top": "off",
"mark-callable-contracts": "off",
"max-line-length": "off",
"no-empty-blocks": "off",
"no-inline-assembly": "off",
"not-rely-on-time": "off",
"no-unused-vars": "warn",
"quotes": ["error", "double"],
"reason-string": "off",
"var-name-mixedcase": "off",
"visibility-modifier-order": "off"
}
}
4 changes: 2 additions & 2 deletions contracts/BinaryOptionMarket.sol
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,8 @@ contract BinaryOptionMarket is MinimalProxyFactory, OwnedWithInit, IBinaryOption
_updatePrices(longBid, shortBid, initialDeposit);

// Instantiate the options themselves
options.long = BinaryOption(_cloneAsMinimalProxy(_manager().binaryOptionMastercopy, "Could not create a Binary Option"));
options.short = BinaryOption(_cloneAsMinimalProxy(_manager().binaryOptionMastercopy, "Could not create a Binary Option"));
options.long = BinaryOption(_cloneAsMinimalProxy(_manager().binaryOptionMastercopy(), "Could not create a Binary Option"));
options.short = BinaryOption(_cloneAsMinimalProxy(_manager().binaryOptionMastercopy(), "Could not create a Binary Option"));
options.long.initialize(_creator, longBid, "Binary Option Short", "sLONG");
options.short.initialize(_creator, shortBid, "Binary Option Long", "sSHORT");

Expand Down
7 changes: 4 additions & 3 deletions contracts/BinaryOptionMarketFactory.sol
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ contract BinaryOptionMarketFactory is MinimalProxyFactory, Owned {

function createMarket(
address creator,
IAddressResolver _resolver,
uint[2] calldata creatorLimits,
bytes32 oracleKey,
uint strikePrice,
Expand All @@ -39,17 +40,17 @@ contract BinaryOptionMarketFactory is MinimalProxyFactory, Owned {
BinaryOptionMarket(
_cloneAsMinimalProxy(binaryOptionMarketMastercopy, "Could not create a Binary Option Market")
);
bom.initialize(manager, resolver, creator, creatorLimits, oracleKey, strikePrice, refundsEnabled, times, bids, fees);
bom.initialize(binaryOptionMarketManager, _resolver, creator, creatorLimits, oracleKey, strikePrice, refundsEnabled, times, bids, fees);
return bom;
}


/* ========== SETTERS ========== */
function setBinaryOptionMarketManager(address _binaryOptionMarketManager) only_owner {
function setBinaryOptionMarketManager(address _binaryOptionMarketManager) public onlyOwner {
binaryOptionMarketManager = _binaryOptionMarketManager;
}

function setBinaryOptionMarketMastercopy(address _binaryOptionMarketMastercopy) only_owner {
function setBinaryOptionMarketMastercopy(address _binaryOptionMarketMastercopy) public onlyOwner {
binaryOptionMarketMastercopy = _binaryOptionMarketMastercopy;
}

Expand Down
13 changes: 5 additions & 8 deletions contracts/BinaryOptionMarketManager.sol
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,11 @@ contract BinaryOptionMarketManager is Owned, Pausable, IBinaryOptionMarketManage
}

/* ========== SETTERS ========== */
function setBinaryOptionsMasterCopy(address _binaryOptionMastercopy) only_owner {
function setBinaryOptionsMasterCopy(address _binaryOptionMastercopy) public onlyOwner {
binaryOptionMastercopy = _binaryOptionMastercopy;
}

function setBinaryOptionsMarketFactory(address _binaryOptionMarketFactory) only_owner {
function setBinaryOptionsMarketFactory(address _binaryOptionMarketFactory) public onlyOwner {
binaryOptionMarketFactory = _binaryOptionMarketFactory;
}

Expand All @@ -111,17 +111,13 @@ contract BinaryOptionMarketManager is Owned, Pausable, IBinaryOptionMarketManage
/* ---------- Related Contracts ---------- */

function _sUSD() internal view returns (IERC20) {
return IERC20(requireAndGetAddress(CONTRACT_SYNTHSUSD, "Synth sUSD contract not found"));
return IERC20(resolver.requireAndGetAddress(CONTRACT_SYNTHSUSD, "Synth sUSD contract not found"));
}

function _exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(resolver.requireAndGetAddress(CONTRACT_EXRATES, "ExchangeRates contract not found"));
}

function _factory() internal view returns (BinaryOptionMarketFactory) {
return BinaryOptionMarketFactory(resolver.requireAndGetAddress(CONTRACT_BINARYOPTIONMARKETFACTORY, "BinaryOptionMarketFactory contract not found"));
}

/* ---------- Market Information ---------- */

function _isKnownMarket(address candidate) internal view returns (bool) {
Expand Down Expand Up @@ -263,8 +259,9 @@ contract BinaryOptionMarketManager is Owned, Pausable, IBinaryOptionMarketManage
// The market itself validates the capital and skew requirements.

BinaryOptionMarket market =
_factory().createMarket(
BinaryOptionMarketFactory(binaryOptionMarketFactory).createMarket(
msg.sender,
resolver,
[creatorLimits.capitalRequirement, creatorLimits.skewLimit],
oracleKey,
strikePrice,
Expand Down
69 changes: 54 additions & 15 deletions hardhat.config.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
require("@nomiclabs/hardhat-waffle");
'use strict';
require('dotenv').config();

// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async () => {
const accounts = await ethers.getSigners();
const path = require('path');

for (const account of accounts) {
console.log(account.address);
}
});
require('./hardhat');
require('@nomiclabs/hardhat-truffle5');
require('solidity-coverage');
require('hardhat-gas-reporter');

// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more
const {
constants: { inflationStartTimestampInSecs, AST_FILENAME, AST_FOLDER, BUILD_FOLDER },
} = require('.');

const GAS_PRICE = 20e9; // 20 GWEI
const CACHE_FOLDER = 'cache';

/**
* @type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
GAS_PRICE,
ovm: {
solcVersion: '0.5.16',
},
solidity: {
compilers: [
{
Expand All @@ -27,5 +30,41 @@ module.exports = {
},
],
},
paths: {
sources: './contracts',
tests: './test/contracts',
artifacts: path.join(BUILD_FOLDER, 'artifacts'),
cache: path.join(BUILD_FOLDER, CACHE_FOLDER),
},
astdocs: {
path: path.join(BUILD_FOLDER, AST_FOLDER),
file: AST_FILENAME,
ignores: 'test-helpers',
},
defaultNetwork: 'hardhat',
networks: {
hardhat: {
gas: 12e6,
blockGasLimit: 12e6,
allowUnlimitedContractSize: true,
gasPrice: GAS_PRICE,
initialDate: new Date(inflationStartTimestampInSecs * 1000).toISOString(),
// Note: forking settings are injected at runtime by hardhat/tasks/task-node.js
},
localhost: {
gas: 12e6,
blockGasLimit: 12e6,
url: 'http://localhost:8545',
},
},
gasReporter: {
enabled: false,
showTimeSpent: true,
currency: 'USD',
maxMethodDiff: 25, // CI will fail if gas usage is > than this %
outputFile: 'test-gas-used.log',
},
mocha: {
timeout: 30e3, // 30s
},
};

8 changes: 8 additions & 0 deletions hardhat/extensions/extension-log.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const { extendEnvironment } = require('hardhat/config');
const { gray } = require('chalk');

const log = (...text) => console.log(gray(...['└─> [DEBUG]'].concat(text)));

extendEnvironment(hre => {
hre.log = log;
});
9 changes: 9 additions & 0 deletions hardhat/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const fs = require('fs');
const path = require('path');

// now require all extensions and tasks
['extensions', 'tasks'].forEach(folder =>
fs
.readdirSync(path.join(__dirname, folder))
.forEach(mod => require(path.join(__dirname, folder, mod)))
);
92 changes: 92 additions & 0 deletions hardhat/tasks/task-compile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
const path = require('path');

const { subtask, task, internalTask } = require('hardhat/config');
const {
TASK_COMPILE_SOLIDITY_GET_SOLC_BUILD,
TASK_COMPILE_SOLIDITY_GET_SOURCE_PATHS,
TASK_COMPILE_SOLIDITY_GET_DEPENDENCY_GRAPH,
} = require('hardhat/builtin-tasks/task-names');
const { gray, yellow, red } = require('chalk');

const optimizeIfRequired = require('../util/optimizeIfRequired');

const { collectContractBytesCodes } = require('../util/collectContractBytecodes');
const { logContractSizes } = require('../../publish/src/contract-size');

task('compile')
.addFlag('showsize', 'Show size of compiled contracts')
.addFlag('optimizer', 'Compile with the optimizer')
.addFlag('failOversize', 'Fail if any contract is oversize')
.addFlag('native', 'Compile with the native solc compiler')
.setAction(async (taskArguments, hre, runSuper) => {

if (taskArguments.native) {
hre.config.solc.native = true;
}

optimizeIfRequired({ hre, taskArguments });

await runSuper(taskArguments);

if (taskArguments.showsize || taskArguments.failOversize) {
const contractToObjectMap = collectContractBytesCodes();
const sizes = logContractSizes({ contractToObjectMap });

if (taskArguments.failOversize) {
const offenders = sizes.filter(entry => +entry.pcent.split('%')[0] > 100);
if (offenders.length > 0) {
const names = offenders.map(o => o.file);
console.log(red('Oversized contracts:'), yellow(`[${names}]`));
throw new Error(
'Compilation failed, because some contracts are too big to be deployed. See above.'
);
}
}
}
});

subtask(TASK_COMPILE_SOLIDITY_GET_SOLC_BUILD).setAction(({ solcVersion }, hre, runSuper) => {

console.log(gray('Solc version ' + solcVersion));
if (!hre.isOvm) {
return runSuper();
}

if (solcVersion === '0.4.25') {
return runSuper();
}

const compilerPath = path.resolve(
__dirname,
'node_modules',
'@eth-optimism',
'solc',
'soljson.js'
);

console.log("Compile path is " + compilerPath);

return {
compilerPath,
isSolcJs: true,
version: solcVersion,
longVersion: solcVersion,
};
});

internalTask(TASK_COMPILE_SOLIDITY_GET_SOURCE_PATHS, async (_, { config }, runSuper) => {
let filePaths = await runSuper();

return filePaths;
});

// See internalTask(TASK_COMPILE_SOLIDITY_GET_SOURCE_PATHS) first.
// Filtering the right sources should be enough. However, knowing which are the right sources can be hard.
// I.e. you may mark TradingRewards to be ignored, but it ends up in the compilation anyway
// because test-helpers/FakeTradingRewards uses it.
// We also override this task to more easily detect when this is happening.
internalTask(TASK_COMPILE_SOLIDITY_GET_DEPENDENCY_GRAPH, async (_, { config }, runSuper) => {
const graph = await runSuper();

return graph;
});
12 changes: 12 additions & 0 deletions hardhat/tasks/task-describe.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const { task } = require('hardhat/config');
const { gray, green } = require('chalk');

const describeSources = require('../util/describeSources');

task('describe').setAction(async (taskArguments, hre) => {
await hre.run('compile', taskArguments);

console.log(gray('Processing Solidity sources and output ASTs...'));
const descriptions = await describeSources({ hre });
console.log(green(`Done describing ${Object.keys(descriptions).length} sources 💯`));
});
Loading

0 comments on commit 0765c8b

Please sign in to comment.